Compare commits

..

No commits in common. "cd944403bd2b84137d165c09daea9dab51aff976" and "0908576ef20f0c39f33076df194ec7be4365289f" have entirely different histories.

5 changed files with 225 additions and 210 deletions

View File

@ -27,7 +27,6 @@ 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)';
@ -40,7 +39,6 @@ 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))
@ -154,10 +152,6 @@ 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 ?? '',
@ -170,8 +164,12 @@ 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' => $materials->first()->name ?? null, 'existing_material_name' => $singleMaterial ? $materials->first()->name : null,
'existing_quantities' => $existingQuantities, 'existing_quantities' => $singleMaterial
? $items->mapWithKeys(fn (PurchaseItem $item) => [
(int) $item->raw_material_price_id => (int) $item->quantity,
])->all()
: [],
]; ];
} }

View File

@ -20,7 +20,6 @@ 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,6 +84,9 @@ 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]) => [
@ -129,34 +132,10 @@ export default function PurchaseEdit({
); );
const total = subtotal - discount + shippingCost; const total = subtotal - discount + shippingCost;
const purchasedVariantsByMaterial = useMemo(() => { const selectedMaterial = useMemo(
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.find((m) => m.name === selectedMaterialName) ?? 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) => ({
@ -262,23 +241,92 @@ export default function PurchaseEdit({
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
{Array.from(purchasedVariantsByMaterial.entries()).map(([materialName, group]) => ( <div className="grid gap-2">
<div key={materialName} className="space-y-2"> <Label>
{isMultiMaterial && ( Nama Bahan Baku{' '}
<p className="text-sm font-medium text-muted-foreground"> <span className="text-destructive">
{group.name} ({group.unit}) *
</p> </span>
</Label>
<Combobox
items={rawMaterials}
itemToStringLabel={(
m,
) => m.name}
value={selectedMaterial}
onValueChange={(
value,
) =>
setSelectedMaterialName(
value?.name ??
'',
)
}
>
<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>
)} )}
{group.items.map((price) => ( </ComboboxList>
</ComboboxContent>
</Combobox>
<InputError
message={
errors.existing_items
}
/>
</div>
{selectedMaterial && (
<div className="space-y-2">
{selectedMaterial.raw_material_prices.map(
(price) => (
<div <div
key={price.id} key={
className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-primary p-3" 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"> <div className="flex min-w-0 items-center gap-3">
{price.photo_conversion_url ?? price.photo_url ? ( {price.photo_conversion_url ?? price.photo_url ? (
<img <img
src={price.photo_conversion_url ?? price.photo_url!} src={
alt={price.variant} price.photo_conversion_url ?? price.photo_url
}
alt={
price.variant
}
className="h-10 w-10 shrink-0 rounded-md object-cover" className="h-10 w-10 shrink-0 rounded-md object-cover"
/> />
) : ( ) : (
@ -288,12 +336,24 @@ export default function PurchaseEdit({
)} )}
<div className="min-w-0"> <div className="min-w-0">
<p className="truncate font-medium"> <p className="truncate font-medium">
{price.variant} {
price.variant
}
</p> </p>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Stok:{' '} Stok:{' '}
{formatQuantity(Number(price.stock))}{' '} {formatQuantity(
{group.unit} · {formatCurrency(price.price)} Number(
price.stock,
),
)}{' '}
{
selectedMaterial.unit
}{' '}
·{' '}
{formatCurrency(
price.price,
)}
</p> </p>
</div> </div>
</div> </div>
@ -303,19 +363,39 @@ export default function PurchaseEdit({
variant="outline" variant="outline"
size="icon" size="icon"
disabled={ disabled={
(quantities[price.id] ?? 0) <= 0 !(
quantities[
price
.id
] ??
0
)
} }
onClick={() => onClick={() =>
incrementQuantity(price.id, -1) incrementQuantity(
price.id,
-1,
)
} }
> >
<Minus className="h-4 w-4" /> <Minus className="h-4 w-4" />
</Button> </Button>
<NumberInput <NumberInput
className="w-24 text-center" className="w-24 text-center"
value={quantities[price.id] ?? 0} value={
onValueChange={(val) => quantities[
updateQuantity(price.id, val) price
.id
] ??
0
}
onValueChange={(
val,
) =>
updateQuantity(
price.id,
val,
)
} }
/> />
<Button <Button
@ -323,16 +403,20 @@ export default function PurchaseEdit({
variant="outline" variant="outline"
size="icon" size="icon"
onClick={() => onClick={() =>
incrementQuantity(price.id, 1) incrementQuantity(
price.id,
1,
)
} }
> >
<Plus className="h-4 w-4" /> <Plus className="h-4 w-4" />
</Button> </Button>
</div> </div>
</div> </div>
))} ),
)}
</div> </div>
))} )}
</CardContent> </CardContent>
</Card> </Card>
</div> </div>

View File

@ -28,7 +28,6 @@ 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 ?? '';
@ -59,11 +58,7 @@ export function PurchaseCardRow({
</div> </div>
<div className="mt-1 text-xs text-muted-foreground"> <div className="mt-1 text-xs text-muted-foreground">
{materialsCount > 1 ? ( {rawMaterialName}
<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,7 +9,6 @@ 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({
@ -21,31 +20,10 @@ export function PurchaseItemSubRow({
items: PurchaseItemDetail[]; items: PurchaseItemDetail[];
isLoading: boolean; isLoading: boolean;
}) { }) {
const items = loadedItems ?? []; const unit = purchase.unit ?? '';
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="overflow-x-auto rounded-md border"> <div className="space-y-4 overflow-x-auto">
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow> <TableRow>
@ -69,7 +47,7 @@ export function PurchaseItemSubRow({
Memuat item... Memuat item...
</TableCell> </TableCell>
</TableRow> </TableRow>
) : items.length === 0 ? ( ) : loadedItems.length === 0 ? (
<TableRow> <TableRow>
<TableCell <TableCell
colSpan={6} colSpan={6}
@ -79,43 +57,10 @@ export function PurchaseItemSubRow({
</TableCell> </TableCell>
</TableRow> </TableRow>
) : ( ) : (
<> loadedItems.map((item, index) => (
{materialEntries.map(([materialName, group]) => {
const totalQty = group.items.reduce(
(sum, item) => sum + item.quantity,
0,
);
const totalSubtotal = group.items.reduce(
(sum, item) => sum + item.subtotal,
0,
);
return (
<Fragment key={materialName}>
{isMultiMaterial && (
<TableRow>
<TableCell
colSpan={4}
className="text-center font-medium text-muted-foreground bg-muted/20"
>
{materialName}
</TableCell>
<TableCell className="text-center font-medium text-muted-foreground bg-muted/20">
{formatNumber(totalQty)}{' '}
{group.unit}
</TableCell>
<TableCell className="text-right font-medium text-muted-foreground bg-muted/20">
{formatCurrency(totalSubtotal)}
</TableCell>
</TableRow>
)}
{group.items.map((item) => {
counter++;
return (
<TableRow key={item.id}> <TableRow key={item.id}>
<TableCell className="text-center"> <TableCell className="text-center">
{counter} {index + 1}
</TableCell> </TableCell>
<TableCell> <TableCell>
{item.raw_material_price?.photo_url ? ( {item.raw_material_price?.photo_url ? (
@ -141,19 +86,13 @@ export function PurchaseItemSubRow({
{formatCurrency(item.unit_price)} {formatCurrency(item.unit_price)}
</TableCell> </TableCell>
<TableCell className="text-center"> <TableCell className="text-center">
{formatNumber(item.quantity)}{' '} {formatNumber(item.quantity)} {unit}
{group.unit}
</TableCell> </TableCell>
<TableCell className="text-right font-medium"> <TableCell className="text-right font-medium">
{formatCurrency(item.subtotal)} {formatCurrency(item.subtotal)}
</TableCell> </TableCell>
</TableRow> </TableRow>
); ))
})}
</Fragment>
);
})}
</>
)} )}
</TableBody> </TableBody>
</Table> </Table>