397 lines
15 KiB
TypeScript
397 lines
15 KiB
TypeScript
import React, { useState } from 'react';
|
|
import type { SlotSnippetInput } from '@packages/shared'
|
|
import { View, Text, TouchableOpacity, Alert, Keyboard } from 'react-native';
|
|
import { Formik, FieldArray } from 'formik';
|
|
import DateTimePickerMod from 'common-ui/src/components/date-time-picker';
|
|
import { tw, MyTextInput, BottomDialog } from 'common-ui';
|
|
import { trpc } from '../src/trpc-client';
|
|
import ProductsSelector from '../components/ProductsSelector';
|
|
|
|
// Snippet form row — single source in @packages/shared (complete payload)
|
|
type VendorSnippet = SlotSnippetInput
|
|
|
|
// __DEV__ test hook: parse a YYYY-MM-DD + HH:MM wall-clock as IST (UTC+5:30).
|
|
// Returns null for bad shapes, out-of-range fields, or impossible dates.
|
|
const IST_OFFSET_MS = (5 * 60 + 30) * 60 * 1000
|
|
|
|
function parseIstDateTime(dateStr: string, timeStr: string): Date | null {
|
|
const dateMatch = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dateStr.trim())
|
|
const timeMatch = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(timeStr.trim())
|
|
if (!dateMatch || !timeMatch) return null
|
|
const year = Number(dateMatch[1])
|
|
const month = Number(dateMatch[2])
|
|
const day = Number(dateMatch[3])
|
|
const hour = Number(timeMatch[1])
|
|
const minute = Number(timeMatch[2])
|
|
const utcMs = Date.UTC(year, month - 1, day, hour, minute) - IST_OFFSET_MS
|
|
// Round-trip through the offset: impossible dates (e.g. Feb 30) shift.
|
|
const check = new Date(utcMs + IST_OFFSET_MS)
|
|
if (
|
|
check.getUTCFullYear() !== year ||
|
|
check.getUTCMonth() !== month - 1 ||
|
|
check.getUTCDate() !== day ||
|
|
check.getUTCHours() !== hour ||
|
|
check.getUTCMinutes() !== minute
|
|
) {
|
|
return null
|
|
}
|
|
return new Date(utcMs)
|
|
}
|
|
|
|
interface SlotFormProps {
|
|
onSlotAdded?: () => void;
|
|
initialDeliveryTime?: Date | null;
|
|
initialFreezeTime?: Date | null;
|
|
initialIsActive?: boolean;
|
|
slotId?: number;
|
|
initialProductIds?: number[];
|
|
initialGroupIds?: number[];
|
|
}
|
|
|
|
export default function SlotForm({
|
|
onSlotAdded,
|
|
initialDeliveryTime,
|
|
initialFreezeTime,
|
|
initialIsActive = true,
|
|
slotId,
|
|
initialProductIds = [],
|
|
initialGroupIds = [],
|
|
}: SlotFormProps) {
|
|
const { data: slotData } = trpc.admin.slots.getSlotById.useQuery(
|
|
{ id: slotId! },
|
|
{ enabled: !!slotId }
|
|
);
|
|
|
|
const vendorSnippetsFromSlot = (slotData?.slot?.vendorSnippets || []).map((snippet: any) => ({
|
|
name: snippet.name || '',
|
|
groupIds: snippet.groupIds || [],
|
|
skuIds: snippet.skuIds || [],
|
|
validTill: snippet.validTill || null,
|
|
})) as VendorSnippet[];
|
|
|
|
const initialValues = {
|
|
deliveryTime: initialDeliveryTime || (slotData?.slot?.deliveryTime ? new Date(slotData.slot.deliveryTime) : null),
|
|
freezeTime: initialFreezeTime || (slotData?.slot?.freezeTime ? new Date(slotData.slot.freezeTime) : null),
|
|
selectedGroupIds: initialGroupIds.length > 0 ? initialGroupIds : (slotData?.slot?.groupIds || []),
|
|
selectedSkuIds: initialProductIds.length > 0 ? initialProductIds : (slotData?.slot?.products?.map((p: any) => p.id) || []),
|
|
vendorSnippetList: vendorSnippetsFromSlot,
|
|
};
|
|
|
|
const { mutate: createSlot, isPending: isCreating } = trpc.admin.slots.createSlot.useMutation();
|
|
const { mutate: updateSlot, isPending: isUpdating } = trpc.admin.slots.updateSlot.useMutation();
|
|
const utils = trpc.useUtils();
|
|
|
|
const isEditMode = !!slotId;
|
|
const isPending = isCreating || isUpdating;
|
|
|
|
const { data: groupsData } = trpc.admin.product.getGroups.useQuery();
|
|
|
|
// __DEV__-only hidden datetime entry (avoids the native date/time scrollers
|
|
// in tests). Fields stay blank on every open — no prefill.
|
|
const [devDialogOpen, setDevDialogOpen] = useState(false)
|
|
const [devDeliveryDate, setDevDeliveryDate] = useState('')
|
|
const [devDeliveryTime, setDevDeliveryTime] = useState('')
|
|
const [devFreezeDate, setDevFreezeDate] = useState('')
|
|
const [devFreezeTime, setDevFreezeTime] = useState('')
|
|
const [devError, setDevError] = useState<string | null>(null)
|
|
|
|
const openDevDialog = () => {
|
|
setDevDeliveryDate('')
|
|
setDevDeliveryTime('')
|
|
setDevFreezeDate('')
|
|
setDevFreezeTime('')
|
|
setDevError(null)
|
|
setDevDialogOpen(true)
|
|
}
|
|
|
|
const handleFormSubmit = (values: typeof initialValues) => {
|
|
if (!values.deliveryTime || !values.freezeTime) {
|
|
Alert.alert('Error', 'Please fill all fields');
|
|
return;
|
|
}
|
|
|
|
if (values.freezeTime > values.deliveryTime) {
|
|
Alert.alert('Error', 'Freeze time must be before or equal to delivery time');
|
|
return;
|
|
}
|
|
|
|
const slotInputData = {
|
|
deliveryTime: values.deliveryTime.toISOString(),
|
|
freezeTime: values.freezeTime.toISOString(),
|
|
isActive: initialIsActive,
|
|
groupIds: values.selectedGroupIds,
|
|
skuIds: values.selectedSkuIds,
|
|
vendorSnippets: values.vendorSnippetList.map((snippet: VendorSnippet) => ({
|
|
name: snippet.name,
|
|
skuIds: snippet.skuIds,
|
|
validTill: snippet.validTill ?? undefined,
|
|
})),
|
|
};
|
|
|
|
if (isEditMode && slotId) {
|
|
updateSlot(
|
|
{ id: slotId, ...slotInputData },
|
|
{
|
|
onSuccess: () => {
|
|
Alert.alert('Success', 'Slot updated successfully!');
|
|
// Nothing else refreshes the slot list/detail the admin came from.
|
|
utils.admin.slots.invalidate();
|
|
onSlotAdded?.();
|
|
},
|
|
onError: (error: any) => {
|
|
console.log({msg: JSON.stringify(error.message)})
|
|
|
|
Alert.alert('Error', error.message || 'Failed to update slot');
|
|
},
|
|
}
|
|
);
|
|
} else {
|
|
createSlot(
|
|
slotInputData,
|
|
{
|
|
onSuccess: () => {
|
|
Alert.alert('Success', 'Slot created successfully!');
|
|
onSlotAdded?.();
|
|
},
|
|
onError: (error: any) => {
|
|
Alert.alert('Error', error.message || 'Failed to create slot');
|
|
},
|
|
}
|
|
);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<Formik
|
|
initialValues={initialValues}
|
|
onSubmit={handleFormSubmit}
|
|
>
|
|
{({ handleSubmit, values, setFieldValue }) => {
|
|
const mappedGroups = (groupsData?.groups || []).map(group => ({
|
|
...group,
|
|
products: group.products.map(product => ({
|
|
...product,
|
|
id: product.id,
|
|
})),
|
|
}));
|
|
|
|
return (
|
|
<View style={tw`mb-4`}>
|
|
<Text style={tw`text-xl font-bold mb-6 text-center`}>
|
|
{isEditMode ? 'Edit Slot' : 'Create New Slot'}
|
|
</Text>
|
|
|
|
<View style={tw`mb-4`}>
|
|
<Text style={tw`text-lg font-semibold mb-2`}>Delivery Date & Time</Text>
|
|
<DateTimePickerMod
|
|
dateTestID="delivery-date-picker"
|
|
timeTestID="delivery-time-picker"
|
|
value={values.deliveryTime}
|
|
setValue={(value) => setFieldValue('deliveryTime', value)}
|
|
/>
|
|
</View>
|
|
|
|
<View style={tw`mb-4`}>
|
|
<Text style={tw`text-lg font-semibold mb-2`}>Freeze Date & Time</Text>
|
|
<DateTimePickerMod
|
|
dateTestID="freeze-date-picker"
|
|
timeTestID="freeze-time-picker"
|
|
value={values.freezeTime}
|
|
setValue={(value) => setFieldValue('freezeTime', value)}
|
|
/>
|
|
</View>
|
|
|
|
<View style={tw`mb-4`}>
|
|
<ProductsSelector
|
|
value={values.selectedSkuIds}
|
|
onChange={(newSkuIds) => setFieldValue('selectedSkuIds', newSkuIds)}
|
|
groups={mappedGroups}
|
|
selectedGroupIds={values.selectedGroupIds}
|
|
onGroupChange={(newGroupIds) => setFieldValue('selectedGroupIds', newGroupIds)}
|
|
label="Select Products"
|
|
testID="slot-products-selector"
|
|
placeholder="Select products for this slot"
|
|
/>
|
|
</View>
|
|
|
|
{/* Vendor Snippets */}
|
|
<FieldArray name="vendorSnippetList">
|
|
{({ push, remove }) => (
|
|
<View style={tw`mb-4`}>
|
|
<Text style={tw`text-lg font-semibold mb-4`}>Vendor Snippets</Text>
|
|
{values.vendorSnippetList.map((snippet: VendorSnippet, index: number) => (
|
|
<View key={index} style={tw`bg-gray-50 p-4 rounded-lg mb-4`}>
|
|
<View style={tw`mb-4`}>
|
|
<MyTextInput
|
|
topLabel="Snippet Name *"
|
|
placeholder="Enter snippet name"
|
|
value={snippet.name}
|
|
onChangeText={(text) => setFieldValue(`vendorSnippetList.${index}.name`, text)}
|
|
/>
|
|
</View>
|
|
|
|
<View style={tw`mb-4`}>
|
|
<ProductsSelector
|
|
value={snippet.skuIds || []}
|
|
onChange={(newSkuIds) => setFieldValue(`vendorSnippetList.${index}.skuIds`, newSkuIds)}
|
|
groups={mappedGroups.filter(group =>
|
|
values.selectedGroupIds.includes(group.id)
|
|
).map(group => ({
|
|
...group,
|
|
products: group.products.filter((p: any) => values.selectedSkuIds.includes(p.id))
|
|
}))}
|
|
selectedGroupIds={snippet.groupIds || []}
|
|
onGroupChange={(newGroupIds) => setFieldValue(`vendorSnippetList.${index}.groupIds`, newGroupIds)}
|
|
label="Select Products"
|
|
testID="snippet-products-selector"
|
|
placeholder="Select products for snippet"
|
|
isDisabled={(sku) => !values.selectedSkuIds.includes(sku.id)}
|
|
/>
|
|
</View>
|
|
<TouchableOpacity
|
|
onPress={() => remove(index)}
|
|
style={tw`bg-red-500 px-4 py-2 rounded-lg self-end`}
|
|
>
|
|
<Text style={tw`text-white font-medium`}>Remove Snippet</Text>
|
|
</TouchableOpacity>
|
|
</View>
|
|
))}
|
|
<TouchableOpacity
|
|
onPress={() => push({ name: '', groupIds: [], skuIds: [], validTill: '' })}
|
|
style={tw`bg-blue-500 px-4 py-3 rounded-lg items-center`}
|
|
>
|
|
<Text style={tw`text-white font-medium`}>Add Vendor Snippet</Text>
|
|
</TouchableOpacity>
|
|
</View>
|
|
)}
|
|
</FieldArray>
|
|
|
|
<TouchableOpacity
|
|
testID="create-slot-button"
|
|
accessibilityLabel="create-slot-button"
|
|
onPress={() => handleSubmit()}
|
|
disabled={isPending}
|
|
style={tw`${isPending ? 'bg-pink2' : 'bg-pink1'} p-3 rounded-lg items-center mt-6 pb-4`}
|
|
>
|
|
<Text style={tw`text-white text-base font-bold`}>
|
|
{isPending ? (isEditMode ? 'Updating...' : 'Creating...') : (isEditMode ? 'Update Slot' : 'Create Slot')}
|
|
</Text>
|
|
</TouchableOpacity>
|
|
|
|
{__DEV__ && (
|
|
<TouchableOpacity
|
|
testID="test-set-current-datetime"
|
|
accessibilityRole="button"
|
|
accessibilityLabel="test-set-current-datetime"
|
|
accessible={true}
|
|
onPress={openDevDialog}
|
|
// 1x1 transparent pixel instead of left:-1000: iOS drops
|
|
// off-screen views from the accessibility tree, so Maestro could
|
|
// never find the button by testID. No opacity:0 — a 1x1 fully
|
|
// transparent pixel is invisible but stays in the tree.
|
|
style={{
|
|
position: 'absolute',
|
|
top: 0,
|
|
left: 0,
|
|
width: 1,
|
|
height: 1,
|
|
}}
|
|
/>
|
|
)}
|
|
|
|
{__DEV__ && (
|
|
<BottomDialog open={devDialogOpen} onClose={() => setDevDialogOpen(false)}>
|
|
<View style={tw`p-6`}>
|
|
<TouchableOpacity
|
|
testID="dev-datetime-header"
|
|
accessibilityRole="button"
|
|
activeOpacity={1}
|
|
onPress={() => Keyboard.dismiss()}
|
|
>
|
|
<Text style={tw`text-xl font-bold mb-1 text-center`}>Set Slot Datetimes</Text>
|
|
<Text style={tw`text-gray-500 text-center mb-4 text-sm`}>
|
|
Dates as YYYY-MM-DD, times as HH:MM (24h). Interpreted as IST.
|
|
</Text>
|
|
</TouchableOpacity>
|
|
|
|
<View style={tw`mb-4`}>
|
|
<MyTextInput
|
|
testID="dev-delivery-date"
|
|
topLabel="Delivery Date (YYYY-MM-DD)"
|
|
placeholder="YYYY-MM-DD"
|
|
value={devDeliveryDate}
|
|
onChangeText={setDevDeliveryDate}
|
|
/>
|
|
</View>
|
|
<View style={tw`mb-4`}>
|
|
<MyTextInput
|
|
testID="dev-delivery-time"
|
|
topLabel="Delivery Time (HH:MM)"
|
|
placeholder="HH:MM"
|
|
value={devDeliveryTime}
|
|
onChangeText={setDevDeliveryTime}
|
|
/>
|
|
</View>
|
|
<View style={tw`mb-4`}>
|
|
<MyTextInput
|
|
testID="dev-freeze-date"
|
|
topLabel="Freeze Date (YYYY-MM-DD)"
|
|
placeholder="YYYY-MM-DD"
|
|
value={devFreezeDate}
|
|
onChangeText={setDevFreezeDate}
|
|
/>
|
|
</View>
|
|
<View style={tw`mb-4`}>
|
|
<MyTextInput
|
|
testID="dev-freeze-time"
|
|
topLabel="Freeze Time (HH:MM)"
|
|
placeholder="HH:MM"
|
|
value={devFreezeTime}
|
|
onChangeText={setDevFreezeTime}
|
|
/>
|
|
</View>
|
|
|
|
{devError && (
|
|
<Text testID="dev-datetime-error" style={tw`text-red-500 mb-4 text-sm`}>
|
|
{devError}
|
|
</Text>
|
|
)}
|
|
|
|
<View style={tw`flex-row gap-3`}>
|
|
<TouchableOpacity
|
|
testID="dev-cancel-datetime"
|
|
style={tw`flex-1 bg-gray-100 py-3.5 rounded-xl items-center`}
|
|
onPress={() => setDevDialogOpen(false)}
|
|
>
|
|
<Text style={tw`text-gray-700 font-bold`}>Cancel</Text>
|
|
</TouchableOpacity>
|
|
<TouchableOpacity
|
|
testID="dev-apply-datetime"
|
|
style={tw`flex-1 bg-pink1 py-3.5 rounded-xl items-center`}
|
|
onPress={() => {
|
|
const delivery = parseIstDateTime(devDeliveryDate, devDeliveryTime)
|
|
const freeze = parseIstDateTime(devFreezeDate, devFreezeTime)
|
|
if (!delivery || !freeze) {
|
|
setDevError('Use YYYY-MM-DD and HH:MM (24h, IST) for both.')
|
|
return
|
|
}
|
|
if (freeze.getTime() > delivery.getTime()) {
|
|
setDevError('Freeze time must be before or equal to delivery time.')
|
|
return
|
|
}
|
|
setFieldValue('deliveryTime', delivery)
|
|
setFieldValue('freezeTime', freeze)
|
|
setDevDialogOpen(false)
|
|
}}
|
|
>
|
|
<Text style={tw`text-white font-bold`}>Apply</Text>
|
|
</TouchableOpacity>
|
|
</View>
|
|
</View>
|
|
</BottomDialog>
|
|
)}
|
|
</View>
|
|
)}}
|
|
</Formik>
|
|
);
|
|
}
|