freshyo/apps/admin-web/src/routes/dashboard.customize-app.tsx
2026-10-07 13:36:48 +05:30

625 lines
20 KiB
TypeScript

import React, { useEffect, useMemo, useState } from 'react'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { Formik } from 'formik'
import { Pencil, ChevronRight, ArrowDownUp } from 'lucide-react'
import { p as MyText, pInput as MyTextInput, AppContainer, Checkbox } from 'web-components'
import { trpc } from '@/lib/trpc-client'
export const Route = createFileRoute('/dashboard/customize-app')({
component: CustomizeApp,
})
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',
welcomeMessage: 'Welcome Message',
}
const CONST_VISIBILITY: Record<string, boolean> = {
minRegularOrderValue: true,
freeDeliveryThreshold: true,
deliveryCharge: true,
flashFreeDeliveryThreshold: true,
flashDeliveryCharge: true,
platformFeePercent: true,
taxRate: false,
minOrderAmountForCoupon: true,
maxCouponDiscount: false,
flashDeliverySlotId: true,
readableOrderId: false,
versionNum: true,
playStoreUrl: true,
appStoreUrl: true,
popularItems: true,
allItemsOrder: true,
isFlashDeliveryEnabled: true,
supportMobile: true,
supportEmail: true,
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
if (allowSectionNavigation && constantKey === 'popularItems') {
return (
<div>
<MyText className="mb-2 text-sm font-medium text-gray-700">
{CONST_LABELS[constantKey] || constantKey}
</MyText>
<button
onClick={() => router.push('/dashboard/customize-app/popular')}
className="flex flex-row items-center justify-center rounded-lg border-2 border-dashed border-blue-200 bg-blue-50 p-4"
>
<Pencil size={20} color="#3b82f6" className="mr-2" />
<MyText className="font-medium text-blue-700">
Manage Popular Items ({Array.isArray(value) ? value.length : 0} items)
</MyText>
<ChevronRight size={20} color="#3b82f6" className="ml-2" />
</button>
</div>
)
}
if (allowSectionNavigation && constantKey === 'allItemsOrder') {
return (
<div>
<MyText className="mb-2 text-sm font-medium text-gray-700">
{CONST_LABELS[constantKey] || constantKey}
</MyText>
<button
onClick={() => router.push('/dashboard/customize-app/ordering')}
className="flex flex-row items-center justify-center rounded-lg border-2 border-dashed border-green-200 bg-green-50 p-4"
>
<ArrowDownUp size={20} color="#16a34a" className="mr-2" />
<MyText className="font-medium text-green-700">
Manage All Visible Items ({Array.isArray(value) ? value.length : 0} items)
</MyText>
<ChevronRight size={20} color="#16a34a" className="ml-2" />
</button>
</div>
)
}
if (typeof value === 'boolean') {
return (
<div>
<MyText className="mb-2 text-sm font-medium text-gray-700">
{CONST_LABELS[constantKey] || constantKey}
</MyText>
<div className="flex flex-row items-center">
<Checkbox
checked={value}
onPress={() => setFieldValue(fieldName, !value)}
size={28}
/>
<MyText className="ml-3 text-gray-700">
{value ? 'Enabled' : 'Disabled'}
</MyText>
</div>
</div>
)
}
if (typeof value === 'number') {
return (
<MyTextInput
topLabel={CONST_LABELS[constantKey] || constantKey}
value={value.toString()}
onChange={(e) => {
const numValue = parseFloat(e.target.value)
setFieldValue(fieldName, isNaN(numValue) ? 0 : numValue)
}}
type="number"
placeholder="Enter number"
/>
)
}
if (Array.isArray(value)) {
return (
<MyTextInput
topLabel={CONST_LABELS[constantKey] || constantKey}
value={value.join(', ')}
onChange={(e) => {
const arrayValue = e.target.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)}
onChange={(e) => {
setFieldValue(fieldName, e.target.value)
}}
placeholder="Enter welcome message"
multiline
numberOfLines={4}
/>
)
}
return (
<MyTextInput
topLabel={CONST_LABELS[constantKey] || constantKey}
value={value}
onChange={(e) => {
setFieldValue(fieldName, e.target.value)
}}
placeholder="Enter value"
/>
)
}
function CustomizeApp() {
const navigate = useNavigate()
const router = {
push: (to: string) => navigate({ to: to as any }),
}
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 { mutate: updateBoundSettings, isPending: isSavingBound } =
trpc.admin.region.updateBoundSettings.useMutation()
// Global constants (unchanged API) — kept for non-regional keys.
const { data: constants, isLoading: isLoadingConstants, refetch } = 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) {
window.alert('No settings were modified.')
return
}
updateBoundSettings(
{ boundId: selectedBoundId, settings: changed },
{
onSuccess: (response) => {
window.alert(`Updated ${response.updatedCount} settings successfully.`)
refetchBoundSettings()
},
onError: (error) => {
window.alert('Failed to update settings. Please try again.')
console.error('Update bound settings error:', error)
},
},
)
}
const handleGlobalSubmit = (values: ConstantFormData) => {
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) {
window.alert('No constants were modified.')
return
}
updateConstants(
{ constants: changedConstants },
{
onSuccess: (response) => {
window.alert(`Updated ${response.updatedCount} constants successfully.`)
refetch()
},
onError: (error) => {
window.alert('Failed to update constants. Please try again.')
console.error('Update constants error:', error)
},
},
)
}
const renderRegional = () => {
if (isLoadingBounds) {
return (
<div className="flex flex-1 items-center justify-center py-12">
<MyText className="text-gray-500">Loading bounds...</MyText>
</div>
)
}
if (isBoundsError) {
return (
<div className="flex flex-col items-center py-12">
<MyText className="font-semibold text-gray-700">Failed to load bounds</MyText>
<MyText className="mt-1 text-center text-gray-500">
{boundsError?.message || 'Please try again.'}
</MyText>
<button
onClick={() => refetchBounds()}
className="mt-4 rounded-full bg-blue-600 px-6 py-2"
>
<MyText className="font-semibold text-white">Retry</MyText>
</button>
</div>
)
}
if (!bounds || bounds.length === 0) {
return (
<div className="flex flex-col items-center py-12">
<MyText className="font-semibold text-gray-700">No bounds configured</MyText>
<MyText className="mt-1 text-center text-gray-500">
This region has no bounds yet. Ask a superadmin to configure one.
</MyText>
</div>
)
}
const selectedBound = bounds.find((bound) => bound.id === selectedBoundId) ?? null
return (
<div>
<MyText className="mb-4 text-gray-600">
Each bound stores its own business settings. Only the effective bound (lowest priority)
settings apply to checkout.
</MyText>
{/* One tab per bound, ordered ascending by priority. */}
<div className="mb-4 flex flex-row gap-2 overflow-x-auto pb-1">
{bounds.map((bound) => {
const isSelected = bound.id === selectedBoundId
const isEffective = bound.id === effectiveBoundId
return (
<button
key={bound.id}
onClick={() => setSelectedBoundId(bound.id)}
className={`rounded-lg border px-4 py-2 text-left ${
isSelected ? 'border-blue-600 bg-blue-600' : 'border-gray-200 bg-white'
}`}
>
<MyText className={`font-semibold ${isSelected ? 'text-white' : 'text-gray-800'}`}>
{bound.description || `Bound #${bound.id}`}
</MyText>
<div className="mt-1 flex flex-row items-center">
<MyText className={`mr-2 text-xs ${isSelected ? 'text-blue-100' : 'text-gray-400'}`}>
Priority {bound.priority}
</MyText>
{isEffective && (
<span
className={`rounded-full px-2 py-0.5 text-[10px] font-bold uppercase ${
isSelected ? 'bg-white text-blue-700' : 'bg-green-100 text-green-700'
}`}
>
Effective
</span>
)}
</div>
</button>
)
})}
</div>
{selectedBound && (
<MyText className="mb-4 text-sm text-gray-500">
Editing {selectedBound.description || `Bound #${selectedBound.id}`}
{selectedBound.id === effectiveBoundId ? ' — settings apply to checkout' : ''}
</MyText>
)}
{selectedBoundId === null || isLoadingBoundSettings ? (
<div className="flex flex-1 items-center justify-center py-12">
<MyText className="text-gray-500">Loading settings...</MyText>
</div>
) : isBoundSettingsError ? (
<div className="flex flex-col items-center py-12">
<MyText className="font-semibold text-gray-700">Failed to load settings</MyText>
<MyText className="mt-1 text-center text-gray-500">
{boundSettingsError?.message || 'Please try again.'}
</MyText>
<button
onClick={() => refetchBoundSettings()}
className="mt-4 rounded-full bg-blue-600 px-6 py-2"
>
<MyText className="font-semibold text-white">Retry</MyText>
</button>
</div>
) : (
// key forces a fresh form per bound so drafts never leak between tabs.
<Formik
key={selectedBoundId}
initialValues={boundInitialValues}
enableReinitialize
onSubmit={handleBoundSubmit}
>
{({ handleSubmit, values, setFieldValue }) => (
<div>
{REGIONAL_KEYS.map((key) => (
<div key={key} className="mb-4">
<ConstantInput
constantKey={key}
value={values[key]}
setFieldValue={setFieldValue}
router={router}
allowSectionNavigation={false}
/>
</div>
))}
<button
onClick={() => handleSubmit()}
disabled={isSavingBound}
className={`mt-6 rounded-lg bg-blue-500 p-4 ${isSavingBound ? 'opacity-50' : ''}`}
>
<MyText className="text-center font-semibold text-white">
{isSavingBound ? 'Saving...' : 'Save Changes'}
</MyText>
</button>
</div>
)}
</Formik>
)}
</div>
)
}
const renderGlobal = () => {
if (isLoadingConstants) {
return (
<div className="flex flex-1 items-center justify-center">
<MyText className="text-gray-500">Loading constants...</MyText>
</div>
)
}
if (!constants) {
return (
<div className="flex flex-1 items-center justify-center">
<MyText className="text-gray-500">Failed to load constants</MyText>
</div>
)
}
const initialValues: ConstantFormData = constants.reduce((acc, constant) => {
acc[constant.key] = constant.value ?? ''
return acc
}, {} as ConstantFormData)
return (
<Formik initialValues={initialValues} onSubmit={handleGlobalSubmit}>
{({ handleSubmit, values, setFieldValue }) => (
<div>
<MyText className="mb-4 text-sm text-gray-500">
These global constants are not region-specific and still apply app-wide.
</MyText>
{constants.map((constant) => {
if (!CONST_VISIBILITY[constant.key]) {
return null
}
return (
<div key={constant.key} className="mb-4">
<ConstantInput
constantKey={constant.key}
value={values[constant.key]}
setFieldValue={setFieldValue}
router={router}
/>
</div>
)
})}
<button
onClick={() => handleSubmit()}
disabled={isUpdating}
className={`mt-6 rounded-lg bg-blue-500 p-4 ${isUpdating ? 'opacity-50' : ''}`}
>
<MyText className="text-center font-semibold text-white">
{isUpdating ? 'Updating...' : 'Save Changes'}
</MyText>
</button>
</div>
)}
</Formik>
)
}
return (
<AppContainer>
<div className="flex-1 bg-gray-50 p-4">
<MyText className="mb-1 text-xl font-bold">Customize App</MyText>
<MyText className="mb-2 text-gray-600">
{region?.name ? `Region: ${region.name}` : 'Regional business settings'}
</MyText>
<MyText className="mb-4 text-gray-600">
Modify application settings. Changes will take effect immediately.
</MyText>
{/* Top-level switch: per-bound regional settings vs. legacy global constants. */}
<div className="mb-4 flex flex-row rounded-lg bg-gray-100 p-1">
<button
onClick={() => setMode('bounds')}
className={`flex-1 rounded-md py-2 ${mode === 'bounds' ? 'bg-white' : ''}`}
>
<MyText className={`text-center ${mode === 'bounds' ? 'font-semibold text-gray-900' : 'text-gray-500'}`}>
Regional Settings
</MyText>
</button>
<button
onClick={() => setMode('global')}
className={`flex-1 rounded-md py-2 ${mode === 'global' ? 'bg-white' : ''}`}
>
<MyText className={`text-center ${mode === 'global' ? 'font-semibold text-gray-900' : 'text-gray-500'}`}>
Global Constants
</MyText>
</button>
</div>
{mode === 'bounds' ? renderRegional() : renderGlobal()}
</div>
</AppContainer>
)
}