Sync with main

This commit is contained in:
2025-07-06 21:52:36 +02:00
parent 0cdfdbc751
commit eaf5295843
10 changed files with 974 additions and 742 deletions

View File

@@ -1,9 +1,10 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { HoverCard, HoverCardContent, HoverCardTrigger } from '@/components/ui/hover-card';
import { Calendar, Factory, TrendingUp, TrendingDown, Clock, Package, Wrench, Check } from 'lucide-react';
import { Calendar, Factory, TrendingUp, TrendingDown, Clock, Import, Upload, Check } from 'lucide-react';
import { formatISK } from '@/utils/priceUtils';
import { IndJob } from '@/lib/types';
import { Input } from '@/components/ui/input';
@@ -14,17 +15,24 @@ interface JobCardProps {
onEdit: (job: any) => void;
onDelete: (jobId: string) => void;
onUpdateProduced?: (jobId: string, produced: number) => void;
onImportBOM?: (jobId: string, items: { name: string; quantity: number }[]) => void;
isTracked?: boolean;
}
const JobCard: React.FC<JobCardProps> = ({ job, onEdit, onDelete, onUpdateProduced, isTracked = false }) => {
const JobCard: React.FC<JobCardProps> = ({
job,
onEdit,
onDelete,
onUpdateProduced,
onImportBOM,
isTracked = false
}) => {
const navigate = useNavigate();
const [isEditingProduced, setIsEditingProduced] = useState(false);
const [producedValue, setProducedValue] = useState(job.produced?.toString() || '0');
const [copyingBom, setCopyingBom] = useState(false);
const [copyingConsumed, setCopyingConsumed] = useState(false);
const { toast } = useToast();
// Sort transactions by date descending
const sortedExpenditures = [...job.expenditures].sort((a, b) =>
new Date(b.date).getTime() - new Date(a.date).getTime()
);
@@ -32,7 +40,6 @@ const JobCard: React.FC<JobCardProps> = ({ job, onEdit, onDelete, onUpdateProduc
new Date(b.date).getTime() - new Date(a.date).getTime()
);
// Calculate totals for this job (including tracked jobs)
const totalExpenditure = sortedExpenditures.reduce((sum, tx) => sum + tx.totalPrice, 0);
const totalIncome = sortedIncome.reduce((sum, tx) => sum + tx.totalPrice, 0);
const profit = totalIncome - totalExpenditure;
@@ -87,9 +94,59 @@ const JobCard: React.FC<JobCardProps> = ({ job, onEdit, onDelete, onUpdateProduc
}
};
const copyBillOfMaterials = async () => {
if (!job.billOfMaterials?.length) return;
const importBillOfMaterials = async () => {
try {
const clipboardText = await navigator.clipboard.readText();
const lines = clipboardText.split('\n').filter(line => line.trim());
const items: { name: string; quantity: number }[] = [];
for (const line of lines) {
const parts = line.trim().split(/\s+/);
if (parts.length >= 2) {
const name = parts.slice(0, -1).join(' ');
const quantity = parseInt(parts[parts.length - 1]);
if (name && !isNaN(quantity)) {
items.push({ name, quantity });
}
}
}
if (items.length > 0 && onImportBOM) {
onImportBOM(job.id, items);
toast({
title: "BOM Imported",
description: `Successfully imported ${items.length} items`,
duration: 3000,
});
} else {
toast({
title: "No Valid Items",
description: "No valid items found in clipboard. Format: 'Item Name Quantity' per line",
variant: "destructive",
duration: 3000,
});
}
} catch (err) {
toast({
title: "Error",
description: "Failed to read from clipboard",
variant: "destructive",
duration: 2000,
});
}
};
const exportBillOfMaterials = async () => {
if (!job.billOfMaterials?.length) {
toast({
title: "Nothing to Export",
description: "No bill of materials found for this job",
variant: "destructive",
duration: 2000,
});
return;
}
const text = job.billOfMaterials
.map(item => `${item.name}\t${item.quantity.toLocaleString()}`)
.join('\n');
@@ -98,7 +155,7 @@ const JobCard: React.FC<JobCardProps> = ({ job, onEdit, onDelete, onUpdateProduc
await navigator.clipboard.writeText(text);
setCopyingBom(true);
toast({
title: "Copied!",
title: "Exported!",
description: "Bill of materials copied to clipboard",
duration: 2000,
});
@@ -113,30 +170,8 @@ const JobCard: React.FC<JobCardProps> = ({ job, onEdit, onDelete, onUpdateProduc
}
};
const copyConsumedMaterials = async () => {
if (!job.consumedMaterials?.length) return;
const text = job.consumedMaterials
.map(item => `${item.name}\t${item.quantity.toLocaleString()}`)
.join('\n');
try {
await navigator.clipboard.writeText(text);
setCopyingConsumed(true);
toast({
title: "Copied!",
description: "Consumed materials copied to clipboard",
duration: 2000,
});
setTimeout(() => setCopyingConsumed(false), 1000);
} catch (err) {
toast({
title: "Error",
description: "Failed to copy to clipboard",
variant: "destructive",
duration: 2000,
});
}
const handleCardClick = () => {
navigate(`/${job.id}`);
};
const handleProducedClick = (e: React.MouseEvent) => {
@@ -156,88 +191,56 @@ const JobCard: React.FC<JobCardProps> = ({ job, onEdit, onDelete, onUpdateProduc
onDelete(job.id);
};
const handleImportClick = (e: React.MouseEvent) => {
e.stopPropagation();
importBillOfMaterials();
};
const handleExportClick = (e: React.MouseEvent) => {
e.stopPropagation();
exportBillOfMaterials();
};
return (
<Card className={`bg-gray-900 border-gray-700 text-white ${job.status === 'Tracked' ? 'border-l-4 border-l-cyan-600' : ''}`}>
<CardHeader>
<Card
className={`bg-gray-900 border-gray-700 text-white h-full flex flex-col cursor-pointer hover:bg-gray-800/50 transition-colors ${job.status === 'Tracked' ? 'border-l-4 border-l-cyan-600' : ''}`}
onClick={handleCardClick}
>
<CardHeader className="flex-shrink-0">
<div className="flex justify-between items-start">
<div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2">
<CardTitle className="text-blue-400">{job.outputItem}</CardTitle>
<Badge className={`${getStatusColor(job.status)} text-white`}>
<CardTitle className="text-blue-400 truncate">{job.outputItem}</CardTitle>
<Badge className={`${getStatusColor(job.status)} text-white flex-shrink-0`}>
{job.status}
</Badge>
{job.billOfMaterials && job.billOfMaterials.length > 0 && (
<HoverCard>
<HoverCardTrigger asChild>
<Button
variant="ghost"
size="sm"
className="p-1 h-6 w-6 relative group"
onClick={(e) => {
e.stopPropagation();
copyBillOfMaterials();
}}
>
{copyingBom ? (
<Check className="w-4 h-4 text-green-400 absolute transition-opacity" />
) : (
<Package className="w-4 h-4 text-blue-400" />
)}
<span className="sr-only">Copy bill of materials</span>
</Button>
</HoverCardTrigger>
<HoverCardContent className="w-80 bg-gray-800 border-gray-600 text-white">
<div className="space-y-2">
<h4 className="text-sm font-semibold text-blue-400">Bill of Materials (click to copy)</h4>
<div className="text-xs space-y-1 max-h-48 overflow-y-auto">
{job.billOfMaterials.map((item, index) => (
<div key={index} className="flex justify-between">
<span>{item.name}</span>
<span className="text-gray-300">{item.quantity.toLocaleString()}</span>
</div>
))}
</div>
</div>
</HoverCardContent>
</HoverCard>
)}
{job.consumedMaterials && job.consumedMaterials.length > 0 && (
<HoverCard>
<HoverCardTrigger asChild>
<Button
variant="ghost"
size="sm"
className="p-1 h-6 w-6 relative group"
onClick={(e) => {
e.stopPropagation();
copyConsumedMaterials();
}}
>
{copyingConsumed ? (
<Check className="w-4 h-4 text-green-400 absolute transition-opacity" />
) : (
<Wrench className="w-4 h-4 text-yellow-400" />
)}
<span className="sr-only">Copy consumed materials</span>
</Button>
</HoverCardTrigger>
<HoverCardContent className="w-80 bg-gray-800 border-gray-600 text-white">
<div className="space-y-2">
<h4 className="text-sm font-semibold text-yellow-400">Consumed Materials (click to copy)</h4>
<div className="text-xs space-y-1 max-h-48 overflow-y-auto">
{job.consumedMaterials.map((item, index) => (
<div key={index} className="flex justify-between">
<span>{item.name}</span>
<span className="text-gray-300">{item.quantity.toLocaleString()}</span>
</div>
))}
</div>
</div>
</HoverCardContent>
</HoverCard>
)}
<div className="flex gap-1 flex-shrink-0">
<Button
variant="ghost"
size="sm"
className="p-1 h-6 w-6"
onClick={handleImportClick}
title="Import BOM from clipboard"
>
<Import className="w-4 h-4 text-blue-400" />
</Button>
<Button
variant="ghost"
size="sm"
className="p-1 h-6 w-6"
onClick={handleExportClick}
disabled={!job.billOfMaterials?.length}
title="Export BOM to clipboard"
>
{copyingBom ? (
<Check className="w-4 h-4 text-green-400" />
) : (
<Upload className="w-4 h-4 text-blue-400" />
)}
</Button>
</div>
</div>
<p className="text-gray-400">
<p className="text-gray-400 text-sm">
Quantity: {job.outputQuantity.toLocaleString()}
<span className="ml-4">
Produced: {
@@ -269,7 +272,7 @@ const JobCard: React.FC<JobCardProps> = ({ job, onEdit, onDelete, onUpdateProduc
</span>
</p>
</div>
<div className="flex gap-2">
<div className="flex gap-2 flex-shrink-0">
<Button
variant="outline"
size="sm"
@@ -288,42 +291,69 @@ const JobCard: React.FC<JobCardProps> = ({ job, onEdit, onDelete, onUpdateProduc
</div>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 gap-2">
<div className="flex items-center gap-2 text-sm text-gray-400">
<Calendar className="w-4 h-4" />
Created: {formatDateTime(job.created)}
</div>
<div className="flex items-center gap-2 text-sm text-gray-400">
<Clock className="w-4 h-4" />
Start: {formatDateTime(job.jobStart)}
</div>
<div className="flex items-center gap-2 text-sm text-gray-400">
<Factory className="w-4 h-4" />
Job ID: {job.id}
<CardContent className="flex-1 flex flex-col space-y-4">
<div className="flex-shrink-0">
<div className="grid grid-cols-1 gap-2">
<div className="flex items-center gap-2 text-sm text-gray-400">
<Calendar className="w-4 h-4" />
Created: {formatDateTime(job.created)}
</div>
<div className="flex items-center gap-2 text-sm text-gray-400">
<Clock className="w-4 h-4" />
Start: {formatDateTime(job.jobStart)}
</div>
<div className="flex items-center gap-2 text-sm text-gray-400">
<Factory className="w-4 h-4" />
Job ID: {job.id}
</div>
</div>
{job.saleStart && (
<div className="space-y-2 mt-4">
<div className="text-sm text-gray-400">
Sale Period: {formatDateTime(job.saleStart)} - {formatDateTime(job.saleEnd)}
</div>
{itemsPerDay > 0 && (
<div className="text-sm text-gray-400">
Items/Day: {itemsPerDay.toFixed(2)}
</div>
)}
</div>
)}
{job.billOfMaterials && job.billOfMaterials.length > 0 && (
<HoverCard>
<HoverCardTrigger asChild>
<div className="text-sm text-gray-400 mt-2 cursor-pointer hover:text-blue-400">
BOM: {job.billOfMaterials.length} items (hover to view)
</div>
</HoverCardTrigger>
<HoverCardContent className="w-80 bg-gray-800 border-gray-600 text-white">
<div className="space-y-2">
<h4 className="text-sm font-semibold text-blue-400">Bill of Materials</h4>
<div className="text-xs space-y-1 max-h-48 overflow-y-auto">
{job.billOfMaterials.map((item, index) => (
<div key={index} className="flex justify-between">
<span>{item.name}</span>
<span className="text-gray-300">{item.quantity.toLocaleString()}</span>
</div>
))}
</div>
</div>
</HoverCardContent>
</HoverCard>
)}
</div>
{job.saleStart && (
<div className="space-y-2">
<div className="text-sm text-gray-400">
Sale Period: {formatDateTime(job.saleStart)} - {formatDateTime(job.saleEnd)}
</div>
{itemsPerDay > 0 && (
<div className="text-sm text-gray-400">
Items/Day: {itemsPerDay.toFixed(2)}
</div>
)}
</div>
)}
<div className="flex-1" />
<div className="grid grid-cols-3 gap-4 pt-4 border-t border-gray-700">
<div className="grid grid-cols-3 gap-4 pt-4 border-t border-gray-700 flex-shrink-0">
<div className="text-center">
<div className="flex items-center justify-center gap-1 text-red-400">
<TrendingDown className="w-4 h-4" />
<span className="text-sm">Expenditure</span>
</div>
<div className="font-semibold">{formatISK(totalExpenditure)}</div>
<div className="font-semibold text-sm">{formatISK(totalExpenditure)}</div>
{job.projectedCost > 0 && (
<div className="text-xs text-gray-400">
vs Projected: {formatISK(job.projectedCost)}
@@ -341,7 +371,7 @@ const JobCard: React.FC<JobCardProps> = ({ job, onEdit, onDelete, onUpdateProduc
<TrendingUp className="w-4 h-4" />
<span className="text-sm">Income</span>
</div>
<div className="font-semibold">{formatISK(totalIncome)}</div>
<div className="font-semibold text-sm">{formatISK(totalIncome)}</div>
{job.projectedRevenue > 0 && (
<div className="text-xs text-gray-400">
vs Projected: {formatISK(job.projectedRevenue)}
@@ -358,7 +388,7 @@ const JobCard: React.FC<JobCardProps> = ({ job, onEdit, onDelete, onUpdateProduc
<div className="flex items-center justify-center gap-1 text-gray-400">
<span className="text-sm">Profit</span>
</div>
<div className={`font-semibold ${profit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
<div className={`font-semibold text-sm ${profit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
{formatISK(profit)}
<Badge variant={profit >= 0 ? 'default' : 'destructive'} className="ml-1 text-xs">
{margin.toFixed(1)}%

View File

@@ -1,15 +1,13 @@
import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { IndJobStatusOptions, IndJobRecordNoId, IndBillitemRecord } from '@/lib/pbtypes';
import MaterialsImportExport from './MaterialsImportExport';
import { IndJobStatusOptions, IndJobRecordNoId } from '@/lib/pbtypes';
import { IndJob } from '@/lib/types';
import { parseISKAmount } from '@/utils/priceUtils';
// import { getFacilities } from '@/services/facilityService';
interface JobFormProps {
job?: IndJob;
@@ -17,54 +15,36 @@ interface JobFormProps {
onCancel: () => void;
}
const formatDateForInput = (dateString: string | undefined | null): string => {
if (!dateString) return '';
// Convert ISO string to datetime-local format (YYYY-MM-DDTHH:MM)
return new Date(dateString).toISOString().slice(0, 16);
};
const JobForm: React.FC<JobFormProps> = ({ job, onSubmit, onCancel }) => {
// const [facilities, setFacilities] = useState<IndFacilityRecord[]>([]);
const [billOfMaterials, setBillOfMaterials] = useState<IndBillitemRecord[]>(job?.billOfMaterials || []);
const [consumedMaterials, setConsumedMaterials] = useState<IndBillitemRecord[]>(job?.consumedMaterials || []);
const [formData, setFormData] = useState({
outputItem: job?.outputItem || '',
outputQuantity: job?.outputQuantity || 0,
jobStart: job?.jobStart ? job.jobStart.slice(0, 16) : '',
jobEnd: job?.jobEnd ? job.jobEnd.slice(0, 16) : '',
saleStart: job?.saleStart ? job.saleStart.slice(0, 16) : '',
saleEnd: job?.saleEnd ? job.saleEnd.slice(0, 16) : '',
jobStart: formatDateForInput(job?.jobStart),
jobEnd: formatDateForInput(job?.jobEnd),
saleStart: formatDateForInput(job?.saleStart),
saleEnd: formatDateForInput(job?.saleEnd),
status: job?.status || IndJobStatusOptions.Planned,
billOfMaterials: job?.billOfMaterials || [],
consumedMaterials: job?.consumedMaterials || [],
expenditures: job?.expenditures || [],
income: job?.income || [],
projectedCost: job?.projectedCost || 0,
projectedRevenue: job?.projectedRevenue || 0
});
// useEffect(() => {
// const loadFacilities = async () => {
// try {
// const fetchedFacilities = await getFacilities();
// setFacilities(fetchedFacilities);
// } catch (error) {
// console.error('Error loading facilities:', error);
// }
// };
// loadFacilities();
// }, []);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
onSubmit({
outputItem: formData.outputItem,
outputQuantity: formData.outputQuantity,
jobStart: formData.jobStart ? formData.jobStart : undefined,
jobEnd: formData.jobEnd ? formData.jobEnd : undefined,
saleStart: formData.saleStart ? formData.saleStart : undefined,
saleEnd: formData.saleEnd ? formData.saleEnd : undefined,
jobStart: formData.jobStart || undefined,
jobEnd: formData.jobEnd || undefined,
saleStart: formData.saleStart || undefined,
saleEnd: formData.saleEnd || undefined,
status: formData.status,
billOfMaterials: formData.billOfMaterials.map(item => item.id),
consumedMaterials: formData.consumedMaterials.map(item => item.id),
expenditures: formData.expenditures.map(item => item.id),
income: formData.income.map(item => item.id),
projectedCost: formData.projectedCost,
projectedRevenue: formData.projectedRevenue
});
@@ -80,190 +60,157 @@ const JobForm: React.FC<JobFormProps> = ({ job, onSubmit, onCancel }) => {
</CardTitle>
</CardHeader>
<CardContent>
<Tabs defaultValue="basic" className="w-full">
<TabsList className="grid w-full grid-cols-2 bg-gray-800">
<TabsTrigger value="basic" className="text-white">Basic Info</TabsTrigger>
<TabsTrigger value="materials" className="text-white">Materials</TabsTrigger>
</TabsList>
<TabsContent value="basic" className="space-y-4">
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="itemName" className="text-gray-300">Output Item Name</Label>
<Input
id="itemName"
value={formData.outputItem}
onChange={(e) => setFormData({
...formData,
outputItem: e.target.value
})}
className="bg-gray-800 border-gray-600 text-white"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="itemQuantity" className="text-gray-300">Quantity</Label>
<Input
id="itemQuantity"
type="number"
value={formData.outputQuantity}
onChange={(e) => setFormData({
...formData,
outputQuantity: parseInt(e.target.value) || 0
})}
className="bg-gray-800 border-gray-600 text-white"
required
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="status" className="text-gray-300">Status</Label>
<Select
value={formData.status}
onValueChange={(value) => setFormData({ ...formData, status: value as IndJobStatusOptions })}
>
<SelectTrigger className="bg-gray-800 border-gray-600 text-white">
<SelectValue placeholder="Select status" />
</SelectTrigger>
<SelectContent className="bg-gray-800 border-gray-600">
{statusOptions.map((status) => (
<SelectItem key={status} value={status} className="text-white">
{status}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="startDate" className="text-gray-300">Start Date & Time</Label>
<Input
id="startDate"
type="datetime-local"
value={formData.jobStart}
onChange={(e) => setFormData({
...formData,
jobStart: e.target.value
})}
className="bg-gray-800 border-gray-600 text-white"
/>
</div>
<div className="space-y-2">
<Label htmlFor="endDate" className="text-gray-300">End Date & Time</Label>
<Input
id="endDate"
type="datetime-local"
value={formData.jobEnd}
onChange={(e) => setFormData({
...formData,
jobEnd: e.target.value
})}
className="bg-gray-800 border-gray-600 text-white"
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="saleStartDate" className="text-gray-300">Sale Start Date & Time</Label>
<Input
id="saleStartDate"
type="datetime-local"
value={formData.saleStart}
onChange={(e) => setFormData({
...formData,
saleStart: e.target.value
})}
className="bg-gray-800 border-gray-600 text-white"
/>
</div>
<div className="space-y-2">
<Label htmlFor="saleEndDate" className="text-gray-300">Sale End Date & Time</Label>
<Input
id="saleEndDate"
type="datetime-local"
value={formData.saleEnd}
onChange={(e) => setFormData({
...formData,
saleEnd: e.target.value
})}
className="bg-gray-800 border-gray-600 text-white"
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="projectedCost" className="text-gray-300">Projected Cost</Label>
<Input
id="projectedCost"
type="text"
value={formData.projectedCost ? `${formData.projectedCost.toLocaleString()} ISK` : ''}
onChange={(e) => setFormData({
...formData,
projectedCost: parseISKAmount(e.target.value)
})}
className="bg-gray-800 border-gray-600 text-white"
/>
</div>
<div className="space-y-2">
<Label htmlFor="projectedRevenue" className="text-gray-300">Projected Revenue</Label>
<Input
id="projectedRevenue"
type="text"
value={formData.projectedRevenue ? `${formData.projectedRevenue.toLocaleString()} ISK` : ''}
onChange={(e) => setFormData({
...formData,
projectedRevenue: parseISKAmount(e.target.value)
})}
className="bg-gray-800 border-gray-600 text-white"
/>
</div>
</div>
<div className="flex gap-2 pt-4">
<Button type="submit" className="flex-1 bg-blue-600 hover:bg-blue-700">
{job ? 'Update Job' : 'Create Job'}
</Button>
<Button
type="button"
variant="outline"
onClick={onCancel}
className="border-gray-600 hover:bg-gray-800"
>
Cancel
</Button>
</div>
</form>
</TabsContent>
<TabsContent value="materials" className="space-y-4">
<MaterialsImportExport
job={job}
billOfMaterials={billOfMaterials}
consumedMaterials={consumedMaterials}
onBillOfMaterialsUpdate={setBillOfMaterials}
onConsumedMaterialsUpdate={setConsumedMaterials}
/>
<div className="flex gap-2 pt-4">
<Button onClick={handleSubmit} className="flex-1 bg-blue-600 hover:bg-blue-700">
{job ? 'Update Job' : 'Create Job'}
</Button>
<Button
type="button"
variant="outline"
onClick={onCancel}
className="border-gray-600 hover:bg-gray-800"
>
Cancel
</Button>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="itemName" className="text-gray-300">Output Item Name</Label>
<Input
id="itemName"
value={formData.outputItem}
onChange={(e) => setFormData({
...formData,
outputItem: e.target.value
})}
className="bg-gray-800 border-gray-600 text-white"
required
/>
</div>
</TabsContent>
</Tabs>
<div className="space-y-2">
<Label htmlFor="itemQuantity" className="text-gray-300">Quantity</Label>
<Input
id="itemQuantity"
type="number"
value={formData.outputQuantity}
onChange={(e) => setFormData({
...formData,
outputQuantity: parseInt(e.target.value) || 0
})}
className="bg-gray-800 border-gray-600 text-white"
required
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="status" className="text-gray-300">Status</Label>
<Select
value={formData.status}
onValueChange={(value) => setFormData({ ...formData, status: value as IndJobStatusOptions })}
>
<SelectTrigger className="bg-gray-800 border-gray-600 text-white">
<SelectValue placeholder="Select status" />
</SelectTrigger>
<SelectContent className="bg-gray-800 border-gray-600">
{statusOptions.map((status) => (
<SelectItem key={status} value={status} className="text-white">
{status}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="startDate" className="text-gray-300">Start Date & Time</Label>
<Input
id="startDate"
type="datetime-local"
value={formData.jobStart}
onChange={(e) => setFormData({
...formData,
jobStart: e.target.value
})}
className="bg-gray-800 border-gray-600 text-white"
/>
</div>
<div className="space-y-2">
<Label htmlFor="endDate" className="text-gray-300">End Date & Time</Label>
<Input
id="endDate"
type="datetime-local"
value={formData.jobEnd}
onChange={(e) => setFormData({
...formData,
jobEnd: e.target.value
})}
className="bg-gray-800 border-gray-600 text-white"
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="saleStartDate" className="text-gray-300">Sale Start Date & Time</Label>
<Input
id="saleStartDate"
type="datetime-local"
value={formData.saleStart}
onChange={(e) => setFormData({
...formData,
saleStart: e.target.value
})}
className="bg-gray-800 border-gray-600 text-white"
/>
</div>
<div className="space-y-2">
<Label htmlFor="saleEndDate" className="text-gray-300">Sale End Date & Time</Label>
<Input
id="saleEndDate"
type="datetime-local"
value={formData.saleEnd}
onChange={(e) => setFormData({
...formData,
saleEnd: e.target.value
})}
className="bg-gray-800 border-gray-600 text-white"
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="projectedCost" className="text-gray-300">Projected Cost</Label>
<Input
id="projectedCost"
type="text"
value={formData.projectedCost ? `${formData.projectedCost.toLocaleString()} ISK` : ''}
onChange={(e) => setFormData({
...formData,
projectedCost: parseISKAmount(e.target.value)
})}
className="bg-gray-800 border-gray-600 text-white"
/>
</div>
<div className="space-y-2">
<Label htmlFor="projectedRevenue" className="text-gray-300">Projected Revenue</Label>
<Input
id="projectedRevenue"
type="text"
value={formData.projectedRevenue ? `${formData.projectedRevenue.toLocaleString()} ISK` : ''}
onChange={(e) => setFormData({
...formData,
projectedRevenue: parseISKAmount(e.target.value)
})}
className="bg-gray-800 border-gray-600 text-white"
/>
</div>
</div>
<div className="flex gap-2 pt-4">
<Button type="submit" className="flex-1 bg-blue-600 hover:bg-blue-700">
{job ? 'Update Job' : 'Create Job'}
</Button>
<Button
type="button"
variant="outline"
onClick={onCancel}
className="border-gray-600 hover:bg-gray-800"
>
Cancel
</Button>
</div>
</form>
</CardContent>
</Card>
);

View File

@@ -4,13 +4,12 @@ import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Import, Download, FileText } from 'lucide-react';
import { IndBillitemRecord } from '@/lib/pbtypes';
import { IndBillitemRecord, IndBillitemRecordNoId } from '@/lib/pbtypes';
import { IndJob } from '@/lib/types';
import { addBillItem } from '@/services/billItemService';
import { updateJob } from '@/services/jobService';
import { dataService } from '@/services/dataService';
interface MaterialsImportExportProps {
job: IndJob;
job?: IndJob;
billOfMaterials: IndBillitemRecord[];
consumedMaterials: IndBillitemRecord[];
onBillOfMaterialsUpdate: (billItems: IndBillitemRecord[]) => void;
@@ -27,9 +26,9 @@ const MaterialsImportExport: React.FC<MaterialsImportExportProps> = ({
const [bomInput, setBomInput] = useState('');
const [consumedInput, setConsumedInput] = useState('');
const parseBillOfMaterials = async (text: string): Promise<IndJob> => {
const parseBillOfMaterials = (text: string): IndBillitemRecordNoId[] => {
const lines = text.split('\n').filter(line => line.trim());
const materials: IndBillitemRecord[] = [];
const materials: IndBillitemRecordNoId[] = [];
for (const line of lines) {
const parts = line.trim().split(/\s+/);
@@ -37,20 +36,17 @@ const MaterialsImportExport: React.FC<MaterialsImportExportProps> = ({
const name = parts.slice(0, -1).join(' ');
const quantity = parseInt(parts[parts.length - 1]);
if (name && !isNaN(quantity)) {
const newBillItem = await addBillItem(job.id, { name, quantity });
materials.push(newBillItem);
materials.push({ name, quantity });
}
}
}
job.billOfMaterials = materials;
await updateJob(job.id, { billOfMaterials: materials.map(item => item.id) });
return job;
return materials;
};
const parseConsumedMaterials = async (text: string): Promise<IndJob> => {
const parseConsumedMaterials = (text: string): IndBillitemRecordNoId[] => {
const lines = text.split('\n').filter(line => line.trim());
const materials: IndBillitemRecord[] = [];
const materials: IndBillitemRecordNoId[] = [];
for (const line of lines) {
const parts = line.trim().split('\t');
@@ -58,15 +54,12 @@ const MaterialsImportExport: React.FC<MaterialsImportExportProps> = ({
const name = parts[0];
const quantity = parseInt(parts[1]);
if (name && !isNaN(quantity)) {
const newBillItem = await addBillItem(job.id, { name, quantity });
materials.push(newBillItem);
materials.push({ name, quantity });
}
}
}
job.consumedMaterials = materials;
await updateJob(job.id, { consumedMaterials: materials.map(item => item.id) });
return job;
return materials;
};
const exportBillOfMaterials = (): string => {
@@ -78,15 +71,33 @@ const MaterialsImportExport: React.FC<MaterialsImportExportProps> = ({
};
const handleImportBom = async () => {
const parsed = await parseBillOfMaterials(bomInput);
onBillOfMaterialsUpdate(parsed.billOfMaterials);
setBomInput('');
if (!job) return;
const materials = parseBillOfMaterials(bomInput);
if (materials.length > 0) {
try {
const updatedJob = await dataService.createMultipleBillItems(job.id, materials, 'billOfMaterials');
onBillOfMaterialsUpdate(updatedJob.billOfMaterials);
setBomInput('');
} catch (error) {
console.error('Error importing bill of materials:', error);
}
}
};
const handleImportConsumed = async () => {
const parsed = await parseConsumedMaterials(consumedInput);
onConsumedMaterialsUpdate(parsed.consumedMaterials);
setConsumedInput('');
if (!job) return;
const materials = parseConsumedMaterials(consumedInput);
if (materials.length > 0) {
try {
const updatedJob = await dataService.createMultipleBillItems(job.id, materials, 'consumedMaterials');
onConsumedMaterialsUpdate(updatedJob.consumedMaterials);
setConsumedInput('');
} catch (error) {
console.error('Error importing consumed materials:', error);
}
}
};
const handleExportBom = () => {
@@ -131,6 +142,7 @@ const MaterialsImportExport: React.FC<MaterialsImportExportProps> = ({
<Button
onClick={handleImportBom}
className="bg-blue-600 hover:bg-blue-700"
disabled={!job}
>
<Import className="w-4 h-4 mr-2" />
Import Bill of Materials
@@ -160,6 +172,7 @@ const MaterialsImportExport: React.FC<MaterialsImportExportProps> = ({
<Button
onClick={handleImportConsumed}
className="bg-blue-600 hover:bg-blue-700"
disabled={!job}
>
<Import className="w-4 h-4 mr-2" />
Import Consumed Materials