Compare commits

..

2 Commits

5 changed files with 210 additions and 225 deletions

View File

@ -27,6 +27,7 @@ public function paginated(int $perPage = 25, string $search = '', string $sort =
{ {
$itemCountQuery = '(SELECT COUNT(*) FROM purchase_items WHERE purchase_items.purchase_id = purchases.id AND purchase_items.deleted_at IS NULL)'; $itemCountQuery = '(SELECT COUNT(*) FROM purchase_items WHERE purchase_items.purchase_id = purchases.id AND purchase_items.deleted_at IS NULL)';
$totalQtyQuery = '(SELECT IFNULL(SUM(quantity), 0) FROM purchase_items WHERE purchase_items.purchase_id = purchases.id AND purchase_items.deleted_at IS NULL)'; $totalQtyQuery = '(SELECT IFNULL(SUM(quantity), 0) FROM purchase_items WHERE purchase_items.purchase_id = purchases.id AND purchase_items.deleted_at IS NULL)';
$materialsCountQuery = '(SELECT COUNT(DISTINCT raw_materials.id) FROM purchase_items JOIN raw_material_prices ON raw_material_prices.id = purchase_items.raw_material_price_id JOIN raw_materials ON raw_materials.id = raw_material_prices.raw_material_id WHERE purchase_items.purchase_id = purchases.id AND purchase_items.deleted_at IS NULL)';
$materialNameQuery = '(SELECT raw_materials.name FROM purchase_items JOIN raw_material_prices ON raw_material_prices.id = purchase_items.raw_material_price_id JOIN raw_materials ON raw_materials.id = raw_material_prices.raw_material_id WHERE purchase_items.purchase_id = purchases.id AND purchase_items.deleted_at IS NULL LIMIT 1)'; $materialNameQuery = '(SELECT raw_materials.name FROM purchase_items JOIN raw_material_prices ON raw_material_prices.id = purchase_items.raw_material_price_id JOIN raw_materials ON raw_materials.id = raw_material_prices.raw_material_id WHERE purchase_items.purchase_id = purchases.id AND purchase_items.deleted_at IS NULL LIMIT 1)';
$unitQuery = '(SELECT raw_materials.unit FROM purchase_items JOIN raw_material_prices ON raw_material_prices.id = purchase_items.raw_material_price_id JOIN raw_materials ON raw_materials.id = raw_material_prices.raw_material_id WHERE purchase_items.purchase_id = purchases.id AND purchase_items.deleted_at IS NULL LIMIT 1)'; $unitQuery = '(SELECT raw_materials.unit FROM purchase_items JOIN raw_material_prices ON raw_material_prices.id = purchase_items.raw_material_price_id JOIN raw_materials ON raw_materials.id = raw_material_prices.raw_material_id WHERE purchase_items.purchase_id = purchases.id AND purchase_items.deleted_at IS NULL LIMIT 1)';
@ -39,6 +40,7 @@ public function paginated(int $perPage = 25, string $search = '', string $sort =
]) ])
->selectRaw("{$itemCountQuery} as variants_count") ->selectRaw("{$itemCountQuery} as variants_count")
->selectRaw("{$totalQtyQuery} as total_qty") ->selectRaw("{$totalQtyQuery} as total_qty")
->selectRaw("{$materialsCountQuery} as materials_count")
->selectRaw("{$materialNameQuery} as material_name") ->selectRaw("{$materialNameQuery} as material_name")
->selectRaw("{$unitQuery} as unit") ->selectRaw("{$unitQuery} as unit")
->when($highlight, fn ($q) => $q->where('id', $highlight)) ->when($highlight, fn ($q) => $q->where('id', $highlight))
@ -152,6 +154,10 @@ public function getForEdit(Purchase $purchase): array
fn ($media) => $this->s3Service->getTemporaryUrl($media->getPath()) fn ($media) => $this->s3Service->getTemporaryUrl($media->getPath())
)->toArray(); )->toArray();
$existingQuantities = $items->mapWithKeys(fn (PurchaseItem $item) => [
(int) $item->raw_material_price_id => (int) $item->quantity,
])->all();
return [ return [
'id' => $purchase->id, 'id' => $purchase->id,
'name' => $rawMaterial?->name ?? '', 'name' => $rawMaterial?->name ?? '',
@ -164,12 +170,8 @@ public function getForEdit(Purchase $purchase): array
'photo_urls' => $purchasePhotoUrls, 'photo_urls' => $purchasePhotoUrls,
'variants' => $variants, 'variants' => $variants,
'default_mode' => $singleMaterial && ! $sharedWithOther ? 'new' : 'existing', 'default_mode' => $singleMaterial && ! $sharedWithOther ? 'new' : 'existing',
'existing_material_name' => $singleMaterial ? $materials->first()->name : null, 'existing_material_name' => $materials->first()->name ?? null,
'existing_quantities' => $singleMaterial 'existing_quantities' => $existingQuantities,
? $items->mapWithKeys(fn (PurchaseItem $item) => [
(int) $item->raw_material_price_id => (int) $item->quantity,
])->all()
: [],
]; ];
} }

View File

@ -20,6 +20,7 @@ export type Purchase = {
photo_conversion_urls: string[]; photo_conversion_urls: string[];
created_at: string; created_at: string;
variants_count: number; variants_count: number;
materials_count: number;
total_qty: number; total_qty: number;
material_name: string | null; material_name: string | null;
unit: string | null; unit: string | null;

View File

@ -84,9 +84,6 @@ export default function PurchaseEdit({
}); });
const [uploading, setUploading] = useState(false); const [uploading, setUploading] = useState(false);
const [selectedMaterialName, setSelectedMaterialName] = useState(
purchase.existing_material_name ?? '',
);
const [quantities, setQuantities] = useState<Record<number, number>>(() => const [quantities, setQuantities] = useState<Record<number, number>>(() =>
Object.fromEntries( Object.fromEntries(
Object.entries(purchase.existing_quantities).map(([id, qty]) => [ Object.entries(purchase.existing_quantities).map(([id, qty]) => [
@ -132,10 +129,34 @@ export default function PurchaseEdit({
); );
const total = subtotal - discount + shippingCost; const total = subtotal - discount + shippingCost;
const selectedMaterial = useMemo( const purchasedVariantsByMaterial = useMemo(() => {
() => rawMaterials.find((m) => m.name === selectedMaterialName) ?? null, const map = new Map<string, { name: string; unit: string; items: { id: number; variant: string; price: number; stock: number; photo_url: string | null; photo_conversion_url: string | null }[] }>();
[rawMaterials, selectedMaterialName],
); for (const [priceId, quantity] of Object.entries(quantities)) {
const id = Number(priceId);
const price = priceMap.get(id);
const material = materialByPriceId.get(id);
if (!price || !material) continue;
if (!map.has(material.name)) {
map.set(material.name, { name: material.name, unit: material.unit, items: [] });
}
map.get(material.name)!.items.push({
id: price.id,
variant: price.variant,
price: price.price,
stock: price.stock,
photo_url: price.photo_url,
photo_conversion_url: price.photo_conversion_url,
});
}
return map;
}, [quantities, priceMap, materialByPriceId]);
const isMultiMaterial = purchasedVariantsByMaterial.size > 1;
const updateQuantity = useCallback((priceId: number, value: number) => { const updateQuantity = useCallback((priceId: number, value: number) => {
setQuantities((prev) => ({ setQuantities((prev) => ({
@ -241,182 +262,77 @@ export default function PurchaseEdit({
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<div className="grid gap-2"> {Array.from(purchasedVariantsByMaterial.entries()).map(([materialName, group]) => (
<Label> <div key={materialName} className="space-y-2">
Nama Bahan Baku{' '} {isMultiMaterial && (
<span className="text-destructive"> <p className="text-sm font-medium text-muted-foreground">
* {group.name} ({group.unit})
</span> </p>
</Label> )}
<Combobox {group.items.map((price) => (
items={rawMaterials} <div
itemToStringLabel={( key={price.id}
m, className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-primary p-3"
) => m.name} >
value={selectedMaterial} <div className="flex min-w-0 items-center gap-3">
onValueChange={( {price.photo_conversion_url ?? price.photo_url ? (
value, <img
) => src={price.photo_conversion_url ?? price.photo_url!}
setSelectedMaterialName( alt={price.variant}
value?.name ?? className="h-10 w-10 shrink-0 rounded-md object-cover"
'',
)
}
>
<ComboboxInput
placeholder="Cari bahan baku..."
className="w-full"
disabled
/>
<ComboboxContent>
<ComboboxEmpty>
Tidak ada bahan
baku ditemukan.
</ComboboxEmpty>
<ComboboxList>
{(m) => (
<ComboboxItem
key={
m.id
}
value={
m
}
>
{m.name}{' '}
(
{m.unit}
)
</ComboboxItem>
)}
</ComboboxList>
</ComboboxContent>
</Combobox>
<InputError
message={
errors.existing_items
}
/>
</div>
{selectedMaterial && (
<div className="space-y-2">
{selectedMaterial.raw_material_prices.map(
(price) => (
<div
key={
price.id
}
className={
(quantities[
price
.id
] ??
0) >
0
? 'flex flex-wrap items-center justify-between gap-2 rounded-lg border border-primary p-3'
: 'flex flex-wrap items-center justify-between gap-2 rounded-lg border p-3'
}
>
<div className="flex min-w-0 items-center gap-3">
{price.photo_conversion_url ?? price.photo_url ? (
<img
src={
price.photo_conversion_url ?? price.photo_url
}
alt={
price.variant
}
className="h-10 w-10 shrink-0 rounded-md object-cover"
/>
) : (
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-muted text-xs text-muted-foreground">
N/A
</div>
)}
<div className="min-w-0">
<p className="truncate font-medium">
{
price.variant
}
</p>
<p className="text-xs text-muted-foreground">
Stok:{' '}
{formatQuantity(
Number(
price.stock,
),
)}{' '}
{
selectedMaterial.unit
}{' '}
·{' '}
{formatCurrency(
price.price,
)}
</p>
</div>
</div>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="icon"
disabled={
!(
quantities[
price
.id
] ??
0
)
}
onClick={() =>
incrementQuantity(
price.id,
-1,
)
}
>
<Minus className="h-4 w-4" />
</Button>
<NumberInput
className="w-24 text-center"
value={
quantities[
price
.id
] ??
0
}
onValueChange={(
val,
) =>
updateQuantity(
price.id,
val,
)
}
/> />
<Button ) : (
type="button" <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-muted text-xs text-muted-foreground">
variant="outline" N/A
size="icon" </div>
onClick={() => )}
incrementQuantity( <div className="min-w-0">
price.id, <p className="truncate font-medium">
1, {price.variant}
) </p>
} <p className="text-xs text-muted-foreground">
> Stok:{' '}
<Plus className="h-4 w-4" /> {formatQuantity(Number(price.stock))}{' '}
</Button> {group.unit} · {formatCurrency(price.price)}
</p>
</div> </div>
</div> </div>
), <div className="flex items-center gap-2">
)} <Button
type="button"
variant="outline"
size="icon"
disabled={
(quantities[price.id] ?? 0) <= 0
}
onClick={() =>
incrementQuantity(price.id, -1)
}
>
<Minus className="h-4 w-4" />
</Button>
<NumberInput
className="w-24 text-center"
value={quantities[price.id] ?? 0}
onValueChange={(val) =>
updateQuantity(price.id, val)
}
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={() =>
incrementQuantity(price.id, 1)
}
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
))}
</div> </div>
)} ))}
</CardContent> </CardContent>
</Card> </Card>
</div> </div>

View File

@ -28,6 +28,7 @@ export function PurchaseCardRow({
const { can } = useCan(); const { can } = useCan();
const variantCount = purchase.variants_count ?? 0; const variantCount = purchase.variants_count ?? 0;
const totalQty = purchase.total_qty ?? 0; const totalQty = purchase.total_qty ?? 0;
const materialsCount = purchase.materials_count ?? 0;
const rawMaterialName = purchase.material_name ?? '-'; const rawMaterialName = purchase.material_name ?? '-';
const unit = purchase.unit ?? ''; const unit = purchase.unit ?? '';
@ -58,7 +59,11 @@ export function PurchaseCardRow({
</div> </div>
<div className="mt-1 text-xs text-muted-foreground"> <div className="mt-1 text-xs text-muted-foreground">
{rawMaterialName} {materialsCount > 1 ? (
<span>{materialsCount} bahan baku</span>
) : (
<span>{rawMaterialName}</span>
)}
{variantCount > 0 && ( {variantCount > 0 && (
<span className="ml-1"> <span className="ml-1">
({variantCount} varian) ({variantCount} varian)

View File

@ -9,6 +9,7 @@ import {
} from '@/components/ui/table'; } from '@/components/ui/table';
import { formatNumber } from '@/lib/format'; import { formatNumber } from '@/lib/format';
import { formatCurrency } from '@/lib/utils'; import { formatCurrency } from '@/lib/utils';
import { Fragment } from 'react';
import type { Purchase, PurchaseItemDetail } from './columns'; import type { Purchase, PurchaseItemDetail } from './columns';
export function PurchaseItemSubRow({ export function PurchaseItemSubRow({
@ -20,10 +21,31 @@ export function PurchaseItemSubRow({
items: PurchaseItemDetail[]; items: PurchaseItemDetail[];
isLoading: boolean; isLoading: boolean;
}) { }) {
const unit = purchase.unit ?? ''; const items = loadedItems ?? [];
const groupedByMaterial = items.reduce(
(acc, item) => {
const materialName = item.raw_material_price?.raw_material?.name ?? '-';
const unit = item.raw_material_price?.raw_material?.unit ?? '';
if (!acc[materialName]) {
acc[materialName] = { unit, items: [] };
}
acc[materialName].items.push(item);
return acc;
},
{} as Record<string, { unit: string; items: PurchaseItemDetail[] }>,
);
const materialEntries = Object.entries(groupedByMaterial);
const isMultiMaterial = materialEntries.length > 1;
let counter = 0;
return ( return (
<div className="space-y-4 overflow-x-auto"> <div className="overflow-x-auto rounded-md border">
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow> <TableRow>
@ -47,7 +69,7 @@ export function PurchaseItemSubRow({
Memuat item... Memuat item...
</TableCell> </TableCell>
</TableRow> </TableRow>
) : loadedItems.length === 0 ? ( ) : items.length === 0 ? (
<TableRow> <TableRow>
<TableCell <TableCell
colSpan={6} colSpan={6}
@ -57,42 +79,81 @@ export function PurchaseItemSubRow({
</TableCell> </TableCell>
</TableRow> </TableRow>
) : ( ) : (
loadedItems.map((item, index) => ( <>
<TableRow key={item.id}> {materialEntries.map(([materialName, group]) => {
<TableCell className="text-center"> const totalQty = group.items.reduce(
{index + 1} (sum, item) => sum + item.quantity,
</TableCell> 0,
<TableCell> );
{item.raw_material_price?.photo_url ? ( const totalSubtotal = group.items.reduce(
<ImagePreviewButton (sum, item) => sum + item.subtotal,
srcs={[ 0,
item.raw_material_price.photo_conversion_url ?? item.raw_material_price.photo_url, );
]}
modalSrc={item.raw_material_price.photo_url} return (
title={ <Fragment key={materialName}>
item.raw_material_price.variant {isMultiMaterial && (
} <TableRow>
/> <TableCell
) : ( colSpan={4}
<div className="flex h-10 w-10 items-center justify-center rounded-md bg-muted text-xs text-muted-foreground"> className="text-center font-medium text-muted-foreground bg-muted/20"
N/A >
</div> {materialName}
)} </TableCell>
</TableCell> <TableCell className="text-center font-medium text-muted-foreground bg-muted/20">
<TableCell> {formatNumber(totalQty)}{' '}
{item.raw_material_price?.variant ?? '-'} {group.unit}
</TableCell> </TableCell>
<TableCell className="text-right"> <TableCell className="text-right font-medium text-muted-foreground bg-muted/20">
{formatCurrency(item.unit_price)} {formatCurrency(totalSubtotal)}
</TableCell> </TableCell>
<TableCell className="text-center"> </TableRow>
{formatNumber(item.quantity)} {unit} )}
</TableCell> {group.items.map((item) => {
<TableCell className="text-right font-medium"> counter++;
{formatCurrency(item.subtotal)}
</TableCell> return (
</TableRow> <TableRow key={item.id}>
)) <TableCell className="text-center">
{counter}
</TableCell>
<TableCell>
{item.raw_material_price?.photo_url ? (
<ImagePreviewButton
srcs={[
item.raw_material_price.photo_conversion_url ?? item.raw_material_price.photo_url,
]}
modalSrc={item.raw_material_price.photo_url}
title={
item.raw_material_price.variant
}
/>
) : (
<div className="flex h-10 w-10 items-center justify-center rounded-md bg-muted text-xs text-muted-foreground">
N/A
</div>
)}
</TableCell>
<TableCell>
{item.raw_material_price?.variant ?? '-'}
</TableCell>
<TableCell className="text-right">
{formatCurrency(item.unit_price)}
</TableCell>
<TableCell className="text-center">
{formatNumber(item.quantity)}{' '}
{group.unit}
</TableCell>
<TableCell className="text-right font-medium">
{formatCurrency(item.subtotal)}
</TableCell>
</TableRow>
);
})}
</Fragment>
);
})}
</>
)} )}
</TableBody> </TableBody>
</Table> </Table>