Compare commits

..

No commits in common. "d5f2a66a142283caf98343f26d482cc897dd315e" and "71a7863244a535b5c1d2ee8c6862f4b2ad840806" have entirely different histories.

16 changed files with 38 additions and 540 deletions

View File

@ -225,8 +225,8 @@ ### `purchase_items` → PurchaseItem
- Relations: purchase(BelongsTo→Purchase), rawMaterialPrice(BelongsTo→RawMaterialPrice,withTrashed), user(BelongsTo→User) - Relations: purchase(BelongsTo→Purchase), rawMaterialPrice(BelongsTo→RawMaterialPrice,withTrashed), user(BelongsTo→User)
### `restocks` → Restock ### `restocks` → Restock
`id` `created_by_id`(FK→users) `total`(ubig) `notes`(100,null) `stock_type`(enum,default:good) `created_at` `updated_at` `deleted_at` `id` `created_by_id`(FK→users) `subtotal`(ubig) `total`(ubig) `notes`(100,null) `stock_type`(enum,default:good) `created_at` `updated_at` `deleted_at`
- Casts: stock_type(ProductStockQuality), total(int) - Casts: stock_type(ProductStockQuality), subtotal(int), total(int)
- Scopes: good(), reject() - Scopes: good(), reject()
- Relations: createdBy(BelongsTo→User), restockItems(HasMany→RestockItem) - Relations: createdBy(BelongsTo→User), restockItems(HasMany→RestockItem)

View File

@ -1,104 +0,0 @@
<?php
namespace App\Console\Commands;
use App\DataFixes\BaseDataFix;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
class FixDataCommand extends Command
{
protected $signature = 'app:fix-data {--only=} {--skip=}';
protected $description = 'Fix data yang bermasalah (cost, jumlah, dll)';
public function handle(): int
{
$filesystem = new Filesystem;
$fixPath = app_path('DataFixes');
require_once $fixPath.'/BaseDataFix.php';
$files = collect($filesystem->glob($fixPath.'/*.php'))
->map(fn ($file) => basename($file))
->filter(fn ($file) => $file !== 'BaseDataFix.php')
->toArray();
$fixes = [];
foreach ($files as $file) {
require_once $fixPath.'/'.$file;
$className = 'App\\DataFixes\\'.str_replace('.php', '', $file);
if (! class_exists($className)) {
continue;
}
$instance = new $className;
if ($instance instanceof BaseDataFix) {
$fixes[$instance->key()] = $instance;
}
}
$only = $this->option('only') ? explode(',', $this->option('only')) : null;
$skip = $this->option('skip') ? explode(',', $this->option('skip')) : [];
$this->newLine();
$this->info('=== Fix Data ===');
$this->newLine();
$summary = [];
$totalFixed = 0;
$totalSkipped = 0;
foreach ($fixes as $key => $fix) {
if ($only !== null && ! in_array($key, $only)) {
continue;
}
if (in_array($key, $skip)) {
$this->line("SKIP {$key}{$fix->description()}");
continue;
}
$fix->setCommand($this);
$this->info("Running: {$fix->description()}");
$result = $fix->fix();
$fixed = $result['fixed'] ?? 0;
$skipped = $result['skipped'] ?? 0;
$total = $result['total'] ?? 0;
$summary[$key] = [
'Fix' => $key,
'Total' => $total,
'Fixed' => $fixed,
'Skipped' => $skipped,
];
$totalFixed += $fixed;
$totalSkipped += $skipped;
$this->line(" OK Fixed: {$fixed}, Skipped: {$skipped}, Total: {$total}");
$this->newLine();
}
$this->info('=== Summary ===');
$this->info("Total fixed: {$totalFixed}");
$this->info("Total skipped: {$totalSkipped}");
$this->newLine();
if (! empty($summary)) {
$this->table(
['Fix', 'Total', 'Fixed', 'Skipped'],
array_values($summary)
);
}
return Command::SUCCESS;
}
}

View File

@ -1,28 +0,0 @@
<?php
namespace App\DataFixes;
use Illuminate\Console\Command;
abstract class BaseDataFix
{
protected Command $command;
public function setCommand(Command $command): static
{
$this->command = $command;
return $this;
}
abstract public function key(): string;
abstract public function description(): string;
abstract public function fix(): array;
protected function info(string $message): void
{
$this->command->line(" {$message}");
}
}

View File

@ -1,85 +0,0 @@
<?php
namespace App\DataFixes;
use App\Models\Cutting;
class FixCuttingsCost extends BaseDataFix
{
public function key(): string
{
return 'cuttings-cost';
}
public function description(): string
{
return 'Recalculate total_material_cost and cost_per_unit for cuttings';
}
public function fix(): array
{
$cuttings = Cutting::with([
'cuttingMaterials.rawMaterialPrice',
'cuttingResults',
])->get();
$fixed = 0;
$skipped = 0;
$details = [];
foreach ($cuttings as $cutting) {
$oldTotal = $cutting->total_material_cost;
$oldPerUnit = $cutting->cost_per_unit;
$totalMaterialCost = 0;
foreach ($cutting->cuttingMaterials as $material) {
$price = $material->rawMaterialPrice;
if ($price) {
$totalMaterialCost += $price->price * ($material->material_usage ?? 0);
}
}
$cuttingResult = $cutting->cuttingResults->sum('cutting_result');
$costPerUnit = 0;
if ($cuttingResult > 0) {
$costPerUnit = (int) ($totalMaterialCost / $cuttingResult);
}
if ($oldTotal === $totalMaterialCost && $oldPerUnit === $costPerUnit) {
$skipped++;
continue;
}
$cutting->update([
'total_material_cost' => $totalMaterialCost,
'cost_per_unit' => $costPerUnit,
]);
$details[] = [
'ID' => $cutting->id,
'Description' => $cutting->description ?? '-',
'Old Total' => number_format($oldTotal ?? 0),
'New Total' => number_format($totalMaterialCost),
'Old/Unit' => number_format($oldPerUnit ?? 0),
'New/Unit' => number_format($costPerUnit),
];
$fixed++;
}
if (! empty($details)) {
$this->command->newLine();
$this->command->table(
['ID', 'Description', 'Old Total', 'New Total', 'Old/Unit', 'New/Unit'],
$details
);
}
return [
'fixed' => $fixed,
'skipped' => $skipped,
'total' => $cuttings->count(),
];
}
}

View File

@ -1,126 +0,0 @@
<?php
namespace App\DataFixes;
use App\Enums\PriceType;
use App\Enums\ProductStockQuality;
use App\Models\OrderItem;
class FixOrderItemsUnitPrice extends BaseDataFix
{
public function key(): string
{
return 'order-items-unit-price';
}
public function description(): string
{
return 'Fix order_items with unit_price = 0 (lookup correct price from product_prices)';
}
public function fix(): array
{
$items = OrderItem::where('unit_price', 0)
->with(['order', 'productVariant.productPrices'])
->get();
$fixed = 0;
$skipped = 0;
$notFound = 0;
$details = [];
foreach ($items as $item) {
$order = $item->order;
if (! $order) {
$skipped++;
continue;
}
$priceType = $this->resolvePriceType($order->price_type->value, $item->stock_quality->value);
$productPrices = $item->productVariant?->productPrices;
if (! $productPrices) {
$notFound++;
$details[] = [
'Order' => $order->order_number,
'Variant' => $item->product_variant_id,
'Qty' => $item->quantity,
'Old Price' => 0,
'New Price' => 'N/A',
'Status' => 'No prices found',
];
continue;
}
$correctPrice = $productPrices->firstWhere('type', $priceType);
if (! $correctPrice || $correctPrice->price <= 0) {
$notFound++;
$details[] = [
'Order' => $order->order_number,
'Variant' => $item->product_variant_id,
'Qty' => $item->quantity,
'Old Price' => 0,
'New Price' => 'N/A',
'Status' => "No {$priceType} price",
];
continue;
}
$newSubtotal = $correctPrice->price * $item->quantity;
$item->update([
'unit_price' => $correctPrice->price,
'subtotal' => $newSubtotal,
]);
$details[] = [
'Order' => $order->order_number,
'Variant' => $item->product_variant_id,
'Qty' => $item->quantity,
'Old Price' => 0,
'New Price' => number_format($correctPrice->price),
'Status' => 'Fixed',
];
$fixed++;
}
if (! empty($details)) {
$this->command->newLine();
$this->command->table(
['Order', 'Variant', 'Qty', 'Old Price', 'New Price', 'Status'],
$details
);
}
return [
'fixed' => $fixed,
'skipped' => $skipped,
'not_found' => $notFound,
'total' => $items->count(),
];
}
private function resolvePriceType(string $orderPriceType, string $stockQuality): string
{
if ($stockQuality === ProductStockQuality::REJECT->value) {
return PriceType::REJECT->value;
}
$map = [
PriceType::DISTRIBUTOR->value => PriceType::DISTRIBUTOR->value,
PriceType::AGEN->value => PriceType::AGEN->value,
PriceType::SUB_AGEN->value => PriceType::SUB_AGEN->value,
PriceType::WHOLESALE->value => PriceType::WHOLESALE->value,
PriceType::RETAIL->value => PriceType::RETAIL->value,
PriceType::TIKTOK->value => PriceType::TIKTOK->value,
PriceType::SHOPEE->value => PriceType::SHOPEE->value,
];
return $map[$orderPriceType] ?? PriceType::RETAIL->value;
}
}

View File

@ -1,102 +0,0 @@
<?php
namespace App\DataFixes;
use App\Models\Order;
class FixOrdersCogs extends BaseDataFix
{
public function key(): string
{
return 'orders-cogs';
}
public function description(): string
{
return 'Fix COGS yang 0 (hitung dari capital price × quantity)';
}
public function fix(): array
{
$orders = Order::where('cogs', 0)
->where('status', '!=', 'cancelled')
->with(['orderItems.productVariant.productPrices'])
->get();
$fixed = 0;
$skipped = 0;
$noItems = 0;
$details = [];
foreach ($orders as $order) {
if ($order->orderItems->isEmpty()) {
$noItems++;
continue;
}
$totalCogs = 0;
$hasValidCapital = true;
foreach ($order->orderItems as $item) {
$capitalPrice = $item->productVariant?->productPrices
->firstWhere('type', 'capital');
if (! $capitalPrice || $capitalPrice->price <= 0) {
$hasValidCapital = false;
break;
}
$totalCogs += $capitalPrice->price * $item->quantity;
}
if (! $hasValidCapital) {
$skipped++;
$details[] = [
'Order' => $order->order_number,
'Items' => $order->orderItems->count(),
'Old COGS' => '0',
'New COGS' => 'N/A',
'Status' => 'Missing capital price',
];
continue;
}
if ($totalCogs === 0) {
$skipped++;
continue;
}
$order->update([
'cogs' => $totalCogs,
]);
$details[] = [
'Order' => $order->order_number,
'Items' => $order->orderItems->count(),
'Old COGS' => '0',
'New COGS' => number_format($totalCogs),
'Status' => 'Fixed',
];
$fixed++;
}
if (! empty($details)) {
$this->command->newLine();
$this->command->table(
['Order', 'Items', 'Old COGS', 'New COGS', 'Status'],
$details
);
}
return [
'fixed' => $fixed,
'skipped' => $skipped,
'no_items' => $noItems,
'total' => $orders->count(),
];
}
}

View File

@ -1,75 +0,0 @@
<?php
namespace App\DataFixes;
use App\Models\Order;
class FixOrdersNegoPrice extends BaseDataFix
{
public function key(): string
{
return 'orders-nego-price';
}
public function description(): string
{
return 'Fix nego_price yang menyimpan total akhir, bukan potongan';
}
public function fix(): array
{
$orders = Order::where('nego_price', '>', 0)
->where('status', '!=', 'cancelled')
->get();
$fixed = 0;
$skipped = 0;
$details = [];
foreach ($orders as $order) {
$oldNego = $order->nego_price;
$oldTotal = $order->total_amount;
$correctNego = $order->subtotal - $order->discount - $order->total_amount;
if ($correctNego < 0) {
$correctNego = 0;
}
if ($oldNego === $correctNego) {
$skipped++;
continue;
}
$order->update([
'nego_price' => $correctNego,
]);
$details[] = [
'Order' => $order->order_number,
'Subtotal' => number_format($order->subtotal),
'Discount' => number_format($order->discount),
'Old Nego' => number_format($oldNego),
'New Nego' => number_format($correctNego),
'Total' => number_format($oldTotal),
];
$fixed++;
}
if (! empty($details)) {
$this->command->newLine();
$this->command->table(
['Order', 'Subtotal', 'Discount', 'Old Nego', 'New Nego', 'Total'],
$details
);
}
return [
'fixed' => $fixed,
'skipped' => $skipped,
'total' => $orders->count(),
];
}
}

View File

@ -98,7 +98,7 @@ public function cuttingResults(): HasMany
{ {
return $this->hasMany(CuttingResult::class); return $this->hasMany(CuttingResult::class);
} }
public function registerMediaCollections(): void public function registerMediaCollections(): void
{ {
$this->addMediaCollection('photos'); $this->addMediaCollection('photos');

View File

@ -18,7 +18,7 @@
use Spatie\MediaLibrary\InteractsWithMedia; use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media; use Spatie\MediaLibrary\MediaCollections\Models\Media;
#[Appends(['stock_type_label', 'formatted_total'])] #[Appends(['stock_type_label', 'formatted_subtotal', 'formatted_total'])]
#[Guarded(['id'])] #[Guarded(['id'])]
class Restock extends Model implements HasMedia class Restock extends Model implements HasMedia
{ {
@ -28,6 +28,7 @@ protected function casts(): array
{ {
return [ return [
'stock_type' => ProductStockQuality::class, 'stock_type' => ProductStockQuality::class,
'subtotal' => 'integer',
'total' => 'integer', 'total' => 'integer',
]; ];
} }
@ -39,6 +40,13 @@ protected function stockTypeLabel(): Attribute
); );
} }
protected function formattedSubtotal(): Attribute
{
return Attribute::make(
get: fn () => 'Rp '.number_format($this->subtotal, 0, ',', '.'),
);
}
protected function formattedTotal(): Attribute protected function formattedTotal(): Attribute
{ {
return Attribute::make( return Attribute::make(

View File

@ -16,7 +16,7 @@ public function migrate(): array
$results['retail_stock_histories'] = $this->migrateTable('retail_stock_histories'); $results['retail_stock_histories'] = $this->migrateTable('retail_stock_histories');
$results['stok_opnames'] = $this->migrateTable('stok_opnames'); $results['stok_opnames'] = $this->migrateTable('stok_opnames');
$results['stok_opname_items'] = $this->migrateTable('stok_opname_items'); $results['stok_opname_items'] = $this->migrateTable('stok_opname_items');
$results['restocks'] = $this->migrateTableWithoutColumns('restocks', ['subtotal']); $results['restocks'] = $this->migrateTable('restocks');
$results['restock_items'] = $this->migrateTable('restock_items'); $results['restock_items'] = $this->migrateTable('restock_items');
$results['stock_mutations'] = $this->migrateTable('stock_mutations', function ($row) { $results['stock_mutations'] = $this->migrateTable('stock_mutations', function ($row) {
$fields = ['quantity', 'stock_before', 'stock_after']; $fields = ['quantity', 'stock_before', 'stock_after'];

View File

@ -26,7 +26,7 @@ public function __construct(
public function paginated(int $perPage = 25, string $search = '', string $sort = 'created_at', string $direction = 'desc'): LengthAwarePaginator public function paginated(int $perPage = 25, string $search = '', string $sort = 'created_at', string $direction = 'desc'): LengthAwarePaginator
{ {
$paginator = Restock::query() $paginator = Restock::query()
->select(['id', 'created_by_id', 'total', 'notes', 'stock_type', 'created_at']) ->select(['id', 'created_by_id', 'subtotal', 'total', 'notes', 'stock_type', 'created_at'])
->with([ ->with([
'createdBy:id', 'createdBy:id',
'createdBy.userProfile:id,user_id,full_name', 'createdBy.userProfile:id,user_id,full_name',
@ -66,14 +66,15 @@ public function store(array $data): Restock
{ {
return DB::transaction(function () use ($data) { return DB::transaction(function () use ($data) {
$now = now(); $now = now();
$total = 0; $subtotal = 0;
$stockType = $data['stock_type'] ?? ProductStockQuality::GOOD->value; $stockType = $data['stock_type'] ?? ProductStockQuality::GOOD->value;
$itemRows = $this->buildItemRows($data['items'], $stockType, $now, $total); $itemRows = $this->buildItemRows($data['items'], $stockType, $now, $subtotal);
$restock = Restock::create([ $restock = Restock::create([
'created_by_id' => auth()->id(), 'created_by_id' => auth()->id(),
'total' => $total, 'subtotal' => $subtotal,
'total' => $subtotal,
'notes' => $data['notes'] ?? null, 'notes' => $data['notes'] ?? null,
'stock_type' => $stockType, 'stock_type' => $stockType,
]); ]);
@ -89,7 +90,7 @@ public function store(array $data): Restock
NotificationService::notify( NotificationService::notify(
roles: [Role::OWNER, Role::DEVELOPER, Role::ADMIN_TOKO], roles: [Role::OWNER, Role::DEVELOPER, Role::ADMIN_TOKO],
title: 'Restock Baru', title: 'Restock Baru',
body: 'Restock '.($stockType === ProductStockQuality::GOOD->value ? 'produk' : 'reject').' sebesar Rp '.number_format($total, 0, ',', '.').' berhasil dicatat oleh '.auth()->user()->full_name.'.', body: 'Restock '.($stockType === ProductStockQuality::GOOD->value ? 'produk' : 'reject').' sebesar Rp '.number_format($subtotal, 0, ',', '.').' berhasil dicatat oleh '.auth()->user()->full_name.'.',
url: route('admin.manage.restocks.index'), url: route('admin.manage.restocks.index'),
); );
@ -109,10 +110,10 @@ public function update(Restock $restock, array $data): Restock
$restock->restockItems()->delete(); $restock->restockItems()->delete();
$now = now(); $now = now();
$total = 0; $subtotal = 0;
$stockType = $data['stock_type'] ?? $restock->stock_type->value; $stockType = $data['stock_type'] ?? $restock->stock_type->value;
$itemRows = $this->buildItemRows($data['items'], $stockType, $now, $total); $itemRows = $this->buildItemRows($data['items'], $stockType, $now, $subtotal);
foreach ($itemRows as &$row) { foreach ($itemRows as &$row) {
$row['restock_id'] = $restock->id; $row['restock_id'] = $restock->id;
@ -120,7 +121,8 @@ public function update(Restock $restock, array $data): Restock
DB::table('restock_items')->insert($itemRows); DB::table('restock_items')->insert($itemRows);
$restock->update([ $restock->update([
'total' => $total, 'subtotal' => $subtotal,
'total' => $subtotal,
'notes' => $data['notes'] ?? null, 'notes' => $data['notes'] ?? null,
'stock_type' => $stockType, 'stock_type' => $stockType,
]); ]);
@ -148,7 +150,7 @@ public function destroy(Restock $restock): bool
}); });
} }
private function buildItemRows(array $items, string $stockType, $now, int &$total): array private function buildItemRows(array $items, string $stockType, $now, int &$subtotal): array
{ {
$priceType = $stockType === ProductStockQuality::REJECT->value $priceType = $stockType === ProductStockQuality::REJECT->value
? PriceType::REJECT ? PriceType::REJECT
@ -166,11 +168,11 @@ private function buildItemRows(array $items, string $stockType, $now, int &$tota
return [$variant->id => $price?->price ?? 0]; return [$variant->id => $price?->price ?? 0];
}); });
return collect($items)->map(function ($item) use ($now, $prices, &$total) { return collect($items)->map(function ($item) use ($now, $prices, &$subtotal) {
$quantity = (int) $item['quantity']; $quantity = (int) $item['quantity'];
$unitPrice = (int) ($prices[$item['product_variant_id']] ?? 0); $unitPrice = (int) ($prices[$item['product_variant_id']] ?? 0);
$itemSubtotal = $unitPrice * $quantity; $itemSubtotal = $unitPrice * $quantity;
$total += $itemSubtotal; $subtotal += $itemSubtotal;
return [ return [
'restock_id' => null, 'restock_id' => null,

View File

@ -14,6 +14,7 @@ public function up(): void
$table->foreignId('created_by_id')->constrained('users')->cascadeOnDelete(); $table->foreignId('created_by_id')->constrained('users')->cascadeOnDelete();
$table->unsignedBigInteger('subtotal');
$table->unsignedBigInteger('total'); $table->unsignedBigInteger('total');
$table->string('notes', 100)->nullable(); $table->string('notes', 100)->nullable();
$table->enum('stock_type', ProductStockQuality::values())->default(ProductStockQuality::GOOD->value); $table->enum('stock_type', ProductStockQuality::values())->default(ProductStockQuality::GOOD->value);

View File

@ -8,14 +8,14 @@ type PageHeaderProps = {
export function PageHeader({ title, description, actions }: PageHeaderProps) { export function PageHeader({ title, description, actions }: PageHeaderProps) {
return ( return (
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between"> <div className="flex items-center justify-between">
<div className="min-w-0"> <div>
<h2 className="text-2xl font-semibold tracking-tight"> <h2 className="text-2xl font-semibold tracking-tight">
{title} {title}
</h2> </h2>
{description} {description}
</div> </div>
{actions && <div className="flex flex-wrap items-center gap-2">{actions}</div>} {actions}
</div> </div>
); );
} }

View File

@ -97,7 +97,7 @@ export function PurchaseCardRow({
</span> </span>
<span> <span>
<span className="text-muted-foreground"> <span className="text-muted-foreground">
Diskon:{' '} Disc:{' '}
</span> </span>
{formatCurrency(purchase.discount)} {formatCurrency(purchase.discount)}
</span> </span>

View File

@ -21,6 +21,7 @@ export type RestockItem = {
export type Restock = { export type Restock = {
id: number; id: number;
created_by_id: number; created_by_id: number;
subtotal: number;
total: number; total: number;
notes: string | null; notes: string | null;
stock_type: RestockStockType; stock_type: RestockStockType;

View File

@ -120,6 +120,12 @@ export function RestockCardRow({
</span> </span>
{formatNumber(totalQty)} {formatNumber(totalQty)}
</span> </span>
<span>
<span className="text-muted-foreground">
Sub:{' '}
</span>
{formatCurrency(restock.subtotal)}
</span>
<span className="font-semibold"> <span className="font-semibold">
<span className="font-normal text-muted-foreground"> <span className="font-normal text-muted-foreground">
Total:{' '} Total:{' '}