34627-vm/api/add_asset.php
Flatlogic Bot 8d0038be8c satu
2025-10-03 13:56:08 +00:00

71 lines
2.1 KiB
PHP

<?php
// api/add_asset.php
require_once __DIR__ . '/../db/config.php';
header('Content-Type: application/json');
// --- Validation ---
$errors = [];
if (empty($_POST['nama_aset'])) {
$errors[] = 'Nama aset tidak boleh kosong.';
}
if (empty($_POST['id_kategori'])) {
$errors[] = 'Kategori harus dipilih.';
}
if (empty($_POST['id_kantor_lokasi'])) {
$errors[] = 'Lokasi kantor harus dipilih.';
}
if (empty($_POST['tanggal_pembelian'])) {
$errors[] = 'Tanggal pembelian tidak boleh kosong.';
}
if (empty($_POST['harga_pembelian'])) {
$errors[] = 'Harga pembelian tidak boleh kosong.';
}
if (!empty($errors)) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => implode(' ', $errors)]);
exit;
}
try {
$pdo = getDbConnection();
// --- Generate Asset Code ---
$stmt = $pdo->prepare("SELECT kode_kategori FROM kategori_aset WHERE id = ?");
$stmt->execute([$_POST['id_kategori']]);
$kode_kategori = $stmt->fetchColumn();
$tahun = date('Y');
$stmt = $pdo->prepare("SELECT COUNT(*) FROM aset WHERE kode_aset LIKE ?");
$stmt->execute([$kode_kategori . '-' . $tahun . '%']);
$nomor_urut = $stmt->fetchColumn() + 1;
$kode_aset = $kode_kategori . '-' . $tahun . '-' . str_pad($nomor_urut, 4, '0', STR_PAD_LEFT);
// --- Insert into Database ---
$sql = "INSERT INTO aset (kode_aset, nama_aset, id_kategori, id_kantor_lokasi, spesifikasi, tanggal_pembelian, harga_pembelian, vendor, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([
$kode_aset,
$_POST['nama_aset'],
$_POST['id_kategori'],
$_POST['id_kantor_lokasi'],
$_POST['spesifikasi'] ?? null,
$_POST['tanggal_pembelian'],
$_POST['harga_pembelian'],
$_POST['vendor'] ?? null,
$_POST['status'] ?? 'Tersedia'
]);
echo json_encode(['success' => true, 'message' => 'Aset berhasil ditambahkan.', 'new_asset_id' => $pdo->lastInsertId()]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>