440 lines
17 KiB
PHP
440 lines
17 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Admin;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\Lokasi;
|
|
use App\Models\Penjualan;
|
|
use App\Models\PenjualanBarang;
|
|
use App\Models\PergerakanStok;
|
|
use App\Models\ProductUnit;
|
|
use App\Models\Produk;
|
|
use App\Models\Voucher;
|
|
use App\Models\VoucherHistory;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class TransaksiController extends Controller
|
|
{
|
|
public function index(Request $request): JsonResponse
|
|
{
|
|
$data = $request->validate([
|
|
'from' => ['nullable', 'date'],
|
|
'to' => ['nullable', 'date'],
|
|
'q' => ['nullable', 'string', 'max:100'],
|
|
'limit' => ['nullable', 'integer', 'min:1', 'max:200'],
|
|
]);
|
|
|
|
$limit = (int) ($data['limit'] ?? 50);
|
|
|
|
$query = Penjualan::query()
|
|
->withCount('barang')
|
|
->orderByDesc('waktu');
|
|
|
|
if (!empty($data['from'])) {
|
|
$query->where('waktu', '>=', $data['from'] . ' 00:00:00');
|
|
}
|
|
if (!empty($data['to'])) {
|
|
$query->where('waktu', '<=', $data['to'] . ' 23:59:59');
|
|
}
|
|
if (!empty($data['q'])) {
|
|
$s = trim($data['q']);
|
|
$query->where('nomor_penjualan', 'like', "%{$s}%");
|
|
}
|
|
|
|
$rows = $query->limit($limit)->get()->map(function (Penjualan $p) {
|
|
return [
|
|
'id' => $p->id,
|
|
'nomor_penjualan' => $p->nomor_penjualan,
|
|
'waktu' => $p->waktu,
|
|
'subtotal' => (int) $p->subtotal,
|
|
'diskon' => (int) $p->diskon,
|
|
'pajak' => (int) $p->pajak,
|
|
'total' => (int) $p->total,
|
|
'metode_pembayaran' => $p->metode_pembayaran,
|
|
'status_pembayaran' => $p->status_pembayaran ?? 'LUNAS',
|
|
'voucher_kode' => $p->voucher_kode,
|
|
'voucher_amount' => (int) ($p->voucher_amount ?? ($p->voucher_kode ? $p->total : 0)),
|
|
'jumlah_bayar' => (int) $p->jumlah_bayar,
|
|
'kembalian' => (int) $p->kembalian,
|
|
'sisa_piutang' => (int) ($p->sisa_piutang ?? 0),
|
|
'items_count' => (int) ($p->barang_count ?? 0),
|
|
];
|
|
});
|
|
|
|
return response()->json(['data' => $rows]);
|
|
}
|
|
|
|
public function simpanTransaksi(Request $request): JsonResponse
|
|
{
|
|
$payload = $request->validate([
|
|
'lokasi_id' => ['required', 'integer', 'exists:lokasi,id'],
|
|
'items' => ['required', 'array', 'min:1'],
|
|
'items.*.produk_id' => ['required', 'integer', 'exists:produk,id'],
|
|
'items.*.qty' => ['required', 'integer', 'min:1'],
|
|
'items.*.harga' => ['nullable', 'integer', 'min:0'],
|
|
'diskon' => ['nullable', 'integer', 'min:0'],
|
|
'pajak' => ['nullable', 'integer', 'min:0'],
|
|
'metode_pembayaran' => ['required', 'string', 'max:50'],
|
|
'jumlah_bayar' => ['required', 'integer', 'min:0'],
|
|
'voucher_kode' => ['nullable', 'string', 'max:255'],
|
|
'voucher_amount' => ['nullable', 'integer', 'min:0'],
|
|
'vouchers' => ['nullable', 'array', 'max:3'],
|
|
'vouchers.*.kode' => ['required_with:vouchers', 'string', 'max:255'],
|
|
'vouchers.*.amount' => ['required_with:vouchers', 'integer', 'min:1'],
|
|
'unit_piutang' => ['nullable', 'string', 'max:100'],
|
|
]);
|
|
|
|
$lokasi = Lokasi::findOrFail((int) $payload['lokasi_id']);
|
|
|
|
$itemRows = collect($payload['items']);
|
|
$produkIds = $itemRows->pluck('produk_id')->unique()->values();
|
|
$produkMap = Produk::query()->whereIn('id', $produkIds)->get()->keyBy('id');
|
|
|
|
if ($produkMap->count() !== $produkIds->count()) {
|
|
return response()->json(['message' => 'Produk tidak valid.'], 422);
|
|
}
|
|
|
|
$baseUnits = ProductUnit::query()
|
|
->whereIn('produk_id', $produkIds)
|
|
->where('is_base', true)
|
|
->get()
|
|
->keyBy('produk_id');
|
|
|
|
$qtyByProduk = [];
|
|
$computed = [];
|
|
$subtotal = 0;
|
|
|
|
foreach ($itemRows as $row) {
|
|
$pid = (int) $row['produk_id'];
|
|
$qty = (int) $row['qty'];
|
|
$produk = $produkMap->get($pid);
|
|
|
|
$harga = isset($row['harga']) ? (int) $row['harga'] : (int) $produk->harga_jual;
|
|
$lineTotal = $harga * $qty;
|
|
|
|
$qtyByProduk[$pid] = ($qtyByProduk[$pid] ?? 0) + $qty;
|
|
$subtotal += $lineTotal;
|
|
|
|
$computed[] = [
|
|
'produk' => $produk,
|
|
'qty' => $qty,
|
|
'harga' => $harga,
|
|
'total' => $lineTotal,
|
|
];
|
|
}
|
|
|
|
// cek stok per produk di lokasi
|
|
foreach ($qtyByProduk as $pid => $qty) {
|
|
$stok = $this->stokProdukDiLokasi($pid, $lokasi->id);
|
|
if ($stok < $qty) {
|
|
$nama = $produkMap->get($pid)?->nama ?? 'Produk';
|
|
return response()->json([
|
|
'message' => "Stok tidak cukup untuk {$nama}. Stok tersedia: {$stok}",
|
|
], 422);
|
|
}
|
|
}
|
|
|
|
$diskon = (int) ($payload['diskon'] ?? 0);
|
|
$pajak = (int) ($payload['pajak'] ?? 0);
|
|
$total = max(0, $subtotal - $diskon + $pajak);
|
|
$metode = strtoupper((string) $payload['metode_pembayaran']);
|
|
$jumlahBayar = (int) $payload['jumlah_bayar'];
|
|
$voucherKode = null;
|
|
$voucherAmount = 0;
|
|
$unitPiutang = null;
|
|
$voucherList = [];
|
|
|
|
if (!empty($payload['vouchers']) && is_array($payload['vouchers'])) {
|
|
$voucherList = collect($payload['vouchers'])
|
|
->map(function ($v) {
|
|
return [
|
|
'kode' => trim((string) ($v['kode'] ?? '')),
|
|
'amount' => (int) ($v['amount'] ?? 0),
|
|
];
|
|
})
|
|
->filter(fn ($v) => $v['kode'] !== '' && $v['amount'] > 0)
|
|
->values()
|
|
->all();
|
|
|
|
$uniqueCodes = collect($voucherList)->pluck('kode')->unique();
|
|
if ($uniqueCodes->count() !== count($voucherList)) {
|
|
return response()->json([
|
|
'message' => 'Kode voucher tidak boleh duplikat.',
|
|
], 422);
|
|
}
|
|
}
|
|
|
|
if ($metode === 'VOUCHER' || $metode === 'VOUCHER_CASH') {
|
|
if (!empty($voucherList)) {
|
|
$voucherAmount = (int) collect($voucherList)->sum('amount');
|
|
$voucherKode = $voucherList[0]['kode'] ?? null;
|
|
} else {
|
|
$voucherKode = trim((string) ($payload['voucher_kode'] ?? ''));
|
|
if ($voucherKode === '') {
|
|
return response()->json([
|
|
'message' => 'Kode voucher wajib diisi.',
|
|
], 422);
|
|
}
|
|
if ($metode === 'VOUCHER') {
|
|
$voucherAmount = $total;
|
|
$jumlahBayar = 0;
|
|
} else {
|
|
$voucherAmount = (int) ($payload['voucher_amount'] ?? 0);
|
|
if ($voucherAmount <= 0) {
|
|
return response()->json([
|
|
'message' => 'Nominal voucher wajib diisi.',
|
|
], 422);
|
|
}
|
|
if ($voucherAmount > $total) {
|
|
return response()->json([
|
|
'message' => 'Nominal voucher tidak boleh melebihi total.',
|
|
], 422);
|
|
}
|
|
}
|
|
$voucherList = [
|
|
['kode' => $voucherKode, 'amount' => $voucherAmount],
|
|
];
|
|
}
|
|
if ($voucherAmount <= 0) {
|
|
return response()->json([
|
|
'message' => 'Nominal voucher wajib diisi.',
|
|
], 422);
|
|
}
|
|
if ($voucherAmount > $total) {
|
|
return response()->json([
|
|
'message' => 'Nominal voucher tidak boleh melebihi total.',
|
|
], 422);
|
|
}
|
|
if ($metode === 'VOUCHER' && $voucherAmount < $total) {
|
|
return response()->json([
|
|
'message' => 'Saldo voucher tidak mencukupi untuk menutup total.',
|
|
], 422);
|
|
}
|
|
}
|
|
if ($metode === 'PIUTANG') {
|
|
$unitPiutang = trim((string) ($payload['unit_piutang'] ?? ''));
|
|
if ($unitPiutang === '') {
|
|
return response()->json([
|
|
'message' => 'Unit piutang wajib diisi.',
|
|
], 422);
|
|
}
|
|
}
|
|
|
|
$remaining = max(0, $total - $voucherAmount);
|
|
if ($metode !== 'PIUTANG' && $jumlahBayar < $remaining) {
|
|
return response()->json([
|
|
'message' => 'Jumlah bayar harus sama atau lebih besar dari sisa setelah voucher.',
|
|
], 422);
|
|
}
|
|
|
|
try {
|
|
$penjualan = DB::transaction(function () use (
|
|
$computed,
|
|
$baseUnits,
|
|
$lokasi,
|
|
$subtotal,
|
|
$diskon,
|
|
$pajak,
|
|
$total,
|
|
$jumlahBayar,
|
|
$payload,
|
|
$request,
|
|
$metode,
|
|
$voucherKode,
|
|
$voucherAmount,
|
|
$voucherList,
|
|
$unitPiutang
|
|
) {
|
|
$nomor = $this->generateNomor();
|
|
$remaining = max(0, $total - $voucherAmount);
|
|
$kembalian = max(0, $jumlahBayar - $remaining);
|
|
$sisaPiutang = $metode === 'PIUTANG' ? max(0, $remaining - $jumlahBayar) : 0;
|
|
$statusPembayaran = $sisaPiutang > 0 ? 'PIUTANG' : 'LUNAS';
|
|
|
|
$voucherUsageRows = [];
|
|
if ($voucherAmount > 0) {
|
|
foreach ($voucherList as $v) {
|
|
$voucher = Voucher::query()
|
|
->where('kode', $v['kode'])
|
|
->lockForUpdate()
|
|
->first();
|
|
if (!$voucher || !$voucher->aktif) {
|
|
throw new \RuntimeException('VOUCHER_INVALID');
|
|
}
|
|
if ((int) $voucher->saldo < (int) $v['amount']) {
|
|
throw new \RuntimeException('VOUCHER_SALDO');
|
|
}
|
|
$saldoBefore = (int) $voucher->saldo;
|
|
$voucher->saldo = (int) $voucher->saldo - (int) $v['amount'];
|
|
$voucher->save();
|
|
$voucherUsageRows[] = [
|
|
'voucher_id' => $voucher->id,
|
|
'kode' => $voucher->kode,
|
|
'tipe' => 'USE',
|
|
'jumlah' => (int) $v['amount'],
|
|
'saldo_before' => $saldoBefore,
|
|
'saldo_after' => (int) $voucher->saldo,
|
|
'penjualan_id' => null,
|
|
'user_id' => $request->user()?->id,
|
|
'catatan' => null,
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
];
|
|
}
|
|
}
|
|
|
|
$p = Penjualan::create([
|
|
'user_id' => $request->user()?->id,
|
|
'nomor_penjualan' => $nomor,
|
|
'waktu' => now(),
|
|
'subtotal' => $subtotal,
|
|
'diskon' => $diskon,
|
|
'pajak' => $pajak,
|
|
'total' => $total,
|
|
'metode_pembayaran' => $metode,
|
|
'status_pembayaran' => $statusPembayaran,
|
|
'voucher_kode' => $voucherKode,
|
|
'voucher_amount' => $voucherAmount,
|
|
'unit_piutang' => $metode === 'PIUTANG' ? $unitPiutang : null,
|
|
'jumlah_bayar' => $jumlahBayar,
|
|
'kembalian' => $kembalian,
|
|
'sisa_piutang' => $sisaPiutang,
|
|
]);
|
|
|
|
$barangRows = [];
|
|
$movementRows = [];
|
|
|
|
foreach ($computed as $row) {
|
|
/** @var \App\Models\Produk $produk */
|
|
$produk = $row['produk'];
|
|
$qty = (int) $row['qty'];
|
|
$harga = (int) $row['harga'];
|
|
$lineTotal = (int) $row['total'];
|
|
|
|
$barangRows[] = [
|
|
'penjualan_id' => $p->id,
|
|
'produk_id' => $produk->id,
|
|
'jumlah' => $qty,
|
|
'harga' => $harga,
|
|
'total' => $lineTotal,
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
];
|
|
|
|
$unit = $baseUnits->get($produk->id);
|
|
$unitName = $unit?->nama_unit ?? 'PCS';
|
|
$multiplier = (int) ($unit?->multiplier ?? 1);
|
|
|
|
$movementRows[] = [
|
|
'waktu' => now(),
|
|
'produk_id' => $produk->id,
|
|
'dari_lokasi_id' => $lokasi->id,
|
|
'ke_lokasi_id' => null,
|
|
'jenis' => 'PENJUALAN',
|
|
'jumlah' => $qty,
|
|
'unit' => $unitName,
|
|
'qty_input' => $qty,
|
|
'multiplier' => $multiplier,
|
|
'catatan' => "Penjualan {$nomor}",
|
|
'referensi_tipe' => 'PENJUALAN',
|
|
'referensi_id' => $p->id,
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
];
|
|
}
|
|
|
|
PenjualanBarang::insert($barangRows);
|
|
PergerakanStok::insert($movementRows);
|
|
|
|
if ($voucherAmount > 0) {
|
|
foreach ($voucherUsageRows as &$row) {
|
|
$row['penjualan_id'] = $p->id;
|
|
}
|
|
unset($row);
|
|
VoucherHistory::insert($voucherUsageRows);
|
|
}
|
|
|
|
return $p;
|
|
});
|
|
} catch (\RuntimeException $e) {
|
|
if ($e->getMessage() === 'VOUCHER_INVALID') {
|
|
return response()->json([
|
|
'message' => 'Voucher tidak valid atau tidak aktif.',
|
|
], 422);
|
|
}
|
|
if ($e->getMessage() === 'VOUCHER_SALDO') {
|
|
return response()->json([
|
|
'message' => 'Saldo voucher tidak mencukupi.',
|
|
], 422);
|
|
}
|
|
throw $e;
|
|
}
|
|
|
|
return response()->json([
|
|
'data' => $penjualan,
|
|
], 201);
|
|
}
|
|
|
|
public function show(Penjualan $penjualan): JsonResponse
|
|
{
|
|
$penjualan->load(['barang.produk:id,nama,barcode']);
|
|
|
|
$items = $penjualan->barang->map(function (PenjualanBarang $b) {
|
|
return [
|
|
'produk_id' => $b->produk_id,
|
|
'nama' => $b->produk?->nama,
|
|
'barcode' => $b->produk?->barcode,
|
|
'jumlah' => (int) $b->jumlah,
|
|
'harga' => (int) $b->harga,
|
|
'total' => (int) $b->total,
|
|
];
|
|
});
|
|
|
|
return response()->json([
|
|
'data' => [
|
|
'id' => $penjualan->id,
|
|
'nomor_penjualan' => $penjualan->nomor_penjualan,
|
|
'waktu' => $penjualan->waktu,
|
|
'subtotal' => (int) $penjualan->subtotal,
|
|
'diskon' => (int) $penjualan->diskon,
|
|
'pajak' => (int) $penjualan->pajak,
|
|
'total' => (int) $penjualan->total,
|
|
'metode_pembayaran' => $penjualan->metode_pembayaran,
|
|
'status_pembayaran' => $penjualan->status_pembayaran ?? 'LUNAS',
|
|
'voucher_kode' => $penjualan->voucher_kode,
|
|
'voucher_amount' => (int) ($penjualan->voucher_amount ?? ($penjualan->voucher_kode ? $penjualan->total : 0)),
|
|
'jumlah_bayar' => (int) $penjualan->jumlah_bayar,
|
|
'kembalian' => (int) $penjualan->kembalian,
|
|
'sisa_piutang' => (int) ($penjualan->sisa_piutang ?? 0),
|
|
'items' => $items,
|
|
],
|
|
]);
|
|
}
|
|
|
|
private function stokProdukDiLokasi(int $produkId, int $lokasiId): int
|
|
{
|
|
$in = (int) DB::table('pergerakan_stok')
|
|
->where('produk_id', $produkId)
|
|
->where('ke_lokasi_id', $lokasiId)
|
|
->sum('jumlah');
|
|
|
|
$out = (int) DB::table('pergerakan_stok')
|
|
->where('produk_id', $produkId)
|
|
->where('dari_lokasi_id', $lokasiId)
|
|
->sum('jumlah');
|
|
|
|
return $in - $out;
|
|
}
|
|
|
|
private function generateNomor(): string
|
|
{
|
|
do {
|
|
$nomor = 'PJ' . now()->format('ymdHis') . random_int(100, 999);
|
|
} while (Penjualan::query()->where('nomor_penjualan', $nomor)->exists());
|
|
|
|
return $nomor;
|
|
}
|
|
}
|