krishnasales_mobile/src/screens/CallsPage.tsx
2026-07-21 19:05:13 +05:30

198 lines
7.9 KiB
TypeScript

import { useNavigate, useParams } from 'react-router-dom';
import { Modal } from '../components/reusable';
import { CallsView } from '../components/rv';
import { CallDetail } from '../components/dv';
import { useState } from 'react';
import { Button } from '../components/buttons/Button';
import { Phone, Plus } from 'lucide-react';
import { DynamicForm } from '../components/forms/DynamicForm';
import { ORDER_BOOKING } from '../api/config';
import { orderBookingClient } from '../api/clients';
export function CallsPage() {
const params = useParams();
const instanceId = params.instanceId ? Number(params.instanceId) : undefined;
const navigate = useNavigate();
const [isCreating, setIsCreating] = useState(false);
const [createTitle, setCreateTitle] = useState("Log Visit");
const [refreshKey, setRefreshKey] = useState(0);
const [activeActivity, setActiveActivity] = useState<{ id: string; name: string } | null>(null);
const [isFabOpen, setIsFabOpen] = useState(false);
const [miningLoading, setMiningLoading] = useState(false);
const [miningPrefill, setMiningPrefill] = useState<Record<string, unknown> | undefined>();
const [selectedRow, setSelectedRow] = useState<Record<string, any> | null>(null);
const handlePotentialMiningClick = async () => {
setMiningLoading(true);
setMiningPrefill(undefined);
try {
const storeCode = selectedRow?.store_code || selectedRow?.code || selectedRow?.store?.store_code;
if (!storeCode) {
console.warn("Store code not found on selected row, proceeding anyway.");
}
const payload = {
store_code: storeCode,
instance_id: String(instanceId)
};
const response = await orderBookingClient.request<{ potential: { potential: any[] } }>(
'POST',
'/api/papi2/potential-mining',
payload,
{ 'TemplateID': '146' }
);
const rawPotential = response.potential?.potential || [];
const mappedPotential = rawPotential.map((row: any) => {
const cat = row.product_category || row.product_category_ || row.category;
return {
...row,
product_category_: cat,
product_category: cat,
productcategory: cat,
category: cat,
product_category_1: cat
};
});
setMiningPrefill({ potential: mappedPotential });
setActiveActivity({ id: ORDER_BOOKING.activities.POTENTIAL_MINING.uid, name: 'Potential Mining' });
} catch (e: any) {
alert("Failed to fetch potential mining data: " + (e.message || "Unknown error"));
} finally {
setMiningLoading(false);
setIsFabOpen(false);
}
};
return (
<>
<CallsView
refreshKey={refreshKey}
onRowClick={(row) => {
setSelectedRow(row);
const id = row.instance_id as number | string | undefined;
if (id != null) navigate(`/calls/${id}`);
}}
/>
{/* Global Floating Action Button for Add Call */}
<button
onClick={() => { setIsCreating(true); setCreateTitle("Log Visit"); }}
className="fixed bottom-24 right-6 w-[60px] h-[60px] bg-[var(--z-bg-primary-400)] rounded-3xl flex items-center justify-center shadow-[0_4px_12px_rgba(var(--z-bg-primary-400-rgb),0.4)] text-white z-40 hover:opacity-90 transition-transform hover:scale-105 active:scale-95"
>
<Phone size={20} className="text-white" />
</button>
<Modal
open={isCreating}
onClose={() => setIsCreating(false)}
title={createTitle}
width="md"
>
<DynamicForm
client={orderBookingClient}
activityId={ORDER_BOOKING.activities.LOG_VISIT.uid}
onSuccess={() => {
setIsCreating(false);
setRefreshKey(k => k + 1);
}}
onCancel={() => setIsCreating(false)}
onActivityChange={(name) => setCreateTitle(name)}
/>
</Modal>
<Modal
open={instanceId != null}
onClose={() => { navigate(`/calls`); setIsFabOpen(false); }}
title={instanceId != null ? `Call #${instanceId}` : undefined}
width="lg"
>
{instanceId != null && (
<>
<CallDetail instanceId={instanceId} onDataLoad={setSelectedRow} />
<div className="absolute bottom-6 right-6 flex flex-col items-end gap-3 z-50">
{isFabOpen && (
<div className="flex flex-col gap-2 bg-white p-3 rounded-sm shadow-xl border border-border-subtle animate-in fade-in slide-in-from-bottom-2">
<Button size="sm" variant="secondary" onClick={handlePotentialMiningClick} disabled={miningLoading}>
{miningLoading ? 'Loading...' : 'Potential Mining'}
</Button>
{(() => {
const stateName = String(selectedRow?.current_state_name || selectedRow?.current_state_name_ || selectedRow?.current_state || selectedRow?.status || '').toLowerCase();
if (stateName.includes('ordered') || stateName === 'ordered') {
return (
<Button size="sm" onClick={(e) => {
e.stopPropagation();
e.preventDefault();
setActiveActivity({ id: ORDER_BOOKING.activities.EDIT_ORDER.uid, name: 'Edit Order' });
setIsFabOpen(false);
}}>
Edit Order
</Button>
);
} else if (stateName.includes('productive')) {
return (
<Button size="sm" onClick={(e) => {
e.stopPropagation();
e.preventDefault();
setActiveActivity({ id: ORDER_BOOKING.activities.PLACE_ORDER.uid, name: 'Place Order' });
setIsFabOpen(false);
}}>
Place Order
</Button>
);
} else if (stateName.includes('no order') || stateName.includes('non-productive') || stateName.includes('non productive')) {
return null;
}
return (
<Button size="sm" onClick={(e) => {
e.stopPropagation();
e.preventDefault();
setActiveActivity({ id: ORDER_BOOKING.activities.PLACE_ORDER.uid, name: 'Place Order' });
setIsFabOpen(false);
}}>
Place Order
</Button>
);
})()}
</div>
)}
<Button size='fab'
className="rounded-full shadow-xl flex items-center justify-center !p-0"
onClick={() => setIsFabOpen(!isFabOpen)}
>
<Plus size={24} className={`transition-transform duration-200 ${isFabOpen ? "rotate-45" : ""}`} />
</Button>
</div>
</>
)}
</Modal>
<Modal
open={activeActivity != null}
onClose={() => setActiveActivity(null)}
title={activeActivity?.name}
width="md"
>
{activeActivity && (
<DynamicForm
client={orderBookingClient}
activityId={activeActivity.id}
instanceId={instanceId}
ignorePrefill={activeActivity.id === ORDER_BOOKING.activities.PLACE_ORDER.uid}
customPrefillData={activeActivity.id === ORDER_BOOKING.activities.POTENTIAL_MINING.uid ? miningPrefill : undefined}
onSuccess={() => {
setActiveActivity(null);
setRefreshKey(k => k + 1);
}}
onCancel={() => setActiveActivity(null)}
onActivityChange={(name) => setActiveActivity(prev => prev ? { ...prev, name } : null)}
/>
)}
</Modal>
</>
);
}