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 type ConstTab = 'region' | 'bound' // --- key groups (mirrors packages/db_helper_sqlite/src/lib/const-keys.ts) --- // Region tab: region_consts minus the version counters (owned by the cache // pipeline) and tagsOrder (edited on its own Tag Orders screen). const REGION_KEYS = [ 'popularItems', 'allItemsOrder', 'isFlashDeliveryEnabled', 'supportMobile', 'supportEmail', 'welcomeMessage', ] const BOUND_KEYS = [ 'freeDeliveryThreshold', 'deliveryCharge', 'flashFreeDeliveryThreshold', 'flashDeliveryCharge', ] const CONST_LABELS: Record = { freeDeliveryThreshold: 'Free Delivery Threshold', deliveryCharge: 'Delivery Charge', flashFreeDeliveryThreshold: 'Flash Free Delivery Threshold', flashDeliveryCharge: 'Flash Delivery Charge', platformFeePercent: 'Platform Fee Percent', taxRate: 'Tax Rate', tester: 'Tester', 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', tagsOrder: 'Tags Order', isFlashDeliveryEnabled: 'Enable Flash Delivery', supportMobile: 'Support Mobile', supportEmail: 'Support Email', internalAppVersion: 'Internal App Version', welcomeMessage: 'Welcome Message', }; type ConstValueType = 'number' | 'boolean' | 'array' | 'string' const KEY_TYPES: Record = { freeDeliveryThreshold: 'number', deliveryCharge: 'number', flashFreeDeliveryThreshold: 'number', flashDeliveryCharge: 'number', popularItems: 'array', allItemsOrder: 'array', tagsOrder: 'array', isFlashDeliveryEnabled: 'boolean', supportMobile: 'string', supportEmail: 'string', welcomeMessage: 'string', platformFeePercent: 'number', taxRate: 'number', tester: 'string', minOrderAmountForCoupon: 'number', maxCouponDiscount: 'number', flashDeliverySlotId: 'number', readableOrderId: 'number', versionNum: 'string', playStoreUrl: 'string', appStoreUrl: 'string', internalAppVersion: 'number', }; /** Convert a stored string value into the type ConstantInput expects. */ const parseConstValue = (key: string, raw: string | null | undefined): any => { const type = 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 constants API. */ const serializeConstValue = (key: string, value: any): string => { const type = 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 = ({ constantKey, value, setFieldValue, router, allowSectionNavigation = true, }) => { const fieldName = constantKey // Special handling for popularItems - show navigation button instead of input if (allowSectionNavigation && constantKey === 'popularItems') { return ( {CONST_LABELS[constantKey] || constantKey} 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`} > Manage Popular Items ({Array.isArray(value) ? value.length : 0} items) ); } // Special handling for allItemsOrder - show navigation button instead of input if (allowSectionNavigation && constantKey === 'allItemsOrder') { return ( {CONST_LABELS[constantKey] || constantKey} 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`} > Manage All Visible Items ({Array.isArray(value) ? value.length : 0} items) ); } // Handle boolean values - show checkbox if (typeof value === 'boolean') { return ( {CONST_LABELS[constantKey] || constantKey} setFieldValue(fieldName, !value)} size={28} /> {value ? 'Enabled' : 'Disabled'} ); } // Handle different value types if (typeof value === 'number') { return ( { const numValue = parseFloat(value); setFieldValue(fieldName, isNaN(numValue) ? 0 : numValue); }} keyboardType="numeric" placeholder="Enter number" /> ); } if (Array.isArray(value)) { return ( { 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 ( { setFieldValue(fieldName, value) }} placeholder="Enter welcome message" multiline numberOfLines={4} style={tw`min-h-24`} /> ); } // Default to string return ( { setFieldValue(fieldName, value) }} placeholder="Enter value" /> ); }; export default function CustomizeApp() { const router = useRouter(); const [tab, setTab] = useState('bound'); const [selectedBoundId, setSelectedBoundId] = useState(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(); // Region-scoped constants (region_consts) for the caller's region. const { data: regionConstants, isLoading: isLoadingRegionConstants, refetch: refetchRegionConstants, } = trpc.admin.region.getRegionConstants.useQuery(); const updateRegionConstants = trpc.admin.region.updateRegionConstants.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 = useMemo(() => { const values: Record = {}; for (const key of BOUND_KEYS) { values[key] = parseConstValue(key, boundSettings ? boundSettings[key] : null); } return values; }, [boundSettings]); const handleBoundSubmit = (values: ConstantFormData) => { if (selectedBoundId === null) return; const original = boundSettings ?? {}; const changed = BOUND_KEYS.filter((key) => { const next = serializeConstValue(key, values[key]); const prev = original[key] ?? null; return next !== prev; }).map((key) => ({ key, value: serializeConstValue(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); }, } ); }; // --- Region tab --- const regionValueByKey = useMemo(() => { const map: Record = {}; for (const row of regionConstants ?? []) map[row.key] = row.value as string | null; return map; }, [regionConstants]); const regionInitialValues: ConstantFormData = useMemo(() => { const values: ConstantFormData = {}; for (const key of REGION_KEYS) values[key] = parseConstValue(key, regionValueByKey[key]); return values; }, [regionValueByKey]); const handleRegionSubmit = (values: ConstantFormData) => { const changed = REGION_KEYS.filter((key) => { const next = serializeConstValue(key, values[key]); const prev = regionValueByKey[key] ?? null; return next !== prev; }).map((key) => ({ key, value: serializeConstValue(key, values[key]) })); if (changed.length === 0) { Alert.alert('No Changes', 'No region settings were modified.'); return; } updateRegionConstants.mutate( { constants: changed }, { onSuccess: (response) => { Alert.alert('Success', `Updated ${response.updatedCount} region settings successfully.`); refetchRegionConstants(); }, onError: (error) => { Alert.alert('Error', 'Failed to update region settings. Please try again.'); console.error('Update region constants error:', error); }, } ); }; const renderBound = () => { if (isLoadingBounds) { return ( Loading bounds... ); } if (isBoundsError) { return ( Failed to load bounds {boundsError?.message || 'Please try again.'} refetchBounds()} style={tw`mt-4 bg-blue-600 px-6 py-2 rounded-full`} > Retry ); } if (!bounds || bounds.length === 0) { return ( No bounds configured This region has no bounds yet. Ask a superadmin to configure one. ); } const selectedBound = bounds.find((bound) => bound.id === selectedBoundId) ?? null; return ( Each bound stores its own business settings. The Effective bound (lowest priority) is the one whose settings apply to checkout. {/* One tab per bound, ordered ascending by priority. */} {bounds.map((bound) => { const isSelected = bound.id === selectedBoundId; const isEffective = bound.id === effectiveBoundId; return ( 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' }`} > {bound.description || `Bound #${bound.id}`} Priority {bound.priority} {isEffective && ( Effective )} ); })} {selectedBound && ( Editing {selectedBound.description || `Bound #${selectedBound.id}`} {selectedBound.id === effectiveBoundId ? ' — settings apply to checkout' : ''} )} {selectedBoundId === null || isLoadingBoundSettings ? ( Loading settings... ) : isBoundSettingsError ? ( Failed to load settings {boundSettingsError?.message || 'Please try again.'} refetchBoundSettings()} style={tw`mt-4 bg-blue-600 px-6 py-2 rounded-full`} > Retry ) : ( // key forces a fresh form per bound so drafts never leak between tabs. {({ handleSubmit, values, setFieldValue }) => ( {BOUND_KEYS.map((key) => ( ))} handleSubmit()} disabled={updateBoundSettings.isPending} style={tw`bg-blue-500 p-4 rounded-lg mt-6 ${ updateBoundSettings.isPending ? 'opacity-50' : '' }`} > {updateBoundSettings.isPending ? 'Saving...' : 'Save Changes'} )} )} ); }; const renderRegion = () => { if (isLoadingRegionConstants) { return ( Loading region settings... ); } return ( {({ handleSubmit, values, setFieldValue }) => ( Region settings apply to every bound in this region. {REGION_KEYS.map((key) => ( ))} handleSubmit()} disabled={updateRegionConstants.isPending} style={tw`bg-blue-500 p-4 rounded-lg mt-6 ${ updateRegionConstants.isPending ? 'opacity-50' : '' }`} > {updateRegionConstants.isPending ? 'Saving...' : 'Save Changes'} )} ); }; const tabs: { id: ConstTab; label: string }[] = [ { id: 'region', label: 'Region' }, { id: 'bound', label: 'Bound' }, ]; return ( Customize App {region?.name ? `Region: ${region.name}` : 'Regional business settings'} {/* Top-level switch: region vs. per-bound settings. */} {tabs.map((t) => ( setTab(t.id)} style={tw`flex-1 py-2 rounded-md ${tab === t.id ? 'bg-white' : ''}`} > {t.label} ))} {tab === 'region' && renderRegion()} {tab === 'bound' && renderBound()} ); }