added potential mining

This commit is contained in:
suryacp23 2026-07-14 16:50:09 +05:30
parent aced981fae
commit ef707baeec
5 changed files with 89 additions and 18 deletions

View File

@ -47,8 +47,8 @@ export class ZinoClient {
return this.token; return this.token;
} }
private async request<T>(method: string, path: string, body?: unknown): Promise<T> { async request<T>(method: string, path: string, body?: unknown, customHeaders?: Record<string, string>): Promise<T> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' }; const headers: Record<string, string> = { 'Content-Type': 'application/json', ...customHeaders };
if (this.token) headers['Authorization'] = `Bearer ${this.token}`; if (this.token) headers['Authorization'] = `Bearer ${this.token}`;
return this.send<T>(method, path, { return this.send<T>(method, path, {

View File

@ -2,33 +2,33 @@ import { formatValue } from '../../lib/format';
export function CallCard({ row }: { row: Record<string, any> }) { export function CallCard({ row }: { row: Record<string, any> }) {
const instanceId = row.instance_id || '—'; const instanceId = row.instance_id || '—';
// Status // Status
const stateName = String(row.status || row.current_state_name || 'Pending'); const stateName = String(row.status || row.current_state_name || 'Pending');
const isProductive = stateName.toLowerCase().includes('productive') || stateName.toLowerCase().includes('completed') || stateName.toLowerCase().includes('success'); const isProductive = stateName.toLowerCase().includes('productive') || stateName.toLowerCase().includes('completed') || stateName.toLowerCase().includes('success');
// Store Details // Store Details
const storeName = formatValue(row.store || row.store_name || row.customer_name || 'Unknown Store'); const storeName = formatValue(row.store || row.store_name || row.customer_name || 'Unknown Store');
const storeCode = formatValue(row.store_code || '—'); const storeCode = formatValue(row.store_code || '—');
// Grid Details // Grid Details
const totalWeight = formatValue(row.total_kgs || row.total_weight || row.weight || 0); const totalWeight = formatValue(row.total_kgs || row.total_weight || row.weight || 0);
const totalQuantity = formatValue(row.total_bags || row.total_quantity || row.quantity || 0); const totalQuantity = formatValue(row.total_bags || row.total_quantity || row.quantity || 0);
const totalOrders = formatValue(row.order_count || row.total_orders || 0); const totalOrders = formatValue(row.order_count || row.total_orders || 0);
// Route & Assignment // Route & Assignment
const routeName = formatValue(row.route_name || row.route || '—'); const routeName = formatValue(row.route_name || row.route || '—');
const areaName = formatValue(row.area || row.area_name || '—'); const areaName = formatValue(row.area || row.area_name || '—');
// User // User
const userName = formatValue(row.sales_officer || row.user_name || '—'); const userName = formatValue(row.sales_officer || row.user_name || '—');
const userEmail = formatValue(row.performed_by_email || row.user_email || '—'); const userEmail = formatValue(row.performed_by_email || row.user_email || '—');
const initials = userName !== '—' ? String(userName).substring(0, 2).toUpperCase() : 'SO'; const initials = userName !== '—' ? String(userName).substring(0, 2).toUpperCase() : 'SO';
// Date & Time // Date & Time
let dateStr = '—'; let dateStr = '—';
let timeStr = '—'; let timeStr = '—';
if (row.visit_date) { if (row.visit_date) {
try { try {
const d = new Date(row.visit_date as string); const d = new Date(row.visit_date as string);
@ -65,9 +65,6 @@ export function CallCard({ row }: { row: Record<string, any> }) {
<span className={`w-2.5 h-2.5 rounded-full ${statusDot}`}></span> <span className={`w-2.5 h-2.5 rounded-full ${statusDot}`}></span>
<span className={`text-[13px] font-bold ${statusText} tracking-wide uppercase`}>{stateName}</span> <span className={`text-[13px] font-bold ${statusText} tracking-wide uppercase`}>{stateName}</span>
</div> </div>
<span className="text-[11px] font-mono bg-white border border-slate-200 text-slate-600 px-2.5 py-1 rounded-md font-medium shadow-sm">
ID: {instanceId}
</span>
</div> </div>
{/* Main Content */} {/* Main Content */}

View File

@ -26,9 +26,10 @@ export interface DynamicFormProps {
onSuccess?: () => void; onSuccess?: () => void;
onCancel?: () => void; onCancel?: () => void;
ignorePrefill?: boolean; ignorePrefill?: boolean;
customPrefillData?: Record<string, unknown>;
} }
export function DynamicForm({ client, activityId: initialActivityId, instanceId: initialInstanceId, onSuccess, onCancel, ignorePrefill }: DynamicFormProps) { export function DynamicForm({ client, activityId: initialActivityId, instanceId: initialInstanceId, onSuccess, onCancel, ignorePrefill, customPrefillData }: DynamicFormProps) {
const [currentActivityId, setCurrentActivityId] = useState(initialActivityId); const [currentActivityId, setCurrentActivityId] = useState(initialActivityId);
const [currentInstanceId, setCurrentInstanceId] = useState<number | string | undefined>(initialInstanceId); const [currentInstanceId, setCurrentInstanceId] = useState<number | string | undefined>(initialInstanceId);
const [chainQueue, setChainQueue] = useState<Array<{ activity_uid: string; activity_name: string }>>([]); const [chainQueue, setChainQueue] = useState<Array<{ activity_uid: string; activity_name: string }>>([]);
@ -84,6 +85,12 @@ export function DynamicForm({ client, activityId: initialActivityId, instanceId:
}); });
} }
} }
if (customPrefillData) {
Object.entries(customPrefillData).forEach(([k, v]) => {
if (!imageFieldIds.has(k)) defaultValues[k] = v;
});
}
setValues(defaultValues); setValues(defaultValues);
setLoading(false); setLoading(false);

View File

@ -23,7 +23,8 @@ export function SmartGridField({
const visibleColumns = columns.filter(c => { const visibleColumns = columns.filter(c => {
const normalized = c.id.toLowerCase().replace(/[^a-z]/g, ''); const normalized = c.id.toLowerCase().replace(/[^a-z]/g, '');
return ['productcategory', 'productname', 'bags'].includes(normalized); // Use a blacklist so we don't accidentally hide important columns from other grids
return !['sku', 'rowkgs', 'brcode'].includes(normalized);
}); });
const removeRow = (idx: number) => { const removeRow = (idx: number) => {
@ -118,11 +119,27 @@ export function SmartGridField({
<td key={col.id} className="p-3 text-sm text-strong whitespace-nowrap"> <td key={col.id} className="p-3 text-sm text-strong whitespace-nowrap">
{(() => { {(() => {
const val = row[col.id]; const val = row[col.id];
let displayVal = String(val ?? '-');
if (col.data_type === 'select' || col.data_type === 'multiselect') { if (col.data_type === 'select' || col.data_type === 'multiselect') {
const opt = col.properties?.options?.find(o => String(o.value) === String(val)); const opt = col.properties?.options?.find(o => String(o.value) === String(val));
return opt ? opt.label : String(val ?? '-'); if (opt) displayVal = opt.label;
} }
return String(val ?? '-');
if ((col.id.toLowerCase().includes('difference') || col.name?.toLowerCase().includes('difference')) && val != null && val !== '') {
const numVal = Number(val);
if (!isNaN(numVal)) {
if (numVal < 0) {
displayVal = `${Math.abs(numVal)} kgs less`;
} else if (numVal > 0) {
displayVal = `${numVal} kgs more`;
} else {
displayVal = `0 kgs`;
}
}
}
return displayVal;
})()} })()}
</td> </td>
))} ))}

View File

@ -17,12 +17,61 @@ export function CallsPage() {
const [refreshKey, setRefreshKey] = useState(0); const [refreshKey, setRefreshKey] = useState(0);
const [activeActivity, setActiveActivity] = useState<{ id: string; name: string } | null>(null); const [activeActivity, setActiveActivity] = useState<{ id: string; name: string } | null>(null);
const [isFabOpen, setIsFabOpen] = useState(false); 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 ( return (
<> <>
<CallsView <CallsView
refreshKey={refreshKey} refreshKey={refreshKey}
onRowClick={(row) => { onRowClick={(row) => {
setSelectedRow(row);
const id = row.instance_id as number | string | undefined; const id = row.instance_id as number | string | undefined;
if (id != null) navigate(`/calls/${id}`); if (id != null) navigate(`/calls/${id}`);
}} }}
@ -62,8 +111,8 @@ export function CallsPage() {
<div className="absolute bottom-6 right-6 flex flex-col items-end gap-3 z-50"> <div className="absolute bottom-6 right-6 flex flex-col items-end gap-3 z-50">
{isFabOpen && ( {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"> <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={() => { setActiveActivity({ id: ORDER_BOOKING.activities.POTENTIAL_MINING.uid, name: 'Potential Mining' }); setIsFabOpen(false); }}> <Button size="sm" variant="secondary" onClick={handlePotentialMiningClick} disabled={miningLoading}>
Potential Mining {miningLoading ? 'Loading...' : 'Potential Mining'}
</Button> </Button>
<Button size="sm" onClick={() => { setActiveActivity({ id: ORDER_BOOKING.activities.PLACE_ORDER.uid, name: 'Place Order' }); setIsFabOpen(false); }}> <Button size="sm" onClick={() => { setActiveActivity({ id: ORDER_BOOKING.activities.PLACE_ORDER.uid, name: 'Place Order' }); setIsFabOpen(false); }}>
Place Order Place Order
@ -93,6 +142,7 @@ export function CallsPage() {
activityId={activeActivity.id} activityId={activeActivity.id}
instanceId={instanceId} instanceId={instanceId}
ignorePrefill={activeActivity.id === ORDER_BOOKING.activities.PLACE_ORDER.uid} ignorePrefill={activeActivity.id === ORDER_BOOKING.activities.PLACE_ORDER.uid}
customPrefillData={activeActivity.id === ORDER_BOOKING.activities.POTENTIAL_MINING.uid ? miningPrefill : undefined}
onSuccess={() => { onSuccess={() => {
setActiveActivity(null); setActiveActivity(null);
setRefreshKey(k => k + 1); setRefreshKey(k => k + 1);