freshyo/apps/superadmin-ui/src/routes/constants.tsx
2026-10-01 13:22:34 +05:30

276 lines
8.5 KiB
TypeScript

import { createFileRoute } from '@tanstack/react-router'
import React from 'react'
import { Formik } from 'formik'
import { AppContainer, Checkbox, MyButton, p as MyText, pInput as PInput } from 'web-components'
import { ChevronRight, ListOrdered, Pencil } from 'lucide-react'
import { trpc } from '../lib/trpc-client'
import { ProtectedRoute } from '../components/ProtectedRoute'
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',
}
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,
internalAppVersion: true,
tester: false,
}
interface ConstantInputProps {
constantKey: string
value: any
setFieldValue: (field: string, value: any) => void
}
const ConstantInput: React.FC<ConstantInputProps> = ({ constantKey, value, setFieldValue }) => {
const fieldName = constantKey
if (constantKey === 'popularItems') {
return (
<div>
<MyText className="mb-2 block text-sm font-medium text-gray-700">
{CONST_LABELS[constantKey] || constantKey}
</MyText>
<button
type="button"
disabled
className="flex w-full cursor-not-allowed items-center justify-center rounded-lg border-2 border-dashed border-blue-200 bg-blue-50 p-4 opacity-70"
>
<Pencil className="mr-2 h-5 w-5 text-blue-500" />
<span className="font-medium text-blue-700">
Manage Popular Items ({Array.isArray(value) ? value.length : 0} items)
</span>
<ChevronRight className="ml-2 h-5 w-5 text-blue-500" />
</button>
</div>
)
}
if (constantKey === 'allItemsOrder') {
return (
<div>
<MyText className="mb-2 block text-sm font-medium text-gray-700">
{CONST_LABELS[constantKey] || constantKey}
</MyText>
<button
type="button"
disabled
className="flex w-full cursor-not-allowed items-center justify-center rounded-lg border-2 border-dashed border-green-200 bg-green-50 p-4 opacity-70"
>
<ListOrdered className="mr-2 h-5 w-5 text-green-600" />
<span className="font-medium text-green-700">
Manage All Visible Items ({Array.isArray(value) ? value.length : 0} items)
</span>
<ChevronRight className="ml-2 h-5 w-5 text-green-600" />
</button>
</div>
)
}
if (typeof value === 'boolean') {
return (
<div>
<MyText className="mb-2 block text-sm font-medium text-gray-700">
{CONST_LABELS[constantKey] || constantKey}
</MyText>
<div className="flex items-center">
<Checkbox
checked={value}
onPress={() => setFieldValue(fieldName, !value)}
size={28}
/>
<span className="ml-3 text-gray-700">{value ? 'Enabled' : 'Disabled'}</span>
</div>
</div>
)
}
if (typeof value === 'number') {
return (
<PInput
topLabel={CONST_LABELS[constantKey] || constantKey}
value={value.toString()}
inputMode="decimal"
onChange={(e) => {
const numValue = parseFloat(e.target.value)
setFieldValue(fieldName, isNaN(numValue) ? 0 : numValue)
}}
placeholder="Enter number"
/>
)
}
if (Array.isArray(value)) {
return (
<PInput
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"
/>
)
}
return (
<PInput
topLabel={CONST_LABELS[constantKey] || constantKey}
value={value === null || value === undefined ? '' : String(value)}
onChange={(e) => setFieldValue(fieldName, e.target.value)}
placeholder="Enter value"
/>
)
}
function CustomizeApp() {
const { data: constants, isLoading: isLoadingConstants, refetch } = trpc.admin.const.getConstants.useQuery()
const { mutate: updateConstants, isPending: isUpdating } = trpc.admin.const.updateConstants.useMutation()
const handleSubmit = (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 Changes\n\nNo constants were modified.')
return
}
updateConstants(
{ constants: changedConstants },
{
onSuccess: (response) => {
window.alert(`Success\n\nUpdated ${response.updatedCount} constants successfully.`)
refetch()
},
onError: (error) => {
window.alert('Error\n\nFailed to update constants. Please try again.')
console.error('Update constants error:', error)
},
}
)
}
if (isLoadingConstants) {
return (
<div className="flex flex-1 items-center justify-center p-8">
<MyText className="text-gray-500">Loading constants...</MyText>
</div>
)
}
if (!constants) {
return (
<div className="flex flex-1 items-center justify-center p-8">
<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 (
<AppContainer>
<div className="bg-gray-50 p-4">
<MyText className="mb-4 block text-xl font-bold text-gray-900">
Customize App Constants
</MyText>
<MyText className="mb-6 block text-gray-600">
Modify application constants. Changes will take effect immediately.
</MyText>
<Formik initialValues={initialValues} onSubmit={handleSubmit}>
{({ handleSubmit, values, setFieldValue }) => (
<form onSubmit={handleSubmit}>
{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}
/>
</div>
)
})}
<MyButton
type="submit"
disabled={isUpdating}
fullWidth
className={`mt-6 rounded-lg bg-blue-500 p-4 text-base text-white ${isUpdating ? 'opacity-50' : ''}`}
>
{isUpdating ? 'Updating...' : 'Save Changes'}
</MyButton>
</form>
)}
</Formik>
</div>
</AppContainer>
)
}
export const Route = createFileRoute('/constants')({
component: () => (
<ProtectedRoute>
<CustomizeApp />
</ProtectedRoute>
),
})