Fix Purchase Order modal and reorganize documentation

Frontend Changes:
- Fix runtime error: Remove undefined handleModify reference from ActionQueueCard in DashboardPage
- Migrate PurchaseOrderDetailsModal to use correct PurchaseOrderItem type from purchase_orders service
- Fix item display: Parse unit_price as string (Decimal) instead of number
- Use correct field names: item_notes instead of notes
- Remove deprecated PurchaseOrder types from suppliers.ts to prevent type conflicts
- Update CreatePurchaseOrderModal to use unified types
- Clean up API exports: Remove old PO hooks re-exported from suppliers
- Add comprehensive translations for PO modal (en, es, eu)

Documentation Reorganization:
- Move WhatsApp implementation docs to docs/03-features/notifications/whatsapp/
- Move forecast validation docs to docs/03-features/forecasting/
- Move specification docs to docs/03-features/specifications/
- Move deployment docs (Colima, K8s, VPS sizing) to docs/05-deployment/
- Archive completed implementation summaries to docs/archive/implementation-summaries/
- Delete obsolete FRONTEND_CHANGES_NEEDED.md
- Standardize filenames to lowercase with hyphens

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Urtzi Alfaro
2025-11-18 11:59:23 +01:00
parent 5c45164c8e
commit 3c3d3ce042
32 changed files with 654 additions and 874 deletions

View File

@@ -3,26 +3,25 @@
// ================================================================
/**
* Purchase Order Details Modal
* Quick view of PO details from the Action Queue
* Unified view/edit modal for PO details from the Action Queue
* Now using EditViewModal with proper API response structure
*/
import React from 'react';
import React, { useState, useMemo } from 'react';
import {
X,
Package,
Building2,
Calendar,
Truck,
Euro,
FileText,
CheckCircle,
Clock,
AlertCircle,
Edit,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { usePurchaseOrder } from '../../api/hooks/purchase-orders';
import { formatDistanceToNow } from 'date-fns';
import { es, enUS, eu as euLocale } from 'date-fns/locale';
import { usePurchaseOrder, useUpdatePurchaseOrder } from '../../api/hooks/purchase-orders';
import { useUserById } from '../../api/hooks/user';
import { EditViewModal, EditViewModalSection } from '../ui/EditViewModal/EditViewModal';
import type { PurchaseOrderItem } from '../../api/services/purchase_orders';
interface PurchaseOrderDetailsModalProps {
poId: string;
@@ -30,380 +29,439 @@ interface PurchaseOrderDetailsModalProps {
isOpen: boolean;
onClose: () => void;
onApprove?: (poId: string) => void;
onModify?: (poId: string) => void;
initialMode?: 'view' | 'edit';
}
const localeMap = {
es: es,
en: enUS,
eu: euLocale,
};
export const PurchaseOrderDetailsModal: React.FC<PurchaseOrderDetailsModalProps> = ({
poId,
tenantId,
isOpen,
onClose,
onApprove,
onModify,
initialMode = 'view',
}) => {
const { t, i18n } = useTranslation();
const { data: po, isLoading } = usePurchaseOrder(tenantId, poId);
const { t, i18n } = useTranslation(['purchase_orders', 'common']);
const { data: po, isLoading, refetch } = usePurchaseOrder(tenantId, poId);
const [mode, setMode] = useState<'view' | 'edit'>(initialMode);
const updatePurchaseOrderMutation = useUpdatePurchaseOrder();
if (!isOpen) return null;
// Component to display user name with data fetching
const UserName: React.FC<{ userId: string | undefined | null }> = ({ userId }) => {
if (!userId) return <>{t('common:not_available')}</>;
const dateLocale = localeMap[i18n.language as keyof typeof localeMap] || enUS;
if (userId === '00000000-0000-0000-0000-000000000001' || userId === '00000000-0000-0000-0000-000000000000') {
return <>{t('common:system')}</>;
}
// Format currency
const formatCurrency = (value: any) => {
const num = Number(value);
return isNaN(num) ? '0.00' : num.toFixed(2);
const { data: user, isLoading } = useUserById(userId, {
retry: 1,
staleTime: 10 * 60 * 1000,
});
if (isLoading) return <>{t('common:loading')}</>;
if (!user) return <>{t('common:unknown_user')}</>;
return <>{user.full_name || user.email || t('common:user')}</>;
};
const getStatusBadge = (status: string) => {
const statusConfig = {
draft: {
bg: 'var(--color-gray-100)',
text: 'var(--color-gray-700)',
label: t('purchase_orders:status.draft'),
},
pending_approval: {
bg: 'var(--color-warning-100)',
text: 'var(--color-warning-700)',
label: t('purchase_orders:status.pending_approval'),
},
approved: {
bg: 'var(--color-success-100)',
text: 'var(--color-success-700)',
label: t('purchase_orders:status.approved'),
},
sent: {
bg: 'var(--color-info-100)',
text: 'var(--color-info-700)',
label: t('purchase_orders:status.sent'),
},
partially_received: {
bg: 'var(--color-warning-100)',
text: 'var(--color-warning-700)',
label: t('purchase_orders:status.partially_received'),
},
received: {
bg: 'var(--color-success-100)',
text: 'var(--color-success-700)',
label: t('purchase_orders:status.received'),
},
cancelled: {
bg: 'var(--color-error-100)',
text: 'var(--color-error-700)',
label: t('purchase_orders:status.cancelled'),
},
};
// Component to display PO items
const PurchaseOrderItemsTable: React.FC<{ items: PurchaseOrderItem[] }> = ({ items }) => {
if (!items || items.length === 0) {
return (
<div className="text-center py-8 text-[var(--text-secondary)] border-2 border-dashed border-[var(--border-secondary)] rounded-lg">
<Package className="h-12 w-12 mx-auto mb-2 opacity-50" />
<p>{t('no_items')}</p>
</div>
);
}
const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.draft;
const totalAmount = items.reduce((sum, item) => {
const price = parseFloat(item.unit_price) || 0;
const quantity = item.ordered_quantity || 0;
return sum + (price * quantity);
}, 0);
return (
<span
className="px-3 py-1 rounded-full text-sm font-medium"
style={{ backgroundColor: config.bg, color: config.text }}
>
{config.label}
</span>
<div className="space-y-3">
{items.map((item: PurchaseOrderItem, index: number) => {
const unitPrice = parseFloat(item.unit_price) || 0;
const quantity = item.ordered_quantity || 0;
const itemTotal = unitPrice * quantity;
const productName = item.product_name || `${t('product')} ${index + 1}`;
return (
<div
key={item.id || index}
className="p-4 border border-[var(--border-secondary)] rounded-lg bg-[var(--bg-secondary)]/50 space-y-3"
>
<div className="flex justify-between items-start">
<div className="flex-1">
<h4 className="font-semibold text-[var(--text-primary)]">{productName}</h4>
{item.product_code && (
<p className="text-sm text-[var(--text-secondary)]">
{t('sku')}: {item.product_code}
</p>
)}
</div>
<div className="text-right">
<p className="font-bold text-lg text-[var(--color-primary-600)]">
{itemTotal.toFixed(2)}
</p>
</div>
</div>
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<p className="text-[var(--text-secondary)]">{t('quantity')}</p>
<p className="font-medium text-[var(--text-primary)]">
{quantity} {item.unit_of_measure}
</p>
</div>
<div>
<p className="text-[var(--text-secondary)]">{t('unit_price')}</p>
<p className="font-medium text-[var(--text-primary)]">{unitPrice.toFixed(2)}</p>
</div>
</div>
{item.quality_requirements && (
<div className="pt-2 border-t border-[var(--border-secondary)]">
<p className="text-xs text-[var(--text-secondary)]">{t('quality_requirements')}</p>
<p className="text-sm text-[var(--text-primary)]">{item.quality_requirements}</p>
</div>
)}
{item.item_notes && (
<div className="pt-2 border-t border-[var(--border-secondary)]">
<p className="text-xs text-[var(--text-secondary)]">{t('common:notes')}</p>
<p className="text-sm text-[var(--text-primary)]">{item.item_notes}</p>
</div>
)}
</div>
);
})}
<div className="flex justify-between items-center pt-4 border-t-2 border-[var(--border-primary)]">
<span className="font-semibold text-lg text-[var(--text-primary)]">{t('total')}</span>
<span className="font-bold text-2xl text-[var(--color-primary-600)]">{totalAmount.toFixed(2)}</span>
</div>
</div>
);
};
// Priority and unit options for edit mode
const priorityOptions = [
{ value: 'urgent', label: t('priority_urgent') },
{ value: 'high', label: t('priority_high') },
{ value: 'normal', label: t('priority_normal') },
{ value: 'low', label: t('priority_low') }
];
const unitOptions = [
{ value: 'kg', label: t('unit_kg') },
{ value: 'g', label: t('unit_g') },
{ value: 'l', label: t('unit_l') },
{ value: 'ml', label: t('unit_ml') },
{ value: 'units', label: t('unit_units') },
{ value: 'boxes', label: t('unit_boxes') },
{ value: 'bags', label: t('unit_bags') }
];
// Build sections for EditViewModal
const buildViewSections = (): EditViewModalSection[] => {
if (!po) return [];
const formatCurrency = (value: any) => {
const num = Number(value);
return isNaN(num) ? '0.00' : num.toFixed(2);
};
const sections: EditViewModalSection[] = [
{
title: t('general_information'),
icon: FileText,
fields: [
{
label: t('po_number'),
value: po.po_number,
type: 'text' as const
},
{
label: t('status_label'),
value: t(`status.${po.status}`),
type: 'status' as const
},
{
label: t('priority'),
value: t(`priority_${po.priority}` as any) || po.priority,
type: 'text' as const
},
{
label: t('created'),
value: new Date(po.created_at).toLocaleDateString(i18n.language, {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
}),
type: 'text' as const
}
]
},
{
title: t('supplier_info'),
icon: Building2,
fields: [
{
label: t('supplier_name'),
value: po.supplier?.name || t('common:unknown'),
type: 'text' as const
}
]
},
{
title: t('financial_summary'),
icon: Euro,
fields: [
{
label: t('total_amount'),
value: `${formatCurrency(po.total_amount)}`,
type: 'text' as const,
highlight: true
}
]
},
{
title: t('items'),
icon: Package,
fields: [
{
label: '',
value: <PurchaseOrderItemsTable items={po.items || []} />,
type: 'component' as const,
span: 2
}
]
},
{
title: t('dates'),
icon: Calendar,
fields: [
{
label: t('order_date'),
value: new Date(po.order_date).toLocaleDateString(i18n.language, {
year: 'numeric',
month: 'short',
day: 'numeric'
}),
type: 'text' as const
},
...(po.required_delivery_date ? [{
label: t('required_delivery_date'),
value: new Date(po.required_delivery_date).toLocaleDateString(i18n.language, {
year: 'numeric',
month: 'short',
day: 'numeric'
}),
type: 'text' as const
}] : []),
...(po.estimated_delivery_date ? [{
label: t('expected_delivery'),
value: new Date(po.estimated_delivery_date).toLocaleDateString(i18n.language, {
year: 'numeric',
month: 'short',
day: 'numeric'
}),
type: 'text' as const
}] : [])
]
}
];
// Add notes section if present
if (po.notes) {
sections.push({
title: t('notes'),
icon: FileText,
fields: [
{
label: t('order_notes'),
value: po.notes,
type: 'text' as const
}
]
});
}
return sections;
};
// Build sections for edit mode
const buildEditSections = (): EditViewModalSection[] => {
if (!po) return [];
return [
{
title: t('supplier_info'),
icon: Building2,
fields: [
{
label: t('supplier'),
value: po.supplier?.name || t('common:unknown'),
type: 'text' as const,
editable: false,
helpText: t('supplier_cannot_modify')
}
]
},
{
title: t('order_details'),
icon: Calendar,
fields: [
{
label: t('priority'),
value: po.priority,
type: 'select' as const,
editable: true,
options: priorityOptions,
helpText: t('adjust_priority')
},
{
label: t('required_delivery_date'),
value: po.required_delivery_date || '',
type: 'date' as const,
editable: true,
helpText: t('delivery_deadline')
},
{
label: t('notes'),
value: po.notes || '',
type: 'textarea' as const,
editable: true,
placeholder: t('special_instructions'),
span: 2,
helpText: t('additional_info')
}
]
},
{
title: t('products'),
icon: Package,
fields: [
{
label: t('products'),
value: (po.items || []).map((item: PurchaseOrderItem) => ({
id: item.id,
inventory_product_id: item.inventory_product_id,
product_code: item.product_code || '',
product_name: item.product_name || '',
ordered_quantity: item.ordered_quantity,
unit_of_measure: item.unit_of_measure,
unit_price: parseFloat(item.unit_price),
})),
type: 'list' as const,
editable: true,
span: 2,
helpText: t('modify_quantities')
}
]
}
];
};
// Save handler for edit mode
const handleSave = async (formData: Record<string, any>) => {
try {
const items = formData.items || [];
if (items.length === 0) {
throw new Error(t('at_least_one_product'));
}
// Validate quantities
const invalidQuantities = items.some((item: any) => item.ordered_quantity <= 0);
if (invalidQuantities) {
throw new Error(t('quantities_greater_zero'));
}
// Validate required fields
const invalidProducts = items.some((item: any) => !item.product_name);
if (invalidProducts) {
throw new Error(t('products_need_names'));
}
// Prepare the update data
const updateData: any = {
notes: formData.notes || undefined,
priority: formData.priority || undefined,
};
// Add delivery date if changed
if (formData.required_delivery_date) {
updateData.required_delivery_date = formData.required_delivery_date;
}
// Update purchase order
await updatePurchaseOrderMutation.mutateAsync({
tenantId,
poId,
data: updateData
});
// Refetch data and switch back to view mode
await refetch();
setMode('view');
} catch (error) {
console.error('Error modifying purchase order:', error);
throw error;
}
};
// Build actions for modal footer - only Approve button for pending approval POs
const buildActions = () => {
if (!po) return undefined;
// Only show Approve button in view mode for pending approval POs
if (mode === 'view' && po.status === 'pending_approval') {
return [
{
label: t('actions.approve'),
icon: CheckCircle,
onClick: () => {
onApprove?.(poId);
onClose();
},
variant: 'primary' as const
}
];
}
return undefined;
};
const sections = mode === 'view' ? buildViewSections() : buildEditSections();
return (
<div
className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4 animate-fadeIn"
onClick={onClose}
style={{
backdropFilter: 'blur(4px)',
animation: 'fadeIn 0.2s ease-out'
<EditViewModal
isOpen={isOpen}
onClose={() => {
setMode('view');
onClose();
}}
>
<div
className="bg-white rounded-xl shadow-2xl max-w-3xl w-full max-h-[90vh] overflow-hidden transform transition-all"
onClick={(e) => e.stopPropagation()}
style={{
backgroundColor: 'var(--bg-primary)',
animation: 'slideUp 0.3s ease-out'
}}
>
<style>{`
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px) scale(0.95);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
`}</style>
{/* Header */}
<div
className="flex items-center justify-between p-6 border-b bg-gradient-to-r from-transparent to-transparent"
style={{
borderColor: 'var(--border-primary)',
background: 'linear-gradient(to right, var(--bg-primary), var(--bg-secondary))'
}}
>
<div className="flex items-center gap-4">
<div
className="p-3 rounded-xl"
style={{
backgroundColor: 'var(--color-primary-100)',
boxShadow: '0 2px 8px rgba(0, 0, 0, 0.05)'
}}
>
<Package className="w-6 h-6" style={{ color: 'var(--color-primary-600)' }} />
</div>
<div>
<h2 className="text-2xl font-bold mb-1" style={{ color: 'var(--text-primary)' }}>
{isLoading ? t('common:loading') : po?.po_number || t('purchase_orders:purchase_order')}
</h2>
{po && (
<p className="text-sm flex items-center gap-1" style={{ color: 'var(--text-secondary)' }}>
<Clock className="w-3.5 h-3.5" />
{t('purchase_orders:created')} {formatDistanceToNow(new Date(po.created_at), { addSuffix: true, locale: dateLocale })}
</p>
)}
</div>
</div>
<button
onClick={onClose}
className="p-2 rounded-lg hover:bg-gray-100 transition-all hover:scale-110"
style={{ color: 'var(--text-secondary)' }}
aria-label={t('purchase_orders:actions.close')}
>
<X className="w-5 h-5" />
</button>
</div>
{/* Content */}
<div className="p-6 overflow-y-auto max-h-[calc(90vh-200px)]">
{isLoading ? (
<div className="flex items-center justify-center py-12">
<div className="animate-spin rounded-full h-10 w-10 border-3 border-primary-200 border-t-primary-600"></div>
</div>
) : po ? (
<div className="space-y-6">
{/* Status and Key Info */}
<div className="flex flex-wrap items-center gap-4 p-4 rounded-xl" style={{
backgroundColor: 'var(--bg-secondary)',
border: '1px solid var(--border-primary)'
}}>
{getStatusBadge(po.status)}
<div className="flex-1 min-w-[200px]">
<p className="text-xs uppercase tracking-wide mb-1" style={{ color: 'var(--text-secondary)' }}>
{t('purchase_orders:total_amount')}
</p>
<div className="flex items-baseline gap-2">
<Euro className="w-5 h-5" style={{ color: 'var(--color-primary-600)' }} />
<span className="text-2xl font-bold" style={{ color: 'var(--text-primary)' }}>
{formatCurrency(po.total_amount)}
</span>
</div>
</div>
</div>
{/* Supplier Info */}
<div className="rounded-xl p-5 border" style={{
backgroundColor: 'var(--bg-secondary)',
borderColor: 'var(--border-primary)',
boxShadow: '0 1px 3px rgba(0, 0, 0, 0.05)'
}}>
<div className="flex items-center gap-2 mb-3">
<div className="p-2 rounded-lg" style={{ backgroundColor: 'var(--color-primary-100)' }}>
<Building2 className="w-5 h-5" style={{ color: 'var(--color-primary-600)' }} />
</div>
<h3 className="font-semibold text-sm uppercase tracking-wide" style={{ color: 'var(--text-secondary)' }}>
{t('purchase_orders:supplier')}
</h3>
</div>
<p className="text-xl font-semibold ml-1" style={{ color: 'var(--text-primary)' }}>
{po.supplier_name || t('common:unknown')}
</p>
</div>
{/* Dates */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="rounded-xl p-4 border" style={{
backgroundColor: 'var(--bg-secondary)',
borderColor: 'var(--border-primary)',
boxShadow: '0 1px 3px rgba(0, 0, 0, 0.05)'
}}>
<div className="flex items-center gap-2 mb-3">
<div className="p-1.5 rounded-lg" style={{ backgroundColor: 'var(--color-primary-100)' }}>
<Calendar className="w-4 h-4" style={{ color: 'var(--color-primary-600)' }} />
</div>
<h3 className="font-semibold text-xs uppercase tracking-wide" style={{ color: 'var(--text-secondary)' }}>
{t('purchase_orders:order_date')}
</h3>
</div>
<p className="text-lg font-semibold ml-1" style={{ color: 'var(--text-primary)' }}>
{new Date(po.order_date).toLocaleDateString(i18n.language, {
year: 'numeric',
month: 'short',
day: 'numeric'
})}
</p>
</div>
{po.expected_delivery_date && (
<div className="rounded-xl p-4 border" style={{
backgroundColor: 'var(--bg-secondary)',
borderColor: 'var(--border-primary)',
boxShadow: '0 1px 3px rgba(0, 0, 0, 0.05)'
}}>
<div className="flex items-center gap-2 mb-3">
<div className="p-1.5 rounded-lg" style={{ backgroundColor: 'var(--color-success-100)' }}>
<Truck className="w-4 h-4" style={{ color: 'var(--color-success-600)' }} />
</div>
<h3 className="font-semibold text-xs uppercase tracking-wide" style={{ color: 'var(--text-secondary)' }}>
{t('purchase_orders:expected_delivery')}
</h3>
</div>
<p className="text-lg font-semibold ml-1" style={{ color: 'var(--text-primary)' }}>
{new Date(po.expected_delivery_date).toLocaleDateString(i18n.language, {
year: 'numeric',
month: 'short',
day: 'numeric'
})}
</p>
</div>
)}
</div>
{/* Items */}
<div>
<div className="flex items-center gap-2 mb-4">
<div className="p-2 rounded-lg" style={{ backgroundColor: 'var(--color-primary-100)' }}>
<FileText className="w-5 h-5" style={{ color: 'var(--color-primary-600)' }} />
</div>
<h3 className="font-bold text-lg" style={{ color: 'var(--text-primary)' }}>
{t('purchase_orders:items')}
</h3>
{po.items && po.items.length > 0 && (
<span
className="ml-auto px-3 py-1 rounded-full text-sm font-medium"
style={{
backgroundColor: 'var(--color-primary-100)',
color: 'var(--color-primary-700)'
}}
>
{po.items.length} {po.items.length === 1 ? t('common:item') : t('common:items')}
</span>
)}
</div>
<div className="space-y-3">
{po.items && po.items.length > 0 ? (
po.items.map((item: any, index: number) => (
<div
key={index}
className="flex justify-between items-center p-4 rounded-xl border transition-all hover:shadow-md"
style={{
backgroundColor: 'var(--bg-secondary)',
borderColor: 'var(--border-primary)'
}}
>
<div className="flex-1">
<p className="font-semibold text-base mb-1" style={{ color: 'var(--text-primary)' }}>
{item.ingredient_name || item.product_name}
</p>
<p className="text-sm flex items-center gap-1.5" style={{ color: 'var(--text-secondary)' }}>
<span className="font-medium">{item.quantity} {item.unit}</span>
<span>×</span>
<span>{formatCurrency(item.unit_price)}</span>
</p>
</div>
<p className="font-bold text-lg ml-4" style={{ color: 'var(--color-primary-600)' }}>
{formatCurrency(item.subtotal)}
</p>
</div>
))
) : (
<div className="text-center py-8 rounded-xl border-2 border-dashed" style={{
borderColor: 'var(--border-primary)',
color: 'var(--text-secondary)'
}}>
<FileText className="w-12 h-12 mx-auto mb-2 opacity-30" />
<p>{t('purchase_orders:no_items')}</p>
</div>
)}
</div>
</div>
{/* Notes */}
{po.notes && (
<div className="rounded-xl p-5 border-l-4" style={{
backgroundColor: 'var(--color-info-50)',
borderLeftColor: 'var(--color-info-500)',
boxShadow: '0 1px 3px rgba(0, 0, 0, 0.05)'
}}>
<div className="flex items-center gap-2 mb-3">
<div className="p-1.5 rounded-lg" style={{ backgroundColor: 'var(--color-info-100)' }}>
<AlertCircle className="w-5 h-5" style={{ color: 'var(--color-info-600)' }} />
</div>
<h3 className="font-semibold text-sm uppercase tracking-wide" style={{ color: 'var(--color-info-700)' }}>
{t('purchase_orders:notes')}
</h3>
</div>
<p className="text-sm leading-relaxed ml-1" style={{ color: 'var(--text-primary)' }}>{po.notes}</p>
</div>
)}
</div>
) : (
<div className="text-center py-12">
<p style={{ color: 'var(--text-secondary)' }}>{t('purchase_orders:not_found')}</p>
</div>
)}
</div>
{/* Footer Actions */}
{po && po.status === 'pending_approval' && (
<div
className="flex justify-end gap-3 p-6 border-t bg-gradient-to-r from-transparent to-transparent"
style={{
borderColor: 'var(--border-primary)',
background: 'linear-gradient(to right, var(--bg-secondary), var(--bg-primary))'
}}
>
<button
onClick={() => {
onModify?.(poId);
onClose();
}}
className="px-6 py-2.5 rounded-xl font-semibold transition-all hover:scale-105 hover:shadow-md border"
style={{
backgroundColor: 'var(--bg-primary)',
color: 'var(--text-primary)',
borderColor: 'var(--border-primary)'
}}
>
{t('purchase_orders:actions.modify')}
</button>
<button
onClick={() => {
onApprove?.(poId);
onClose();
}}
className="px-6 py-2.5 rounded-xl font-semibold text-white transition-all hover:scale-105 hover:shadow-lg flex items-center gap-2"
style={{
backgroundColor: 'var(--color-primary-600)',
boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
}}
>
<CheckCircle className="w-4 h-4" />
{t('purchase_orders:actions.approve')}
</button>
</div>
)}
</div>
</div>
mode={mode}
onModeChange={setMode}
title={po?.po_number || t('purchase_order')}
subtitle={po ? new Date(po.created_at).toLocaleDateString(i18n.language, {
year: 'numeric',
month: 'long',
day: 'numeric'
}) : undefined}
sections={sections}
actions={buildActions()}
isLoading={isLoading}
size="lg"
// Enable edit mode via standard Edit button (only for pending approval)
onEdit={po?.status === 'pending_approval' ? () => setMode('edit') : undefined}
onSave={mode === 'edit' ? handleSave : undefined}
onCancel={mode === 'edit' ? () => setMode('view') : undefined}
saveLabel={t('actions.save')}
cancelLabel={t('actions.cancel')}
/>
);
};

View File

@@ -2,11 +2,12 @@ import React, { useState, useEffect, useMemo } from 'react';
import { Plus, Package, Calendar, Building2 } from 'lucide-react';
import { AddModal } from '../../ui/AddModal/AddModal';
import { useSuppliers } from '../../../api/hooks/suppliers';
import { useCreatePurchaseOrder } from '../../../api/hooks/suppliers';
import { useCreatePurchaseOrder } from '../../../api/hooks/purchase-orders';
import { useIngredients } from '../../../api/hooks/inventory';
import { useTenantStore } from '../../../stores/tenant.store';
import { suppliersService } from '../../../api/services/suppliers';
import type { ProcurementRequirementResponse, PurchaseOrderItem } from '../../../api/types/orders';
import type { ProcurementRequirementResponse } from '../../../api/types/orders';
import type { PurchaseOrderItemCreate } from '../../../api/services/purchase_orders';
import type { SupplierSummary } from '../../../api/types/suppliers';
import type { IngredientResponse } from '../../../api/types/inventory';
import { statusColors } from '../../../styles/colors';
@@ -127,7 +128,7 @@ export const CreatePurchaseOrderModal: React.FC<CreatePurchaseOrderModalProps> =
setLoading(true);
try {
let items: PurchaseOrderItem[] = [];
let items: PurchaseOrderItemCreate[] = [];
if (requirements && requirements.length > 0) {
// Create items from requirements list
@@ -149,13 +150,11 @@ export const CreatePurchaseOrderModal: React.FC<CreatePurchaseOrderModalProps> =
const originalReq = requirements.find(req => req.id === item.id);
return {
inventory_product_id: originalReq?.product_id || '',
product_code: item.product_sku || '',
product_name: item.product_name,
ordered_quantity: item.quantity,
unit_of_measure: item.unit_of_measure,
unit_price: item.unit_price,
unit_price: String(item.unit_price || 0), // ✅ Convert to string for Decimal
quality_requirements: originalReq?.quality_specifications ? JSON.stringify(originalReq.quality_specifications) : undefined,
notes: originalReq?.special_requirements || undefined
item_notes: originalReq?.special_requirements || undefined
};
});
} else {
@@ -180,29 +179,27 @@ export const CreatePurchaseOrderModal: React.FC<CreatePurchaseOrderModalProps> =
// Prepare purchase order items from manual entries with ingredient data
items = manualProducts.map((item: any) => {
// Find the selected ingredient data
const selectedIngredient = ingredientsData.find(ing => ing.id === item.ingredient_id);
return {
inventory_product_id: item.ingredient_id,
product_code: selectedIngredient?.sku || '',
product_name: selectedIngredient?.name || 'Ingrediente desconocido',
ordered_quantity: item.quantity,
unit_of_measure: item.unit_of_measure,
unit_price: item.unit_price,
unit_price: String(item.unit_price || 0), // ✅ Convert to string for Decimal
quality_requirements: undefined,
notes: undefined
item_notes: undefined
};
});
}
// Create purchase order
// Create purchase order using procurement service
await createPurchaseOrderMutation.mutateAsync({
supplier_id: formData.supplier_id,
priority: 'normal',
required_delivery_date: formData.delivery_date || undefined,
notes: formData.notes || undefined,
items
tenantId,
data: {
supplier_id: formData.supplier_id,
priority: 'normal',
required_delivery_date: formData.delivery_date || undefined,
notes: formData.notes || undefined,
items
}
});
// Purchase order created successfully