All files / src/permintaan permintaan.service.ts

95.83% Statements 115/120
71.05% Branches 27/38
100% Functions 22/22
97.16% Lines 103/106

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 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 3192x         2x 2x 2x 2x 2x     2x   2x     2x     23x   23x   23x 23x       6x 1x   5x 5x 5x 2x           3x 3x 3x         3x 1x       2x 1x             1x   1x           1x     1x 1x             1x   1x               1x           1x             2x       2x   1x             1x                       10x 10x       10x 1x 9x 2x   7x 7x 1x       6x 6x 6x 6x 1x 5x 2x       3x 1x       2x 2x       2x 1x 1x 1x   1x   1x 1x 1x         1x             2x 2x 1x   2x 2x 2x 2x   2x 2x   2x                 1x                 1x               1x 1x 1x                       1x 1x 12x 12x 23x 12x   1x       1x 1x     1x                     1x     1x                                                 1x                                 1x 1x 1x 121x 1x 1x 1x        
import {
  Injectable,
  BadRequestException,
  NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Permintaan } from '../entities/permintaan.entity';
import { DetailPermintaan } from '../entities/detail_permintaan.entity';
import { Barang } from '../entities/barang.entity';
import { Repository, DataSource, Between, Raw } from 'typeorm';
import { CreatePermintaanDto } from './dto/create-permintaan.dto';
import { VerifikasiPermintaanDto } from './dto/verifikasi-permintaan.dto';
import * as PdfPrinter from 'pdfmake';
import * as fs from 'fs';
import * as path from 'path';
 
@Injectable()
export class PermintaanService {
  constructor(
    @InjectRepository(Permintaan)
    private permintaanRepo: Repository<Permintaan>,
    @InjectRepository(DetailPermintaan)
    private detailRepo: Repository<DetailPermintaan>,
    @InjectRepository(Barang)
    private barangRepo: Repository<Barang>,
    private dataSource: DataSource, // inject DataSource
  ) {}
 
  async create(dto: CreatePermintaanDto, userId: number) {
    if (!dto.items || dto.items.length === 0) {
      throw new BadRequestException('Items tidak boleh kosong');
    }
    const barangIds = dto.items.map((i) => i.id_barang);
    const barangList = (await this.barangRepo.findByIds(barangIds)) ?? [];
    if (barangList.length !== barangIds.length) {
      throw new BadRequestException(
        'Ada barang yang tidak ditemukan atau tidak aktif',
      );
    }
 
    // === Tambahan: Validasi stok tersedia ===
    for (const item of dto.items) {
      const barang = barangList.find((b) => b.id === item.id_barang);
      Iif (!barang) {
        throw new BadRequestException(
          `Barang dengan ID ${item.id_barang} tidak ditemukan`,
        );
      }
      if (barang.status_aktif === false) {
        throw new BadRequestException(
          `Barang dengan ID ${item.id_barang} tidak aktif`,
        );
      }
      if (barang.stok < item.jumlah) {
        throw new BadRequestException(
          `Stok barang "${barang.nama_barang}" tidak mencukupi. Stok tersedia: ${barang.stok}, diminta: ${item.jumlah}`,
        );
      }
    }
    // === End validasi stok ===
 
    return await this.dataSource.transaction(async (manager) => {
      // Simpan permintaan
      const permintaan = this.permintaanRepo.create({
        id_user_pemohon: userId,
        catatan: dto.catatan,
        status: 'Menunggu',
        tanggal_permintaan: new Date(),
      });
      const savedPermintaan = await manager.save(permintaan);
 
      // Simpan detail_permintaan
      const details = dto.items.map((item) =>
        this.detailRepo.create({
          id_permintaan: savedPermintaan.id,
          id_barang: item.id_barang,
          jumlah_diminta: item.jumlah,
          jumlah_disetujui: 0,
        }),
      );
      const savedDetails = await manager.save(details);
 
      return {
        ...savedPermintaan,
        items: savedDetails,
      };
    });
  }
 
  async getRiwayatByUser(userId: number) {
    const riwayat = await this.permintaanRepo.find({
      where: { id_user_pemohon: userId },
      order: { tanggal_permintaan: 'DESC' },
      relations: ['details', 'details.barang'],
    });
    // Tambahkan field items agar konsisten dengan response detail
    return riwayat.map((permintaan) => ({
      ...permintaan,
      items: permintaan.details,
    }));
  }
 
  async findOneById(id: number) {
    const permintaan = await this.permintaanRepo.findOne({
      where: { id },
      relations: ['details', 'details.barang', 'pemohon'],
    });
    if (!permintaan) throw new NotFoundException('Permintaan tidak ditemukan');
    // Map details ke items agar response konsisten
    return {
      ...permintaan,
      items: permintaan.details,
    };
  }
 
  async getPermintaanMenunggu() {
    return this.permintaanRepo.find({
      where: { status: 'Menunggu' },
      order: { tanggal_permintaan: 'ASC' },
      relations: ['details', 'details.barang', 'pemohon'],
    });
  }
 
  async verifikasiPermintaan(
    id: number,
    dto: VerifikasiPermintaanDto,
    verifikatorId: number,
  ) {
    return this.dataSource.transaction(async (manager) => {
      const permintaan = await manager.findOne(Permintaan, {
        where: { id },
        relations: ['details', 'details.barang'],
      });
      if (!permintaan)
        throw new NotFoundException('Permintaan tidak ditemukan');
      if (permintaan.status !== 'Menunggu')
        throw new BadRequestException('Permintaan sudah diverifikasi');
 
      const allowed = ['setuju', 'setuju_sebagian', 'tolak'];
      if (!allowed.includes(dto.keputusan)) {
        throw new BadRequestException('Keputusan tidak valid');
      }
 
      // Validasi dan update detail_permintaan
      let totalDisetujui = 0;
      for (const item of dto.items) {
        const detail = permintaan.details.find((d) => d.id === item.id_detail);
        if (!detail)
          throw new BadRequestException(`Detail permintaan tidak ditemukan`);
        if (item.jumlah_disetujui > detail.barang.stok) {
          throw new BadRequestException(
            `Stok barang "${detail.barang.nama_barang}" tidak mencukupi. Stok tersedia: ${detail.barang.stok}, diminta: ${item.jumlah_disetujui}`,
          );
        }
        if (item.jumlah_disetujui > detail.jumlah_diminta) {
          throw new BadRequestException(
            `Jumlah disetujui tidak boleh melebihi jumlah diminta`,
          );
        }
        detail.jumlah_disetujui = item.jumlah_disetujui;
        totalDisetujui += item.jumlah_disetujui;
      }
 
      // Update stok barang jika disetujui
      if (dto.keputusan !== 'tolak') {
        for (const item of dto.items) {
          const detail = permintaan.details.find(
            (d) => d.id === item.id_detail,
          );
          Iif (!detail)
            throw new BadRequestException(`Detail permintaan tidak ditemukan`);
          if (item.jumlah_disetujui > 0) {
            detail.barang.stok -= item.jumlah_disetujui;
            Iif (detail.barang.stok < 0) {
              throw new BadRequestException(
                `Stok barang "${detail.barang.nama_barang}" tidak boleh minus`,
              );
            }
            await manager.save(detail.barang);
          }
        }
      }
 
      // Update status permintaan
      let status: 'Menunggu' | 'Disetujui' | 'Disetujui Sebagian' | 'Ditolak' =
        'Ditolak';
      if (dto.keputusan === 'setuju') status = 'Disetujui';
      else Iif (dto.keputusan === 'sebagian') status = 'Disetujui Sebagian';
 
      permintaan.status = status;
      permintaan.id_user_verifikator = verifikatorId;
      permintaan.tanggal_verifikasi = new Date();
      permintaan.catatan = dto.catatan_verifikasi ?? '';
 
      await manager.save(permintaan.details);
      await manager.save(permintaan);
 
      return {
        ...permintaan,
        items: permintaan.details,
      };
    });
  }
 
  async getDashboardStatistik() {
    const [totalBarang, totalPermintaanTertunda, totalBarangKritis] =
      await Promise.all([
        this.barangRepo.count(),
        this.permintaanRepo.count({ where: { status: 'Menunggu' } }),
        this.barangRepo
          .createQueryBuilder('barang')
          .where('barang.stok <= barang.ambang_batas_kritis')
          .andWhere('barang.status_aktif = :aktif', { aktif: true })
          .getCount(),
      ]);
    return {
      totalBarang,
      totalPermintaanTertunda,
      totalBarangKritis,
    };
  }
 
  async getTrenPermintaanBulanan() {
    const now = new Date();
    const start = new Date(now.getFullYear(), now.getMonth() - 11, 1);
    const data = await this.permintaanRepo
      .createQueryBuilder('permintaan')
      .select([
        "TO_CHAR(permintaan.tanggal_permintaan, 'YYYY-MM') AS bulan",
        'COUNT(*)::int AS jumlah',
      ])
      .where('permintaan.tanggal_permintaan >= :start', { start })
      .groupBy('bulan')
      .orderBy('bulan', 'ASC')
      .getRawMany();
 
    // Lengkapi bulan yang tidak ada permintaan dengan 0
    const result: { bulan: string; jumlah: number }[] = [];
    for (let i = 0; i < 12; i++) {
      const d = new Date(now.getFullYear(), now.getMonth() - 11 + i, 1);
      const bulan = d.toISOString().slice(0, 7);
      const found = data.find((row) => row.bulan === bulan);
      result.push({ bulan, jumlah: found ? Number(found.jumlah) : 0 });
    }
    return result;
  }
 
  async generateBuktiPermintaanPDF(id: number): Promise<Buffer> {
    const permintaan = await this.findOneById(id);
    Iif (!permintaan) throw new NotFoundException('Permintaan tidak ditemukan');
 
    // Load font
    const fonts = {
      Roboto: {
        normal: path.join(__dirname, '../assets/fonts/Roboto-Regular.ttf'),
        bold: path.join(__dirname, '../assets/fonts/Roboto-Bold.ttf'),
        italics: path.join(__dirname, '../assets/fonts/Roboto-Italic.ttf'),
        bolditalics: path.join(
          __dirname,
          '../assets/fonts/Roboto-BoldItalic.ttf',
        ),
      },
    };
    const printer = new PdfPrinter(fonts);
 
    // Compose document definition
    const docDefinition = {
      content: [
        { text: 'Bukti Permintaan Barang', style: 'header' },
        { text: `Nomor: ${permintaan.id}`, margin: [0, 10, 0, 0] },
        {
          text: `Tanggal: ${new Date(permintaan.tanggal_permintaan).toLocaleDateString('id-ID')}`,
        },
        { text: `Pemohon: ${permintaan.pemohon?.nama ?? '-'}` },
        { text: `Unit Kerja: ${permintaan.pemohon?.unit_kerja ?? '-'}` },
        { text: `Status: ${permintaan.status}` },
        {
          text: `Catatan: ${permintaan.catatan ?? '-'}`,
          margin: [0, 0, 0, 10],
        },
        {
          table: {
            headerRows: 1,
            widths: ['*', 50, 50, 50],
            body: [
              [
                { text: 'Nama Barang', style: 'tableHeader' },
                { text: 'Diminta', style: 'tableHeader' },
                { text: 'Disetujui', style: 'tableHeader' },
                { text: 'Satuan', style: 'tableHeader' },
              ],
              ...permintaan.items.map((item) => [
                item.barang?.nama_barang ?? '-',
                item.jumlah_diminta,
                item.jumlah_disetujui,
                item.barang?.satuan ?? '-',
              ]),
            ],
          },
          layout: 'lightHorizontalLines',
        },
      ],
      styles: {
        header: { fontSize: 16, bold: true, alignment: 'center' },
        tableHeader: { bold: true, fillColor: '#eeeeee' },
      },
    };
 
    const pdfDoc = printer.createPdfKitDocument(docDefinition);
    const chunks: Buffer[] = [];
    return new Promise<Buffer>((resolve, reject) => {
      pdfDoc.on('data', (chunk) => chunks.push(chunk));
      pdfDoc.on('end', () => resolve(Buffer.concat(chunks)));
      pdfDoc.on('error', reject);
      pdfDoc.end();
    });
  }
}