freshyo/apps/admin-ui/app/(drawer)/dashboard/customize-app/index.tsx
2026-10-07 13:36:48 +05:30

646 lines
22 KiB
TypeScript

import React, { useEffect, useMemo, useState } from 'react';
import { View, ScrollView, Alert } from 'react-native';
import { Formik } from 'formik';
import { MyText, MyTextInput, MyTouchableOpacity, tw, AppContainer, Checkbox } from 'common-ui';
import { trpc } from '@/src/trpc-client';
import { useRouter } from 'expo-router';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
type ConstantFormData = Record<string, any>
const CONST_LABELS: Record<string, string> = {
minRegularOrderValue: 'Minimum Regular Order Value',
freeDeliveryThreshold: 'Free Delivery Threshold',
deliveryCharge: 'Delivery Charge',
flashFreeDeliveryThreshold: 'Flash Free Delivery Threshold',
flashDeliveryCharge: 'Flash Delivery Charge',
platformFeePercent: 'Platform Fee Percent',
taxRate: 'Tax Rate',
minOrderAmountForCoupon: 'Minimum Order Amount for Coupon',
maxCouponDiscount: 'Maximum Coupon Discount',
flashDeliverySlotId: 'Flash Delivery Slot ID',
readableOrderId: 'Readable Order ID',
versionNum: 'Version Number',
playStoreUrl: 'Play Store URL',
appStoreUrl: 'App Store URL',
popularItems: 'Popular Items',
allItemsOrder: 'All Items Order',
isFlashDeliveryEnabled: 'Enable Flash Delivery',
supportMobile: 'Support Mobile',
supportEmail: 'Support Email',
internalAppVersion: 'Internal App Version',
welcomeMessage: 'Welcome Message',
};
const CONST_VISIBILITY: Record<string, boolean> = {
minRegularOrderValue: true,
freeDeliveryThreshold: true,
deliveryCharge: true,
flashFreeDeliveryThreshold: true,
flashDeliveryCharge: true,
platformFeePercent: false,
taxRate: false,
minOrderAmountForCoupon: false,
maxCouponDiscount: false,
flashDeliverySlotId: false,
readableOrderId: false,
versionNum: false,
playStoreUrl: false,
appStoreUrl: false,
popularItems: true,
allItemsOrder: true,
isFlashDeliveryEnabled: true,
supportMobile: true,
supportEmail: true,
internalAppVersion: false,
welcomeMessage: true,
tester: false,
};
// The 11 constants that are edited per region bound.
type BoundValueType = 'number' | 'boolean' | 'array' | 'string'
const BOUND_KEY_TYPES: Record<string, BoundValueType> = {
minRegularOrderValue: 'number',
freeDeliveryThreshold: 'number',
deliveryCharge: 'number',
flashFreeDeliveryThreshold: 'number',
flashDeliveryCharge: 'number',
popularItems: 'array',
allItemsOrder: 'array',
isFlashDeliveryEnabled: 'boolean',
supportMobile: 'string',
supportEmail: 'string',
welcomeMessage: 'string',
};
const REGIONAL_KEYS = Object.keys(BOUND_KEY_TYPES);
/** Convert a stored string value into the type ConstantInput expects. */
const parseBoundValue = (key: string, raw: string | null | undefined): any => {
const type = BOUND_KEY_TYPES[key] ?? 'string';
if (raw === null || raw === undefined || raw === '') {
if (type === 'number') return 0;
if (type === 'boolean') return false;
if (type === 'array') return [];
return '';
}
switch (type) {
case 'number': {
const num = parseFloat(raw);
return isNaN(num) ? 0 : num;
}
case 'boolean':
return raw === 'true' || raw === '1' || raw === 'yes' || raw === 'on';
case 'array':
return raw.split(',').map((s) => s.trim()).filter((s) => s.length > 0);
default:
return raw;
}
};
/** Convert a form value back into the string stored by the bound settings API. */
const serializeBoundValue = (key: string, value: any): string => {
const type = BOUND_KEY_TYPES[key] ?? 'string';
switch (type) {
case 'number': {
const num = typeof value === 'number' ? value : parseFloat(value);
return isNaN(num) ? '0' : String(num);
}
case 'boolean':
return value ? 'true' : 'false';
case 'array':
return Array.isArray(value) ? value.join(',') : String(value ?? '');
default:
return value === null || value === undefined ? '' : String(value);
}
};
interface ConstantInputProps {
constantKey: string;
value: any;
setFieldValue: (field: string, value: any) => void;
router: any;
/** When false, popularItems/allItemsOrder render as inline inputs instead of links. */
allowSectionNavigation?: boolean;
}
const ConstantInput: React.FC<ConstantInputProps> = ({
constantKey,
value,
setFieldValue,
router,
allowSectionNavigation = true,
}) => {
const fieldName = constantKey
// Special handling for popularItems - show navigation button instead of input
if (allowSectionNavigation && constantKey === 'popularItems') {
return (
<View>
<MyText style={tw`text-sm font-medium text-gray-700 mb-2`}>
{CONST_LABELS[constantKey] || constantKey}
</MyText>
<MyTouchableOpacity
onPress={() => router.push('/(drawer)/dashboard/customize-app/popular-items')}
style={tw`bg-blue-50 border-2 border-dashed border-blue-200 p-4 rounded-lg flex-row items-center justify-center`}
>
<MaterialIcons name="edit" size={20} color="#3b82f6" style={tw`mr-2`} />
<MyText style={tw`text-blue-700 font-medium`}>
Manage Popular Items ({Array.isArray(value) ? value.length : 0} items)
</MyText>
<MaterialIcons name="chevron-right" size={20} color="#3b82f6" style={tw`ml-2`} />
</MyTouchableOpacity>
</View>
);
}
// Special handling for allItemsOrder - show navigation button instead of input
if (allowSectionNavigation && constantKey === 'allItemsOrder') {
return (
<View>
<MyText style={tw`text-sm font-medium text-gray-700 mb-2`}>
{CONST_LABELS[constantKey] || constantKey}
</MyText>
<MyTouchableOpacity
onPress={() => router.push('/(drawer)/dashboard/customize-app/all-items-order')}
style={tw`bg-green-50 border-2 border-dashed border-green-200 p-4 rounded-lg flex-row items-center justify-center`}
>
<MaterialIcons name="reorder" size={20} color="#16a34a" style={tw`mr-2`} />
<MyText style={tw`text-green-700 font-medium`}>
Manage All Visible Items ({Array.isArray(value) ? value.length : 0} items)
</MyText>
<MaterialIcons name="chevron-right" size={20} color="#16a34a" style={tw`ml-2`} />
</MyTouchableOpacity>
</View>
);
}
// Handle boolean values - show checkbox
if (typeof value === 'boolean') {
return (
<View>
<MyText style={tw`text-sm font-medium text-gray-700 mb-2`}>
{CONST_LABELS[constantKey] || constantKey}
</MyText>
<View style={tw`flex-row items-center`}>
<Checkbox
checked={value}
onPress={() => setFieldValue(fieldName, !value)}
size={28}
/>
<MyText style={tw`ml-3 text-gray-700`}>
{value ? 'Enabled' : 'Disabled'}
</MyText>
</View>
</View>
);
}
// Handle different value types
if (typeof value === 'number') {
return (
<MyTextInput
topLabel={CONST_LABELS[constantKey] || constantKey}
value={value.toString()}
onChangeText={(value) => {
const numValue = parseFloat(value);
setFieldValue(fieldName, isNaN(numValue) ? 0 : numValue);
}}
keyboardType="numeric"
placeholder="Enter number"
/>
);
}
if (Array.isArray(value)) {
return (
<MyTextInput
topLabel={CONST_LABELS[constantKey] || constantKey}
value={value.join(', ')}
onChangeText={(value) => {
const arrayValue = value.split(',').map(s => s.trim()).filter(s => s.length > 0);
setFieldValue(fieldName, arrayValue);
}}
placeholder="Enter comma separated values"
/>
);
}
// Welcome message — multiline text area
if (constantKey === 'welcomeMessage') {
return (
<MyTextInput
topLabel={CONST_LABELS[constantKey] || constantKey}
value={value === null || value === undefined ? '' : String(value)}
onChangeText={(value) => {
setFieldValue(fieldName, value)
}}
placeholder="Enter welcome message"
multiline
numberOfLines={4}
style={tw`min-h-24`}
/>
);
}
// Default to string
return (
<MyTextInput
topLabel={CONST_LABELS[constantKey] || constantKey}
value={value}
onChangeText={(value) => {
setFieldValue(fieldName, value)
}}
placeholder="Enter value"
/>
);
};
export default function CustomizeApp() {
const router = useRouter();
const [mode, setMode] = useState<'bounds' | 'global'>('bounds');
const [selectedBoundId, setSelectedBoundId] = useState<number | null>(null);
const { data: region } = trpc.admin.region.current.useQuery();
const {
data: bounds,
isLoading: isLoadingBounds,
isError: isBoundsError,
error: boundsError,
refetch: refetchBounds,
} = trpc.admin.region.bounds.useQuery();
// Only fetch the selected bound's settings (avoid requesting boundId 0).
const {
data: boundSettings,
isLoading: isLoadingBoundSettings,
isError: isBoundSettingsError,
error: boundSettingsError,
refetch: refetchBoundSettings,
} = trpc.admin.region.getBoundSettings.useQuery(
{ boundId: selectedBoundId ?? 0 },
{ enabled: selectedBoundId !== null }
);
const updateBoundSettings = trpc.admin.region.updateBoundSettings.useMutation();
// Global constants (unchanged API) — kept for non-regional keys.
const { data: constants, isLoading: isLoadingConstants, refetch: refetchConstants } =
trpc.admin.const.getConstants.useQuery();
const { mutate: updateConstants, isPending: isUpdating } = trpc.admin.const.updateConstants.useMutation();
// Default-select the lowest-priority bound (first, ascending by priority).
useEffect(() => {
if (bounds && bounds.length > 0) {
setSelectedBoundId((prev) => {
if (prev !== null && bounds.some((b) => b.id === prev)) {
return prev;
}
return bounds[0].id;
});
}
}, [bounds]);
// The effective bound is the one with the lowest-numbered priority.
const effectiveBoundId = useMemo(() => {
if (!bounds || bounds.length === 0) return null;
return bounds.reduce((min, bound) =>
Number(bound.priority) < Number(min.priority) ? bound : min
).id;
}, [bounds]);
// Parse the selected bound's stored settings into form-ready values.
const boundInitialValues: Record<string, any> = useMemo(() => {
const values: Record<string, any> = {};
for (const key of REGIONAL_KEYS) {
values[key] = parseBoundValue(key, boundSettings ? boundSettings[key] : null);
}
return values;
}, [boundSettings]);
const handleBoundSubmit = (values: ConstantFormData) => {
if (selectedBoundId === null) return;
const original = boundSettings ?? {};
const changed = REGIONAL_KEYS.filter((key) => {
const next = serializeBoundValue(key, values[key]);
const prev = original[key] ?? null;
return next !== prev;
}).map((key) => ({
key,
value: serializeBoundValue(key, values[key]),
}));
if (changed.length === 0) {
Alert.alert('No Changes', 'No settings were modified.');
return;
}
updateBoundSettings.mutate(
{ boundId: selectedBoundId, settings: changed },
{
onSuccess: (response) => {
Alert.alert('Success', `Updated ${response.updatedCount} settings successfully.`);
refetchBoundSettings();
},
onError: (error) => {
Alert.alert('Error', 'Failed to update settings. Please try again.');
console.error('Update bound settings error:', error);
},
}
);
};
const handleGlobalSubmit = (values: ConstantFormData) => {
// Filter out constants that haven't changed
const changedConstants = (constants || []).filter((constant) => {
const nextValue = values[constant.key]
return JSON.stringify(nextValue) !== JSON.stringify(constant.value)
}).map((constant) => ({
key: constant.key,
value: values[constant.key],
}))
if (changedConstants.length === 0) {
Alert.alert('No Changes', 'No constants were modified.');
return;
}
updateConstants(
{ constants: changedConstants },
{
onSuccess: (response) => {
Alert.alert('Success', `Updated ${response.updatedCount} constants successfully.`);
refetchConstants();
},
onError: (error) => {
Alert.alert('Error', 'Failed to update constants. Please try again.');
console.error('Update constants error:', error);
},
}
);
};
const globalInitialValues: ConstantFormData = (constants ?? []).reduce((acc, constant) => {
acc[constant.key] = constant.value ?? ''
return acc
}, {} as ConstantFormData)
const renderRegional = () => {
if (isLoadingBounds) {
return (
<View style={tw`py-12 items-center`}>
<MyText style={tw`text-gray-500`}>Loading bounds...</MyText>
</View>
);
}
if (isBoundsError) {
return (
<View style={tw`py-12 items-center`}>
<MaterialIcons name="error-outline" size={48} color="#ef4444" />
<MyText style={tw`text-gray-700 mt-3 font-semibold`}>Failed to load bounds</MyText>
<MyText style={tw`text-gray-500 mt-1 text-center`}>
{boundsError?.message || 'Please try again.'}
</MyText>
<MyTouchableOpacity
onPress={() => refetchBounds()}
style={tw`mt-4 bg-blue-600 px-6 py-2 rounded-full`}
>
<MyText style={tw`text-white font-semibold`}>Retry</MyText>
</MyTouchableOpacity>
</View>
);
}
if (!bounds || bounds.length === 0) {
return (
<View style={tw`py-12 items-center`}>
<MaterialIcons name="map" size={48} color="#d1d5db" />
<MyText style={tw`text-gray-700 mt-3 font-semibold`}>No bounds configured</MyText>
<MyText style={tw`text-gray-500 mt-1 text-center`}>
This region has no bounds yet. Ask a superadmin to configure one.
</MyText>
</View>
);
}
const selectedBound = bounds.find((bound) => bound.id === selectedBoundId) ?? null;
return (
<View>
<MyText style={tw`text-gray-600 mb-4`}>
Each bound stores its own business settings. The Effective bound (lowest
priority) is the one whose settings apply to checkout.
</MyText>
{/* One tab per bound, ordered ascending by priority. */}
<ScrollView horizontal showsHorizontalScrollIndicator={false} style={tw`mb-4`}>
{bounds.map((bound) => {
const isSelected = bound.id === selectedBoundId;
const isEffective = bound.id === effectiveBoundId;
return (
<MyTouchableOpacity
key={bound.id}
onPress={() => setSelectedBoundId(bound.id)}
style={tw`mr-2 px-4 py-2 rounded-lg border ${
isSelected ? 'bg-blue-600 border-blue-600' : 'bg-white border-gray-200'
}`}
>
<MyText
style={tw`${isSelected ? 'text-white' : 'text-gray-800'} font-semibold`}
>
{bound.description || `Bound #${bound.id}`}
</MyText>
<View style={tw`flex-row items-center mt-1`}>
<MyText
style={tw`${isSelected ? 'text-blue-100' : 'text-gray-400'} text-xs mr-2`}
>
Priority {bound.priority}
</MyText>
{isEffective && (
<View
style={tw`px-2 py-0.5 rounded-full ${
isSelected ? 'bg-white' : 'bg-green-100'
}`}
>
<MyText
style={tw`${
isSelected ? 'text-blue-700' : 'text-green-700'
} text-[10px] font-bold uppercase`}
>
Effective
</MyText>
</View>
)}
</View>
</MyTouchableOpacity>
);
})}
</ScrollView>
{selectedBound && (
<MyText style={tw`text-gray-500 text-sm mb-4`}>
Editing {selectedBound.description || `Bound #${selectedBound.id}`}
{selectedBound.id === effectiveBoundId ? ' — settings apply to checkout' : ''}
</MyText>
)}
{selectedBoundId === null || isLoadingBoundSettings ? (
<View style={tw`py-12 items-center`}>
<MyText style={tw`text-gray-500`}>Loading settings...</MyText>
</View>
) : isBoundSettingsError ? (
<View style={tw`py-12 items-center`}>
<MaterialIcons name="error-outline" size={48} color="#ef4444" />
<MyText style={tw`text-gray-700 mt-3 font-semibold`}>Failed to load settings</MyText>
<MyText style={tw`text-gray-500 mt-1 text-center`}>
{boundSettingsError?.message || 'Please try again.'}
</MyText>
<MyTouchableOpacity
onPress={() => refetchBoundSettings()}
style={tw`mt-4 bg-blue-600 px-6 py-2 rounded-full`}
>
<MyText style={tw`text-white font-semibold`}>Retry</MyText>
</MyTouchableOpacity>
</View>
) : (
// key forces a fresh form per bound so drafts never leak between tabs.
<Formik
key={selectedBoundId}
initialValues={boundInitialValues}
enableReinitialize
onSubmit={handleBoundSubmit}
>
{({ handleSubmit, values, setFieldValue }) => (
<View>
{REGIONAL_KEYS.map((key) => (
<View key={key} style={tw`mb-4`}>
<ConstantInput
constantKey={key}
value={values[key]}
setFieldValue={setFieldValue}
router={router}
allowSectionNavigation={false}
/>
</View>
))}
<MyTouchableOpacity
onPress={() => handleSubmit()}
disabled={updateBoundSettings.isPending}
style={tw`bg-blue-500 p-4 rounded-lg mt-6 ${
updateBoundSettings.isPending ? 'opacity-50' : ''
}`}
>
<MyText style={tw`text-white text-center font-semibold`}>
{updateBoundSettings.isPending ? 'Saving...' : 'Save Changes'}
</MyText>
</MyTouchableOpacity>
</View>
)}
</Formik>
)}
</View>
);
};
const renderGlobal = () => {
if (isLoadingConstants) {
return (
<View style={tw`py-12 items-center`}>
<MyText style={tw`text-gray-500`}>Loading constants...</MyText>
</View>
);
}
if (!constants) {
return (
<View style={tw`py-12 items-center`}>
<MyText style={tw`text-gray-500`}>Failed to load constants</MyText>
</View>
);
}
return (
<Formik initialValues={globalInitialValues} onSubmit={handleGlobalSubmit}>
{({ handleSubmit, values, setFieldValue }) => (
<View>
<MyText style={tw`text-gray-500 text-sm mb-4`}>
These global constants are not region-specific and still apply app-wide.
</MyText>
{constants.map((constant) => {
if (!CONST_VISIBILITY[constant.key]) {
return null
}
return (
<View key={constant.key} style={tw`mb-4`}>
<ConstantInput
constantKey={constant.key}
value={values[constant.key]}
setFieldValue={setFieldValue}
router={router}
/>
</View>
)
})}
<MyTouchableOpacity
onPress={() => handleSubmit()}
disabled={isUpdating}
style={tw`bg-blue-500 p-4 rounded-lg mt-6 ${isUpdating ? 'opacity-50' : ''}`}
>
<MyText style={tw`text-white text-center font-semibold`}>
{isUpdating ? 'Updating...' : 'Save Changes'}
</MyText>
</MyTouchableOpacity>
</View>
)}
</Formik>
);
};
return (
<AppContainer>
<MyText style={tw`text-xl font-bold`}>Customize App</MyText>
<MyText style={tw`text-gray-500 mt-1`}>
{region?.name ? `Region: ${region.name}` : 'Regional business settings'}
</MyText>
{/* Top-level switch: per-bound regional settings vs. legacy global constants. */}
<View style={tw`flex-row bg-gray-100 rounded-lg p-1 mt-4 mb-4`}>
<MyTouchableOpacity
onPress={() => setMode('bounds')}
style={tw`flex-1 py-2 rounded-md ${mode === 'bounds' ? 'bg-white' : ''}`}
>
<MyText
style={tw`text-center ${
mode === 'bounds' ? 'text-gray-900 font-semibold' : 'text-gray-500'
}`}
>
Regional Settings
</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
onPress={() => setMode('global')}
style={tw`flex-1 py-2 rounded-md ${mode === 'global' ? 'bg-white' : ''}`}
>
<MyText
style={tw`text-center ${
mode === 'global' ? 'text-gray-900 font-semibold' : 'text-gray-500'
}`}
>
Global Constants
</MyText>
</MyTouchableOpacity>
</View>
{mode === 'bounds' ? renderRegional() : renderGlobal()}
</AppContainer>
);
}