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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
import prisma from '../utils/db';
import { catatAudit } from '../utils/audit';
import { APIError } from '../utils/errors';

export class StokService {
  static async tambahStok(params: {
    produkId: number;
    qty: number;
    hargaBeli: number;
    batchNo?: string | null;
    expiredDate?: Date | null;
    supplierId?: number | null;
    userId?: number | null;
    catatan?: string | null;
    referensi?: string | null;
  }) {
    const { produkId, qty, hargaBeli, batchNo, expiredDate, supplierId, userId, catatan, referensi } = params;

    // 1. Ambil data produk
    const produk = await prisma.produk.findUnique({
      where: { id: produkId },
    });
    if (!produk) {
      throw new APIError(`Produk dengan ID ${produkId} tidak ditemukan.`, 404);
    }

    // 2. Buat StokBatch baru
    const batch = await prisma.stok_batch.create({
      data: {
        produk_id: produkId,
        batch_no: batchNo ?? null,
        qty_masuk: qty,
        qty_sisa: qty,
        harga_beli: hargaBeli,
        expired_date: expiredDate ?? null,
        supplier_id: supplierId ?? null,
        catatan: catatan ?? null,
      },
    });

    // 3. Update stok di tabel produk
    const stokSebelum = Number(produk.stok);
    const stokSesudah = stokSebelum + qty;

    // Update harga beli rata-rata produk (Moving Average)
    let newHargaBeli = hargaBeli;
    if (stokSebelum > 0) {
      const totalNilaiLama = stokSebelum * Number(produk.harga_beli);
      const totalNilaiBaru = qty * hargaBeli;
      newHargaBeli = (totalNilaiLama + totalNilaiBaru) / stokSesudah;
    }

    await prisma.produk.update({
      where: { id: produkId },
      data: {
        stok: stokSesudah,
        harga_beli: newHargaBeli,
      },
    });

    // 4. Catat mutasi di stok_log
    const log = await prisma.stok_log.create({
      data: {
        produk_id: produkId,
        batch_id: batch.id,
        tipe: 'masuk',
        qty: qty,
        stok_sebelum: stokSebelum,
        stok_sesudah: stokSesudah,
        referensi: referensi ?? null,
        user_id: userId ?? null,
        catatan: catatan ?? null,
      },
    });

    return { batch, log };
  }

  static async kurangiStokFEFO(params: {
    produkId: number;
    qtyToDeduct: number;
    userId?: number | null;
    referensi?: string | null;
    catatan?: string | null;
  }) {
    const { produkId, qtyToDeduct, userId, referensi, catatan } = params;

    const produk = await prisma.produk.findUnique({
      where: { id: produkId },
    });
    if (!produk) {
      throw new APIError(`Produk dengan ID ${produkId} tidak ditemukan.`, 404);
    }

    const stokSebelum = Number(produk.stok);
    if (stokSebelum < qtyToDeduct) {
      throw new APIError(`Stok produk '${produk.nama}' tidak mencukupi. Dibutuhkan: ${qtyToDeduct}, Tersedia: ${stokSebelum}`, 400);
    }

    const stokSesudah = stokSebelum - qtyToDeduct;

    // Update stok produk di database
    await prisma.produk.update({
      where: { id: produkId },
      data: { stok: stokSesudah },
    });

    // Ambil batch stok yang aktif (qty_sisa > 0) terurut FEFO:
    // 1. Expired date terdekat (yang tidak null)
    // 2. Batch tanpa expired date (null) ditaruh di paling belakang
    const batches = (await prisma.$queryRawUnsafe(
      `SELECT * FROM stok_batch 
       WHERE produk_id = ? AND qty_sisa > 0 
       ORDER BY (expired_date IS NULL) ASC, expired_date ASC`,
      produkId
    )) as any[];

    let remainingQty = qtyToDeduct;
    const deductedBatches: Array<{ batchId: number; qty: number }> = [];

    for (const batch of batches) {
      if (remainingQty <= 0) break;

      const qtySisa = Number(batch.qty_sisa);
      if (qtySisa >= remainingQty) {
        // Kurangi dari batch ini sepenuhnya
        await prisma.stok_batch.update({
          where: { id: batch.id },
          data: { qty_sisa: qtySisa - remainingQty },
        });

        deductedBatches.push({ batchId: batch.id, qty: remainingQty });

        // Catat log mutasi
        await prisma.stok_log.create({
          data: {
            produk_id: produkId,
            batch_id: batch.id,
            tipe: 'keluar',
            qty: -remainingQty,
            stok_sebelum: stokSebelum,
            stok_sesudah: stokSesudah,
            referensi: referensi ?? null,
            user_id: userId ?? null,
            catatan: catatan ?? null,
          },
        });

        remainingQty = 0;
      } else {
        // Kurangi semua qty sisa di batch ini
        const deductAmount = qtySisa;
        await prisma.stok_batch.update({
          where: { id: batch.id },
          data: { qty_sisa: 0 },
        });

        deductedBatches.push({ batchId: batch.id, qty: deductAmount });
        remainingQty -= deductAmount;

        // Catat log mutasi
        await prisma.stok_log.create({
          data: {
            produk_id: produkId,
            batch_id: batch.id,
            tipe: 'keluar',
            qty: -deductAmount,
            stok_sebelum: stokSebelum,
            stok_sesudah: stokSesudah,
            referensi: referensi ?? null,
            user_id: userId ?? null,
            catatan: catatan ?? null,
          },
        });
      }
    }

    // Cek minimum threshold stok
    const updatedProduk = await prisma.produk.findUnique({ where: { id: produkId } });
    if (updatedProduk) {
      await this.cekThresholdStok(updatedProduk);
    }

    return deductedBatches;
  }

  static async cekThresholdStok(produk: any) {
    const stokVal = Number(produk.stok);
    const stokMinVal = Number(produk.stok_min);

    if (stokVal <= stokMinVal) {
      const tipeNotif = stokVal <= 0 ? 'stok_habis' : 'stok_rendah';
      const judul = stokVal <= 0 ? `Stok Habis: ${produk.nama}` : `Stok Rendah: ${produk.nama}`;
      const pesan = `Stok produk ${produk.nama} tersisa ${stokVal} ${produk.satuan}. Batas minimum: ${stokMinVal} ${produk.satuan}.`;

      // Cek apakah notifikasi serupa yang belum dibaca sudah ada
      const exists = await prisma.notifikasi.findFirst({
        where: {
          tipe: tipeNotif,
          referensi_id: produk.id,
          is_dibaca: 0,
        },
      });

      if (!exists) {
        await prisma.notifikasi.create({
          data: {
            tipe: tipeNotif,
            judul,
            pesan,
            referensi_id: produk.id,
          },
        });
      }
    }
  }

  static async tambahBarangMasuk(data: any, actorId: number, ip: string, userAgent: string) {
    const { batch } = await this.tambahStok({
      produkId: data.produk_id,
      qty: data.qty,
      hargaBeli: data.harga_beli,
      batchNo: data.batch_no,
      expiredDate: data.expired_date,
      supplierId: data.supplier_id,
      userId: actorId,
      catatan: data.catatan,
      referensi: 'INCOMING',
    });

    await catatAudit({
      userId: actorId,
      aksi: 'create',
      entitas: 'stok_batch',
      entitasId: batch.id,
      dataBaru: { produk_id: data.produk_id, qty: Number(data.qty), batch_no: data.batch_no },
      ipAddress: ip,
      userAgent,
    });

    return batch;
  }

  static async buatStokOpname(data: any, actorId: number, ip: string, userAgent: string) {
    const produk = await prisma.produk.findFirst({
      where: { id: data.produk_id, deleted_at: null },
    });
    if (!produk) {
      throw new APIError('Produk tidak ditemukan', 404);
    }

    const stokSistem = Number(produk.stok);
    const selisih = data.stok_fisik - stokSistem;

    const opname = await prisma.stok_opname.create({
      data: {
        produk_id: data.produk_id,
        user_id: actorId,
        stok_sistem: stokSistem,
        stok_fisik: data.stok_fisik,
        selisih: selisih,
        alasan: data.alasan ?? null,
        status: 'draft',
      },
    });

    await catatAudit({
      userId: actorId,
      aksi: 'create',
      entitas: 'stok_opname',
      entitasId: opname.id,
      dataBaru: { produk_id: data.produk_id, stok_fisik: Number(data.stok_fisik), selisih: Number(selisih) },
      ipAddress: ip,
      userAgent,
    });

    return opname;
  }

  static async approveStokOpname(opnameId: number, actorId: number, ip: string, userAgent: string) {
    const opname = await prisma.stok_opname.findUnique({
      where: { id: opnameId },
    });
    if (!opname) {
      throw new APIError('Pencatatan stok opname tidak ditemukan', 404);
    }

    if (opname.status === 'approved') {
      throw new APIError('Stok opname ini sudah disetujui sebelumnya', 400);
    }

    const produk = await prisma.produk.findUnique({
      where: { id: opname.produk_id },
    });
    if (!produk) {
      throw new APIError('Produk terkait tidak ditemukan', 404);
    }

    const stokSebelum = Number(produk.stok);
    const stokSesudah = Number(opname.stok_fisik);

    // Apply adjustments in main product stock
    await prisma.produk.update({
      where: { id: opname.produk_id },
      data: { stok: stokSesudah },
    });

    // Log stock change
    await prisma.stok_log.create({
      data: {
        produk_id: opname.produk_id,
        tipe: 'opname',
        qty: opname.selisih,
        stok_sebelum: stokSebelum,
        stok_sesudah: stokSesudah,
        referensi: `OPNAME-${opname.id}`,
        user_id: actorId,
        catatan: `Persetujuan Opname. Alasan: ${opname.alasan || '-'}`,
      },
    });

    const selisihVal = Number(opname.selisih);

    if (selisihVal < 0) {
      // Negative discrepancy, reduce from latest batch
      let remainingReduction = Math.abs(selisihVal);
      const batches = await prisma.stok_batch.findMany({
        where: { produk_id: opname.produk_id, qty_sisa: { gt: 0 } },
        orderBy: { created_at: 'desc' },
      });

      for (const batch of batches) {
        if (remainingReduction <= 0) break;
        const qtySisa = Number(batch.qty_sisa);
        if (qtySisa >= remainingReduction) {
          await prisma.stok_batch.update({
            where: { id: batch.id },
            data: { qty_sisa: qtySisa - remainingReduction },
          });
          remainingReduction = 0;
        } else {
          await prisma.stok_batch.update({
            where: { id: batch.id },
            data: { qty_sisa: 0 },
          });
          remainingReduction -= qtySisa;
        }
      }
    } else if (selisihVal > 0) {
      // Excess stock, add as an adjustment batch
      await prisma.stok_batch.create({
        data: {
          produk_id: opname.produk_id,
          batch_no: 'OPNAME-ADJ',
          qty_masuk: selisihVal,
          qty_sisa: selisihVal,
          harga_beli: produk.harga_beli,
          catatan: `Penyesuaian lebih stok dari opname #${opname.id}`,
        },
      });
    }

    // Update opname status
    const updatedOpname = await prisma.stok_opname.update({
      where: { id: opnameId },
      data: { status: 'approved' },
    });

    // Check threshold again
    const updatedProduk = await prisma.produk.findUnique({ where: { id: opname.produk_id } });
    if (updatedProduk) {
      await this.cekThresholdStok(updatedProduk);
    }

    await catatAudit({
      userId: actorId,
      aksi: 'update',
      entitas: 'stok_opname',
      entitasId: opname.id,
      dataLama: { status: 'draft' },
      dataBaru: { status: 'approved' },
      ipAddress: ip,
      userAgent,
    });

    return updatedOpname;
  }

  static async getStokLogs(skip = 0, limit = 20, produkId?: number, tipe?: string) {
    const where: any = {};
    if (produkId) where.produk_id = produkId;
    if (tipe) where.tipe = tipe;

    return await prisma.stok_log.findMany({
      where,
      orderBy: { created_at: 'desc' },
      skip,
      take: limit,
      include: {
        produk: true,
      },
    });
  }

  static async getStokBatches(skip = 0, limit = 20, produkId?: number) {
    const where: any = {
      qty_sisa: { gt: 0 },
    };
    if (produkId) where.produk_id = produkId;

    return await prisma.stok_batch.findMany({
      where,
      orderBy: { expired_date: 'asc' },
      skip,
      take: limit,
      include: {
        produk: true,
      },
    });
  }
}