Sync with main
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
import { Toaster as Sonner } from "@/components/ui/sonner";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
||||
import Index from "./pages/Index";
|
||||
import JobDetails from "./pages/JobDetails";
|
||||
import NotFound from "./pages/NotFound";
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
@@ -16,6 +18,7 @@ const App = () => (
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/:jobId" element={<JobDetails />} />
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
|
||||
@@ -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,8 +94,58 @@ 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()}`)
|
||||
@@ -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>
|
||||
<div className="flex gap-1 flex-shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="p-1 h-6 w-6 relative group"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
copyBillOfMaterials();
|
||||
}}
|
||||
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 absolute transition-opacity" />
|
||||
<Check className="w-4 h-4 text-green-400" />
|
||||
) : (
|
||||
<Package className="w-4 h-4 text-blue-400" />
|
||||
<Upload 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>
|
||||
<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,7 +291,8 @@ const JobCard: React.FC<JobCardProps> = ({ job, onEdit, onDelete, onUpdateProduc
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<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" />
|
||||
@@ -305,7 +309,7 @@ const JobCard: React.FC<JobCardProps> = ({ job, onEdit, onDelete, onUpdateProduc
|
||||
</div>
|
||||
|
||||
{job.saleStart && (
|
||||
<div className="space-y-2">
|
||||
<div className="space-y-2 mt-4">
|
||||
<div className="text-sm text-gray-400">
|
||||
Sale Period: {formatDateTime(job.saleStart)} - {formatDateTime(job.saleEnd)}
|
||||
</div>
|
||||
@@ -317,13 +321,39 @@ const JobCard: React.FC<JobCardProps> = ({ job, onEdit, onDelete, onUpdateProduc
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-3 gap-4 pt-4 border-t border-gray-700">
|
||||
{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>
|
||||
|
||||
<div className="flex-1" />
|
||||
|
||||
<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)}%
|
||||
|
||||
@@ -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,13 +60,6 @@ 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">
|
||||
@@ -238,32 +211,6 @@ const JobForm: React.FC<JobFormProps> = ({ job, onSubmit, onCancel }) => {
|
||||
</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>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -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);
|
||||
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);
|
||||
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
|
||||
|
||||
73
frontend/src/hooks/useDataService.ts
Normal file
73
frontend/src/hooks/useDataService.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { dataService } from '@/services/dataService';
|
||||
import { IndJob } from '@/lib/types';
|
||||
|
||||
export function useJobs() {
|
||||
const [jobs, setJobs] = useState<IndJob[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const loadJobs = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
await dataService.loadJobs();
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load jobs');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadJobs();
|
||||
|
||||
const unsubscribe = dataService.subscribe(() => {
|
||||
setJobs(dataService.getJobs());
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribe();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
jobs,
|
||||
loading,
|
||||
error,
|
||||
createJob: dataService.createJob.bind(dataService),
|
||||
updateJob: dataService.updateJob.bind(dataService),
|
||||
deleteJob: dataService.deleteJob.bind(dataService),
|
||||
createTransaction: dataService.createTransaction.bind(dataService),
|
||||
createMultipleTransactions: dataService.createMultipleTransactions.bind(dataService),
|
||||
updateTransaction: dataService.updateTransaction.bind(dataService),
|
||||
deleteTransaction: dataService.deleteTransaction.bind(dataService),
|
||||
createBillItem: dataService.createBillItem.bind(dataService),
|
||||
createMultipleBillItems: dataService.createMultipleBillItems.bind(dataService)
|
||||
};
|
||||
}
|
||||
|
||||
export function useJob(jobId: string | null) {
|
||||
const [job, setJob] = useState<IndJob | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!jobId) {
|
||||
setJob(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const updateJob = () => {
|
||||
setJob(dataService.getJob(jobId));
|
||||
};
|
||||
|
||||
updateJob();
|
||||
|
||||
const unsubscribe = dataService.subscribe(updateJob);
|
||||
return () => {
|
||||
unsubscribe();
|
||||
};
|
||||
}, [jobId]);
|
||||
|
||||
return job;
|
||||
}
|
||||
@@ -1,45 +1,52 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Plus, Factory, TrendingUp, Briefcase, FileText } from 'lucide-react';
|
||||
import { IndTransactionRecordNoId, IndJobRecordNoId, IndTransactionRecord, IndJobStatusOptions } from '@/lib/pbtypes';
|
||||
import * as jobService from '@/services/jobService';
|
||||
import * as transactionService from '@/services/transactionService';
|
||||
import { IndTransactionRecordNoId, IndJobRecordNoId, IndJobStatusOptions } from '@/lib/pbtypes';
|
||||
import { formatISK } from '@/utils/priceUtils';
|
||||
import JobCard from '@/components/JobCard';
|
||||
import JobForm from '@/components/JobForm';
|
||||
import TransactionForm from '@/components/TransactionForm';
|
||||
import TransactionTable from '@/components/TransactionTable';
|
||||
import { IndJob } from '@/lib/types';
|
||||
import { createJob } from '@/services/jobService';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import BatchTransactionForm from '@/components/BatchTransactionForm';
|
||||
import { useJobs } from '@/hooks/useDataService';
|
||||
|
||||
// TODO: Bill of materials just does not work currently Fix this shit
|
||||
// Extended job type for UI components
|
||||
const Index = () => {
|
||||
const [jobs, setJobs] = useState<IndJob[]>([]);
|
||||
const {
|
||||
jobs,
|
||||
loading,
|
||||
error,
|
||||
createJob,
|
||||
updateJob,
|
||||
deleteJob,
|
||||
createMultipleTransactions,
|
||||
createMultipleBillItems
|
||||
} = useJobs();
|
||||
|
||||
const [showJobForm, setShowJobForm] = useState(false);
|
||||
const [editingJob, setEditingJob] = useState<IndJob | null>(null);
|
||||
const [selectedJob, setSelectedJob] = useState<IndJob | null>(null);
|
||||
const [showBatchForm, setShowBatchForm] = useState(false);
|
||||
const [collapsedGroups, setCollapsedGroups] = useState<Record<string, boolean>>(() => {
|
||||
const saved = localStorage.getItem('jobGroupsCollapsed');
|
||||
return saved ? JSON.parse(saved) : {};
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
loadJobs();
|
||||
}, []);
|
||||
|
||||
const loadJobs = async () => {
|
||||
try {
|
||||
const fetchedJobs = await jobService.getJobsFull();
|
||||
// Convert to JobWithRelations format
|
||||
const jobsWithRelations: IndJob[] = fetchedJobs;
|
||||
setJobs(jobsWithRelations);
|
||||
} catch (error) {
|
||||
console.error('Error loading jobs:', error);
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-950 p-6 flex items-center justify-center">
|
||||
<div className="text-white">Loading jobs...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-950 p-6 flex items-center justify-center">
|
||||
<div className="text-red-400">Error: {error}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Sort jobs by status priority
|
||||
const getStatusPriority = (status: IndJobStatusOptions): number => {
|
||||
switch (status) {
|
||||
case 'Planned': return 6;
|
||||
@@ -48,7 +55,7 @@ const Index = () => {
|
||||
case 'Done': return 3;
|
||||
case 'Selling': return 4;
|
||||
case 'Closed': return 5;
|
||||
case 'Tracked': return 7; // Put tracked jobs at the end
|
||||
case 'Tracked': return 7;
|
||||
default: return 0;
|
||||
}
|
||||
};
|
||||
@@ -70,17 +77,14 @@ const Index = () => {
|
||||
const priorityA = getStatusPriority(a.status);
|
||||
const priorityB = getStatusPriority(b.status);
|
||||
if (priorityA === priorityB) {
|
||||
// If same status, sort by creation date (newest first)
|
||||
return new Date(b.created || '').getTime() - new Date(a.created || '').getTime();
|
||||
}
|
||||
return priorityA - priorityB;
|
||||
});
|
||||
|
||||
// Separate regular and tracked jobs
|
||||
const regularJobs = sortedJobs.filter(job => job.status !== 'Tracked');
|
||||
const trackedJobs = sortedJobs.filter(job => job.status === 'Tracked');
|
||||
|
||||
// Calculate totals excluding tracked jobs
|
||||
const totalJobs = regularJobs.length;
|
||||
const totalProfit = regularJobs.reduce((sum, job) => {
|
||||
const expenditure = job.expenditures.reduce((sum, tx) => sum + tx.totalPrice, 0);
|
||||
@@ -94,15 +98,7 @@ const Index = () => {
|
||||
|
||||
const handleCreateJob = async (jobData: IndJobRecordNoId) => {
|
||||
try {
|
||||
const newJob = await createJob(jobData);
|
||||
const jobWithRelations: IndJob = {
|
||||
...newJob,
|
||||
expenditures: [],
|
||||
income: [],
|
||||
billOfMaterials: [],
|
||||
consumedMaterials: []
|
||||
};
|
||||
setJobs([...jobs, jobWithRelations]);
|
||||
await createJob(jobData);
|
||||
setShowJobForm(false);
|
||||
} catch (error) {
|
||||
console.error('Error creating job:', error);
|
||||
@@ -118,22 +114,9 @@ const Index = () => {
|
||||
if (!editingJob) return;
|
||||
|
||||
try {
|
||||
const updatedJob = await jobService.updateJob(editingJob.id, jobData);
|
||||
const updatedJobWithRelations: IndJob = {
|
||||
...updatedJob,
|
||||
expenditures: editingJob.expenditures,
|
||||
income: editingJob.income,
|
||||
billOfMaterials: editingJob.billOfMaterials,
|
||||
consumedMaterials: editingJob.consumedMaterials
|
||||
};
|
||||
|
||||
setJobs(jobs.map(job => job.id === editingJob.id ? updatedJobWithRelations : job));
|
||||
await updateJob(editingJob.id, jobData);
|
||||
setShowJobForm(false);
|
||||
setEditingJob(null);
|
||||
|
||||
if (selectedJob?.id === editingJob.id) {
|
||||
setSelectedJob(updatedJobWithRelations);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating job:', error);
|
||||
}
|
||||
@@ -142,88 +125,34 @@ const Index = () => {
|
||||
const handleDeleteJob = async (jobId: string) => {
|
||||
if (confirm('Are you sure you want to delete this job?')) {
|
||||
try {
|
||||
await jobService.deleteJob(jobId);
|
||||
setJobs(jobs.filter(job => job.id !== jobId));
|
||||
if (selectedJob?.id === jobId) {
|
||||
setSelectedJob(null);
|
||||
}
|
||||
await deleteJob(jobId);
|
||||
} catch (error) {
|
||||
console.error('Error deleting job:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleTransactionsAdded = async (transactions: IndTransactionRecordNoId[], type: 'expenditure' | 'income') => {
|
||||
if (!selectedJob) return;
|
||||
|
||||
try {
|
||||
let updatedJob = selectedJob;
|
||||
for (const transaction of transactions) {
|
||||
updatedJob = await transactionService.createTransaction(updatedJob, transaction, type);
|
||||
}
|
||||
|
||||
// Update local state
|
||||
setSelectedJob(updatedJob);
|
||||
setJobs(jobs.map(job => job.id === selectedJob.id ? updatedJob : job));
|
||||
} catch (error) {
|
||||
console.error('Error adding transactions:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateTransaction = async (transactionId: string, updates: Partial<IndTransactionRecord>) => {
|
||||
if (!selectedJob) return;
|
||||
|
||||
try {
|
||||
let updatedJob = selectedJob;
|
||||
updatedJob = await transactionService.updateTransaction(updatedJob, transactionId, updates);
|
||||
// Update local state
|
||||
setSelectedJob(updatedJob);
|
||||
setJobs(jobs.map(job => job.id === selectedJob.id ? updatedJob : job));
|
||||
} catch (error) {
|
||||
console.error('Error updating transaction:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteTransaction = async (transactionId: string) => {
|
||||
if (!selectedJob) return;
|
||||
|
||||
try {
|
||||
await transactionService.deleteTransaction(selectedJob, transactionId);
|
||||
|
||||
// Update local state
|
||||
const updatedJob = { ...selectedJob };
|
||||
updatedJob.expenditures = updatedJob.expenditures.filter(tx => tx.id !== transactionId);
|
||||
updatedJob.income = updatedJob.income.filter(tx => tx.id !== transactionId);
|
||||
|
||||
setSelectedJob(updatedJob);
|
||||
setJobs(jobs.map(job => job.id === selectedJob.id ? updatedJob : job));
|
||||
} catch (error) {
|
||||
console.error('Error deleting transaction:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateProduced = async (jobId: string, produced: number) => {
|
||||
if (!selectedJob) return;
|
||||
|
||||
try {
|
||||
const updatedJob = await jobService.updateJob(jobId, { produced });
|
||||
// Update local state
|
||||
const jobWithRelations: IndJob = {
|
||||
...updatedJob,
|
||||
expenditures: selectedJob.expenditures,
|
||||
income: selectedJob.income,
|
||||
billOfMaterials: selectedJob.billOfMaterials,
|
||||
consumedMaterials: selectedJob.consumedMaterials
|
||||
};
|
||||
|
||||
setSelectedJob(jobWithRelations);
|
||||
setJobs(jobs.map(job => job.id === jobId ? jobWithRelations : job));
|
||||
await updateJob(jobId, { produced });
|
||||
} catch (error) {
|
||||
console.error('Error updating produced quantity:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Group jobs by status
|
||||
const handleImportBOM = async (jobId: string, items: { name: string; quantity: number }[]) => {
|
||||
try {
|
||||
const billItems = items.map(item => ({
|
||||
name: item.name,
|
||||
quantity: item.quantity,
|
||||
unitPrice: 0
|
||||
}));
|
||||
await createMultipleBillItems(jobId, billItems, 'billOfMaterials');
|
||||
} catch (error) {
|
||||
console.error('Error importing BOM:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const jobGroups = regularJobs.reduce((groups, job) => {
|
||||
const status = job.status;
|
||||
if (!groups[status]) {
|
||||
@@ -233,13 +162,6 @@ const Index = () => {
|
||||
return groups;
|
||||
}, {} as Record<string, IndJob[]>);
|
||||
|
||||
// Load collapsed state from localStorage
|
||||
const [collapsedGroups, setCollapsedGroups] = useState<Record<string, boolean>>(() => {
|
||||
const saved = localStorage.getItem('jobGroupsCollapsed');
|
||||
return saved ? JSON.parse(saved) : {};
|
||||
});
|
||||
|
||||
// Toggle group collapse
|
||||
const toggleGroup = (status: string) => {
|
||||
const newState = { ...collapsedGroups, [status]: !collapsedGroups[status] };
|
||||
setCollapsedGroups(newState);
|
||||
@@ -249,15 +171,7 @@ const Index = () => {
|
||||
const handleBatchTransactionsAssigned = async (assignments: { jobId: string, transactions: IndTransactionRecordNoId[] }[]) => {
|
||||
try {
|
||||
for (const { jobId, transactions } of assignments) {
|
||||
const job = jobs.find(j => j.id === jobId);
|
||||
if (job) {
|
||||
let updatedJob = job;
|
||||
for (const transaction of transactions) {
|
||||
updatedJob = await transactionService.createTransaction(updatedJob, transaction, 'income');
|
||||
}
|
||||
// Update local state
|
||||
setJobs(jobs.map(j => j.id === jobId ? updatedJob : j));
|
||||
}
|
||||
await createMultipleTransactions(jobId, transactions, 'income');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error assigning batch transactions:', error);
|
||||
@@ -281,61 +195,8 @@ const Index = () => {
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedJob) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-950 p-6">
|
||||
<div className="max-w-7xl mx-auto space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-white">Job Details</h1>
|
||||
<p className="text-gray-400">{selectedJob.outputItem}</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setSelectedJob(null)}
|
||||
className="border-gray-600 hover:bg-gray-800"
|
||||
>
|
||||
Back to Jobs
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<JobCard
|
||||
job={selectedJob}
|
||||
onEdit={handleEditJob}
|
||||
onDelete={handleDeleteJob}
|
||||
onUpdateProduced={handleUpdateProduced}
|
||||
/>
|
||||
<TransactionForm
|
||||
jobId={selectedJob.id}
|
||||
onTransactionsAdded={handleTransactionsAdded}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<TransactionTable
|
||||
title="Expenditures"
|
||||
transactions={selectedJob.expenditures}
|
||||
type="expenditure"
|
||||
onUpdateTransaction={handleUpdateTransaction}
|
||||
onDeleteTransaction={handleDeleteTransaction}
|
||||
/>
|
||||
<TransactionTable
|
||||
title="Income"
|
||||
transactions={selectedJob.income}
|
||||
type="income"
|
||||
onUpdateTransaction={handleUpdateTransaction}
|
||||
onDeleteTransaction={handleDeleteTransaction}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 space-y-4">
|
||||
{/* Stats Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<Card className="bg-gray-900 border-gray-700 text-white">
|
||||
<CardHeader>
|
||||
@@ -374,7 +235,6 @@ const Index = () => {
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Regular Jobs */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<h2 className="text-xl font-bold text-white">Jobs</h2>
|
||||
@@ -421,14 +281,14 @@ const Index = () => {
|
||||
{!collapsedGroups[status] && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{statusJobs.map(job => (
|
||||
<div key={job.id} onClick={() => setSelectedJob(job)} className="cursor-pointer">
|
||||
<JobCard
|
||||
key={job.id}
|
||||
job={job}
|
||||
onEdit={handleEditJob}
|
||||
onDelete={handleDeleteJob}
|
||||
onUpdateProduced={handleUpdateProduced}
|
||||
onImportBOM={handleImportBOM}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
@@ -437,7 +297,6 @@ const Index = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tracked Jobs */}
|
||||
{trackedJobs.length > 0 && (
|
||||
<div className="space-y-4 mt-8 pt-8 border-t border-gray-700">
|
||||
<div
|
||||
@@ -457,61 +316,21 @@ const Index = () => {
|
||||
{!collapsedGroups['Tracked'] && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{trackedJobs.map(job => (
|
||||
<div key={job.id} onClick={() => setSelectedJob(job)} className="cursor-pointer">
|
||||
<JobCard
|
||||
key={job.id}
|
||||
job={job}
|
||||
onEdit={handleEditJob}
|
||||
onDelete={handleDeleteJob}
|
||||
onUpdateProduced={handleUpdateProduced}
|
||||
onImportBOM={handleImportBOM}
|
||||
isTracked={true}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Job Form Modal */}
|
||||
{showJobForm && (
|
||||
<JobForm
|
||||
job={editingJob}
|
||||
onSubmit={editingJob ? handleUpdateJob : handleCreateJob}
|
||||
onCancel={() => {
|
||||
setShowJobForm(false);
|
||||
setEditingJob(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Transaction Details */}
|
||||
{selectedJob && (
|
||||
<div className="mt-8 space-y-4">
|
||||
<Card className="bg-gray-900 border-gray-700 text-white">
|
||||
<CardHeader>
|
||||
<CardTitle>Transactions for {selectedJob.outputItem}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<TransactionForm
|
||||
jobId={selectedJob.id}
|
||||
onTransactionsAdded={handleTransactionsAdded}
|
||||
/>
|
||||
<TransactionTable
|
||||
title="Transactions"
|
||||
transactions={[
|
||||
...selectedJob.expenditures.map(tx => ({ ...tx, type: 'expenditure' as const })),
|
||||
...selectedJob.income.map(tx => ({ ...tx, type: 'income' as const }))
|
||||
]}
|
||||
type="expenditure"
|
||||
onUpdateTransaction={handleUpdateTransaction}
|
||||
onDeleteTransaction={handleDeleteTransaction}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Batch Transaction Form */}
|
||||
{showBatchForm && (
|
||||
<BatchTransactionForm
|
||||
jobs={jobs}
|
||||
|
||||
170
frontend/src/pages/JobDetails.tsx
Normal file
170
frontend/src/pages/JobDetails.tsx
Normal file
@@ -0,0 +1,170 @@
|
||||
|
||||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import JobCard from '@/components/JobCard';
|
||||
import TransactionForm from '@/components/TransactionForm';
|
||||
import TransactionTable from '@/components/TransactionTable';
|
||||
import JobForm from '@/components/JobForm';
|
||||
import { IndTransactionRecordNoId, IndJobRecordNoId, IndTransactionRecord } from '@/lib/pbtypes';
|
||||
import { useJobs, useJob } from '@/hooks/useDataService';
|
||||
import { useState } from 'react';
|
||||
import { IndJob } from '@/lib/types';
|
||||
|
||||
const JobDetails = () => {
|
||||
const { jobId } = useParams<{ jobId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const [showJobForm, setShowJobForm] = useState(false);
|
||||
const [editingJob, setEditingJob] = useState<IndJob | null>(null);
|
||||
|
||||
const {
|
||||
createMultipleTransactions,
|
||||
updateTransaction,
|
||||
deleteTransaction,
|
||||
updateJob,
|
||||
deleteJob
|
||||
} = useJobs();
|
||||
|
||||
const job = useJob(jobId || null);
|
||||
|
||||
if (!jobId) {
|
||||
navigate('/');
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!job) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-950 p-6 flex items-center justify-center">
|
||||
<div className="text-white">Job not found</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const handleEditJob = (job: IndJob) => {
|
||||
setEditingJob(job);
|
||||
setShowJobForm(true);
|
||||
};
|
||||
|
||||
const handleUpdateJob = async (jobData: IndJobRecordNoId) => {
|
||||
if (!editingJob) return;
|
||||
|
||||
try {
|
||||
await updateJob(editingJob.id, jobData);
|
||||
setShowJobForm(false);
|
||||
setEditingJob(null);
|
||||
} catch (error) {
|
||||
console.error('Error updating job:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteJob = async (jobId: string) => {
|
||||
if (confirm('Are you sure you want to delete this job?')) {
|
||||
try {
|
||||
await deleteJob(jobId);
|
||||
navigate('/');
|
||||
} catch (error) {
|
||||
console.error('Error deleting job:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleTransactionsAdded = async (transactions: IndTransactionRecordNoId[], type: 'expenditure' | 'income') => {
|
||||
try {
|
||||
await createMultipleTransactions(jobId, transactions, type);
|
||||
} catch (error) {
|
||||
console.error('Error adding transactions:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateTransaction = async (transactionId: string, updates: Partial<IndTransactionRecord>) => {
|
||||
try {
|
||||
await updateTransaction(jobId, transactionId, updates);
|
||||
} catch (error) {
|
||||
console.error('Error updating transaction:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteTransaction = async (transactionId: string) => {
|
||||
try {
|
||||
await deleteTransaction(jobId, transactionId);
|
||||
} catch (error) {
|
||||
console.error('Error deleting transaction:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateProduced = async (jobId: string, produced: number) => {
|
||||
try {
|
||||
await updateJob(jobId, { produced });
|
||||
} catch (error) {
|
||||
console.error('Error updating produced quantity:', error);
|
||||
}
|
||||
};
|
||||
|
||||
if (showJobForm) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-950 p-6">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<JobForm
|
||||
job={editingJob || undefined}
|
||||
onSubmit={handleUpdateJob}
|
||||
onCancel={() => {
|
||||
setShowJobForm(false);
|
||||
setEditingJob(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-950 p-6">
|
||||
<div className="max-w-7xl mx-auto space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-white">Job Details</h1>
|
||||
<p className="text-gray-400">{job.outputItem}</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate('/')}
|
||||
className="border-gray-600 hover:bg-gray-800"
|
||||
>
|
||||
Back to Jobs
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<JobCard
|
||||
job={job}
|
||||
onEdit={handleEditJob}
|
||||
onDelete={handleDeleteJob}
|
||||
onUpdateProduced={handleUpdateProduced}
|
||||
/>
|
||||
<TransactionForm
|
||||
jobId={job.id}
|
||||
onTransactionsAdded={handleTransactionsAdded}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<TransactionTable
|
||||
title="Expenditures"
|
||||
transactions={job.expenditures}
|
||||
type="expenditure"
|
||||
onUpdateTransaction={handleUpdateTransaction}
|
||||
onDeleteTransaction={handleDeleteTransaction}
|
||||
/>
|
||||
<TransactionTable
|
||||
title="Income"
|
||||
transactions={job.income}
|
||||
type="income"
|
||||
onUpdateTransaction={handleUpdateTransaction}
|
||||
onDeleteTransaction={handleDeleteTransaction}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default JobDetails;
|
||||
250
frontend/src/services/dataService.ts
Normal file
250
frontend/src/services/dataService.ts
Normal file
@@ -0,0 +1,250 @@
|
||||
|
||||
|
||||
import { IndJob } from '@/lib/types';
|
||||
import { IndJobRecord, IndJobRecordNoId, IndTransactionRecord, IndTransactionRecordNoId, IndBillitemRecord, IndBillitemRecordNoId } from '@/lib/pbtypes';
|
||||
import * as jobService from './jobService';
|
||||
import * as transactionService from './transactionService';
|
||||
import * as billItemService from './billItemService';
|
||||
|
||||
export class DataService {
|
||||
private static instance: DataService;
|
||||
private jobs: IndJob[] = [];
|
||||
private listeners: Set<() => void> = new Set();
|
||||
|
||||
private constructor() { }
|
||||
|
||||
static getInstance(): DataService {
|
||||
if (!DataService.instance) {
|
||||
DataService.instance = new DataService();
|
||||
}
|
||||
return DataService.instance;
|
||||
}
|
||||
|
||||
subscribe(listener: () => void) {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
private notifyListeners() {
|
||||
this.listeners.forEach(listener => listener());
|
||||
}
|
||||
|
||||
getJobs(): IndJob[] {
|
||||
return [...this.jobs];
|
||||
}
|
||||
|
||||
getJob(id: string): IndJob | null {
|
||||
return this.jobs.find(job => job.id === id) || null;
|
||||
}
|
||||
|
||||
async loadJobs(): Promise<IndJob[]> {
|
||||
console.log('Loading jobs from database');
|
||||
this.jobs = await jobService.getJobs();
|
||||
this.notifyListeners();
|
||||
return this.getJobs();
|
||||
}
|
||||
|
||||
async createJob(jobData: IndJobRecordNoId): Promise<IndJob> {
|
||||
console.log('Creating job:', jobData);
|
||||
const newJob = await jobService.createJob(jobData);
|
||||
this.jobs.push(newJob);
|
||||
this.notifyListeners();
|
||||
return newJob;
|
||||
}
|
||||
|
||||
async updateJob(id: string, updates: Partial<IndJobRecord>): Promise<IndJob> {
|
||||
console.log('Updating job:', id, updates);
|
||||
const updatedRecord = await jobService.updateJob(id, updates);
|
||||
|
||||
const jobIndex = this.jobs.findIndex(job => job.id === id);
|
||||
if (jobIndex !== -1) {
|
||||
this.jobs[jobIndex] = updatedRecord;
|
||||
this.notifyListeners();
|
||||
return this.jobs[jobIndex];
|
||||
}
|
||||
|
||||
throw new Error(`Job with id ${id} not found in local state`);
|
||||
}
|
||||
|
||||
async deleteJob(id: string): Promise<void> {
|
||||
console.log('Deleting job:', id);
|
||||
await jobService.deleteJob(id);
|
||||
|
||||
this.jobs = this.jobs.filter(job => job.id !== id);
|
||||
this.notifyListeners();
|
||||
}
|
||||
|
||||
async createTransaction(jobId: string, transaction: IndTransactionRecordNoId, type: 'expenditure' | 'income'): Promise<IndJob> {
|
||||
console.log('Creating transaction for job:', jobId, transaction, type);
|
||||
|
||||
const job = this.getJob(jobId);
|
||||
if (!job) throw new Error(`Job with id ${jobId} not found`);
|
||||
|
||||
// Create the transaction in the database
|
||||
transaction.job = jobId;
|
||||
const createdTransaction = await transactionService.createTransaction(job, transaction);
|
||||
|
||||
// Update the job's transaction references in the database
|
||||
const field = type === 'expenditure' ? 'expenditures' : 'income';
|
||||
const currentIds = (job[field] || []).map(tr => tr.id);
|
||||
await jobService.updateJob(jobId, {
|
||||
[field]: [...currentIds, createdTransaction.id]
|
||||
});
|
||||
|
||||
// Update local state without re-fetching
|
||||
const jobIndex = this.jobs.findIndex(j => j.id === jobId);
|
||||
if (jobIndex !== -1) {
|
||||
if (type === 'expenditure') {
|
||||
this.jobs[jobIndex].expenditures.push(createdTransaction);
|
||||
} else {
|
||||
this.jobs[jobIndex].income.push(createdTransaction);
|
||||
}
|
||||
this.notifyListeners();
|
||||
return this.jobs[jobIndex];
|
||||
}
|
||||
|
||||
throw new Error(`Job with id ${jobId} not found in local state`);
|
||||
}
|
||||
|
||||
async createMultipleTransactions(jobId: string, transactions: IndTransactionRecordNoId[], type: 'expenditure' | 'income'): Promise<IndJob> {
|
||||
console.log('Creating multiple transactions for job:', jobId, transactions.length, type);
|
||||
|
||||
const job = this.getJob(jobId);
|
||||
if (!job) throw new Error(`Job with id ${jobId} not found`);
|
||||
|
||||
const createdTransactions: IndTransactionRecord[] = [];
|
||||
|
||||
// Create all transactions
|
||||
for (const transaction of transactions) {
|
||||
transaction.job = jobId;
|
||||
const createdTransaction = await transactionService.createTransaction(job, transaction);
|
||||
createdTransactions.push(createdTransaction);
|
||||
}
|
||||
|
||||
// Update the job's transaction references in one database call
|
||||
const field = type === 'expenditure' ? 'expenditures' : 'income';
|
||||
const currentIds = (job[field] || []).map(tr => tr.id);
|
||||
const newIds = createdTransactions.map(tr => tr.id);
|
||||
await jobService.updateJob(jobId, {
|
||||
[field]: [...currentIds, ...newIds]
|
||||
});
|
||||
|
||||
// Update local state
|
||||
const jobIndex = this.jobs.findIndex(j => j.id === jobId);
|
||||
if (jobIndex !== -1) {
|
||||
if (type === 'expenditure') {
|
||||
this.jobs[jobIndex].expenditures.push(...createdTransactions);
|
||||
} else {
|
||||
this.jobs[jobIndex].income.push(...createdTransactions);
|
||||
}
|
||||
this.notifyListeners();
|
||||
return this.jobs[jobIndex];
|
||||
}
|
||||
|
||||
throw new Error(`Job with id ${jobId} not found in local state`);
|
||||
}
|
||||
|
||||
async updateTransaction(jobId: string, transactionId: string, updates: Partial<IndTransactionRecord>): Promise<IndJob> {
|
||||
console.log('Updating transaction:', transactionId, updates);
|
||||
|
||||
const job = this.getJob(jobId);
|
||||
if (!job) throw new Error(`Job with id ${jobId} not found`);
|
||||
|
||||
const updatedTransaction = await transactionService.updateTransaction(job, transactionId, updates);
|
||||
|
||||
// Update local state
|
||||
const jobIndex = this.jobs.findIndex(j => j.id === jobId);
|
||||
if (jobIndex !== -1) {
|
||||
this.jobs[jobIndex].expenditures = this.jobs[jobIndex].expenditures.map(tx =>
|
||||
tx.id === transactionId ? updatedTransaction : tx
|
||||
);
|
||||
this.jobs[jobIndex].income = this.jobs[jobIndex].income.map(tx =>
|
||||
tx.id === transactionId ? updatedTransaction : tx
|
||||
);
|
||||
this.notifyListeners();
|
||||
return this.jobs[jobIndex];
|
||||
}
|
||||
|
||||
throw new Error(`Job with id ${jobId} not found in local state`);
|
||||
}
|
||||
|
||||
async deleteTransaction(jobId: string, transactionId: string): Promise<IndJob> {
|
||||
console.log('Deleting transaction:', transactionId);
|
||||
|
||||
const job = this.getJob(jobId);
|
||||
if (!job) throw new Error(`Job with id ${jobId} not found`);
|
||||
|
||||
await transactionService.deleteTransaction(job, transactionId);
|
||||
|
||||
// Update local state
|
||||
const jobIndex = this.jobs.findIndex(j => j.id === jobId);
|
||||
if (jobIndex !== -1) {
|
||||
this.jobs[jobIndex].expenditures = this.jobs[jobIndex].expenditures.filter(tx => tx.id !== transactionId);
|
||||
this.jobs[jobIndex].income = this.jobs[jobIndex].income.filter(tx => tx.id !== transactionId);
|
||||
this.notifyListeners();
|
||||
return this.jobs[jobIndex];
|
||||
}
|
||||
|
||||
throw new Error(`Job with id ${jobId} not found in local state`);
|
||||
}
|
||||
|
||||
async createBillItem(jobId: string, billItem: IndBillitemRecordNoId, type: 'billOfMaterials' | 'consumedMaterials'): Promise<IndJob> {
|
||||
console.log('Creating bill item for job:', jobId, billItem, type);
|
||||
|
||||
const job = this.getJob(jobId);
|
||||
if (!job) throw new Error(`Job with id ${jobId} not found`);
|
||||
|
||||
const createdBillItem = await billItemService.addBillItem(jobId, billItem);
|
||||
|
||||
// Update the job's bill item references
|
||||
const currentIds = (job[type] || []).map(item => item.id);
|
||||
await jobService.updateJob(jobId, {
|
||||
[type]: [...currentIds, createdBillItem.id]
|
||||
});
|
||||
|
||||
// Update local state
|
||||
const jobIndex = this.jobs.findIndex(j => j.id === jobId);
|
||||
if (jobIndex !== -1) {
|
||||
this.jobs[jobIndex][type].push(createdBillItem);
|
||||
this.notifyListeners();
|
||||
return this.jobs[jobIndex];
|
||||
}
|
||||
|
||||
throw new Error(`Job with id ${jobId} not found in local state`);
|
||||
}
|
||||
|
||||
async createMultipleBillItems(jobId: string, billItems: IndBillitemRecordNoId[], type: 'billOfMaterials' | 'consumedMaterials'): Promise<IndJob> {
|
||||
console.log('Creating multiple bill items for job:', jobId, billItems.length, type);
|
||||
|
||||
const job = this.getJob(jobId);
|
||||
if (!job) throw new Error(`Job with id ${jobId} not found`);
|
||||
|
||||
const createdBillItems: IndBillitemRecord[] = [];
|
||||
|
||||
// Create all bill items
|
||||
for (const billItem of billItems) {
|
||||
const createdBillItem = await billItemService.addBillItem(jobId, billItem);
|
||||
createdBillItems.push(createdBillItem);
|
||||
}
|
||||
|
||||
// Update the job's bill item references in one database call
|
||||
const currentIds = (job[type] || []).map(item => item.id);
|
||||
const newIds = createdBillItems.map(item => item.id);
|
||||
await jobService.updateJob(jobId, {
|
||||
[type]: [...currentIds, ...newIds]
|
||||
});
|
||||
|
||||
// Update local state
|
||||
const jobIndex = this.jobs.findIndex(j => j.id === jobId);
|
||||
if (jobIndex !== -1) {
|
||||
this.jobs[jobIndex][type].push(...createdBillItems);
|
||||
this.notifyListeners();
|
||||
return this.jobs[jobIndex];
|
||||
}
|
||||
|
||||
throw new Error(`Job with id ${jobId} not found in local state`);
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton instance
|
||||
export const dataService = DataService.getInstance();
|
||||
@@ -1,118 +1,61 @@
|
||||
|
||||
import { IndJob } from '@/lib/types';
|
||||
import type { IndJobRecord, IndTransactionRecord, IndBillitemRecord, IndJobRecordNoId } from '../lib/pbtypes';
|
||||
import type { IndJobRecord, IndJobRecordNoId } from '../lib/pbtypes';
|
||||
import pb from '../lib/pocketbase';
|
||||
|
||||
export type { IndJobRecord as Job } from '../lib/pbtypes';
|
||||
export type { IndTransactionRecord as Transaction } from '../lib/pbtypes';
|
||||
export type { IndBillitemRecord as BillItem } from '../lib/pbtypes';
|
||||
|
||||
export async function createJob(job: IndJobRecordNoId): Promise<IndJobRecord> {
|
||||
export async function createJob(job: IndJobRecordNoId): Promise<IndJob> {
|
||||
console.log('Creating job:', job);
|
||||
return await pb.collection<IndJobRecord>('ind_job').create(job);
|
||||
const newJob = await pb.collection<IndJobRecord>('ind_job').create(job)
|
||||
return await getJob(newJob.id);
|
||||
}
|
||||
|
||||
export async function getJobs(): Promise<IndJobRecord[]> {
|
||||
const expand = 'billOfMaterials,consumedMaterials,expenditures,income';
|
||||
|
||||
export async function getJobs(): Promise<IndJob[]> {
|
||||
console.log('Getting jobs');
|
||||
const result = await pb.collection<IndJobRecord>('ind_job').getFullList();
|
||||
return result;
|
||||
}
|
||||
export async function getJobsFull(): Promise<IndJob[]> {
|
||||
const jobs = await getJobs();
|
||||
console.log('Jobs:', jobs);
|
||||
return await Promise.all(jobs.map(toFullJob));
|
||||
// const result = await pb.collection<IndJobRecord>('ind_job').getFullList();
|
||||
const result = await pb.collection('ind_job').getFullList(10000, { expand });
|
||||
const jobs: IndJob[] = [];
|
||||
for (const job of result) {
|
||||
jobs.push({
|
||||
...job,
|
||||
billOfMaterials: job.expand["billOfMaterials"] || [],
|
||||
consumedMaterials: job.expand["consumedMaterials"] || [],
|
||||
expenditures: job.expand["expenditures"] || [],
|
||||
income: job.expand["income"] || []
|
||||
});
|
||||
}
|
||||
return jobs;
|
||||
}
|
||||
|
||||
export async function getJob(id: string): Promise<IndJobRecord | null> {
|
||||
export async function getJob(id: string): Promise<IndJob | null> {
|
||||
console.log('Getting job:', id);
|
||||
try {
|
||||
return await pb.collection<IndJobRecord>('ind_job').getOne(id);
|
||||
const job = await pb.collection('ind_job').getOne(id, { expand });
|
||||
return {
|
||||
...job,
|
||||
billOfMaterials: job.expand["billOfMaterials"] || [],
|
||||
consumedMaterials: job.expand["consumedMaterials"] || [],
|
||||
expenditures: job.expand["expenditures"] || [],
|
||||
income: job.expand["income"] || []
|
||||
};
|
||||
} catch (e) {
|
||||
if (e.status === 404) return null;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
export async function getJobFull(id: string): Promise<IndJob | null> {
|
||||
console.log('Getting job full:', id);
|
||||
const job = await getJob(id);
|
||||
if (!job) return null;
|
||||
return await toFullJob(job);
|
||||
}
|
||||
|
||||
export async function updateJob(id: string, updates: Partial<IndJobRecord>): Promise<IndJobRecord> {
|
||||
export async function updateJob(id: string, updates: Partial<IndJobRecord>): Promise<IndJob> {
|
||||
console.log('Updating job:', id, updates);
|
||||
return await pb.collection<IndJobRecord>('ind_job').update(id, updates);
|
||||
await pb.collection<IndJobRecord>('ind_job').update(id, updates)
|
||||
return getJob(id);
|
||||
}
|
||||
|
||||
export async function deleteJob(id: string): Promise<void> {
|
||||
console.log('Deleting job:', id);
|
||||
await pb.collection<IndJobRecord>('ind_job').delete(id);
|
||||
}
|
||||
|
||||
async function toFullJob(job: IndJobRecord): Promise<IndJob> {
|
||||
console.log('Converting job to full job:', job);
|
||||
const fullJob = {
|
||||
...job,
|
||||
expenditures: [],
|
||||
income: [],
|
||||
billOfMaterials: [],
|
||||
consumedMaterials: []
|
||||
};
|
||||
|
||||
if (job.expenditures) {
|
||||
for (const txId of job.expenditures) {
|
||||
try {
|
||||
const tx = await pb.collection('ind_transaction').getOne(txId);
|
||||
fullJob.expenditures.push(tx as IndTransactionRecord);
|
||||
} catch (e) {
|
||||
console.warn('Failed to fetch expenditure transaction:', txId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (job.income) {
|
||||
for (const txId of job.income) {
|
||||
try {
|
||||
const tx = await pb.collection('ind_transaction').getOne(txId);
|
||||
fullJob.income.push(tx as IndTransactionRecord);
|
||||
} catch (e) {
|
||||
console.warn('Failed to fetch income transaction:', txId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (job.billOfMaterials) {
|
||||
for (const itemId of job.billOfMaterials) {
|
||||
try {
|
||||
const item = await pb.collection('ind_billItem').getOne(itemId);
|
||||
fullJob.billOfMaterials.push(item as IndBillitemRecord);
|
||||
} catch (e) {
|
||||
console.warn('Failed to fetch bill item:', itemId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (job.consumedMaterials) {
|
||||
for (const itemId of job.consumedMaterials) {
|
||||
try {
|
||||
const item = await pb.collection('ind_billItem').getOne(itemId);
|
||||
fullJob.consumedMaterials.push(item as IndBillitemRecord);
|
||||
} catch (e) {
|
||||
console.warn('Failed to fetch consumed material:', itemId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fullJob;
|
||||
}
|
||||
|
||||
async function toHollowJob(job: IndJob): Promise<IndJobRecord> {
|
||||
console.log('Converting job to hollow job:', job);
|
||||
return {
|
||||
...job,
|
||||
expenditures: job.expenditures.map(tx => tx.id),
|
||||
income: job.income.map(tx => tx.id),
|
||||
billOfMaterials: job.billOfMaterials.map(item => item.id),
|
||||
consumedMaterials: job.consumedMaterials.map(item => item.id)
|
||||
};
|
||||
}
|
||||
@@ -1,44 +1,28 @@
|
||||
|
||||
import { IndJob } from '@/lib/types';
|
||||
import type { IndTransactionRecord, IndTransactionRecordNoId } from '../lib/pbtypes';
|
||||
import pb from '../lib/pocketbase';
|
||||
import { getJob, updateJob } from './jobService';
|
||||
import { updateJob } from './jobService';
|
||||
|
||||
export async function createTransaction(
|
||||
job: IndJob,
|
||||
transaction: IndTransactionRecordNoId,
|
||||
type: 'expenditure' | 'income'
|
||||
): Promise<IndJob> {
|
||||
): Promise<IndTransactionRecord> {
|
||||
console.log('Creating transaction:', transaction);
|
||||
// Create the transaction
|
||||
transaction.job = job.id;
|
||||
const createdTransaction = await pb.collection<IndTransactionRecord>('ind_transaction').create(transaction);
|
||||
|
||||
// Update the job to include the new transaction
|
||||
const field = type === 'expenditure' ? 'expenditures' : 'income';
|
||||
const currentIds = (job[field] || []).map(tr => tr.id);
|
||||
|
||||
await updateJob(job.id, {
|
||||
[field]: [...currentIds, createdTransaction.id]
|
||||
});
|
||||
|
||||
if (type === 'expenditure') {
|
||||
job.expenditures.push(createdTransaction);
|
||||
} else {
|
||||
job.income.push(createdTransaction);
|
||||
}
|
||||
return job;
|
||||
return createdTransaction;
|
||||
}
|
||||
|
||||
export async function updateTransaction(
|
||||
job: IndJob,
|
||||
transactionId: string,
|
||||
updates: Partial<IndTransactionRecord>
|
||||
): Promise<IndJob> {
|
||||
): Promise<IndTransactionRecord> {
|
||||
console.log('Updating transaction:', transactionId, updates);
|
||||
const updatedTransaction = await pb.collection<IndTransactionRecord>('ind_transaction').update(transactionId, updates);
|
||||
job.expenditures = job.expenditures.map(exp => exp.id === transactionId ? updatedTransaction : exp);
|
||||
job.income = job.income.map(inc => inc.id === transactionId ? updatedTransaction : inc);
|
||||
return job;
|
||||
return updatedTransaction;
|
||||
}
|
||||
|
||||
export async function deleteTransaction(job: IndJob, transactionId: string): Promise<void> {
|
||||
|
||||
Reference in New Issue
Block a user