['nullable', 'string', 'max:50'], 'note' => ['nullable', 'string', 'max:100'], 'purchase_date' => ['required', 'date', 'before_or_equal:today'], 'warehouse_id' => ['required', Rule::exists('warehouses', 'id')], 'total' => ['required', new UnsignedInteger], 'image' => ['nullable', 'array', 'max:1'], ]; } public function validationAttributes(): array { return [ 'invoice_number' => 'nomor invoice', 'note' => 'catatan', 'purchase_date' => 'tanggal belanja', 'warehouse_id' => 'gudang', 'image' => 'gambar', ]; } public function setPurchase(Purchase $purchase): void { $this->purchase = $purchase; $this->invoice_number = $purchase->invoice_number; $this->note = $purchase->note; $this->purchase_date = $purchase->purchase_date; $this->warehouse_id = $purchase->warehouse_id; $this->total = $purchase->total; $this->image = $this->mapMediaCollection($purchase->getMedia('image')); } public function store(): void { $this->validate(); $purchaseItems = $this->loadPurchaseItems(); // Recalculate total to ensure data integrity $calculatedTotal = $purchaseItems->sum(function ($item) { return $item->unit_price * $item->quantity; }); // Override the total input with the calculated one to prevent mismatches $this->total = formatCurrencyNumber($calculatedTotal); DB::transaction(function () use ($purchaseItems, $calculatedTotal) { $data = $this->prepareSavedData(); $data['total'] = $calculatedTotal; // Use strict calculated total $purchase = Purchase::create($data); $purchase->load('warehouse'); $this->uploadMedia($this->image, $purchase, 'image'); foreach ($purchaseItems as $item) { // Ensure item integrity before linking if ($item->quantity <= 0 || $item->unit_price <= 0) { continue; // Or throw exception } $item->update(['purchase_id' => $purchase->id]); $this->increaseWarehouseStock($purchase->warehouse, $item); } }); } private function prepareSavedData(): array { return [ 'invoice_number' => $this->invoice_number, 'note' => $this->note, 'warehouse_id' => $this->warehouse_id, 'purchase_date' => $this->purchase_date, 'total' => parseRupiahToInt($this->total), ]; } }