2 Commits

Author SHA1 Message Date
33666a2f5f add: inventaris item coa mapping API 2026-07-09 16:30:53 +07:00
b29ba9f225 add: inventaris coa mapping API 2026-07-09 15:47:24 +07:00
15 changed files with 1934 additions and 7240 deletions

View File

@@ -1,10 +1,8 @@
<?php
class InventarisCoaMapping extends MY_Controller
{
class InventarisCoaMapping extends MY_Controller {
var $db;
public function index()
{
public function index() {
echo "Inventaris COA Mapping API";
}
@@ -13,226 +11,8 @@ class InventarisCoaMapping extends MY_Controller
parent::__construct();
}
## QUERY ##
public function getListCoa()
{
try {
if (!$this->isLogin) {
throw new Exception('Invalid token');
}
$para = $this->sys_input;
$keyword = "%" . $para['keyword'] . "%";
$sql = "SELECT
coaID,
coaAccountNo,
coaDescription
FROM coa
WHERE coaIsInput = 'Y'
AND (
coaDescription LIKE ?
OR coaAccountNo LIKE ?
)
AND coaIsActive = 'Y'
LIMIT 15";
$que = $this->db->query($sql, [$keyword, $keyword]);
if (!$que) {
throw new Exception('failed to query data inventaris gol', 1);
}
$data = $que->result_array();
$this->sys_ok($data);
} catch (Exception $e) {
$msg = '[Error] ' . $e->getMessage();
$code = $e->getCode();
if ($code == 0) {
$this->sys_error($msg);
} else {
$this->sys_error_db($msg);
}
exit;
}
}
public function getListInventarisGol()
{
try {
if (!$this->isLogin) {
throw new Exception('Invalid token');
}
$sql = "SELECT
M_InventarisGolID,
M_InventarisGolCode,
M_InventarisGolName
FROM m_inventaris_gol gol
WHERE gol.M_InventarisGolIsActive = 'Y'
AND NOT EXISTS (
SELECT 1
FROM m_inventaris_coa_mapping m
WHERE m.M_InventarisCoaMappingM_InventarisGolID = gol.M_InventarisGolID
AND m.M_InventarisCoaMappingIsActive = 'Y'
);";
$que = $this->db->query($sql);
if (!$que) {
throw new Exception('failed to query data inventaris gol', 1);
}
$data = $que->result_array();
$output = [
'records' => $data,
'total' => count($data)
];
$this->sys_ok($output);
} catch (Exception $e) {
$msg = '[Error] ' . $e->getMessage();
$code = $e->getCode();
if ($code == 0) {
$this->sys_error($msg);
} else {
$this->sys_error_db($msg);
}
exit;
}
}
public function getListInventorygolMapping()
{
try {
if (!$this->isLogin) {
throw new Exception('invalid token');
}
$para = $this->sys_input;
$keyword = "%" . $para['keyword'] . "%";
$limit = 10;
$offset = 0;
if ($para['currpage'] > 0) {
$offset = ($para['currpage'] - 1) * $limit;
}
$sql = "SELECT
M_InventarisGolID,
M_InventarisGolCode,
M_InventarisGolName,
M_InventarisCoaMappingID,
M_InventarisCoaMappingCoaInventarisID,
coaInv.coaAccountNo AS CoaInventarisAccountNo,
coaInv.coaDescription AS CoaInventarisDescription,
M_InventarisCoaMappingCoaHutangID,
coaHtg.coaAccountNo AS CoaHutangAccountNo,
coaHtg.coaDescription AS CoaHutangDescription,
M_InventarisCoaMappingCoaBebanPenyusutanID,
coaBbn.coaAccountNo AS CoaBebanPenyusutanAccountNo,
coaBbn.coaDescription AS CoaBebanPenyusutanDescription,
M_InventarisCoaMappingCoaAkumulasiPenyusutanID,
coaAkm.coaAccountNo AS CoaAkumulasiPenyusutanAccountNo,
coaAkm.coaDescription AS CoaAkumulasiPenyusutanDescription,
M_InventarisCoaMappingCoaLabaPelepasanID,
coaLab.coaAccountNo AS CoaLabaPelepasanAccountNo,
coaLab.coaDescription AS CoaLabaPelepasanDescription,
M_InventarisCoaMappingCoaRugiPelepasanID,
coaRug.coaAccountNo AS CoaRugiPelepasanAccountNo,
coaRug.coaDescription AS CoaRugiPelepasanDescription
FROM m_inventaris_gol
JOIN m_inventaris_coa_mapping
ON M_InventarisCoaMappingM_InventarisGolID = M_InventarisGolID
AND M_InventarisCoaMappingIsActive = 'Y'
AND M_InventarisGolIsActive = 'Y'
AND M_InventarisGolName LIKE ?
LEFT JOIN coa AS coaInv
ON M_InventarisCoaMappingCoaInventarisID = coaInv.coaID
LEFT JOIN coa AS coaHtg
ON M_InventarisCoaMappingCoaHutangID = coaHtg.coaID
LEFT JOIN coa AS coaBbn
ON M_InventarisCoaMappingCoaBebanPenyusutanID = coaBbn.coaID
LEFT JOIN coa AS coaAkm
ON M_InventarisCoaMappingCoaAkumulasiPenyusutanID = coaAkm.coaID
LEFT JOIN coa AS coaLab
ON M_InventarisCoaMappingCoaLabaPelepasanID = coaLab.coaID
LEFT JOIN coa AS coaRug
ON M_InventarisCoaMappingCoaRugiPelepasanID = coaRug.coaID
WHERE M_InventarisGolIsActive = 'Y'";
$sql_data = $sql . " ORDER BY M_InventarisGolID LIMIT ? OFFSET ? ";
$que = $this->db->query($sql_data, [
$keyword,
$limit,
$offset
]);
if (!$que) {
throw new Exception('failed to query data mapping coa inventaris golongan', 1);
}
$sql_total = "SELECT COUNT(*) AS total FROM ($sql) AS x";
$que_total = $this->db->query($sql_total, [$keyword]);
if (!$que_total) {
throw new Exception('failed to get total rows data', 1);
}
$this->sys_ok([
"records" => $que->result_array(),
"total" => $que_total->row_array()['total']
]);
} catch (Exception $e) {
$msg = '[Error] ' . $e->getMessage();
$code = $e->getCode();
if ($code == 0) {
$this->sys_error($msg);
} else {
$this->sys_error_db($msg);
}
exit;
}
}
public function getInvCoaMappingDetail()
{
try {
if (!$this->isLogin) {
$this->sys_error("invalid token");
exit;
}
$para = $this->sys_input;
$sql = "SELECT
M_InventarisCoaMappingID,
M_InventarisCoaMappingM_InventarisGolID,
M_InventarisCoaMappingCoaInventarisID,
M_InventarisCoaMappingCoaHutangID,
M_InventarisCoaMappingCoaPembelianID,
M_InventarisCoaMappingCoaBebanPenyusutanID,
M_InventarisCoaMappingCoaAkumulasiPenyusutanID,
M_InventarisCoaMappingCoaLabaPelepasanID,
M_InventarisCoaMappingCoaRugiPelepasanID,
M_InventarisCoaMappingCreatedUserID,
M_InventarisCoaMappingCreated,
M_InventarisCoaMappingLastUpdated
FROM m_inventaris_coa_mapping
WHERE M_InventarisCoaMappingIsActive = 'Y'
AND M_InventarisCoaMappingID = ?";
$query = $this->db->query($sql, [$para['M_InventarisCoaMappingID']]);
if (!$query) {
$this->sys_error_db("[Error] get data m_inventaris_coa_mapping");
exit;
}
$data = $query->row_array();
$this->sys_ok($data);
} catch (Exception $exc) {
$msg = $exc->getMessage();
$this->sys_error($msg);
}
}
## MUTATIONS ##
public function createInvCoaMapping()
{
public function createInvCoaMapping() {
try {
if (!$this->isLogin) {
$this->sys_error("invalid token");
@@ -284,8 +64,48 @@ class InventarisCoaMapping extends MY_Controller
}
}
public function editInvCoaMapping()
{
## QUERY ##
public function getInvCoaMapping() {
try {
if (!$this->isLogin) {
$this->sys_error("invalid token");
exit;
}
$para = $this->sys_input;
$sql = "SELECT
M_InventarisCoaMappingID,
M_InventarisCoaMappingM_InventarisGolID,
M_InventarisCoaMappingCoaInventarisID,
M_InventarisCoaMappingCoaHutangID,
M_InventarisCoaMappingCoaPembelianID,
M_InventarisCoaMappingCoaBebanPenyusutanID,
M_InventarisCoaMappingCoaAkumulasiPenyusutanID,
M_InventarisCoaMappingCoaLabaPelepasanID,
M_InventarisCoaMappingCoaRugiPelepasanID,
M_InventarisCoaMappingCreatedUserID,
M_InventarisCoaMappingCreated,
M_InventarisCoaMappingLastUpdated
FROM m_inventaris_coa_mapping
WHERE M_InventarisCoaMappingIsActive = 'Y'
AND M_InventarisCoaMappingID = ?";
$query = $this->db->query($sql, [$para['M_InventarisCoaMappingID']]);
if (!$query) {
$this->sys_error_db("[Error] get data m_inventaris_coa_mapping");
exit;
}
$data = $query->row_array();
$this->sys_ok($data);
} catch (Exception $exc) {
$msg = $exc->getMessage();
$this->sys_error($msg);
}
}
## MUTATIONS ##
public function editInvCoaMapping() {
try {
if (!$this->isLogin) {
$this->sys_error("invalid token");
@@ -334,8 +154,7 @@ class InventarisCoaMapping extends MY_Controller
}
}
public function deleteInvCoaMapping()
{
public function deleteInvCoaMapping() {
try {
if (!$this->isLogin) {
$this->sys_error("invalid token");
@@ -366,129 +185,8 @@ class InventarisCoaMapping extends MY_Controller
}
}
## QUERY ITEM ##
public function getListItemInventaris()
{
try {
if (!$this->isLogin) {
throw new Exception('Invalid token');
}
$para = $this->sys_input;
$sql = "SELECT
M_ItemID,
M_ItemCode,
M_ItemDesc,
M_ItemM_InventarisGolID AS itemGolID,
IFNULL(M_InventarisItemCoaMappingID, 0) AS itemCoaMapID,
M_InventarisItemCoaMappingCoaInventarisID,
coaInv.coaAccountNo AS CoaInventarisAccountNo,
coaInv.coaDescription AS CoaInventarisDescription,
M_InventarisItemCoaMappingCoaHutangID,
coaHtg.coaAccountNo AS CoaHutangAccountNo,
coaHtg.coaDescription AS CoaHutangDescription,
M_InventarisItemCoaMappingCoaBebanPenyusutanID,
coaBbn.coaAccountNo AS CoaBebanPenyusutanAccountNo,
coaBbn.coaDescription AS CoaBebanPenyusutanDescription,
M_InventarisItemCoaMappingCoaAkumulasiPenyusutanID,
coaAkm.coaAccountNo AS CoaAkumulasiPenyusutanAccountNo,
coaAkm.coaDescription AS CoaAkumulasiPenyusutanDescription,
M_InventarisItemCoaMappingCoaLabaPelepasanID,
coaLab.coaAccountNo AS CoaLabaPelepasanAccountNo,
coaLab.coaDescription AS CoaLabaPelepasanDescription,
M_InventarisItemCoaMappingCoaRugiPelepasanID,
coaRug.coaAccountNo AS CoaRugiPelepasanAccountNo,
coaRug.coaDescription AS CoaRugiPelepasanDescription
FROM m_item
LEFT JOIN m_inventaris_item_coa_mapping
ON M_ItemID = M_InventarisItemCoaMappingM_ItemID
AND M_InventarisItemCoaMappingIsActive = 'Y'
LEFT JOIN coa AS coaInv
ON M_InventarisItemCoaMappingCoaInventarisID = coaInv.coaID
LEFT JOIN coa AS coaHtg
ON M_InventarisItemCoaMappingCoaHutangID = coaHtg.coaID
LEFT JOIN coa AS coaBbn
ON M_InventarisItemCoaMappingCoaBebanPenyusutanID = coaBbn.coaID
LEFT JOIN coa AS coaAkm
ON M_InventarisItemCoaMappingCoaAkumulasiPenyusutanID = coaAkm.coaID
LEFT JOIN coa AS coaLab
ON M_InventarisItemCoaMappingCoaLabaPelepasanID = coaLab.coaID
LEFT JOIN coa AS coaRug
ON M_InventarisItemCoaMappingCoaRugiPelepasanID = coaRug.coaID
WHERE M_ItemItem_CategoryID = 2
AND M_ItemM_InventarisGolID = ?
AND M_ItemIsActive = 'Y'";
$que = $this->db->query($sql, [
$para['golID']
]);
if (!$que) {
throw new Exception('failed to query data inventaris gol', 1);
}
$data = $que->result_array();
$output = [
'records' => $data,
'total' => count($data)
];
$this->sys_ok($output);
} catch (Exception $e) {
$msg = '[Error] ' . $e->getMessage();
$code = $e->getCode();
if ($code == 0) {
$this->sys_error($msg);
} else {
$this->sys_error_db($msg);
}
exit;
}
}
public function getInvItemCoaMapping()
{
try {
if (!$this->isLogin) {
$this->sys_error("invalid token");
exit;
}
$para = $this->sys_input;
$sql = "SELECT
M_InventarisItemCoaMappingID,
M_InventarisItemCoaMappingM_ItemID,
M_InventarisItemCoaMappingCoaInventarisID,
M_InventarisItemCoaMappingCoaHutangID,
M_InventarisItemCoaMappingCoaPembelianID,
M_InventarisItemCoaMappingCoaBebanPenyusutanID,
M_InventarisItemCoaMappingCoaAkumulasiPenyusutanID,
M_InventarisItemCoaMappingCoaLabaPelepasanID,
M_InventarisItemCoaMappingCoaRugiPelepasanID,
M_InventarisItemCoaMappingCreatedUserID,
M_InventarisItemCoaMappingCreated,
M_InventarisItemCoaMappingLastUpdated
FROM m_inventaris_item_coa_mapping
WHERE M_InventarisItemCoaMappingIsActive = 'Y'
AND M_InventarisItemCoaMappingID = ?";
$query = $this->db->query($sql, [$para['M_InventarisItemCoaMappingID']]);
if (!$query) {
$this->sys_error_db("[Error] get data m_inventaris_item_coa_mapping");
exit;
}
$data = $query->row_array();
$this->sys_ok($data);
} catch (Exception $exc) {
$msg = $exc->getMessage();
$this->sys_error($msg);
}
}
## MUTATIONS ITEM ##
public function createInvItemCoaMapping()
{
public function createInvItemCoaMapping() {
try {
if (!$this->isLogin) {
$this->sys_error("invalid token");
@@ -533,15 +231,55 @@ class InventarisCoaMapping extends MY_Controller
$insertID = $this->db->insert_id();
$this->db->trans_commit();
$this->sys_ok("[Success] insert coa item");
$this->sys_ok($insertID);
} catch (Exception $exc) {
$msg = $exc->getMessage();
$this->sys_error($msg);
}
}
public function editInvItemCoaMapping()
{
## QUERY ITEM ##
public function getInvItemCoaMapping() {
try {
if (!$this->isLogin) {
$this->sys_error("invalid token");
exit;
}
$para = $this->sys_input;
$sql = "SELECT
M_InventarisItemCoaMappingID,
M_InventarisItemCoaMappingM_ItemID,
M_InventarisItemCoaMappingCoaInventarisID,
M_InventarisItemCoaMappingCoaHutangID,
M_InventarisItemCoaMappingCoaPembelianID,
M_InventarisItemCoaMappingCoaBebanPenyusutanID,
M_InventarisItemCoaMappingCoaAkumulasiPenyusutanID,
M_InventarisItemCoaMappingCoaLabaPelepasanID,
M_InventarisItemCoaMappingCoaRugiPelepasanID,
M_InventarisItemCoaMappingCreatedUserID,
M_InventarisItemCoaMappingCreated,
M_InventarisItemCoaMappingLastUpdated
FROM m_inventaris_item_coa_mapping
WHERE M_InventarisItemCoaMappingIsActive = 'Y'
AND M_InventarisItemCoaMappingID = ?";
$query = $this->db->query($sql, [$para['M_InventarisItemCoaMappingID']]);
if (!$query) {
$this->sys_error_db("[Error] get data m_inventaris_item_coa_mapping");
exit;
}
$data = $query->row_array();
$this->sys_ok($data);
} catch (Exception $exc) {
$msg = $exc->getMessage();
$this->sys_error($msg);
}
}
## MUTATIONS ITEM ##
public function editInvItemCoaMapping() {
try {
if (!$this->isLogin) {
$this->sys_error("invalid token");
@@ -590,8 +328,7 @@ class InventarisCoaMapping extends MY_Controller
}
}
public function deleteInvItemCoaMapping()
{
public function deleteInvItemCoaMapping() {
try {
if (!$this->isLogin) {
$this->sys_error("invalid token");

View File

@@ -496,7 +496,6 @@ class Fakturv4 extends MY_Controller
ELSE ''
END as WarehouseName,
ReceiveOrderPoID,
ReceiveOrderPoTypePurchase,
PurchaseOrderItemCategoryID
FROM supplier_invoice
JOIN supplier_invoice_detail ON SupplierInvoiceID = SupplierInvoiceDetailSupplierInvoiceID
@@ -589,11 +588,12 @@ class Fakturv4 extends MY_Controller
'P'
) AS DiscountType,
SupplierInvoiceReceiveOrderPoID,
ReceiveOrderPoNumber,
ReceiveOrderPoTypePurchase AS typePurchase
ReceiveOrderPoNumber
FROM supplier_invoice
JOIN supplier ON SupplierInvoiceSupplierID = SupplierID
JOIN receive_order_po ON ReceiveOrderPoID = SupplierInvoiceReceiveOrderPoID
-- JOIN purchase_order ON SupplierInvoicePurchaseOrderID = PurchaseOrderID
-- AND PurchaseOrderIsActive = 'Y'
WHERE SupplierInvoiceIsActive = 'Y'
AND SupplierInvoiceID = ?";
$que = $this->db->query($sql, $para['SInvoiceID']);
@@ -601,7 +601,6 @@ class Fakturv4 extends MY_Controller
$this->sys_error_db('[Error] get detail data invoice');
exit;
}
$data = $que->row_array();
$sqldet = "SELECT
SupplierInvoiceDetailID,
@@ -637,30 +636,7 @@ class Fakturv4 extends MY_Controller
exit;
}
if (isset($data['typePurchase']) && $data['typePurchase'] == 'aset') {
$sql_dp = "SELECT
IFNULL(SupplierDownpaymentAmount, 0) AS dp_amount
FROM supplier_invoice
JOIN receive_order_po
ON ReceiveOrderPoID = SupplierInvoiceReceiveOrderPoID
JOIN purchase_order_asset_contract
ON PurchaseOrderAssetContractReceiveOrderPoID = ReceiveOrderPoID
AND PurchaseOrderAssetContractIsActive = 'Y'
JOIN supplier_downpayment
ON SupplierDownpaymentPurchasOrderID = PurchaseOrderAssetContractPurchaseOrderID
AND SupplierDownpaymentIsActive = 'Y'
WHERE SupplierInvoiceID = ?";
$que_dp = $this->db->query($sql_dp, [
$para['SInvoiceID']
]);
if (!$que_dp) {
$this->sys_error_db("[Error] get info contract asset");
exit;
}
$dp_amount = $que_dp->row_array()['dp_amount'];
$data['dp_amount'] = $dp_amount;
}
$data = $que->result_array()[0];
$data['detail'] = $quedet->result_array();
$result = $data;
@@ -1341,8 +1317,7 @@ class Fakturv4 extends MY_Controller
supplier_invoice_detail.*,
ReceiveOrderPoNumber,
ReceiveOrderPoM_BranchCode,
ReceiveOrderPoS_RegionalID,
ReceiveOrderPoTypePurchase AS typePurchase
ReceiveOrderPoS_RegionalID
FROM supplier_invoice
JOIN supplier_invoice_detail ON SupplierInvoiceDetailSupplierInvoiceID = SupplierInvoiceID
AND SupplierInvoiceDetailIsActive = 'Y'
@@ -1478,6 +1453,7 @@ class Fakturv4 extends MY_Controller
$coapph = $quepph->result_array()[0];
$pphval = doubleval($invoice[0]['SupplierInvoiceTaxAmountPph']);
if ($pphval > 0.00) {
$insertpph = $this->InsertJurnalTx(
$jurnalID,
@@ -1489,22 +1465,22 @@ class Fakturv4 extends MY_Controller
);
if (!$insertpph['status']) {
$this->db->trans_rollback();
$this->sys_error_db($insertpph['msg']);
$this->sys_error_db($insertpajak['msg']);
exit;
}
}
# insert shipping cost ke jurnal #
// ----------------------------------------------------------------------------------------
if ($ship_cost > 0.00) {
$queryshipcost = $this->db->query($sqlcoa, ['5320700001']);
if (!$queryshipcost) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] get coa cost ");
exit;
}
$coashipcost = $queryshipcost->result_array()[0];
$queryshipcost = $this->db->query($sqlcoa, ['5320700001']);
if (!$queryshipcost) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] get coa cost ");
exit;
}
$coashipcost = $queryshipcost->result_array()[0];
if ($ship_cost > 0.00) {
$insertcost = $this->InsertJurnalTx(
$jurnalID,
$coashipcost['coaID'],
@@ -1520,63 +1496,6 @@ class Fakturv4 extends MY_Controller
}
}
/* Insert jurnal tx for down payment asset */
// ----------------------------------------------------------------------------------------
if (isset($invoice[0]['typePurchase']) && $invoice[0]['typePurchase'] == 'aset') {
$sql_dpasset = "SELECT
PurchaseOrderAssetContractID,
PurchaseOrderAssetContractName,
SupplierDownpaymentAmount,
coaID,
coaDescription
FROM purchase_order_asset_contract
JOIN purchase_order ON PurchaseOrderID = PurchaseOrderAssetContractPurchaseOrderID
JOIN supplier_downpayment
ON SupplierDownpaymentPurchasOrderID = PurchaseOrderID
AND SupplierDownpaymentIsActive = 'Y'
JOIN purchase_order_detail
ON PurchaseOrderID = PurchaseOrderDetailPurchaseOrderID
AND PurchaseOrderDetailIsActive = 'Y'
JOIN m_item ON M_ItemID = PurchaseOrderDetailItemID
AND M_ItemItem_CategoryID = 3
JOIN fa_class ON Fa_ClassID = M_ItemFa_ClassID
AND Fa_ClassIsActive = 'Y'
JOIN coa ON coaID = Fa_ClassDownPaymentCoaID
AND coaIsActive = 'Y'
WHERE PurchaseOrderAssetContractReceiveOrderPoID = ?
AND PurchaseOrderAssetContractIsActive = 'Y'
LIMIT 1";
$que_dpasset = $this->db->query($sql_dpasset, [
$invoice[0]['SupplierInvoiceReceiveOrderPoID']
]);
if (!$que_dpasset) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] query dp asset not error");
exit;
}
$dpasset_coa = $que_dpasset->row_array();
if (!empty($dpasset_coa)) {
$totalDP = round($dpasset_coa['SupplierDownpaymentAmount'], 2);
if ($totalDP > 0) {
$insert_dp = $this->InsertJurnalTx(
$jurnalID,
$dpasset_coa['coaID'],
$dpasset_coa['coaDescription'],
$user['M_UserID'],
0,
$totalDP
);
if (!$insert_dp['status']) {
$this->db->trans_rollback();
$this->sys_error_db($insert_dp['msg']);
exit;
}
$invoice = $this->CalcProrateDownPaymentAsset($invoice, $totalDP);
}
}
}
// insert jurnal tx hutang per item (kredit)
// ----------------------------------------------------------------------------------------
foreach ($invoice as $key => $inv) {
@@ -1684,20 +1603,52 @@ class Fakturv4 extends MY_Controller
$this->sys_error_db($status['msg']);
exit;
}
} else if ($item['M_ItemItem_CategoryID'] == '3') {
$this->InsertJurnalTxAsset($jurnalID, $item['M_ItemID'], $inv, $user['M_UserID']);
} else if ($item['M_ItemItem_CategoryID'] == '3' && !empty($item['M_ItemFa_ClassID'])) {
$sqlsgp = "SELECT * FROM fa_class WHERE Fa_ClassID = ? AND Fa_ClassIsActive = 'Y'";
$quesgp = $this->db->query($sqlsgp, [$item['M_ItemFa_ClassID']]);
if (!$quesgp) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] get map_nat_subgroup");
exit;
}
$itemGroup = $quesgp->row_array();
if (empty($itemGroup)) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] fa class item tidak ditemukan / belum dimapping");
exit;
}
$price = (doubleval($inv['SupplierInvoiceDetailTotal']) - doubleval($inv['SupplierInvoiceDetailDiscountPoProrata']));
// $taxPPH = doubleval($inv['SupplierInvoiceTaxPercentPph']) * $price / 100;
$taxPPN = doubleval($inv['SupplierInvoiceTaxPercentPpn']) * $price / 100;
$kredit = round($price + $taxPPN, 2);
$status = $this->InsertJurnalTx(
$jurnalID,
$itemGroup['Fa_ClassCoaID'],
$itemGroup['Fa_ClassCoaDesc'],
$user['M_UserID'],
0,
$kredit
);
if (!$status) {
$this->sys_error_db($status['msg']);
exit;
}
} else if ($item['M_ItemItem_CategoryID'] == '4') {
$this->InsertJurnalTxJasa($jurnalID, $item['M_ItemID'], $inv, $user['M_UserID']);
}
}
$sqlinvgr = "INSERT INTO jurnal_addon (
jurnalAddOnJurnalID,
jurnalAddOnCode,
jurnalAddOnValue,
jurnalAddOnCreated,
jurnalAddOnCreatedUserID
) VALUES (?,?,?,NOW(),?)";
jurnalAddOnJurnalID,
jurnalAddOnCode,
jurnalAddOnValue,
jurnalAddOnCreated,
jurnalAddOnCreatedUserID
) VALUES (?,?,?,NOW(),?)";
$queinvgr = $this->db->query($sqlinvgr, [
$jurnalID,
'INVGR',
@@ -1723,13 +1674,13 @@ class Fakturv4 extends MY_Controller
private function InsertJurnalTxJasa($jurnalID, $itemid, $invoice, $userid)
{
$sql_coa = "SELECT
JasaCoaMapHutangCoaID,
JasaCoaMapHutangCoaNo,
JasaCoaMapHutangCoaDesc
FROM jasa_coa_map
JOIN coa ON coaID = JasaCoaMapHutangCoaID
AND coaIsActive = 'Y'
WHERE JasaCoaMapM_ItemID = ?";
JasaCoaMapHutangCoaID,
JasaCoaMapHutangCoaNo,
JasaCoaMapHutangCoaDesc
FROM jasa_coa_map
JOIN coa ON coaID = JasaCoaMapHutangCoaID
AND coaIsActive = 'Y'
WHERE JasaCoaMapM_ItemID = ?";
$que_coa = $this->db->query($sql_coa, [$itemid]);
if (!$que_coa) {
$this->db->trans_rollback();
@@ -1766,93 +1717,6 @@ class Fakturv4 extends MY_Controller
}
}
private function InsertJurnalTxAsset($jurnalID, $itemid, $invoice, $userid)
{
$sql_coa = "SELECT
Fa_ClassHutangCoaID,
Fa_ClassHutangCoaAccountNo,
Fa_ClassHutangCoaDesc
FROM m_item
JOIN fa_class ON Fa_ClassID = M_ItemFa_ClassID
WHERE M_ItemID = ?";
$que_coa = $this->db->query($sql_coa, $itemid);
if (!$que_coa) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] failed get coa hutang asset");
exit;
}
$coaasset = $que_coa->row_array();
if ($que_coa->num_rows() <= 0) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] aset debt coa not found");
exit;
}
$invtotal = doubleval($invoice['SupplierInvoiceDetailTotal']);
$disprorata = doubleval($invoice['SupplierInvoiceDetailDiscountPoProrata']);
$price = $invtotal - $disprorata;
$taxPPN = doubleval($invoice['SupplierInvoiceTaxPercentPpn']) * $price / 100;
$kredit = round($price + $taxPPN, 2);
$finalValue = round($kredit - doubleval($invoice['dpReduction']), 2);
$insert = $this->InsertJurnalTx(
$jurnalID,
$coaasset['Fa_ClassHutangCoaID'],
$coaasset['Fa_ClassHutangCoaDesc'],
$userid,
0,
$finalValue
);
if (!$insert) {
$this->db->trans_rollback();
$this->sys_error_db($insert['msg']);
exit;
}
}
private function CalcProrateDownPaymentAsset($items, $dpAmount)
{
$totalKredit = 0;
foreach ($items as $key => $value) {
$invtotal = doubleval($value['SupplierInvoiceDetailTotal']);
$disprorata = doubleval($value['SupplierInvoiceDetailDiscountPoProrata']);
$price = $invtotal - $disprorata;
$taxPPN = doubleval($value['SupplierInvoiceTaxPercentPpn']) * $price / 100;
$kredit = round($price + $taxPPN, 2);
$totalKredit = $totalKredit + $kredit;
$items[$key]['kredit'] = $kredit;
}
if ($totalKredit <= 0) {
foreach ($items as $key => $value) {
$items[$key]['dpReduction'] = 0;
}
return $items;
}
$runningReduction = 0;
end($items);
$lastKey = key($items);
reset($items);
foreach ($items as $key => $value) {
if ($key === $lastKey) {
$reduction = round($dpAmount - $runningReduction, 2);
} else {
$ratio = $value['kredit'] / $totalKredit;
$reduction = round($dpAmount * $ratio, 2);
$runningReduction += $reduction;
}
$items[$key]['dpReduction'] = $reduction;
}
return $items;
}
function InsertJurnalTx($jurnalID, $coaID, $desc, $userID, $debit = 0, $kredit = 0): array
{
try {

View File

@@ -1,90 +0,0 @@
@host = https://accone.aplikasi.web.id/one-api
@date = 2026-07-14
@coaBayarID = 1110100001
@coaHutangID = 2110100030
# =============================================================================
# JurnalPiCicilanOrderAset — Contoh Pemanggilan Endpoint
# =============================================================================
# Urutan penggunaan yang disarankan:
# 1. ListEligiblePurchaseOrderAssetContracts → lihat kontrak yang akan diproses
# 2. GenerateJournalsFromContracts (dryRun=Y) → simulasi tanpa simpan ke DB
# 3. GenerateJournalsFromContracts (dryRun=N) → generate jurnal sesungguhnya
# 4. CreateJournal → buat jurnal manual 1 per 1
# =============================================================================
### 1. Lihat kontrak aset yang eligible untuk dibuatkan jurnal bulan ini
GET {{host}}/index.php/mockup/scheduler/JurnalPiCicilanOrderAset/ListEligiblePurchaseOrderAssetContracts
Content-Type: application/json
{
"startDate": "2026-07-01",
"endDate": "2026-07-31"
}
### 2. Simulasi generate jurnal (dryRun=Y) — tidak menyimpan ke database
POST {{host}}/index.php/mockup/scheduler/JurnalPiCicilanOrderAset/GenerateJournalsFromContracts
Content-Type: application/json
{
"date" : "{{date}}",
"dryRun" : "Y"
}
### 3. Generate jurnal untuk semua kontrak eligible bulan ini (sesungguhnya)
POST {{host}}/index.php/mockup/scheduler/JurnalPiCicilanOrderAset/GenerateJournalsFromContracts
Content-Type: application/json
{
"date" : "{{date}}",
"dryRun" : "N"
}
### 4. Generate jurnal untuk 1 kontrak tertentu saja (contractID=99)
POST {{host}}/index.php/mockup/scheduler/JurnalPiCicilanOrderAset/GenerateJournalsFromContracts
Content-Type: application/json
{
"date" : "{{date}}",
"dryRun" : "Y",
"contractID" : 00
}
### 5. Buat jurnal manual (1 jurnal, input detail sendiri)
POST {{host}}/index.php/mockup/scheduler/JurnalPiCicilanOrderAset/CreateJournal
Content-Type: application/json
{
"date" : "{{date}}",
"branchCode" : "BA",
"regionalID" : 8,
"branchCompanyID": 1,
"jurnalTypeID" : 11,
"title" : "Jurnal PI Cicilan Order Aset",
"description" : "Cicilan ke-1 dari 12 | Kontrak Kendaraan Operasional | Periode 2026-07",
"details" : [
{
"coaID" : {{coaHutangID}},
"description": "Hutang cicilan aset - Kendaraan Operasional",
"debit" : 15000000,
"credit" : 0,
"addonCode" : "PIINSTALMENT",
"addonValue" : "42",
"mItemID" : 123
},
{
"coaID" : {{coaBayarID}},
"description": "Pembayaran cicilan aset - Kendaraan Operasional",
"debit" : 0,
"credit" : 15000000,
"addonCode" : "PIINSTALMENT",
"addonValue" : "42",
"mItemID" : 123
}
]
}

View File

@@ -1,970 +0,0 @@
<?php
/**
* JurnalPiCicilanOrderAset
*
* Controller scheduler untuk membuat jurnal akuntansi atas Purchase Invoice (PI)
* cicilan order aset secara otomatis.
*
* Alur bisnis proses:
* 1. Validasi parameter input (tanggal, branchCode, title, description, details)
* 2. Insert header jurnal ke tabel `jurnal`
* - Nomor jurnal di-generate via fn_numbering('J')
* - Tipe jurnal: PAYMENT
* - Berisi: title, description, tanggal, regionalID, kode cabang, branchCompanyID
* 3. Insert baris transaksi ke tabel `jurnal_tx` (untuk setiap baris cicilan)
* - Referensi ke jurnalID header
* - COA (Chart of Account) dan deskripsinya:
* * Sisi hutang cicilan → nilai DEBIT (diambil dari HutangCoaID di fa_class)
* * Sisi pembayaran cicilan → nilai KREDIT (diambil dari ItemCoaID di fa_class)
* 4. Insert data tambahan ke tabel `jurnal_addon` (jika ada addonValue atau mItemID)
* - Referensi ke jurnalID dan jurnalTxID
* - Berisi: addonCode (default: "PIINSTALMENT"), addonValue, mItemID
*
* Endpoint:
* POST /mockup/scheduler/JurnalPiCicilanOrderAset/CreateJournal
* POST /mockup/scheduler/JurnalPiCicilanOrderAset/GenerateJournalsFromContracts
* GET /mockup/scheduler/JurnalPiCicilanOrderAset/ListEligiblePurchaseOrderAssetContracts
*/
class JurnalPiCicilanOrderAset extends MY_Controller
{
var $db;
/**
* Endpoint default — menampilkan nama controller sebagai penanda aktif.
*/
public function index()
{
echo "Jurnal PI Cicilan Order Aset";
}
/**
* Konstruktor — inisialisasi parent controller.
*/
public function __construct()
{
parent::__construct();
}
/**
* CreateJournal — Membuat jurnal PI cicilan order aset.
*
* Proses bisnis:
* 1. Validasi semua parameter wajib: date, branchCode, title, description, details
* 2. Ambil periodeID dari tanggal transaksi (tabel periode)
* 3. Ambil regionalID dari branchCode (tabel m_branch)
* 4. Ambil branchCompanyID dari branchCode (tabel m_branch_companydetail)
* 5. Ambil jurnalTypeID dari kode tipe jurnal (default: "PAYMENT")
* 6. Generate nomor jurnal otomatis via fn_numbering('J')
* 7. Validasi balance: total debit harus sama dengan total credit
* 8. INSERT header jurnal ke tabel `jurnal`:
* - jurnalNo : nomor jurnal hasil generate
* - jurnalJurnalTypeID: tipe PAYMENT
* - jurnalTitle : judul jurnal
* - jurnalDescription: keterangan jurnal
* - jurnalDate : tanggal transaksi
* - JurnalS_RegionalID: ID regional cabang
* - jurnalM_BranchCode: kode cabang
* 9. Untuk setiap baris detail, INSERT ke `jurnal_tx`:
* - jurnalTxJurnalID : referensi ke header jurnal
* - jurnalTxCoaID : COA yang digunakan (hutang cicilan / kas/bank)
* - jurnalTxDescription: keterangan baris (nama cicilan/aset)
* - jurnalTxDebit : nilai hutang (sisi debit)
* - jurnalTxCredit : nilai bayar (sisi kredit)
* 10. Jika ada addonValue atau mItemID, INSERT ke `jurnal_addon`:
* - jurnalAddOnJurnalID : referensi ke header jurnal
* - jurnalAddOnJurnalTxID: referensi ke baris jurnal_tx
* - jurnalAddOnCode : kode addon (default: "PIINSTALMENT")
* - jurnalAddOnValue : nilai tambahan (misal: nomor PI/kontrak)
* - jurnalAddOnM_ItemID : ID item aset yang terkait
*
* Parameter (POST JSON):
* - date : Tanggal jurnal (YYYY-MM-DD). Default: hari ini.
* - branchCode : Kode cabang. WAJIB.
* - title : Judul jurnal. WAJIB.
* - description : Keterangan jurnal. WAJIB.
* - details : Array baris transaksi. WAJIB, minimal 1 baris.
* - coaID : ID Chart of Account. WAJIB per baris.
* - description : Keterangan baris.
* - debit : Nilai debit (hutang cicilan).
* - credit : Nilai kredit (pembayaran cicilan).
* - addonValue : (opsional) Nilai addon, misal nomor PI.
* - mItemID : (opsional) ID item aset.
* - addonCode : (opsional) Kode addon. Default: "PIINSTALMENT".
* - periodeID : (opsional) ID periode. Default: diambil dari tanggal.
* - regionalID : (opsional) ID regional. Default: diambil dari branchCode.
* - branchCompanyID: (opsional) ID branch company. Default: diambil dari branchCode.
* - jurnalTypeID : (opsional) ID tipe jurnal. Default: diambil dari jurnalTypeCode.
* - jurnalTypeCode: (opsional) Kode tipe jurnal. Default: "PAYMENT".
* - userID : ID user yang membuat jurnal.
*
* @return JSON { jurnalID, jurnalNo, detailCount, addonCount }
*/
public function CreateJournal()
{
try {
$para = $this->sys_input;
$date = isset($para["date"]) && $para["date"] != "" ? $para["date"] : date("Y-m-d");
if (!$this->isValidDate($date)) {
throw new Exception("Format tanggal tidak valid. Gunakan YYYY-MM-DD.");
}
$branchCode = isset($para["branchCode"]) ? trim($para["branchCode"]) : "";
if ($branchCode == "") {
throw new Exception("branchCode wajib diisi.");
}
$title = isset($para["title"]) ? trim($para["title"]) : "";
if ($title == "") {
throw new Exception("title wajib diisi.");
}
$description = isset($para["description"]) ? trim($para["description"]) : "";
if ($description == "") {
throw new Exception("description wajib diisi.");
}
$details = isset($para["details"]) && is_array($para["details"]) ? $para["details"] : [];
if (count($details) == 0) {
throw new Exception("details wajib diisi minimal 1 baris.");
}
$periodeID = isset($para["periodeID"]) && (int) $para["periodeID"] > 0
? (int) $para["periodeID"]
: $this->getPeriodeIDByDate($date);
if ($periodeID <= 0) {
throw new Exception("Periode jurnal tidak ditemukan untuk tanggal {$date}.");
}
$regionalID = isset($para["regionalID"]) && (int) $para["regionalID"] > 0
? (int) $para["regionalID"]
: $this->getRegionalIDByBranchCode($branchCode);
if ($regionalID <= 0) {
throw new Exception("regionalID wajib diisi atau harus bisa diturunkan dari branchCode.");
}
$branchCompanyID = isset($para["branchCompanyID"]) && (int) $para["branchCompanyID"] > 0
? (int) $para["branchCompanyID"]
: $this->getBranchCompanyIDByBranchCode($branchCode);
if ($branchCompanyID <= 0) {
throw new Exception("branchCompanyID wajib diisi atau harus bisa diturunkan dari branchCode.");
}
$jurnalTypeID = isset($para["jurnalTypeID"]) && (int) $para["jurnalTypeID"] > 0
? (int) $para["jurnalTypeID"]
: $this->getJurnalTypeID(isset($para["jurnalTypeCode"]) && $para["jurnalTypeCode"] != "" ? $para["jurnalTypeCode"] : "PAYMENT");
if ($jurnalTypeID <= 0) {
throw new Exception("jurnalTypeID / jurnalTypeCode tidak valid.");
}
$userID = 0;
$result = $this->insertJournal(
$date,
$branchCode,
$title,
$description,
$details,
$periodeID,
$regionalID,
$branchCompanyID,
$jurnalTypeID,
$userID
);
if ($result === false) {
exit;
}
$this->sys_ok($result);
} catch (Exception $exc) {
$this->sys_error($exc->getMessage());
}
}
/**
* GenerateJournalsFromContracts — Generate jurnal otomatis dari seluruh kontrak aset eligible.
*
* Fungsi ini mengintegrasikan data dari getEligiblePurchaseOrderAssetContracts()
* dengan proses pembuatan jurnal (insertJournal()) secara otomatis.
*
* Untuk setiap kontrak yang eligible, dibuat 1 jurnal dengan 2 baris transaksi:
* - Baris DEBIT : COA hutang cicilan (HutangCoaID dari fa_class) — mencatat hutang cicilan
* - Baris KREDIT : COA kas/bank/aset (ItemCoaID dari fa_class) — mencatat pembayaran cicilan
* Addon (jurnal_addon): menyimpan ID kontrak sebagai addonValue dan ItemID sebagai mItemID
*
* Parameter (POST JSON):
* - date : Tanggal jurnal (YYYY-MM-DD). Default: hari ini.
* - userID : ID user yang membuat jurnal.
* - dryRun : "Y" = simulasi tanpa simpan ke DB. Default: "N".
* - contractID : (opsional) Filter hanya 1 kontrak tertentu.
*
* Syarat kontrak dilewati (skipped):
* - branchCode kosong (data cabang belum lengkap)
* - COA hutang (HutangCoaID) tidak ditemukan di fa_class
* - COA bayar/aset (ItemCoaID) tidak ditemukan di fa_class
*
* @return JSON { tanggal, totalDibuat, totalDilewati, daftarDibuat[], daftarDilewati[] }
*/
public function GenerateJournalsFromContracts()
{
try {
$para = $this->sys_input;
$date = isset($para["date"]) && $para["date"] != "" ? $para["date"] : date("Y-m-d");
if (!$this->isValidDate($date)) {
throw new Exception("Format tanggal tidak valid. Gunakan YYYY-MM-DD.");
}
$userID = 0;
$dryRun = isset($para["dryRun"]) && ($para["dryRun"] === true || $para["dryRun"] == "Y" || $para["dryRun"] == "1");
$filterContractID = isset($para["contractID"]) && (int) $para["contractID"] > 0
? (int) $para["contractID"]
: null;
$monthStart = date("Y-m-01", strtotime($date));
$monthEnd = date("Y-m-t", strtotime($date));
// Ambil semua kontrak yang eligible untuk periode bulan ini
$contracts = $this->getEligiblePurchaseOrderAssetContracts($monthStart, $monthEnd);
$dibuat = [];
$dilewati = [];
foreach ($contracts as $kontrak) {
$contractID = (int) $kontrak["PurchaseOrderAssetContractID"];
// Filter 1 kontrak jika diminta
if ($filterContractID !== null && $contractID !== $filterContractID) {
continue;
}
$branchCode = $kontrak["M_BranchCode"] ?? "";
$regionalID = (int) ($kontrak["M_BranchS_RegionalID"] ?? 0);
$branchCompanyID = (int) ($kontrak["M_BranchCompanyID"] ?? 0);
$coaHutangID = (int) ($kontrak["HutangCoaID"] ?? 0); // COA debit dari fa_class (Fa_ClassHutangCoaID)
$coaBayarID = (int) ($kontrak["ItemCoaID"] ?? 0); // COA kredit dari fa_class (Fa_ClassCoaID)
$jumlah = (float) $kontrak["PurchaseOrderAssetContractInstallmentPayAmount"];
$itemID = (int) ($kontrak["PurchaseOrderSummaryItemID"] ?? 0);
$namaKontrak = $kontrak["PurchaseOrderAssetContractName"] != ""
? $kontrak["PurchaseOrderAssetContractName"]
: "Kontrak ID {$contractID}";
$nomorPO = $kontrak["PurchaseOrderNumber"] ?? "";
$cicilanKe = ((int) $kontrak["PurchaseOrderAssetContractInstallmentPaid"]) + 1;
$totalCicilan = (int) $kontrak["PurchaseOrderAssetContractInstallmentNumber"];
$periode = date("Y-m", strtotime($date));
$invoiceNumber = $kontrak["SupplierInvoiceNumber"] ?? "";
$invoiceID = (int) ($kontrak["SupplierInvoiceID"] ?? 0);
// Validasi: branchCode harus ada
if ($branchCode == "") {
$dilewati[] = [
"kontrakID" => $contractID,
"alasan" => "Kode cabang (branchCode) tidak ditemukan. Pastikan warehouse PO sudah terhubung ke data cabang."
];
continue;
}
// Validasi: COA hutang harus ada (untuk sisi DEBIT)
if ($coaHutangID <= 0) {
$dilewati[] = [
"kontrakID" => $contractID,
"branchCode" => $branchCode,
"alasan" => "COA hutang tidak ditemukan. Pastikan item PO memiliki Fa_Class dengan Fa_ClassHutangCoaID."
];
continue;
}
// Validasi: COA bayar/aset harus ada (untuk sisi KREDIT)
if ($coaBayarID <= 0) {
$dilewati[] = [
"kontrakID" => $contractID,
"branchCode" => $branchCode,
"alasan" => "COA bayar/aset tidak ditemukan. Pastikan item PO memiliki Fa_Class dengan Fa_ClassCoaID."
];
continue;
}
// Mode simulasi: catat tanpa simpan ke DB
if ($dryRun) {
$dibuat[] = [
"kontrakID" => $contractID,
"branchCode" => $branchCode,
"namaKontrak" => $namaKontrak,
"invoiceNumber" => $invoiceNumber,
"jumlah" => $jumlah,
"coaHutangID" => $coaHutangID,
"coaBayarID" => $coaBayarID,
"keterangan" => "Mode simulasi (dryRun), data tidak disimpan."
];
continue;
}
// Susun title dan description jurnal
$title = "PI Cicilan Aset - {$invoiceNumber}";
$description = "Jurnal cicilan ke-{$cicilanKe} dari {$totalCicilan} | {$namaKontrak} | PO: {$nomorPO} | Periode {$periode}";
// Ambil periodeID dari tanggal
$periodeID = $this->getPeriodeIDByDate($date);
if ($periodeID <= 0) {
$dilewati[] = [
"kontrakID" => $contractID,
"branchCode" => $branchCode,
"alasan" => "Periode jurnal tidak ditemukan untuk tanggal {$date}."
];
continue;
}
// Ambil jurnalTypeID untuk tipe PAYMENT
$jurnalTypeID = $this->getJurnalTypeID("PAYMENTINV");
if ($jurnalTypeID <= 0) {
$dilewati[] = [
"kontrakID" => $contractID,
"branchCode" => $branchCode,
"alasan" => "Tipe jurnal PAYMENT tidak ditemukan di tabel jurnal_type."
];
continue;
}
// Ambil description detail dari database fa_class dengan fallback jika kosong
$descHutang = isset($kontrak["HutangCoaDesc"]) && $kontrak["HutangCoaDesc"] != ""
? $kontrak["HutangCoaDesc"]
: "Hutang cicilan aset - {$namaKontrak}";
$descBayar = isset($kontrak["ItemCoaDesc"]) && $kontrak["ItemCoaDesc"] != ""
? $kontrak["ItemCoaDesc"]
: "Pembayaran cicilan aset - {$namaKontrak}";
// Susun 2 baris detail jurnal:
// Baris 1 — DEBIT : hutang cicilan aset (COA dari fa_class)
// Baris 2 — KREDIT : pembayaran cicilan (COA kas/bank dari parameter)
$details = [
[
"coaID" => $coaHutangID,
"description" => $descHutang,
"debit" => $jumlah,
"credit" => 0,
"addonValue" => $invoiceNumber,
"mItemID" => $itemID,
"addonCode" => "PIINSTALMENT"
],
[
"coaID" => $coaBayarID,
"description" => $descBayar,
"debit" => 0,
"credit" => $jumlah,
"addonValue" => $invoiceNumber,
"mItemID" => $itemID,
"addonCode" => "PIINSTALMENT"
]
];
// Panggil insertJournal() untuk simpan ke DB
$result = $this->insertJournal(
$date,
$branchCode,
$title,
$description,
$details,
$periodeID,
$regionalID,
$branchCompanyID,
$jurnalTypeID,
$userID
);
if ($result === false) {
$dilewati[] = [
"kontrakID" => $contractID,
"branchCode" => $branchCode,
"alasan" => "Gagal menyimpan jurnal ke database."
];
continue;
}
$dibuat[] = [
"kontrakID" => $contractID,
"branchCode" => $branchCode,
"namaKontrak" => $namaKontrak,
"jurnalID" => $result["jurnalID"],
"jurnalNo" => $result["jurnalNo"],
"jumlah" => $jumlah
];
}
$this->sys_ok([
"tanggal" => $date,
"periodeAwal" => $monthStart,
"periodeAkhir" => $monthEnd,
"totalDibuat" => count($dibuat),
"totalDilewati" => count($dilewati),
"daftarDibuat" => $dibuat,
"daftarDilewati" => $dilewati
]);
} catch (Exception $exc) {
$this->sys_error($exc->getMessage());
}
}
/**
* ListEligiblePurchaseOrderAssetContracts — Menampilkan daftar kontrak aset
* yang memenuhi syarat untuk dibuatkan jurnal PI cicilan pada periode tertentu.
*
* Syarat kontrak eligible:
* - Kontrak aktif dan berstatus "belum lunas"
* - Nilai cicilan > 0
* - Jumlah cicilan terbayar < total cicilan
* - Tanggal kontrak masuk dalam rentang startDateendDate
* - PO sudah berstatus Approved
* - Barang sudah diterima (receive_order_po sudah confirmed)
*
* Endpoint ini digunakan untuk preview/verifikasi sebelum proses generate jurnal
* dijalankan secara massal oleh CRON.
*
* Parameter (GET/POST):
* - startDate : Awal periode (YYYY-MM-DD). Default: tanggal 1 bulan ini.
* - endDate : Akhir periode (YYYY-MM-DD). Default: tanggal akhir bulan ini.
*
* @return JSON { startDate, endDate, total, records[] }
*/
public function ListEligiblePurchaseOrderAssetContracts()
{
try {
$para = $this->sys_input;
$startDate = isset($para["startDate"]) && $para["startDate"] != ""
? $para["startDate"]
: date("Y-m-01");
$endDate = isset($para["endDate"]) && $para["endDate"] != ""
? $para["endDate"]
: date("Y-m-t");
if (!$this->isValidDate($startDate) || !$this->isValidDate($endDate)) {
throw new Exception("Format tanggal tidak valid. Gunakan YYYY-MM-DD.");
}
if (strtotime($startDate) > strtotime($endDate)) {
throw new Exception("startDate tidak boleh lebih besar dari endDate");
}
$records = $this->getEligiblePurchaseOrderAssetContracts($startDate, $endDate);
$this->sys_ok([
"startDate" => $startDate,
"endDate" => $endDate,
"total" => count($records),
"records" => $records
]);
} catch (Exception $exc) {
$this->sys_error($exc->getMessage());
}
}
// =========================================================================
// FUNGSI PRIVATE / HELPER
// =========================================================================
/**
* insertJournal — Menyimpan 1 jurnal lengkap ke database (header + tx + addon).
*
* Fungsi internal yang dipanggil oleh CreateJournal() dan GenerateJournalsFromContracts().
* Mengelola transaksi DB secara penuh (begin → commit/rollback).
*
* Alur:
* 1. Validasi balance debit == kredit
* 2. Generate nomor jurnal via fn_numbering('J')
* 3. INSERT header ke tabel `jurnal`
* 4. INSERT baris transaksi ke `jurnal_tx` (per detail)
* 5. INSERT addon ke `jurnal_addon` (jika addonValue atau mItemID ada)
*
* @param string $date Tanggal jurnal (YYYY-MM-DD)
* @param string $branchCode Kode cabang
* @param string $title Judul jurnal
* @param string $description Keterangan jurnal
* @param array $details Baris transaksi [ coaID, description, debit, credit, addonValue?, mItemID?, addonCode? ]
* @param int $periodeID ID periode akuntansi
* @param int $regionalID ID regional
* @param int $branchCompanyID ID branch company
* @param int $jurnalTypeID ID tipe jurnal
* @param int $userID ID user pembuat jurnal
*
* @return array|false Array { jurnalID, jurnalNo, detailCount, addonCount }, atau false jika gagal
*/
private function insertJournal($date, $branchCode, $title, $description, $details, $periodeID, $regionalID, $branchCompanyID, $jurnalTypeID, $userID)
{
// Validasi balance sebelum menyimpan
$totalDebit = 0;
$totalCredit = 0;
foreach ($details as $idx => $detail) {
$debit = isset($detail["debit"]) ? (float) $detail["debit"] : 0;
$credit = isset($detail["credit"]) ? (float) $detail["credit"] : 0;
if ($debit < 0 || $credit < 0) {
$this->sys_error("Nilai debit/credit tidak boleh negatif pada detail ke-" . ($idx + 1));
return false;
}
$totalDebit += $debit;
$totalCredit += $credit;
}
if (round($totalDebit, 2) !== round($totalCredit, 2)) {
$this->sys_error("Total debit dan credit harus sama. Debit={$totalDebit}, Credit={$totalCredit}");
return false;
}
$jurnalNo = $this->generateJournalNumber();
if ($jurnalNo === false || $jurnalNo == "") {
$this->sys_error("Gagal generate nomor jurnal.");
return false;
}
$this->db->trans_begin();
// -----------------------------------------------------------------
// INSERT header jurnal ke tabel `jurnal`
// -----------------------------------------------------------------
$sqlHeader = "INSERT INTO jurnal (
jurnalM_BranchCompanyID,
JurnalS_RegionalID,
jurnalM_BranchCode,
jurnalperiodeID,
jurnalNo,
jurnalTitle,
jurnalDescription,
jurnalDate,
jurnalJurnalTypeID,
jurnalCreated,
jurnalM_UserID
) VALUES (?,?,?,?,?,?,?,?,?,NOW(),?)";
$qryHeader = $this->db->query($sqlHeader, [
$branchCompanyID,
$regionalID,
$branchCode,
$periodeID,
$jurnalNo,
$title,
$description,
$date,
$jurnalTypeID,
$userID
]);
if (!$qryHeader) {
$this->db->trans_rollback();
$this->sys_error_db("Gagal insert jurnal header.");
return false;
}
$jurnalID = $this->db->insert_id();
$createdAddonCount = 0;
// -----------------------------------------------------------------
// INSERT baris transaksi ke tabel `jurnal_tx` (per baris cicilan)
// -----------------------------------------------------------------
foreach ($details as $idx => $detail) {
$coaID = isset($detail["coaID"]) ? (int) $detail["coaID"] : 0;
$descriptionTx = isset($detail["description"]) ? trim($detail["description"]) : "";
$debit = isset($detail["debit"]) ? (float) $detail["debit"] : 0;
$credit = isset($detail["credit"]) ? (float) $detail["credit"] : 0;
if ($coaID <= 0) {
$this->db->trans_rollback();
$this->sys_error_db("coaID wajib diisi pada detail ke-" . ($idx + 1));
return false;
}
// Sisi debit = hutang cicilan (COA hutang aset dari fa_class)
// Sisi kredit = pembayaran cicilan (COA kas/bank)
$sqlTx = "INSERT INTO jurnal_tx (
jurnalTxJurnalID,
jurnalTxCoaID,
jurnalTxDescription,
jurnalTxDebit,
jurnalTxCredit,
jurnalTxCreated,
jurnalTxM_UserID
) VALUES (?,?,?,?,?,NOW(),?)";
$qryTx = $this->db->query($sqlTx, [
$jurnalID,
$coaID,
$descriptionTx,
$debit,
$credit,
$userID
]);
if (!$qryTx) {
$this->db->trans_rollback();
$this->sys_error_db("Gagal insert jurnal_tx pada detail ke-" . ($idx + 1));
return false;
}
$jurnalTxID = $this->db->insert_id();
// -----------------------------------------------------------------
// INSERT addon ke `jurnal_addon` (jika addonValue atau mItemID ada)
// addonValue = ID kontrak aset (untuk tracing)
// mItemID = ID item aset dari purchase_order_summary
// -----------------------------------------------------------------
$addonValue = isset($detail["addonValue"]) ? trim($detail["addonValue"]) : "";
$mItemID = isset($detail["mItemID"]) ? (int) $detail["mItemID"] : 0;
$addonCode = isset($detail["addonCode"]) && $detail["addonCode"] != "" ? trim($detail["addonCode"]) : "PIINSTALMENT";
if ($addonValue != "" || $mItemID > 0) {
$sqlAddon = "INSERT INTO jurnal_addon (
jurnalAddOnJurnalID,
jurnalAddOnJurnalTxID,
jurnalAddOnCode,
jurnalAddOnValue,
jurnalAddOnM_ItemID,
jurnalAddOnCreated,
jurnalAddOnCreatedUserID
) VALUES (?,?,?,?,?,NOW(),?)";
$qryAddon = $this->db->query($sqlAddon, [
$jurnalID,
$jurnalTxID,
$addonCode,
$addonValue,
$mItemID > 0 ? $mItemID : null,
$userID
]);
if (!$qryAddon) {
$this->db->trans_rollback();
$this->sys_error_db("Gagal insert jurnal_addon pada detail ke-" . ($idx + 1));
return false;
}
$createdAddonCount++;
}
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
$this->sys_error_db("Transaksi jurnal gagal.");
return false;
}
$this->db->trans_commit();
return [
"jurnalID" => $jurnalID,
"jurnalNo" => $jurnalNo,
"detailCount" => count($details),
"addonCount" => $createdAddonCount
];
}
/**
* generateJournalNumber — Generate nomor jurnal otomatis.
*
* Memanggil stored function MySQL fn_numbering('J') untuk mendapatkan
* nomor jurnal berikutnya sesuai urutan penomoran yang berlaku.
*
* @return string|false Nomor jurnal (misal: "J/2025/07/0001"), atau false jika gagal.
*/
private function generateJournalNumber()
{
$qry = $this->db->query("SELECT fn_numbering('J') AS JNumber");
if (!$qry || $qry->num_rows() == 0) {
return false;
}
return $qry->row_array()["JNumber"];
}
/**
* getPeriodeIDByDate — Ambil ID periode akuntansi berdasarkan tanggal transaksi.
*
* Periode diambil dari tabel `periode` yang aktif dan mencakup tanggal yang diberikan.
* Digunakan untuk mengisi field jurnalperiodeID pada header jurnal.
*
* @param string $date Tanggal transaksi (format YYYY-MM-DD)
* @return int periodeID yang sesuai, atau 0 jika tidak ditemukan
*/
private function getPeriodeIDByDate($date)
{
$sql = "SELECT periodeID
FROM periode
WHERE periodeIsActive = 'Y'
AND DATE(?) BETWEEN periodeStartDate AND periodeEndDate
LIMIT 1";
$qry = $this->db->query($sql, [$date]);
if (!$qry || $qry->num_rows() == 0) {
return 0;
}
return (int) $qry->row_array()["periodeID"];
}
/**
* getBranchCompanyIDByBranchCode — Ambil ID branch company berdasarkan kode cabang.
*
* Data diambil dari tabel `m_branch_companydetail` yang aktif.
* Digunakan untuk mengisi field jurnalM_BranchCompanyID pada header jurnal.
*
* @param string $branchCode Kode cabang (misal: "JKT-01")
* @return int branchCompanyID yang sesuai, atau 0 jika tidak ditemukan
*/
private function getBranchCompanyIDByBranchCode($branchCode)
{
$sql = "SELECT M_BranchCompanyDetailM_BranchCompanyID AS branchCompanyID
FROM m_branch_companydetail
WHERE M_BranchCompanyDetailM_BranchCode = ?
AND M_BranchCompanyDetailIsActive = 'Y'
LIMIT 1";
$qry = $this->db->query($sql, [$branchCode]);
if (!$qry || $qry->num_rows() == 0) {
return 0;
}
return (int) $qry->row_array()["branchCompanyID"];
}
/**
* getRegionalIDByBranchCode — Ambil ID regional berdasarkan kode cabang.
*
* Data diambil dari tabel `m_branch` yang aktif.
* Digunakan untuk mengisi field JurnalS_RegionalID pada header jurnal.
*
* @param string $branchCode Kode cabang (misal: "JKT-01")
* @return int regionalID yang sesuai, atau 0 jika tidak ditemukan
*/
private function getRegionalIDByBranchCode($branchCode)
{
$sql = "SELECT M_BranchS_RegionalID AS regionalID
FROM m_branch
WHERE M_BranchCode = ?
AND M_BranchIsActive = 'Y'
LIMIT 1";
$qry = $this->db->query($sql, [$branchCode]);
if (!$qry || $qry->num_rows() == 0) {
return 0;
}
return (int) $qry->row_array()["regionalID"];
}
/**
* getJurnalTypeID — Ambil ID tipe jurnal berdasarkan kode tipe.
*
* Data diambil dari tabel `jurnal_type` yang aktif.
* Untuk PI cicilan order aset, kode yang digunakan adalah "PAYMENT".
*
* @param string $jurnalTypeCode Kode tipe jurnal (misal: "PAYMENT")
* @return int JurnalTypeID yang sesuai, atau 0 jika tidak ditemukan
*/
private function getJurnalTypeID($jurnalTypeCode)
{
$sql = "SELECT JurnalTypeID
FROM jurnal_type
WHERE JurnalTypeCode = ?
AND JurnalTypeIsActive = 'Y'
LIMIT 1";
$qry = $this->db->query($sql, [$jurnalTypeCode]);
if (!$qry || $qry->num_rows() == 0) {
return 0;
}
return (int) $qry->row_array()["JurnalTypeID"];
}
/**
* getEligiblePurchaseOrderAssetContracts — Ambil kontrak aset yang layak dibuatkan jurnal.
*
* Query ini mengambil semua kontrak dari `purchase_order_asset_contract` yang memenuhi
* syarat berikut:
* - Kontrak aktif, status "belum lunas", nilai cicilan > 0
* - Cicilan terbayar masih kurang dari total cicilan
* - Tanggal kontrak masuk dalam rentang periode yang diberikan
* - Tanggal jatuh tempo cicilan sudah lewat atau sama dengan hari ini
* - PO sudah Approved dan aktif
* - Barang sudah diterima dan receive order sudah confirmed
*
* Data yang dikembalikan mencakup:
* - Detail kontrak (ID, nama, tanggal, nilai cicilan)
* - Data PO (nomor PO, supplier, payment term, warehouse)
* - Data cabang (kode cabang, nama, regionalID, branchCompanyID)
* - Data item PO pertama (sebagai referensi baris jurnal)
*
* @param string $startDate Awal periode filter (YYYY-MM-DD)
* @param string $endDate Akhir periode filter (YYYY-MM-DD)
* @return array Array of row kontrak yang eligible
*/
private function getEligiblePurchaseOrderAssetContracts($startDate, $endDate)
{
$sql = "SELECT
c.PurchaseOrderAssetContractID,
si.SupplierInvoiceID,
si.SupplierInvoiceNumber,
c.PurchaseOrderAssetContractPurchaseOrderID,
c.PurchaseOrderAssetContractName,
c.PurchaseOrderAssetContractStartDate,
c.PurchaseOrderAssetContractEndDate,
c.PurchaseOrderAssetContractInstallmentNumber,
c.PurchaseOrderAssetContractInstallmentPaid,
c.PurchaseOrderAssetContractInstallmentDate,
c.PurchaseOrderAssetContractInstallmentPayAmount,
c.PurchaseOrderAssetContractReceiveOrderPoID,
po.PurchaseOrderID,
po.PurchaseOrderNumber,
po.PurchaseOrderSupplierID,
po.PurchaseOrderPaymentTerm,
po.PurchaseOrderWarehouseType,
po.PurchaseOrderWarehouseID,
wh.WarehouseCode,
wh.WarehouseName,
wh.WarehouseType,
wh.WarehouseS_RegionalID AS WarehouseS_RegionalID,
wh.WarehouseM_BranchID AS WarehouseM_BranchID,
ro.ReceiveOrderPoID,
ro.ReceiveOrderPoConfirmed,
mi.M_ItemID AS ItemID,
mi.M_ItemCode AS ItemCode,
mi.M_ItemDesc AS ItemDesc,
mi.M_ItemFa_ClassID,
fc.Fa_ClassID AS ItemFaClassID,
fc.Fa_ClassName AS ItemFaClassName,
coa_bayar.coaID AS ItemCoaID,
coa_bayar.coaAccountNo AS ItemCoaAccountNo,
coa_bayar.coaDescription AS ItemCoaDesc,
coa_hutang.coaID AS HutangCoaID,
coa_hutang.coaAccountNo AS HutangCoaAccountNo,
coa_hutang.coaDescription AS HutangCoaDesc,
m_branch.M_BranchCode,
m_branch.M_BranchName,
m_branch.M_BranchS_RegionalID,
m_branch_companydetail.M_BranchCompanyDetailM_BranchCompanyID AS M_BranchCompanyID,
ps.PurchaseOrderSummaryID,
ps.PurchaseOrderSummaryItemID,
ps.PurchaseOrderSummaryItemUnitID
FROM purchase_order_asset_contract c
-- Pastikan PO sudah Approved dan aktif
JOIN purchase_order po
ON po.PurchaseOrderID = c.PurchaseOrderAssetContractPurchaseOrderID
AND po.PurchaseOrderIsActive = 'Y'
AND po.PurchaseOrderStatus = 'Approved'
-- Data warehouse/gudang tujuan PO
LEFT JOIN warehouse wh
ON wh.WarehouseID = po.PurchaseOrderWarehouseID
-- Ambil 1 item PO pertama sebagai referensi baris jurnal
LEFT JOIN (
SELECT ps0.*
FROM purchase_order_summary ps0
JOIN (
SELECT
PurchaseOrderSummaryPurchaseOrderID,
MIN(PurchaseOrderSummaryID) AS PurchaseOrderSummaryID
FROM purchase_order_summary
WHERE PurchaseOrderSummaryIsActive = 'Y'
GROUP BY PurchaseOrderSummaryPurchaseOrderID
) psx
ON psx.PurchaseOrderSummaryID = ps0.PurchaseOrderSummaryID
) ps
ON ps.PurchaseOrderSummaryPurchaseOrderID = po.PurchaseOrderID
-- Hubungkan dengan detail supplier_invoice_detail terlebih dahulu
JOIN supplier_invoice_detail sid
ON sid.SupplierInvoiceDetailPurchaseOrderID = po.PurchaseOrderID
AND sid.SupplierInvoiceDetailPurchaseOrderSummaryID = ps.PurchaseOrderSummaryID
AND sid.SupplierInvoiceDetailIsActive = 'Y'
-- Baru hubungkan ke header supplier_invoice untuk mengambil nomor invoice
JOIN supplier_invoice si
ON si.SupplierInvoiceID = sid.SupplierInvoiceDetailSupplierInvoiceID
AND si.SupplierInvoiceDate >= DATE(?)
AND si.SupplierInvoiceDate <= DATE(?)
AND si.SupplierInvoiceIsActive = 'Y'
-- Pastikan barang sudah diterima (receive order confirmed)
JOIN (
SELECT
rd.ReceiveOrderPoDetailPurchaseOrderID,
MIN(ro0.ReceiveOrderPoID) AS ReceiveOrderPoID,
MAX(ro0.ReceiveOrderPoConfirmed) AS ReceiveOrderPoConfirmed
FROM receive_order_po ro0
JOIN receive_order_po_detail rd
ON rd.ReceiveOrderPoDetailReceiveOrderPoID = ro0.ReceiveOrderPoID
AND rd.ReceiveOrderPoDetailIsActive = 'Y'
WHERE ro0.ReceiveOrderPoIsActive = 'Y'
AND ro0.ReceiveOrderPoConfirmed = 'Y'
GROUP BY rd.ReceiveOrderPoDetailPurchaseOrderID
) ro
ON ro.ReceiveOrderPoDetailPurchaseOrderID = po.PurchaseOrderID
-- Data cabang dari warehouse
LEFT JOIN m_branch
ON m_branch.M_BranchID = wh.WarehouseM_BranchID
AND m_branch.M_BranchIsActive = 'Y'
-- Data branch company untuk header jurnal
LEFT JOIN m_branch_companydetail
ON m_branch_companydetail.M_BranchCompanyDetailM_BranchCode = m_branch.M_BranchCode
AND m_branch_companydetail.M_BranchCompanyDetailIsActive = 'Y'
-- COA jurnal diambil dari item -> fa_class
LEFT JOIN m_item mi
ON mi.M_ItemID = ps.PurchaseOrderSummaryItemID
AND mi.M_ItemIsActive = 'Y'
LEFT JOIN fa_class fc
ON fc.Fa_ClassID = mi.M_ItemFa_ClassID
AND fc.Fa_ClassIsActive = 'Y'
-- Join langsung ke tabel coa untuk memastikan kevalidan akun dan deskripsi
LEFT JOIN coa coa_hutang
ON coa_hutang.coaID = fc.Fa_ClassHutangCoaID
AND coa_hutang.coaIsActive = 'Y'
LEFT JOIN coa coa_bayar
ON coa_bayar.coaID = fc.Fa_ClassCoaID
AND coa_bayar.coaIsActive = 'Y'
WHERE c.PurchaseOrderAssetContractIsActive = 'Y'
AND c.PurchaseOrderAssetContractStatus = 'belum lunas'
-- Hanya kontrak yang ada nilai cicilannya
AND IFNULL(c.PurchaseOrderAssetContractInstallmentPayAmount, 0) > 0
-- Hanya kontrak yang belum selesai seluruh cicilannya
AND IFNULL(c.PurchaseOrderAssetContractInstallmentPaid, 0) < IFNULL(c.PurchaseOrderAssetContractInstallmentNumber, 0)
-- Kontrak sudah mulai sebelum atau pada akhir periode
AND DATE(c.PurchaseOrderAssetContractStartDate) <= DATE(?)
-- Kontrak belum berakhir (atau tidak ada tanggal akhir)
AND (
c.PurchaseOrderAssetContractEndDate IS NULL
OR DATE(c.PurchaseOrderAssetContractEndDate) >= DATE(?)
)
-- Tanggal jatuh tempo cicilan sudah tiba
AND IFNULL(c.PurchaseOrderAssetContractInstallmentDate, 1) <= ?
-- Pastikan belum pernah dibuatkan jurnal untuk invoice cicilan ini
AND NOT EXISTS (
SELECT 1
FROM jurnal_addon ja
JOIN jurnal j ON j.jurnalID = ja.jurnalAddOnJurnalID
WHERE ja.jurnalAddOnCode = 'PIINSTALMENT'
AND ja.jurnalAddOnValue = si.SupplierInvoiceNumber
)
ORDER BY c.PurchaseOrderAssetContractID ASC";
$qry = $this->db->query($sql, [
$startDate,
$endDate,
$endDate,
$startDate,
(int) date("d", strtotime($endDate))
]);
if (!$qry) {
$this->sys_error_db("Gagal mengambil data purchase_order_asset_contract.");
exit;
}
return $qry->result_array();
}
/**
* isValidDate — Validasi format tanggal YYYY-MM-DD.
*
* @param string $tanggal String tanggal yang akan divalidasi
* @return bool true jika format valid, false jika tidak
*/
private function isValidDate($tanggal)
{
$d = DateTime::createFromFormat("Y-m-d", $tanggal);
return $d && $d->format("Y-m-d") === $tanggal;
}
}

View File

@@ -1,127 +0,0 @@
# ============================================================
# FILE : PurchaseInvoiceInstallment.http
# MODUL : Scheduler — Generate Purchase Invoice Cicilan Aset
# ============================================================
#
# DESKRIPSI
# ---------
# File ini berisi kumpulan HTTP request untuk menguji endpoint
# scheduler yang secara otomatis membuat Purchase Invoice (PI)
# cicilan bulanan berdasarkan kontrak aset aktif.
#
# CARA PAKAI
# ----------
# 1. Gunakan ekstensi "REST Client" di VS Code (humao.rest-client)
# atau tool sejenis (IntelliJ HTTP Client, Postman, dll).
# 2. Ganti nilai @host sesuai environment (local / staging / prod).
# 3. Klik "Send Request" di atas tiap blok ### untuk menjalankan
# request tersebut secara individual.
# 4. Jalankan request secara BERURUTAN sesuai urutan yang disarankan
# (lihat keterangan tiap endpoint di bawah).
#
# ALUR PENGGUNAAN YANG DISARANKAN
# --------------------------------
# [1] ListEligibleContracts → Lihat kontrak mana saja yang akan diproses
# [2] GenerateMonthlyInvoices → Jalankan proses generate PI cicilan sekaligus
# [3] InsertSupplierInvoice → (Opsional) Insert manual 1 PI jika diperlukan
#
# CATATAN
# -------
# - startDate & endDate menentukan periode bulan yang diproses.
# Biasanya diisi dengan tanggal awal dan akhir bulan berjalan.
# - Scheduler ini AMAN dijalankan ulang (idempotent). Kontrak yang
# sudah punya PI di bulan yang sama akan dilewati otomatis.
# - userID pada InsertSupplierInvoice akan diabaikan; sistem
# mengambil userID dari PurchaseOrderAssetContractCreatedUserID.
# ============================================================
@host = https://accone.aplikasi.web.id/one-api
# ============================================================
# [1] LIST KONTRAK ELIGIBLE
# ============================================================
# Gunakan endpoint ini SEBELUM generate untuk melihat preview
# kontrak mana saja yang akan dibuatkan PI pada periode ini.
#
# Response berisi daftar kontrak beserta detail cicilan,
# status GRNI, dan apakah PI bulan ini sudah ada atau belum.
# ============================================================
### [1] List kontrak cicilan eligible yang belum diproses bulan ini
POST {{host}}/mockup/scheduler/PurchaseInvoiceInstallment/ListEligibleContracts
Content-Type: application/json
{
"startDate": "2026-07-01",
"endDate": "2026-07-31"
}
# ============================================================
# [2] GENERATE PI CICILAN BULANAN (MAIN ENDPOINT)
# ============================================================
# Endpoint utama scheduler. Satu request ini akan:
# 1. Mengambil semua kontrak aset aktif yang eligible.
# 2. Mengecek duplikasi — melewati kontrak yang sudah ada PI-nya.
# 3. Membuat nomor PI via fn_penomoran() berdasarkan user
# pembuat kontrak (PurchaseOrderAssetContractCreatedUserID).
# 4. Insert supplier_invoice + supplier_invoice_detail.
#
# Response berisi:
# - berhasil : daftar PI yang berhasil dibuat (dengan nomorPI, supplierInvoiceID, dll)
# - dilewati : daftar kontrak yang dilewati beserta alasannya
# ============================================================
### [2] Generate PI cicilan untuk semua kontrak pada periode ini
POST {{host}}/mockup/scheduler/PurchaseInvoiceInstallment/GenerateMonthlyInvoices
Content-Type: application/json
{
"startDate": "2026-07-01",
"endDate": "2026-07-31"
}
# ============================================================
# [3] INSERT MANUAL SATU PI (INTERNAL / DEBUG)
# ============================================================
# Endpoint ini dipanggil INTERNAL oleh GenerateMonthlyInvoices
# via cURL. Gunakan hanya untuk debugging atau insert manual
# satu PI tertentu tanpa menjalankan proses batch.
#
# FIELD WAJIB:
# - nomorPI : Nomor PI (format dari fn_penomoran)
# - tanggalPI : Tanggal invoice (YYYY-MM-DD)
# - tanggalJatuhTempo : Tanggal jatuh tempo (YYYY-MM-DD)
# - jumlahCicilan : Nominal cicilan (angka, dalam Rupiah)
# - catatan : Catatan singkat pada header invoice
# - deskripsi : Deskripsi baris detail invoice
# - userID : ID user pembuat (ambil dari kontrak)
# - purchaseOrderAssetContractID : ID kontrak aset
# - purchaseOrderID : ID Purchase Order
# - receiveOrderPoID : ID Receive Order PO (GRNI)
# - supplierID : ID Supplier
# - purchaseOrderSummaryID : ID summary item PO
# - purchaseOrderSummaryItemID : ID item (barang/aset)
# - purchaseOrderSummaryItemUnitID: ID satuan item
# ============================================================
### [3] Insert satu supplier_invoice cicilan secara manual (debug)
POST {{host}}/mockup/scheduler/PurchaseInvoiceInstallmentInsert/InsertSupplierInvoice
Content-Type: application/json
{
"nomorPI": "PI-2026-07-0001",
"tanggalPI": "2026-07-31",
"tanggalJatuhTempo": "2026-08-14",
"jumlahCicilan": 15000000,
"catatan": "PI Cicilan Otomatis — Kontrak Aset ID 123 periode 2026-07",
"deskripsi": "Cicilan Kontrak Aset — Kendaraan Operasional periode 2026-07",
"userID": 1,
"purchaseOrderAssetContractID": 123,
"purchaseOrderID": 456,
"receiveOrderPoID": 789,
"supplierID": 12,
"purchaseOrderSummaryID": 111,
"purchaseOrderSummaryItemID": 222,
"purchaseOrderSummaryItemUnitID": 333
}

View File

@@ -1,641 +0,0 @@
<?php
/**
* PurchaseInvoiceInstallment
*
* Digunakan oleh CRON untuk membuat Purchase Invoice (PI) cicilan aset
* secara otomatis setiap bulan berdasarkan kontrak yang aktif.
*
* Endpoint utama:
* POST /scheduler/PurchaseInvoiceInstallment/GenerateMonthlyInvoices
* POST /scheduler/PurchaseInvoiceInstallment/CurlGenerateMonthlyInvoices
*/
class PurchaseInvoiceInstallment extends MY_Controller
{
var $db;
var $baseUrl = "https://accone.aplikasi.web.id/one-api/";
public function index()
{
echo "Purchase Invoice Installment — Auto Generate PI Cicilan Aset";
}
public function __construct()
{
parent::__construct();
}
/**
* GenerateMonthlyInvoices
*
* Membuat Purchase Invoice cicilan untuk semua kontrak aset yang aktif
* dan belum lunas pada bulan yang ditentukan.
*
* Parameter (POST JSON):
* - startDate : Tanggal awal periode (format YYYY-MM-DD). Default: awal bulan ini.
* - endDate : Tanggal akhir periode (format YYYY-MM-DD). Default: akhir bulan ini.
* userID diambil otomatis dari token (sys_user["M_UserID"]).
* Jika CRON berjalan tanpa token, fallback ke user ID 0.
*
* Syarat kontrak diproses:
* 1. Kontrak aktif dan berstatus "belum lunas"
* 2. Nilai cicilan > 0
* 3. Jumlah cicilan terbayar < total cicilan
* 4. Tanggal kontrak masuk dalam bulan yang dituju
* 5. RO sudah confirmed
* 6. PO sudah berstatus Approved
*/
public function GenerateMonthlyInvoices()
{
try {
$para = $this->sys_input;
// Ambil userID dari token JWT (sys_user). Fallback ke 0 jika CRON berjalan tanpa token.
$userID = !empty($this->sys_user["M_UserID"]) ? (int) $this->sys_user["M_UserID"] : 0;
$user = $this->getCronUser($userID);
$startDate = isset($para["startDate"]) && $para["startDate"] != ""
? $para["startDate"]
: (isset($para["date"]) && $para["date"] != "" ? date("Y-m-01", strtotime($para["date"])) : date("Y-m-01"));
$endDate = isset($para["endDate"]) && $para["endDate"] != ""
? $para["endDate"]
: (isset($para["date"]) && $para["date"] != "" ? date("Y-m-t", strtotime($para["date"])) : date("Y-m-t"));
// Validasi format tanggal
if (!$this->isValidDate($startDate) || !$this->isValidDate($endDate)) {
throw new Exception("Format tanggal tidak valid. Gunakan format YYYY-MM-DD, contoh: 2025-07-01");
}
if (strtotime($startDate) > strtotime($endDate)) {
throw new Exception("startDate tidak boleh lebih besar dari endDate");
}
// Tentukan rentang bulan berdasarkan tanggal acuan
$monthStart = $startDate;
$monthEnd = $endDate;
$dayOfMonth = (int) date("d", strtotime($endDate));
// -------------------------------------------------------------------------
// Ambil semua kontrak cicilan yang memenuhi syarat pada bulan ini
// -------------------------------------------------------------------------
$sqlKontrak = "SELECT
c.PurchaseOrderAssetContractID,
c.PurchaseOrderAssetContractPurchaseOrderID,
ro.ReceiveOrderPoID AS PurchaseOrderAssetContractReceiveOrderPoID,
c.PurchaseOrderAssetContractName,
c.PurchaseOrderAssetContractStartDate,
c.PurchaseOrderAssetContractEndDate,
c.PurchaseOrderAssetContractInstallmentNumber,
c.PurchaseOrderAssetContractInstallmentPaid,
c.PurchaseOrderAssetContractInstallmentDate,
c.PurchaseOrderAssetContractInstallmentPayAmount,
c.PurchaseOrderAssetContractCreatedUserID,
po.PurchaseOrderID,
po.PurchaseOrderNumber,
po.PurchaseOrderSupplierID,
po.PurchaseOrderPaymentTerm,
po.PurchaseOrderWarehouseType,
po.PurchaseOrderWarehouseID,
ro.ReceiveOrderPoConfirmed,
ps.PurchaseOrderSummaryID,
ps.PurchaseOrderSummaryItemID,
ps.PurchaseOrderSummaryItemUnitID
FROM purchase_order_asset_contract c
-- Pastikan PO sudah Approved dan aktif
JOIN purchase_order po
ON po.PurchaseOrderID = c.PurchaseOrderAssetContractPurchaseOrderID
AND po.PurchaseOrderIsActive = 'Y'
AND po.PurchaseOrderStatus = 'Approved'
JOIN (
SELECT
rd.ReceiveOrderPoDetailPurchaseOrderID,
MIN(ro0.ReceiveOrderPoID) AS ReceiveOrderPoID,
MAX(ro0.ReceiveOrderPoConfirmed) AS ReceiveOrderPoConfirmed
FROM receive_order_po ro0
JOIN receive_order_po_detail rd
ON rd.ReceiveOrderPoDetailReceiveOrderPoID = ro0.ReceiveOrderPoID
AND rd.ReceiveOrderPoDetailIsActive = 'Y'
WHERE ro0.ReceiveOrderPoIsActive = 'Y'
AND ro0.ReceiveOrderPoConfirmed = 'Y'
GROUP BY rd.ReceiveOrderPoDetailPurchaseOrderID
) ro
ON ro.ReceiveOrderPoDetailPurchaseOrderID = po.PurchaseOrderID
-- Ambil 1 item PO pertama sebagai referensi baris detail PI
LEFT JOIN (
SELECT ps0.*
FROM purchase_order_summary ps0
JOIN (
SELECT
PurchaseOrderSummaryPurchaseOrderID,
MIN(PurchaseOrderSummaryID) AS PurchaseOrderSummaryID
FROM purchase_order_summary
WHERE PurchaseOrderSummaryIsActive = 'Y'
GROUP BY PurchaseOrderSummaryPurchaseOrderID
) psx
ON psx.PurchaseOrderSummaryID = ps0.PurchaseOrderSummaryID
) ps
ON ps.PurchaseOrderSummaryPurchaseOrderID = po.PurchaseOrderID
WHERE c.PurchaseOrderAssetContractIsActive = 'Y'
AND c.PurchaseOrderAssetContractStatus = 'belum lunas'
-- Hanya kontrak yang ada nilai cicilannya
AND IFNULL(c.PurchaseOrderAssetContractInstallmentPayAmount, 0) > 0
-- Hanya kontrak yang belum selesai seluruh cicilannya
AND IFNULL(c.PurchaseOrderAssetContractInstallmentPaid, 0) < IFNULL(c.PurchaseOrderAssetContractInstallmentNumber, 0)
-- Kontrak sudah mulai sebelum atau pada akhir bulan ini
AND DATE(c.PurchaseOrderAssetContractStartDate) <= DATE(?)
-- Kontrak belum berakhir (atau tidak ada tanggal akhir)
AND (
c.PurchaseOrderAssetContractEndDate IS NULL
OR DATE(c.PurchaseOrderAssetContractEndDate) >= DATE(?)
)
-- Tanggal jatuh tempo cicilan sudah melewati atau sama dengan hari ini
AND IFNULL(c.PurchaseOrderAssetContractInstallmentDate, 1) <= ?";
$params = [$monthEnd, $monthStart, $dayOfMonth];
$qryKontrak = $this->db->query($sqlKontrak, $params);
if (!$qryKontrak) {
$this->sys_error_db("Gagal mengambil daftar kontrak cicilan dari database.");
exit;
}
$berhasil = []; // PI yang berhasil dibuat
$dilewati = []; // PI yang dilewati beserta alasannya
// -------------------------------------------------------------------------
// Proses tiap kontrak satu per satu
// -------------------------------------------------------------------------
$kontraks = $qryKontrak->result_array();
foreach ($kontraks as $kontrak) {
// Lewati jika item/satuan PO tidak ditemukan (tidak bisa buat baris detail)
if (empty($kontrak["PurchaseOrderSummaryItemID"]) || empty($kontrak["PurchaseOrderSummaryItemUnitID"])) {
$dilewati[] = [
"kontrakID" => $kontrak["PurchaseOrderAssetContractID"],
"purchaseOrderID" => $kontrak["PurchaseOrderID"],
"alasan" => "Item atau satuan pada Purchase Order tidak ditemukan, tidak bisa membuat baris detail PI."
];
continue;
}
// -------------------------------------------------------
// Cek apakah PI cicilan bulan ini sudah pernah dibuat
// -------------------------------------------------------
$sqlCekDuplikat = "SELECT SupplierInvoiceID, SupplierInvoiceNumber
FROM supplier_invoice
WHERE SupplierInvoiceIsActive = 'Y'
AND SupplierInvoiceDate >= DATE(?)
AND SupplierInvoiceDate <= DATE(?)
AND SupplierInvoiceStatus = 'Draft'
AND (
SupplierInvoiceReceiveOrderPoID = ?
OR EXISTS (
SELECT 1
FROM supplier_invoice_detail sid
WHERE sid.SupplierInvoiceDetailSupplierInvoiceID = SupplierInvoiceID
AND sid.SupplierInvoiceDetailReceiveOrderPoID = ?
AND sid.SupplierInvoiceDetailIsActive = 'Y'
)
)
LIMIT 1";
$qryCekDuplikat = $this->db->query($sqlCekDuplikat, [
$monthStart,
$monthEnd,
$kontrak["PurchaseOrderAssetContractReceiveOrderPoID"],
$kontrak["PurchaseOrderAssetContractReceiveOrderPoID"]
]);
if (!$qryCekDuplikat) {
$this->sys_error_db("Gagal memeriksa duplikasi PI cicilan untuk kontrak ID " . $kontrak["PurchaseOrderAssetContractID"] . ".");
exit;
}
if ($qryCekDuplikat->num_rows() > 0) {
$piExisting = $qryCekDuplikat->row_array();
$dilewati[] = [
"kontrakID" => $kontrak["PurchaseOrderAssetContractID"],
"purchaseOrderID" => $kontrak["PurchaseOrderID"],
"receiveOrderPoID" => $kontrak["PurchaseOrderAssetContractReceiveOrderPoID"],
"supplierInvoiceID" => $piExisting["SupplierInvoiceID"],
"nomorInvoice" => $piExisting["SupplierInvoiceNumber"],
"alasan" => "PI cicilan untuk bulan ini sudah dibuat sebelumnya, tidak perlu dibuat ulang."
];
continue;
}
$contractUserID = (int) ($kontrak["PurchaseOrderAssetContractCreatedUserID"] ?? 0);
$contractUser = $this->getCronUser($contractUserID);
// Generate nomor PI otomatis via stored function fn_penomoran
$nomorPI = $this->generateNomorPI($kontrak, $contractUser);
$jumlahCicilan = (float) $kontrak["PurchaseOrderAssetContractInstallmentPayAmount"];
$paymentTerm = isset($kontrak["PurchaseOrderPaymentTerm"]) && $kontrak["PurchaseOrderPaymentTerm"] !== null
? (int) $kontrak["PurchaseOrderPaymentTerm"]
: 0;
$tanggalJatuhTempo = $this->hitungJatuhTempo($endDate, $paymentTerm);
$catatan = "PI Cicilan Otomatis — Kontrak Aset ID " . $kontrak["PurchaseOrderAssetContractID"] . " periode " . date("Y-m", strtotime($startDate));
// -------------------------------------------------------
// INSERT header + detail Purchase Invoice (supplier_invoice & supplier_invoice_detail)
// -------------------------------------------------------
$deskripsi = $kontrak["PurchaseOrderAssetContractName"] != ""
? $kontrak["PurchaseOrderAssetContractName"]
: "Cicilan Kontrak Aset ID " . $kontrak["PurchaseOrderAssetContractID"];
$deskripsi .= " periode " . date("Y-m", strtotime($startDate));
$payloadInsert = [
"nomorPI" => $nomorPI,
"tanggalPI" => $endDate,
"tanggalJatuhTempo" => $tanggalJatuhTempo,
"jumlahCicilan" => $jumlahCicilan,
"catatan" => $catatan,
"deskripsi" => $deskripsi,
"userID" => $contractUserID,
"purchaseOrderAssetContractID" => $kontrak["PurchaseOrderAssetContractID"],
"purchaseOrderID" => $kontrak["PurchaseOrderID"],
"receiveOrderPoID" => $kontrak["PurchaseOrderAssetContractReceiveOrderPoID"],
"supplierID" => $kontrak["PurchaseOrderSupplierID"],
"purchaseOrderSummaryID" => $kontrak["PurchaseOrderSummaryID"],
"purchaseOrderSummaryItemID" => $kontrak["PurchaseOrderSummaryItemID"],
"purchaseOrderSummaryItemUnitID" => $kontrak["PurchaseOrderSummaryItemUnitID"]
];
$hasilInsert = $this->curlInsertSupplierInvoice($payloadInsert);
if ($hasilInsert === false) {
$this->sys_error_db("Gagal menyimpan Purchase Invoice cicilan untuk kontrak ID " . $kontrak["PurchaseOrderAssetContractID"] . ".");
exit;
}
if (!empty($hasilInsert["duplicate"])) {
$dilewati[] = [
"kontrakID" => $kontrak["PurchaseOrderAssetContractID"],
"purchaseOrderID" => $kontrak["PurchaseOrderID"],
"receiveOrderPoID" => $kontrak["PurchaseOrderAssetContractReceiveOrderPoID"],
"supplierInvoiceID" => $hasilInsert["supplierInvoiceID"],
"nomorInvoice" => $hasilInsert["supplierInvoiceNumber"],
"alasan" => "PI cicilan untuk bulan ini sudah dibuat sebelumnya, tidak perlu dibuat ulang."
];
continue;
}
$supplierInvoiceID = $hasilInsert["supplierInvoiceID"];
// -------------------------------------------------------
// UPDATE jumlah cicilan terbayar pada kontrak
// -------------------------------------------------------
$this->db->trans_begin();
$cicilanTerbayarBaru = ((int) $kontrak["PurchaseOrderAssetContractInstallmentPaid"]) + 1;
$statusKontrakBaru = $cicilanTerbayarBaru >= (int) $kontrak["PurchaseOrderAssetContractInstallmentNumber"]
? "lunas"
: "belum lunas";
$sqlUpdateKontrak = "UPDATE purchase_order_asset_contract
SET PurchaseOrderAssetContractReceiveOrderPoID = ?,
PurchaseOrderAssetContractInstallmentPaid = ?,
PurchaseOrderAssetContractStatus = ?,
PurchaseOrderAssetContractLastUpdated = NOW()
WHERE PurchaseOrderAssetContractID = ?
AND PurchaseOrderAssetContractIsActive = 'Y'";
$qryUpdateKontrak = $this->db->query($sqlUpdateKontrak, [
$kontrak["PurchaseOrderAssetContractReceiveOrderPoID"],
$cicilanTerbayarBaru,
$statusKontrakBaru,
$kontrak["PurchaseOrderAssetContractID"]
]);
if (!$qryUpdateKontrak) {
$this->db->trans_rollback();
$this->sys_error_db("Gagal memperbarui data cicilan terbayar pada kontrak ID " . $kontrak["PurchaseOrderAssetContractID"] . ".");
exit;
}
// Pastikan tidak ada error di dalam transaksi sebelum commit
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
$this->sys_error_db("Transaksi database gagal saat memproses kontrak ID " . $kontrak["PurchaseOrderAssetContractID"] . ". Semua perubahan dibatalkan.");
exit;
}
$this->db->trans_commit();
// Catat PI yang berhasil dibuat
$berhasil[] = [
"kontrakID" => $kontrak["PurchaseOrderAssetContractID"],
"purchaseOrderID" => $kontrak["PurchaseOrderID"],
"supplierInvoiceID" => $supplierInvoiceID,
"nomorInvoice" => $nomorPI,
"jumlahCicilan" => $jumlahCicilan
];
}
// -------------------------------------------------------
// Response sukses — ringkasan hasil proses
// -------------------------------------------------------
$this->sys_ok([
"startDate" => $startDate,
"endDate" => $endDate,
"periodeAwal" => $monthStart,
"periodeAkhir" => $monthEnd,
"totalDibuat" => count($berhasil),
"totalDilewati" => count($dilewati),
"daftarDibuat" => $berhasil,
"daftarDilewati" => $dilewati
]);
} catch (Exception $exc) {
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
}
$this->sys_error($exc->getMessage());
}
}
/**
* Kirim payload insert supplier_invoice ke controller terpisah via cURL.
*
* @param array $payload
* @return array|false
*/
private function curlInsertSupplierInvoice($payload)
{
$endpoint = rtrim($this->baseUrl, "/") . "/mockup/scheduler/PurchaseInvoiceInstallmentInsert/InsertSupplierInvoice";
$ch = curl_init($endpoint);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Accept: application/json"
],
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_CONNECTTIMEOUT => 15,
CURLOPT_TIMEOUT => 120
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
$pesanError = curl_error($ch);
curl_close($ch);
$this->sys_error("Gagal menghubungi endpoint insert supplier_invoice. Detail: " . $pesanError);
return false;
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode < 200 || $httpCode >= 300) {
$this->sys_error("Endpoint insert supplier_invoice mengembalikan HTTP " . $httpCode . ".");
return false;
}
$decoded = json_decode($response, true);
if (!is_array($decoded)) {
$this->sys_error("Response insert supplier_invoice tidak valid JSON.");
return false;
}
if (!isset($decoded["status"]) || strtoupper($decoded["status"]) !== "OK") {
$pesan = isset($decoded["message"]) ? $decoded["message"] : "Insert supplier_invoice gagal.";
$this->sys_error($pesan);
return false;
}
return isset($decoded["data"]) && is_array($decoded["data"]) ? $decoded["data"] : $decoded;
}
public function ListEligibleContracts()
{
try {
$para = $this->sys_input;
$startDate = isset($para["startDate"]) && $para["startDate"] != ""
? $para["startDate"]
: (isset($para["date"]) && $para["date"] != "" ? date("Y-m-01", strtotime($para["date"])) : date("Y-m-01"));
$endDate = isset($para["endDate"]) && $para["endDate"] != ""
? $para["endDate"]
: (isset($para["date"]) && $para["date"] != "" ? date("Y-m-t", strtotime($para["date"])) : date("Y-m-t"));
if (!$this->isValidDate($startDate) || !$this->isValidDate($endDate)) {
throw new Exception("Format tanggal tidak valid. Gunakan format YYYY-MM-DD, contoh: 2025-07-01");
}
if (strtotime($startDate) > strtotime($endDate)) {
throw new Exception("startDate tidak boleh lebih besar dari endDate");
}
$monthStart = $startDate;
$monthEnd = $endDate;
$dayOfMonth = (int) date("d", strtotime($endDate));
$sqlKontrak = "SELECT
c.PurchaseOrderAssetContractID,
c.PurchaseOrderAssetContractPurchaseOrderID,
ro.ReceiveOrderPoID AS PurchaseOrderAssetContractReceiveOrderPoID,
c.PurchaseOrderAssetContractName,
c.PurchaseOrderAssetContractStartDate,
c.PurchaseOrderAssetContractEndDate,
c.PurchaseOrderAssetContractInstallmentNumber,
c.PurchaseOrderAssetContractInstallmentPaid,
c.PurchaseOrderAssetContractInstallmentDate,
c.PurchaseOrderAssetContractInstallmentPayAmount,
po.PurchaseOrderID,
po.PurchaseOrderNumber,
po.PurchaseOrderSupplierID,
po.PurchaseOrderPaymentTerm,
po.PurchaseOrderWarehouseType,
po.PurchaseOrderWarehouseID,
ro.ReceiveOrderPoConfirmed,
ps.PurchaseOrderSummaryID,
ps.PurchaseOrderSummaryItemID,
ps.PurchaseOrderSummaryItemUnitID
FROM purchase_order_asset_contract c
JOIN purchase_order po
ON po.PurchaseOrderID = c.PurchaseOrderAssetContractPurchaseOrderID
AND po.PurchaseOrderIsActive = 'Y'
AND po.PurchaseOrderStatus = 'Approved'
JOIN (
SELECT
rd.ReceiveOrderPoDetailPurchaseOrderID,
MIN(ro0.ReceiveOrderPoID) AS ReceiveOrderPoID,
MAX(ro0.ReceiveOrderPoConfirmed) AS ReceiveOrderPoConfirmed
FROM receive_order_po ro0
JOIN receive_order_po_detail rd
ON rd.ReceiveOrderPoDetailReceiveOrderPoID = ro0.ReceiveOrderPoID
AND rd.ReceiveOrderPoDetailIsActive = 'Y'
WHERE ro0.ReceiveOrderPoIsActive = 'Y'
AND ro0.ReceiveOrderPoConfirmed = 'Y'
GROUP BY rd.ReceiveOrderPoDetailPurchaseOrderID
) ro
ON ro.ReceiveOrderPoDetailPurchaseOrderID = po.PurchaseOrderID
LEFT JOIN (
SELECT ps0.*
FROM purchase_order_summary ps0
JOIN (
SELECT
PurchaseOrderSummaryPurchaseOrderID,
MIN(PurchaseOrderSummaryID) AS PurchaseOrderSummaryID
FROM purchase_order_summary
WHERE PurchaseOrderSummaryIsActive = 'Y'
GROUP BY PurchaseOrderSummaryPurchaseOrderID
) psx
ON psx.PurchaseOrderSummaryID = ps0.PurchaseOrderSummaryID
) ps
ON ps.PurchaseOrderSummaryPurchaseOrderID = po.PurchaseOrderID
WHERE c.PurchaseOrderAssetContractIsActive = 'Y'
AND c.PurchaseOrderAssetContractStatus = 'belum lunas'
AND IFNULL(c.PurchaseOrderAssetContractInstallmentPayAmount, 0) > 0
AND IFNULL(c.PurchaseOrderAssetContractInstallmentPaid, 0) < IFNULL(c.PurchaseOrderAssetContractInstallmentNumber, 0)
AND DATE(c.PurchaseOrderAssetContractStartDate) <= DATE(?)
AND (
c.PurchaseOrderAssetContractEndDate IS NULL
OR DATE(c.PurchaseOrderAssetContractEndDate) >= DATE(?)
)
AND IFNULL(c.PurchaseOrderAssetContractInstallmentDate, 1) <= ?
ORDER BY c.PurchaseOrderAssetContractID ASC";
$qryKontrak = $this->db->query($sqlKontrak, [$monthEnd, $monthStart, $dayOfMonth]);
if (!$qryKontrak) {
$this->sys_error_db("Gagal mengambil daftar kontrak cicilan eligible.");
exit;
}
$this->sys_ok([
"startDate" => $startDate,
"endDate" => $endDate,
"periodeAwal" => $monthStart,
"periodeAkhir" => $monthEnd,
"total" => $qryKontrak->num_rows(),
"records" => $qryKontrak->result_array()
]);
} catch (Exception $exc) {
$this->sys_error($exc->getMessage());
}
}
/**
* CurlGenerateMonthlyInvoices
*
* Wrapper untuk memanggil GenerateMonthlyInvoices melalui HTTP request (cURL).
* Cocok digunakan oleh CRON eksternal yang tidak bisa memanggil function PHP langsung.
*
* Parameter (POST JSON):
* - baseUrl : Base URL server tujuan. Default: URL server ini sendiri.
* - startDate : Tanggal awal periode (YYYY-MM-DD). Default: awal bulan ini.
* - endDate : Tanggal akhir periode (YYYY-MM-DD). Default: akhir bulan ini.
* - userID : ID user yang menjalankan. Default: 0.
*/
// =========================================================================
// FUNGSI PRIVATE / HELPER
// =========================================================================
/**
* Generate nomor Purchase Invoice.
*
* @param array $kontrak Data baris kontrak dari query
* @param array $user Data user CRON
* @return string Nomor PI yang dihasilkan
*/
private function generateNomorPI($kontrak, $user)
{
$userID = isset($user["M_UserID"]) ? (int) $user["M_UserID"] : 0;
// Tentukan area ID dan type
$areaid = isset($user["M_BranchID"]) && (int) $user["M_BranchID"] > 0 ? (int) $user["M_BranchID"] : 0;
$areatype = 'B';
if (isset($user["loginLevel"]) && $user["loginLevel"] == 'regional') {
$areaid = isset($user["S_RegionalID"]) && (int) $user["S_RegionalID"] > 0 ? (int) $user["S_RegionalID"] : 0;
$areatype = 'R';
}
// Ambil divisi user
$userDivID = 0;
if ($userID > 0) {
$sqlusrdivisi = "SELECT M_UserDivisionDivisionID FROM m_userdivision
WHERE M_UserDivisionM_UserID = ? AND M_UserDivisionIsActive = 'Y' LIMIT 1";
$queusrdivisi = $this->db->query($sqlusrdivisi, [$userID]);
if ($queusrdivisi && $queusrdivisi->num_rows() > 0) {
$userDivID = (int) $queusrdivisi->row_array()['M_UserDivisionDivisionID'];
}
}
// Jalankan stored function fn_penomoran
$sqlnum = "SELECT `fn_penomoran`(?, ?, ?, ?, ?, ?) AS numpd;";
$quenum = $this->db->query($sqlnum, ['PI', $userDivID, $areatype, $areaid, 'SM', 'N']);
if ($quenum && $quenum->num_rows() > 0) {
return $quenum->row_array()['numpd'];
}
// Fallback jika stored function gagal
$contractID = isset($kontrak["PurchaseOrderAssetContractID"]) ? (int) $kontrak["PurchaseOrderAssetContractID"] : 0;
return "PI-INS-FALLBACK-" . $contractID . "-" . date("Ymd");
}
/**
* Ambil data user berdasarkan userID untuk keperluan CRON.
* Jika user tidak ditemukan, kembalikan data default (tanpa branch/regional).
*
* @param int $userID
* @return array
*/
private function getCronUser($userID)
{
$sql = "SELECT
M_UserID,
M_UserM_BranchID AS M_BranchID,
M_UserS_RegionalID AS S_RegionalID
FROM m_user
WHERE M_UserID = ?
LIMIT 1";
$qry = $this->db->query($sql, [$userID]);
if ($qry && $qry->num_rows() > 0) {
$user = $qry->row_array();
$user["loginLevel"] = "branch";
return $user;
}
// User tidak ditemukan, gunakan data kosong agar proses tetap berjalan
return [
"M_UserID" => $userID,
"M_BranchID" => 0,
"S_RegionalID" => 0,
"loginLevel" => "branch"
];
}
/**
* Hitung tanggal jatuh tempo berdasarkan tanggal acuan dan payment term (dalam hari).
*
* @param string $tanggal Format YYYY-MM-DD
* @param int $term Jumlah hari payment term
* @return string Tanggal jatuh tempo (YYYY-MM-DD)
*/
private function hitungJatuhTempo($tanggal, $term)
{
$hari = is_numeric($term) ? (int) $term : 0;
if ($hari < 0) {
$hari = 0;
}
return date("Y-m-d", strtotime($tanggal . " +" . $hari . " days"));
}
/**
* Validasi apakah string adalah tanggal yang valid dengan format YYYY-MM-DD.
*
* @param string $tanggal
* @return bool
*/
private function isValidDate($tanggal)
{
$d = DateTime::createFromFormat("Y-m-d", $tanggal);
return $d && $d->format("Y-m-d") === $tanggal;
}
}

View File

@@ -1,220 +0,0 @@
<?php
/**
* PurchaseInvoiceInstallmentInsert
*
* Endpoint khusus untuk menyimpan supplier_invoice dan supplier_invoice_detail
* dari payload yang dikirim controller generator via cURL.
*/
class PurchaseInvoiceInstallmentInsert extends MY_Controller
{
var $db;
public function index()
{
echo "Purchase Invoice Installment Insert";
}
public function __construct()
{
parent::__construct();
}
public function InsertSupplierInvoice()
{
try {
$para = $this->sys_input;
$required = [
"nomorPI",
"tanggalPI",
"tanggalJatuhTempo",
"jumlahCicilan",
"catatan",
"deskripsi",
"userID",
"purchaseOrderAssetContractID",
"purchaseOrderID",
"receiveOrderPoID",
"supplierID",
"purchaseOrderSummaryID",
"purchaseOrderSummaryItemID",
"purchaseOrderSummaryItemUnitID"
];
foreach ($required as $field) {
if (!isset($para[$field]) || $para[$field] === "" || $para[$field] === null) {
throw new Exception("Field wajib belum lengkap: " . $field);
}
}
$tanggalPI = $para["tanggalPI"];
$tanggalJatuhTempo = $para["tanggalJatuhTempo"];
if (!$this->isValidDate($tanggalPI) || !$this->isValidDate($tanggalJatuhTempo)) {
throw new Exception("Format tanggal tidak valid. Gunakan YYYY-MM-DD.");
}
$jumlahCicilan = (float) $para["jumlahCicilan"];
if ($jumlahCicilan <= 0) {
throw new Exception("jumlahCicilan harus lebih besar dari 0.");
}
$receiveOrderPoID = (int) $para["receiveOrderPoID"];
$monthKey = date("Y-m", strtotime($tanggalPI));
$sqlDuplikat = "SELECT SupplierInvoiceID, SupplierInvoiceNumber
FROM supplier_invoice
WHERE SupplierInvoiceIsActive = 'Y'
AND SupplierInvoiceStatus = 'Draft'
AND SupplierInvoiceReceiveOrderPoID = ?
AND DATE_FORMAT(SupplierInvoiceDate, '%Y-%m') = ?
LIMIT 1";
$qryDuplikat = $this->db->query($sqlDuplikat, [$receiveOrderPoID, $monthKey]);
if (!$qryDuplikat) {
$this->sys_error_db("Gagal mengecek duplikasi supplier_invoice.");
exit;
}
if ($qryDuplikat->num_rows() > 0) {
$existing = $qryDuplikat->row_array();
$this->sys_ok([
"duplicate" => true,
"supplierInvoiceID" => $existing["SupplierInvoiceID"],
"supplierInvoiceNumber" => $existing["SupplierInvoiceNumber"]
]);
return;
}
$this->db->trans_begin();
$sqlHeader = "INSERT INTO supplier_invoice (
SupplierInvoiceNumber,
SupplierInvoiceReceiveOrderPoID,
SupplierInvoiceDate,
SupplierInvoiceDueDate,
SupplierInvoiceDraftPaymentDate,
SupplierInvoiceSupplierID,
SupplierInvoiceSupplierInvoiceNumber,
SupplierInvoiceSupplierInvoiceDate,
SupplierInvoiceSubTotal,
SupplierInvoiceDiscountPercent,
SupplierInvoiceDiscountAmount,
SupplierInvoiceTaxPercentPph,
SupplierInvoiceTaxAmountPph,
SupplierInvoiceTaxPercentPpn,
SupplierInvoiceTaxAmountPpn,
SupplierInvoiceShippingCost,
SupplierInvoiceAdjustmentAmount,
SupplierInvoiceAdjustmentNote,
SupplierInvoiceGrandTotal,
SupplierInvoiceUnpaid,
SupplierInvoiceNote,
SupplierInvoiceStatus,
SupplierInvoiceCreatedUserID
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$qryHeader = $this->db->query($sqlHeader, [
$para["nomorPI"],
$receiveOrderPoID,
$tanggalPI,
$tanggalJatuhTempo,
$tanggalPI,
(int) $para["supplierID"],
null,
null,
$jumlahCicilan,
0,
0,
0,
0,
0,
0,
0,
0,
null,
$jumlahCicilan,
$jumlahCicilan,
$para["catatan"],
"Draft",
(int) $para["userID"]
]);
if (!$qryHeader) {
$this->db->trans_rollback();
$this->sys_error_db("Gagal insert header supplier_invoice.");
exit;
}
$supplierInvoiceID = $this->db->insert_id();
$sqlDetail = "INSERT INTO supplier_invoice_detail (
SupplierInvoiceDetailSupplierInvoiceID,
SupplierInvoiceDetailPurchaseOrderID,
SupplierInvoiceDetailReceiveOrderPoID,
SupplierInvoiceDetailPurchaseOrderSummaryID,
SupplierInvoiceDetailItemID,
SupplierInvoiceDetailItemUnitID,
SupplierInvoiceDetailDescription,
SupplierInvoiceDetailQty,
SupplierInvoiceDetailPrice,
SupplierInvoiceDetailDiscountPercent,
SupplierInvoiceDetailDiscountDiscountRupiah,
SupplierInvoiceDetailDiscountDiscountType,
SupplierInvoiceDetailDiscountPoProrata,
SupplierInvoiceDetailDiscountAmount,
SupplierInvoiceDetailTotal,
SupplierInvoiceDetailUnpaid,
SupplierInvoiceDetailCreatedUserID
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$qryDetail = $this->db->query($sqlDetail, [
$supplierInvoiceID,
(int) $para["purchaseOrderID"],
$receiveOrderPoID,
(int) $para["purchaseOrderSummaryID"],
(int) $para["purchaseOrderSummaryItemID"],
(int) $para["purchaseOrderSummaryItemUnitID"],
$para["deskripsi"],
1,
$jumlahCicilan,
0,
0,
"R",
0,
0,
$jumlahCicilan,
$jumlahCicilan,
(int) $para["userID"]
]);
if (!$qryDetail) {
$this->db->trans_rollback();
$this->sys_error_db("Gagal insert detail supplier_invoice_detail.");
exit;
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
$this->sys_error_db("Transaksi insert supplier_invoice gagal.");
exit;
}
$this->db->trans_commit();
$this->sys_ok([
"duplicate" => false,
"supplierInvoiceID" => $supplierInvoiceID,
"supplierInvoiceNumber" => $para["nomorPI"]
]);
} catch (Exception $exc) {
$this->sys_error($exc->getMessage());
}
}
private function isValidDate($tanggal)
{
$d = DateTime::createFromFormat("Y-m-d", $tanggal);
return $d && $d->format("Y-m-d") === $tanggal;
}
}

View File

@@ -28,66 +28,29 @@ class Billv2 extends MY_Controller {
$offset = ($params['currentpage'] - 1) * $limit;
}
// ── UNION base — invoice branch + downpayment branch ────
$sql_base = "
SELECT
sp.SupplierPaymentID,
sp.SupplierPaymentDate,
sp.SupplierPaymentNumber,
sp.SupplierPaymentAmount,
sp.SupplierPaymentStatus,
sp.SupplierPaymentIsVerif,
sp.SupplierPaymentIsApproved,
sp.SupplierPaymentIsActive,
si.SupplierInvoiceID,
si.SupplierInvoiceNumber,
si.SupplierInvoiceDraftPaymentDate,
sup.SupplierCode,
sup.SupplierName,
'INVOICE' AS type
FROM supplier_payment sp
JOIN supplier_invoice si
ON si.SupplierInvoiceID = sp.SupplierPaymentSupplierInvoiceID
JOIN supplier sup
ON sup.SupplierID = si.SupplierInvoiceSupplierID
WHERE sp.SupplierPaymentSupplierInvoiceID > 0
UNION ALL
SELECT
sp.SupplierPaymentID,
sp.SupplierPaymentDate,
sp.SupplierPaymentNumber,
sp.SupplierPaymentAmount,
sp.SupplierPaymentStatus,
sp.SupplierPaymentIsVerif,
sp.SupplierPaymentIsApproved,
sp.SupplierPaymentIsActive,
dp.SupplierDownpaymentID * -1 AS SupplierInvoiceID,
CONCAT('DP-', po.PurchaseOrderNumber) AS SupplierInvoiceNumber,
dp.SupplierDownpaymentDueDate AS SupplierInvoiceDraftPaymentDate,
dp_sup.SupplierCode AS SupplierCode,
dp_sup.SupplierName AS SupplierName,
'DP' AS type
FROM supplier_payment sp
JOIN supplier_downpayment dp
ON dp.SupplierDownpaymentID = sp.SupplierPaymentSupplierDownpaymentID
JOIN supplier dp_sup
ON dp_sup.SupplierID = dp.SupplierDownpaymentSupplierID
JOIN purchase_order po
ON po.PurchaseOrderID = dp.SupplierDownpaymentPurchasOrderID
WHERE sp.SupplierPaymentSupplierDownpaymentID IS NOT NULL";
// ── Outer: common filters + ordering + pagination ───────
$sql_data = "
SELECT * FROM ($sql_base) AS combined
WHERE SupplierPaymentIsActive = 'Y'
AND SupplierPaymentNumber LIKE ?
AND (SupplierPaymentDate BETWEEN DATE(?) AND DATE(?))
AND (SupplierPaymentStatus = ? OR ? = 'All')
ORDER BY SupplierPaymentID DESC
LIMIT ? OFFSET ?";
$sql_base = "SELECT
SupplierPaymentID,
SupplierPaymentDate,
SupplierPaymentNumber,
SupplierPaymentAmount,
SupplierPaymentStatus,
SupplierPaymentIsVerif,
SupplierPaymentIsApproved,
SupplierInvoiceID,
SupplierInvoiceNumber,
SupplierInvoiceDraftPaymentDate,
SupplierCode,
SupplierName
FROM supplier_payment
JOIN supplier_invoice ON SupplierInvoiceID = SupplierPaymentSupplierInvoiceID
AND SupplierPaymentNumber LIKE ?
AND (SupplierPaymentDate BETWEEN DATE(?) AND DATE(?))
AND (SupplierPaymentStatus = ? OR ? = 'All')
JOIN supplier ON SupplierID = SupplierInvoiceSupplierID
WHERE SupplierPaymentIsActive = 'Y'
ORDER BY SupplierPaymentID DESC";
$sql_data = $sql_base . " LIMIT ? OFFSET ? ";
$que_data = $this->db->query($sql_data, [
$keyword, $params['startdate'], $params['enddate'],
$params['status'], $params['status'], $limit, $offset
@@ -96,14 +59,7 @@ class Billv2 extends MY_Controller {
throw new Exception("[Error] failed get data supplier payment", 2);
}
// ── COUNT — wrap UNION in outer filter ──────────────────
$sql_total = "
SELECT COUNT(*) AS total FROM ($sql_base) AS combined
WHERE SupplierPaymentIsActive = 'Y'
AND SupplierPaymentNumber LIKE ?
AND (SupplierPaymentDate BETWEEN DATE(?) AND DATE(?))
AND (SupplierPaymentStatus = ? OR ? = 'All')";
$sql_total = "SELECT COUNT(*) AS total FROM ($sql_base) AS x";
$que_total = $this->db->query($sql_total, [
$keyword, $params['startdate'], $params['enddate'],
$params['status'], $params['status']
@@ -114,9 +70,9 @@ class Billv2 extends MY_Controller {
$output = [
"records" => $que_data->result_array(),
"total" => $que_total->row_array()['total']
"total" =>$que_total->row_array()['total']
];
$this->sys_ok($output);
exit;
} catch (Exception $exc) {
@@ -140,123 +96,70 @@ class Billv2 extends MY_Controller {
$para = $this->sys_input;
// ── Detect payment type ──────────────────────────────────
$sql_type = "SELECT
SupplierPaymentSupplierInvoiceID,
SupplierPaymentSupplierDownpaymentID
FROM supplier_payment
WHERE SupplierPaymentID = ? AND SupplierPaymentIsActive = 'Y'";
$que_type = $this->db->query($sql_type, [$para['paymentID']]);
if (!$que_type) {
throw new Exception("[Error] failed get payment header", 2);
$sql = "SELECT
SupplierInvoiceID,
SupplierInvoiceRefNumber,
SupplierInvoiceDeliveryOrderNumber,
SupplierInvoiceSupplierInvoiceNumber,
SupplierInvoiceSupplierInvoiceDate,
SupplierInvoiceSubTotal,
SupplierInvoiceTaxPercentPph,
SupplierInvoiceTaxPercentPpn,
SupplierInvoiceTaxAmountPpn,
SupplierInvoiceDiscountAmount,
SupplierInvoiceDiscountPercent,
SupplierInvoiceShippingCost,
SupplierInvoiceGrandTotal,
SupplierInvoiceAdjustmentAmount,
SupplierInvoiceAdjustmentNote,
SupplierInvoiceNote,
IF (SupplierInvoiceDiscountAmount > 0, 'R', 'P') AS DiscountType
FROM supplier_payment
JOIN supplier_invoice ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID
AND SupplierPaymentID = ?
AND SupplierPaymentIsActive = 'Y'";
$que = $this->db->query($sql, [$para['paymentID']]);
if (!$que) {
throw new Exception("[Error] failed get row data", 2);
}
$payment = $que_type->row_array();
if (!$payment) {
throw new Exception("[Error] payment not found", 2);
$data = $que->row_array();
$sql_detail = "SELECT
SupplierInvoiceDetailID,
SupplierInvoiceDetailSupplierInvoiceID,
SupplierInvoiceDetailPurchaseOrderID,
SupplierInvoiceDetailPurchaseOrderSummaryID,
SupplierInvoiceDetailReceiveOrderPoID,
SupplierInvoiceDetailReceiveOrderPoDetailID,
SupplierInvoiceDetailItemID,
SupplierInvoiceDetailItemUnitID,
SupplierInvoiceDetailDescription,
SupplierInvoiceDetailQty,
SupplierInvoiceDetailPrice,
SupplierInvoiceDetailDiscountPercent,
SupplierInvoiceDetailDiscountDiscountRupiah,
SupplierInvoiceDetailDiscountDiscountType,
SupplierInvoiceDetailDiscountAmount,
(SupplierInvoiceDetailPrice - SupplierInvoiceDetailDiscountAmount) AS DiscountedPrice,
SupplierInvoiceDetailDiscountPoProrata,
SupplierInvoiceDetailTotal,
M_ItemCode,
M_ItemDesc
FROM supplier_payment_detail
JOIN supplier_invoice_detail ON SupplierInvoiceDetailIsActive = 'Y'
AND SupplierPaymentDetailSupplierPaymentID = ?
AND SupplierInvoiceDetailSupplierInvoiceID = ?
JOIN m_item ON M_ItemID = SupplierInvoiceDetailItemID
AND M_ItemIsActive = 'Y'
GROUP BY SupplierInvoiceDetailID";
$que_detail = $this->db->query($sql_detail, [
$para['paymentID'], $data['SupplierInvoiceID']
]);
if (!$que_detail) {
throw new Exception("[Error] failed to get item payments", 2);
}
// ── INVOICE branch ──────────────────────────────────────
if ($payment['SupplierPaymentSupplierInvoiceID'] > 0) {
$sql = "SELECT
si.SupplierInvoiceSubTotal,
si.SupplierInvoiceShippingCost,
si.SupplierInvoiceDiscountPercent,
si.SupplierInvoiceDiscountAmount,
si.SupplierInvoiceTaxPercentPpn,
si.SupplierInvoiceTaxAmountPpn,
si.SupplierInvoiceGrandTotal,
si.SupplierInvoiceID,
'INVOICE' AS type
FROM supplier_payment sp
JOIN supplier_invoice si
ON si.SupplierInvoiceID = sp.SupplierPaymentSupplierInvoiceID
WHERE sp.SupplierPaymentID = ? AND sp.SupplierPaymentIsActive = 'Y'";
$que = $this->db->query($sql, [$para['paymentID']]);
if (!$que) {
throw new Exception("[Error] failed get row data", 2);
}
$data = $que->row_array();
$sql_detail = "SELECT
M_ItemDesc,
SupplierInvoiceDetailQty,
SupplierInvoiceDetailPrice,
SupplierInvoiceDetailDiscountAmount,
(SupplierInvoiceDetailPrice - SupplierInvoiceDetailDiscountAmount) AS DiscountedPrice,
SupplierInvoiceDetailTotal
FROM supplier_payment_detail
JOIN supplier_invoice_detail
ON SupplierInvoiceDetailIsActive = 'Y'
AND SupplierPaymentDetailSupplierPaymentID = ?
AND SupplierInvoiceDetailSupplierInvoiceID = ?
JOIN m_item
ON M_ItemID = SupplierInvoiceDetailItemID AND M_ItemIsActive = 'Y'
GROUP BY SupplierInvoiceDetailID";
$que_detail = $this->db->query($sql_detail, [
$para['paymentID'], $data['SupplierInvoiceID']
]);
if (!$que_detail) {
throw new Exception("[Error] failed to get item payments", 2);
}
unset($data['SupplierInvoiceID']);
$data['detail'] = $que_detail->result_array();
// ── DOWNPAYMENT branch ──────────────────────────────────
} else {
$sql = "SELECT
dp.SupplierDownpaymentPurchasOrderID,
dp.SupplierDownpaymentAmount AS SupplierInvoiceSubTotal,
0 AS SupplierInvoiceShippingCost,
0 AS SupplierInvoiceDiscountPercent,
0 AS SupplierInvoiceDiscountAmount,
0 AS SupplierInvoiceTaxPercentPpn,
0 AS SupplierInvoiceTaxAmountPpn,
dp.SupplierDownpaymentAmount AS SupplierInvoiceGrandTotal,
'DP' AS type
FROM supplier_payment sp
JOIN supplier_downpayment dp
ON dp.SupplierDownpaymentID = sp.SupplierPaymentSupplierDownpaymentID
WHERE sp.SupplierPaymentID = ? AND sp.SupplierPaymentIsActive = 'Y'";
$que = $this->db->query($sql, [$para['paymentID']]);
if (!$que) {
throw new Exception("[Error] failed get DP row data", 2);
}
$data = $que->row_array();
$sql_detail = "SELECT
CONCAT('DP-', M_ItemDesc) AS M_ItemDesc,
PurchaseOrderDetailQty AS SupplierInvoiceDetailQty,
PurchaseOrderDetailPrice AS SupplierInvoiceDetailPrice,
PurchaseOrderSummaryDiscountAmount AS SupplierInvoiceDetailDiscountAmount,
(PurchaseOrderDetailPrice - PurchaseOrderSummaryDiscountAmount) AS DiscountedPrice,
PurchaseOrderSummaryTotal AS SupplierInvoiceDetailTotal
FROM supplier_downpayment
JOIN purchase_order
ON SupplierDownpaymentPurchasOrderID = PurchaseOrderID
JOIN purchase_order_detail
ON PurchaseOrderDetailPurchaseOrderID = PurchaseOrderID
AND PurchaseOrderDetailIsActive = 'Y'
JOIN purchase_order_summary
ON PurchaseOrderSummaryID = PurchaseOrderDetailPurchaseSummaryID
AND PurchaseOrderSummaryIsActive = 'Y'
JOIN m_item
ON M_ItemID = PurchaseOrderDetailItemID
WHERE SupplierDownpaymentPurchasOrderID = ?";
$que_detail = $this->db->query($sql_detail, [
$data['SupplierDownpaymentPurchasOrderID']
]);
if (!$que_detail) {
throw new Exception('failed to get dp detail', 2);
}
$data['detail'] = $que_detail->result_array();
}
$data['detail'] = $que_detail->result_array();
$this->sys_ok($data);
} catch (Exception $exc) {
@@ -311,12 +214,12 @@ class Billv2 extends MY_Controller {
$user = $this->sys_user;
if ($para['userlevel'] == '1') {
$sql = "UPDATE supplier_payment SET
$sql = "UPDATE supplier_payment SET
SupplierPaymentIsVerif = 'Y',
SupplierPaymentStatus = 'Verified',
SupplierPaymentVerifUserID = ?,
SupplierPaymentVerifDate = NOW()
WHERE SupplierPaymentID = ?
WHERE SupplierPaymentID = ?
AND SupplierPaymentIsActive = 'Y'";
$query = $this->db->query($sql, [
$user['M_UserID'], $para['paymentID']
@@ -328,12 +231,12 @@ class Billv2 extends MY_Controller {
}
if ($para['userlevel'] == '2') {
$sql = "UPDATE supplier_payment SET
$sql = "UPDATE supplier_payment SET
SupplierPaymentIsApproved = 'Y',
SupplierPaymentStatus = 'Approved',
SupplierPaymentApprovedUserID = ?,
SupplierPaymentApprovedDate = NOW()
WHERE SupplierPaymentID = ?
WHERE SupplierPaymentID = ?
AND SupplierPaymentIsActive = 'Y'";
$query = $this->db->query($sql, [
$user['M_UserID'], $para['paymentID']
@@ -358,4 +261,4 @@ class Billv2 extends MY_Controller {
exit;
}
}
}
}

View File

@@ -1,20 +1,19 @@
<?php
class Bill extends MY_Controller
{
var $db_onedev;
public function index()
{
echo "Bill API";
}
public function __construct()
{
parent::__construct();
$this->db_onedev = $this->load->database("onedev", true);
}
var $db_onedev;
public function index()
{
echo "Bill API";
}
public function __construct()
{
parent::__construct();
$this->db_onedev = $this->load->database("onedev", true);
}
public function add_notes($orderid)
{
$sql = "SELECT SupplierPaymentSupplierInvoiceID as note_order_id,
public function add_notes($orderid){
$sql = " SELECT SupplierPaymentSupplierInvoiceID as note_order_id,
SupplierPaymentID as note_id,
SupplierPaymentDetailSupplierInvoiceDetailID as detail_id,
SupplierPaymentDate as note_date,
@@ -34,590 +33,223 @@ class Bill extends MY_Controller
SupplierPaymentIsApproved,
CONCAT('Approved by : ',a.M_UserUsername, ' ',DATE_FORMAT(SupplierPaymentApprovedDate,'%d-%m-%Y %H:%i')) as d_approved,
CONCAT('Verified by : ',b.M_UserUsername, ' ',DATE_FORMAT(SupplierPaymentVerifDate,'%d-%m-%Y %H:%i')) as d_verif
FROM supplier_payment
JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailIsActive = 'Y'
LEFT JOIN coa
ON SupplierPaymentCoaID = coaID
LEFT JOIN m_user n
ON SupplierPaymentUserID = n.M_UserID
LEFT JOIN m_user c
ON SupplierPaymentConfirmUserID = c.M_UserID
LEFT JOIN m_user a
ON SupplierPaymentApprovedUserID = a.M_UserID
LEFT JOIN m_user b
ON SupplierPaymentVerifUserID = b.M_UserID
WHERE SupplierPaymentSupplierInvoiceID = {$orderid}
AND SupplierPaymentIsActive = 'Y'
GROUP BY SupplierPaymentID";
$query = $this->db_onedev->query($sql);
if ($query) {
$rows = $query->result_array();
if ($rows) {
foreach ($rows as $k => $v) {
$rows[$k]['tests'] = $this->add_tests($v['note_id']);
}
}
return $rows;
} else {
$this->sys_error_db("get notes", $this->db_onedev);
exit;
}
}
FROM supplier_payment
JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailIsActive = 'Y'
LEFT JOIN coa ON SupplierPaymentCoaID = coaID
LEFT JOIN m_user n ON SupplierPaymentUserID = n.M_UserID
LEFT JOIN m_user c ON SupplierPaymentConfirmUserID = c.M_UserID
LEFT JOIN m_user a ON SupplierPaymentApprovedUserID = a.M_UserID
LEFT JOIN m_user b ON SupplierPaymentVerifUserID = b.M_UserID
WHERE
SupplierPaymentSupplierInvoiceID = {$orderid}
AND
SupplierPaymentIsActive = 'Y'
GROUP BY SupplierPaymentID";
$query = $this->db_onedev->query($sql);
if ($query) {
$rows = $query->result_array();
if($rows){
foreach($rows as $k => $v){
$rows[$k]['tests'] = $this->add_tests($v['note_id']);
}
}
return $rows;
} else {
$this->sys_error_db("get notes", $this->db_onedev);
exit;
}
}
public function add_tagihans($orderid){
$sql = "SELECT SupplierInvoiceID as tagihan_id,
PurchaseOrderNumber as tagihan_number,
jurnalTxDescription as pasien,
jurnalTxCredit as tagihan_total,
IF(SupplierPaymentDetailID IS NULL , jurnalTxCredit, jurnalTxCredit - SUM(SupplierPaymentDetailAmount)) as tagihan_tagihan,
0 as tagihan_bayar,
DATE_FORMAT(SupplierInvoiceDueDate,'%d-%m-%Y') as tagihan_duedate,
SupplierInvoiceIsActive as tagihan_active,
'N' as show_detail,
jurnalTxID SupplierInvoiceDetailID,
PurchaseOrderID SupplierInvoiceDetailPurchaseOrderID
FROM supplier_invoice
JOIN purchase_order ON SupplierInvoicePurchaseOrderID = PurchaseOrderID
JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber
JOIN jurnal_tx ON jurnalTxJurnalID = jurnalAddOnJurnalID AND jurnalTxCredit <> 0 AND jurnalTxCoaID <> 563
LEFT JOIN supplier_payment ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID AND SupplierInvoiceIsActive = 'Y'
LEFT JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID AND SupplierPaymentDetailSupplierInvoiceDetailID = jurnalTxID AND SupplierPaymentDetailIsActive = 'Y'
WHERE SupplierInvoiceID = ?
GROUP BY jurnalTxID";
$query = $this->db_onedev->query($sql, [$orderid]);
if ($query) {
$rows = $query->result_array();
return $rows;
} else {
$this->sys_error_db("get notes", $this->db_onedev);
exit;
}
}
public function add_tests($orderid){
$sql = " SELECT SupplierPaymentSupplierInvoiceID as note_order_id,
SupplierPaymentID as note_id,
SupplierPaymentDate as note_date,
SupplierPaymentNumber as note_number,
GROUP_CONCAT(coaDescription separator ' , ') as paymenttypes_name,
SUM(SupplierPaymentDetailAmount) as note_amount,
M_UserUsername as note_user,
SupplierPaymentDetailIsActive as note_active,
PurchaseOrderNumber,
SupplierInvoiceDetailTotal,
SupplierPaymentDetailAmount
FROM supplier_payment
JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID
LEFT JOIN supplier_invoice_detail ON SupplierPaymentDetailSupplierInvoiceDetailID = SupplierInvoiceDetailID
LEFT JOIN purchase_order ON SupplierInvoiceDetailPurchaseOrderID = PurchaseOrderID
JOIN coa ON SupplierPaymentCoaID = coaID
LEFT JOIN m_user ON SupplierPaymentDetailUserID = M_UserID
WHERE
SupplierPaymentID = {$orderid}
GROUP BY SupplierPaymentDetailID";
$query = $this->db_onedev->query($sql);
if ($query) {
$rows = $query->result_array();
if($rows){
}
return $rows;
} else {
$this->sys_error_db("get notes", $this->db_onedev);
exit;
}
}
public function search()
{
//# cek token valid
if (! $this->isLogin) {
$this->sys_error("Invalid Token");
exit;
}
$prm = $this->sys_input;
$supplier = $prm["supplier"];
$search = $prm["search"];
$status = $prm["status"];
$startdate = $prm["startdate"];
$enddate = $prm["enddate"];
$regionalid = $this->sys_user['S_RegionalID'];
$number_limit = 10;
$number_offset = ($prm['current_page'] - 1) * $number_limit ;
$where = "SupplierInvoiceIsActive = 'Y'
AND SupplierPaymentIsApproved = 'Y'
AND SupplierPaymentIsVerif = 'Y'
AND SupplierPaymentIsConfirm = '{$status}'
AND (SupplierInvoiceNumber LIKE '%{$search}%' OR SupplierInvoiceSupplierInvoiceNumber LIKE '%{$search}%')
AND SupplierName LIKE '%{$supplier}%'
AND ReceiveOrderPoS_RegionalID = {$regionalid}
AND SupplierInvoiceDraftPaymentDate BETWEEN '{$startdate}' AND '{$enddate}'";
$sql = " SELECT count(*) as total
FROM supplier_invoice
JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber
LEFT JOIN supplier_payment ON SupplierInvoiceID = SupplierPaymentSupplierInvoiceID AND SupplierPaymentIsActive = 'Y'
LEFT JOIN supplier ON SupplierInvoiceSupplierID = SupplierID
JOIN receive_order_po ON SupplierInvoiceReceiveOrderPoID = ReceiveOrderPoID
WHERE
$where
";
// echo $sql;
$query = $this->db_onedev->query($sql, $sql_param);
$tot_count = 0;
$tot_page = 0;
if ($query) {
$tot_count = $query->result_array()[0]["total"];
$tot_page = ceil($tot_count/$number_limit);
} else {
$this->sys_error_db("supplier_invoice count", $this->db_onedev);
exit;
}
$sql = "SELECT supplier_invoice.*,
SupplierName,
'' M_MouName,
0 as totalbill,
0 as paid,
0 as unpaid,
SupplierInvoiceIsLunas as flaglunas,
'' as SupplierPaymentNumber,
0 as SupplierPaymentAmount,
'' as SupplierPaymentDate,
'' as SupplierInvoiceIssueRefNumber,
'' as notes,
'' as tagihans,
'N' as isbillterpusat,
DATE_FORMAT(SupplierInvoiceDraftPaymentDate,'%d-%m-%Y') as tanggalbayar,
DATE_FORMAT(SupplierInvoiceDraftPaymentDate,'%d%m%Y') as tanggalbayartext,
IF(SupplierPaymentID IS NULL,'N','Y') as status_invoice,
SupplierPaymentID,
SupplierPaymentIsConfirm,
DATE_FORMAT(IFNULL(SupplierInvoiceSupplierInvoiceDate,''),'%d-%m-%Y') as tanggalinvoice,
0 xrounding,
'' chex,
IFNULL(SupplierPaymentCashierNumber,'') SupplierPaymentCashierNumber
FROM supplier_invoice
LEFT JOIN supplier ON SupplierInvoiceSupplierID = SupplierID
JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber
JOIN receive_order_po ON SupplierInvoiceReceiveOrderPoID = ReceiveOrderPoID
LEFT JOIN supplier_payment ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID AND SupplierPaymentIsActive = 'Y'
WHERE
$where
GROUP BY SupplierInvoiceID
ORDER BY SupplierInvoiceID ASC
limit $number_limit offset $number_offset";
//echo $sql;
$query = $this->db_onedev->query($sql, $sql_param);
$rows = $query->result_array();
if($rows){
foreach($rows as $k => $v){
$rows[$k]['chex'] = false;
$s_payment = $this->db_onedev->query("SELECT GROUP_CONCAT(SupplierPaymentNumber SEPARATOR ', ') as SupplierPaymentNumber,
SUM(IFNULL(SupplierPaymentAmount,0)) as SupplierPaymentAmount,
GROUP_CONCAT(DATE_FORMAT(SupplierPaymentDate,'%d-%m-%Y') SEPARATOR ', ') as SupplierPaymentDate
FROM supplier_payment
WHERE SupplierPaymentIsActive = 'Y' AND SupplierPaymentSupplierInvoiceID = {$v['SupplierInvoiceID']}")->row();
$s_jurnal = $this->db_onedev->query("SELECT SUM(jurnalTxCredit) totalbill
FROM supplier_invoice
JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber
JOIN jurnal_tx ON jurnalTxJurnalID = jurnalAddOnJurnalID AND jurnalTxCredit <> 0 AND jurnalTxCoaID <> 563
WHERE SupplierInvoiceID = {$v['SupplierInvoiceID']}
GROUP BY SupplierInvoiceID")->row();
$amount = $s_payment->SupplierPaymentAmount ? $s_payment->SupplierPaymentAmount : "0.00";
$unpaid = (float)$s_jurnal->totalbill - (float)$amount;
$rows[$k]['SupplierPaymentNumber'] = $s_payment->SupplierPaymentNumber;
$rows[$k]['SupplierPaymentAmount'] = $amount;
$rows[$k]['SupplierPaymentDate'] = $s_payment->SupplierPaymentDate;
$rows[$k]['paid'] = $amount;
$rows[$k]['totalbill'] = $s_jurnal->totalbill ? $s_jurnal->totalbill : "0.00";
$rows[$k]['unpaid'] = number_format($unpaid, 2, '.', '');
$rows[$k]['notes'] = $this->add_notes($v['SupplierInvoiceID']);
$rows[$k]['tagihans'] = $this->add_tagihans($v['SupplierInvoiceID']);
}
}
$result = array("total" => $tot_page, "records" => $rows, "sql"=> $this->db_onedev->last_query());
$this->sys_ok($result);
exit;
}
public function add_notes_downpayment($orderid)
{
$sql = "SELECT SupplierPaymentSupplierDownpaymentID AS note_order_id,
SupplierPaymentID AS note_id,
SupplierDownpaymentID AS detail_id,
SupplierPaymentDate AS note_date,
SupplierPaymentNumber AS note_number,
GROUP_CONCAT(DISTINCT coaDescription separator ' , ') AS paymenttypes_name,
SUM(SupplierDownpaymentAmount) AS note_amount,
n.M_UserUsername AS note_user,
SupplierDownpaymentIsActive AS note_active,
'N' AS show_detail,
SupplierPaymentNote AS keterangan,
SupplierPaymentCoaID,
coaID,
coaDescription,
SupplierPaymentIsConfirm,
CONCAT(
'Confirmed by : ',c.M_UserUsername, ' ',
DATE_FORMAT(SupplierPaymentConfirmDate, '%d-%m-%Y %H:%i')
) AS d_confirm,
SupplierPaymentIsApproved,
CONCAT(
'Approved by : ',a.M_UserUsername, ' ',
DATE_FORMAT(SupplierPaymentApprovedDate,'%d-%m-%Y %H:%i')
) AS d_approved,
CONCAT(
'Verified by : ',b.M_UserUsername, ' ',
DATE_FORMAT(SupplierPaymentVerifDate,'%d-%m-%Y %H:%i')
) AS d_verif
FROM supplier_payment
JOIN supplier_downpayment
ON SupplierDownpaymentID = SupplierPaymentSupplierDownpaymentID
AND SupplierDownpaymentIsActive = 'Y'
LEFT JOIN coa
ON SupplierPaymentCoaID = coaID
LEFT JOIN m_user n
ON SupplierPaymentUserID = n.M_UserID
LEFT JOIN m_user c
ON SupplierPaymentConfirmUserID = c.M_UserID
LEFT JOIN m_user a
ON SupplierPaymentApprovedUserID = a.M_UserID
LEFT JOIN m_user b
ON SupplierPaymentVerifUserID = b.M_UserID
WHERE SupplierPaymentSupplierDownpaymentID = {$orderid}
AND SupplierPaymentIsActive = 'Y'
GROUP BY SupplierPaymentID";
$query = $this->db_onedev->query($sql);
if ($query) {
$rows = $query->result_array();
return $rows ?: [];
} else {
$this->sys_error_db("get DP notes", $this->db_onedev);
exit;
}
}
public function add_tagihans($orderid)
{
$sql = "SELECT SupplierInvoiceID as tagihan_id,
PurchaseOrderNumber as tagihan_number,
jurnalTxDescription as pasien,
jurnalTxCredit as tagihan_total,
IF(SupplierPaymentDetailID IS NULL , jurnalTxCredit, jurnalTxCredit - SUM(SupplierPaymentDetailAmount)) as tagihan_tagihan,
0 as tagihan_bayar,
DATE_FORMAT(SupplierInvoiceDueDate,'%d-%m-%Y') as tagihan_duedate,
SupplierInvoiceIsActive as tagihan_active,
'N' as show_detail,
jurnalTxID SupplierInvoiceDetailID,
PurchaseOrderID SupplierInvoiceDetailPurchaseOrderID
FROM supplier_invoice
JOIN purchase_order
ON SupplierInvoicePurchaseOrderID = PurchaseOrderID
JOIN jurnal_addon
ON jurnalAddOnValue = SupplierInvoiceNumber
JOIN jurnal_tx
ON jurnalTxJurnalID = jurnalAddOnJurnalID
AND jurnalTxCredit <> 0
AND jurnalTxCoaID <> 563
LEFT JOIN supplier_payment
ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID
AND SupplierInvoiceIsActive = 'Y'
LEFT JOIN supplier_payment_detail
ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID
AND SupplierPaymentDetailSupplierInvoiceDetailID = jurnalTxID
AND SupplierPaymentDetailIsActive = 'Y'
WHERE SupplierInvoiceID = ?
GROUP BY jurnalTxID";
$query = $this->db_onedev->query($sql, [$orderid]);
if ($query) {
$rows = $query->result_array();
return $rows;
} else {
$this->sys_error_db("get notes", $this->db_onedev);
exit;
}
}
public function add_tests($orderid)
{
$sql = "SELECT
SupplierPaymentSupplierInvoiceID as note_order_id,
SupplierPaymentID as note_id,
SupplierPaymentDate as note_date,
SupplierPaymentNumber as note_number,
GROUP_CONCAT(coaDescription separator ' , ') as paymenttypes_name,
SUM(SupplierPaymentDetailAmount) as note_amount,
M_UserUsername as note_user,
SupplierPaymentDetailIsActive as note_active,
PurchaseOrderNumber,
SupplierInvoiceDetailTotal,
SupplierPaymentDetailAmount
FROM supplier_payment
JOIN supplier_payment_detail
ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID
LEFT JOIN supplier_invoice_detail
ON SupplierPaymentDetailSupplierInvoiceDetailID = SupplierInvoiceDetailID
LEFT JOIN purchase_order
ON SupplierInvoiceDetailPurchaseOrderID = PurchaseOrderID
JOIN coa
ON SupplierPaymentCoaID = coaID
LEFT JOIN m_user
ON SupplierPaymentDetailUserID = M_UserID
WHERE SupplierPaymentID = {$orderid}
GROUP BY SupplierPaymentDetailID";
$query = $this->db_onedev->query($sql);
if ($query) {
$rows = $query->result_array();
if ($rows) {
}
return $rows;
} else {
$this->sys_error_db("get notes", $this->db_onedev);
exit;
}
}
public function search_old()
{
if (! $this->isLogin) {
$this->sys_error("Invalid Token");
exit;
}
$prm = $this->sys_input;
$supplier = $prm["supplier"];
$search = $prm["search"];
$status = $prm["status"];
$startdate = $prm["startdate"];
$enddate = $prm["enddate"];
$regionalid = $this->sys_user['S_RegionalID'];
$number_limit = 10;
$number_offset = ((int)$prm['current_page'] - 1) * $number_limit;
// ── WHERE ────────────────────────────────────────────────
$where = " si.SupplierInvoiceIsActive = 'Y'
AND sp.SupplierPaymentIsApproved = 'Y'
AND sp.SupplierPaymentIsVerif = 'Y'
AND sp.SupplierPaymentIsConfirm = ?
AND (si.SupplierInvoiceNumber LIKE ?
OR si.SupplierInvoiceSupplierInvoiceNumber LIKE ?)
AND sup.SupplierName LIKE ?
AND rop.ReceiveOrderPoS_RegionalID = ?
AND si.SupplierInvoiceDraftPaymentDate BETWEEN ? AND ? ";
$where_params = [
$status,
'%' . $search . '%',
'%' . $search . '%',
'%' . $supplier . '%',
$regionalid,
$startdate,
$enddate,
];
// ── COUNT ────────────────────────────────────────────────
$sql_count = "
SELECT count(*) as total
FROM supplier_invoice si
JOIN jurnal_addon ja ON ja.jurnalAddOnValue = si.SupplierInvoiceNumber
JOIN receive_order_po rop ON rop.ReceiveOrderPoID = si.SupplierInvoiceReceiveOrderPoID
LEFT JOIN supplier_payment sp
ON sp.SupplierPaymentSupplierInvoiceID = si.SupplierInvoiceID
AND sp.SupplierPaymentIsActive = 'Y'
LEFT JOIN supplier sup ON sup.SupplierID = si.SupplierInvoiceSupplierID
WHERE $where";
$query = $this->db_onedev->query($sql_count, $where_params);
$tot_count = 0;
$tot_page = 0;
if ($query) {
$tot_count = $query->result_array()[0]["total"];
$tot_page = ceil($tot_count / $number_limit);
} else {
$this->sys_error_db("supplier_invoice count", $this->db_onedev);
exit;
}
// ── DATA — only columns the frontend actually reads ──────
$sql_data = "
SELECT
si.SupplierInvoiceID,
si.SupplierInvoiceNumber,
si.SupplierInvoiceDraftPaymentDate,
si.SupplierInvoiceIsLunas AS flaglunas,
si.SupplierInvoiceSupplierInvoiceNumber,
DATE_FORMAT(
IFNULL(si.SupplierInvoiceSupplierInvoiceDate,''),'%d-%m-%Y'
) AS tanggalinvoice,
sup.SupplierName,
sp.SupplierPaymentID,
sp.SupplierPaymentIsConfirm,
IFNULL(sp.SupplierPaymentCashierNumber,'') AS SupplierPaymentCashierNumber,
DATE_FORMAT(
si.SupplierInvoiceDraftPaymentDate,'%d-%m-%Y'
) AS tanggalbayar,
0 AS totalbill,
0 AS paid,
0 AS unpaid,
'' AS SupplierPaymentNumber,
0 AS SupplierPaymentAmount,
'' AS SupplierPaymentDate,
'' AS notes,
'' AS tagihans,
0 AS xrounding,
'' AS chex
FROM supplier_invoice si
JOIN jurnal_addon ja ON ja.jurnalAddOnValue = si.SupplierInvoiceNumber
JOIN receive_order_po rop ON rop.ReceiveOrderPoID = si.SupplierInvoiceReceiveOrderPoID
LEFT JOIN supplier_payment sp
ON sp.SupplierPaymentSupplierInvoiceID = si.SupplierInvoiceID
AND sp.SupplierPaymentIsActive = 'Y'
LEFT JOIN supplier sup ON sup.SupplierID = si.SupplierInvoiceSupplierID
WHERE $where
GROUP BY si.SupplierInvoiceID
ORDER BY si.SupplierInvoiceID ASC
LIMIT ? OFFSET ?";
$data_params = array_merge($where_params, [$number_limit, $number_offset]);
$query = $this->db_onedev->query($sql_data, $data_params);
$rows = $query->result_array();
// ── ENRICH ───────────────────────────────────────────────
if ($rows) {
foreach ($rows as $k => $v) {
$rows[$k]['chex'] = false;
$inv_id = $v['SupplierInvoiceID'];
$s_payment = $this->db_onedev->query("
SELECT
GROUP_CONCAT(SupplierPaymentNumber SEPARATOR ', ') as SupplierPaymentNumber,
SUM(IFNULL(SupplierPaymentAmount,0)) as SupplierPaymentAmount,
GROUP_CONCAT(
DATE_FORMAT(SupplierPaymentDate,'%d-%m-%Y')
SEPARATOR ', '
) as SupplierPaymentDate
FROM supplier_payment
WHERE SupplierPaymentIsActive = 'Y'
AND SupplierPaymentSupplierInvoiceID = ?",
[$inv_id]
)->row();
$s_jurnal = $this->db_onedev->query("
SELECT SUM(jurnalTxCredit) totalbill
FROM supplier_invoice si
JOIN jurnal_addon ja ON ja.jurnalAddOnValue = si.SupplierInvoiceNumber
JOIN jurnal_tx jt
ON jt.jurnalTxJurnalID = ja.jurnalAddOnJurnalID
AND jt.jurnalTxCredit <> 0
AND jt.jurnalTxCoaID <> 563
WHERE si.SupplierInvoiceID = ?
GROUP BY si.SupplierInvoiceID",
[$inv_id]
)->row();
$amount = $s_payment->SupplierPaymentAmount
? $s_payment->SupplierPaymentAmount
: "0.00";
$unpaid = (float)$s_jurnal->totalbill - (float)$amount;
$rows[$k]['SupplierPaymentNumber'] = $s_payment->SupplierPaymentNumber;
$rows[$k]['SupplierPaymentAmount'] = $amount;
$rows[$k]['SupplierPaymentDate'] = $s_payment->SupplierPaymentDate;
$rows[$k]['paid'] = $amount;
$rows[$k]['totalbill'] = $s_jurnal->totalbill
? $s_jurnal->totalbill
: "0.00";
$rows[$k]['unpaid'] = number_format($unpaid, 2, '.', '');
$rows[$k]['notes'] = $this->add_notes($inv_id);
$rows[$k]['tagihans'] = $this->add_tagihans($inv_id);
}
}
$result = array("total" => $tot_page, "records" => $rows);
$this->sys_ok($result);
exit;
}
public function search()
{
if (! $this->isLogin) {
$this->sys_error("Invalid Token");
exit;
}
$prm = $this->sys_input;
$supplier = $prm["supplier"];
$search = $prm["search"];
$status = $prm["status"];
$startdate = $prm["startdate"];
$enddate = $prm["enddate"];
$regionalid = $this->sys_user['S_RegionalID'];
$number_limit = 10;
$number_offset = ((int)$prm['current_page'] - 1) * $number_limit;
// ── INVOICE branch WHERE ─────────────────────────────────
$inv_where = " si.SupplierInvoiceIsActive = 'Y'
AND rop.ReceiveOrderPoS_RegionalID = ? ";
$inv_params = [$regionalid];
// ── DOWNPAYMENT branch WHERE ─────────────────────────────
$dp_where = " dp.SupplierDownpaymentIsActive = 'Y'
AND po.PurchaseOrderS_RegionalID = ? ";
$dp_params = [$regionalid];
// ── UNION base ───────────────────────────────────────────
$sql_base = "
SELECT
si.SupplierInvoiceID,
si.SupplierInvoiceNumber,
si.SupplierInvoiceDraftPaymentDate,
si.SupplierInvoiceDraftPaymentDate AS filter_date,
si.SupplierInvoiceIsLunas AS flaglunas,
si.SupplierInvoiceSupplierInvoiceNumber,
DATE_FORMAT(
IFNULL(si.SupplierInvoiceSupplierInvoiceDate,''),'%d-%m-%Y'
) AS tanggalinvoice,
sup.SupplierName,
sp.SupplierPaymentID,
sp.SupplierPaymentIsConfirm,
sp.SupplierPaymentIsApproved,
sp.SupplierPaymentIsVerif,
sp.SupplierPaymentIsActive,
IFNULL(sp.SupplierPaymentCashierNumber,'') AS SupplierPaymentCashierNumber,
DATE_FORMAT(
si.SupplierInvoiceDraftPaymentDate,'%d-%m-%Y'
) AS tanggalbayar,
0 AS totalbill,
0 AS paid,
0 AS unpaid,
'' AS SupplierPaymentNumber,
0 AS SupplierPaymentAmount,
'' AS SupplierPaymentDate,
'' AS notes,
'' AS tagihans,
0 AS xrounding,
'' AS chex,
'INVOICE' AS type
FROM supplier_invoice si
JOIN jurnal_addon ja ON ja.jurnalAddOnValue = si.SupplierInvoiceNumber
JOIN receive_order_po rop ON rop.ReceiveOrderPoID = si.SupplierInvoiceReceiveOrderPoID
LEFT JOIN supplier_payment sp
ON sp.SupplierPaymentSupplierInvoiceID = si.SupplierInvoiceID
AND sp.SupplierPaymentIsActive = 'Y'
LEFT JOIN supplier sup ON sup.SupplierID = si.SupplierInvoiceSupplierID
WHERE $inv_where
GROUP BY si.SupplierInvoiceID
UNION ALL
SELECT
dp.SupplierDownpaymentID * -1 AS SupplierInvoiceID,
CONCAT('DP-', po.PurchaseOrderNumber) AS SupplierInvoiceNumber,
dp.SupplierDownpaymentDueDate AS SupplierInvoiceDraftPaymentDate,
dp.SupplierDownpaymentDueDate AS filter_date,
dp.SupplierDownpaymentIsLunas AS flaglunas,
'' AS SupplierInvoiceSupplierInvoiceNumber,
DATE_FORMAT(dp.SupplierDownpaymentDate,'%d-%m-%Y') AS tanggalinvoice,
dp_sup.SupplierName AS SupplierName,
sp.SupplierPaymentID,
sp.SupplierPaymentIsConfirm,
sp.SupplierPaymentIsApproved,
sp.SupplierPaymentIsVerif,
sp.SupplierPaymentIsActive,
IFNULL(sp.SupplierPaymentCashierNumber,'') AS SupplierPaymentCashierNumber,
DATE_FORMAT(
dp.SupplierDownpaymentDueDate,'%d-%m-%Y'
) AS tanggalbayar,
dp.SupplierDownpaymentAmount AS totalbill,
CASE WHEN dp.SupplierDownpaymentStatus = 'Paid'
THEN dp.SupplierDownpaymentAmount
ELSE 0 END AS paid,
CASE WHEN dp.SupplierDownpaymentStatus = 'Paid'
THEN 0
ELSE dp.SupplierDownpaymentAmount END AS unpaid,
'' AS SupplierPaymentNumber,
0 AS SupplierPaymentAmount,
'' AS SupplierPaymentDate,
'' AS notes,
'' AS tagihans,
0 AS xrounding,
'' AS chex,
'DP' AS type
FROM supplier_payment sp
JOIN supplier_downpayment dp
ON dp.SupplierDownpaymentID = sp.SupplierPaymentSupplierDownpaymentID
JOIN supplier dp_sup
ON dp_sup.SupplierID = dp.SupplierDownpaymentSupplierID
JOIN purchase_order po
ON po.PurchaseOrderID = dp.SupplierDownpaymentPurchasOrderID
WHERE $dp_where";
// ── Outer common filters ─────────────────────────────────
$outer_where = " SupplierPaymentIsActive = 'Y'
AND SupplierPaymentIsApproved = 'Y'
AND SupplierPaymentIsVerif = 'Y'
AND SupplierPaymentIsConfirm = ?
AND (SupplierInvoiceNumber LIKE ? OR SupplierInvoiceSupplierInvoiceNumber LIKE ?)
AND SupplierName LIKE ?
AND filter_date BETWEEN ? AND ? ";
$outer_params = [
$status,
'%' . $search . '%',
'%' . $search . '%',
'%' . $supplier . '%',
$startdate,
$enddate,
];
// ── COUNT ────────────────────────────────────────────────
$sql_count = "
SELECT COUNT(*) AS total
FROM ($sql_base) AS combined
WHERE $outer_where";
$count_params = array_merge($inv_params, $dp_params, $outer_params);
$query = $this->db_onedev->query($sql_count, $count_params);
$tot_count = 0;
$tot_page = 0;
if ($query) {
$tot_count = $query->result_array()[0]["total"];
$tot_page = ceil($tot_count / $number_limit);
} else {
$this->sys_error_db("supplier payment count", $this->db_onedev);
exit;
}
// ── DATA ─────────────────────────────────────────────────
$sql_data = "
SELECT * FROM ($sql_base) AS combined
WHERE $outer_where
ORDER BY SupplierInvoiceID ASC
LIMIT ? OFFSET ?";
$data_params = array_merge($inv_params, $dp_params, $outer_params, [$number_limit, $number_offset]);
$query = $this->db_onedev->query($sql_data, $data_params);
$rows = $query->result_array();
// ── ENRICH ───────────────────────────────────────────────
if ($rows) {
foreach ($rows as $k => $v) {
// ── Downpayment branch ──────────────────────────
if ($v['type'] === 'DP') {
$rows[$k]['chex'] = false;
$dp_id = abs($v['SupplierInvoiceID']);
$s_payment = $this->db_onedev->query("
SELECT
GROUP_CONCAT(SupplierPaymentNumber SEPARATOR ', ') as SupplierPaymentNumber,
SUM(IFNULL(SupplierPaymentAmount,0)) as SupplierPaymentAmount,
GROUP_CONCAT(
DATE_FORMAT(SupplierPaymentDate,'%d-%m-%Y')
SEPARATOR ', '
) as SupplierPaymentDate
FROM supplier_payment
WHERE SupplierPaymentIsActive = 'Y'
AND SupplierPaymentSupplierDownpaymentID = ?",
[$dp_id]
)->row();
$amount = $s_payment->SupplierPaymentAmount
? $s_payment->SupplierPaymentAmount
: "0.00";
$rows[$k]['SupplierPaymentNumber'] = $s_payment->SupplierPaymentNumber;
$rows[$k]['SupplierPaymentAmount'] = $amount;
$rows[$k]['SupplierPaymentDate'] = $s_payment->SupplierPaymentDate;
$rows[$k]['paid'] = $amount;
$rows[$k]['notes'] = $this->add_notes_downpayment($dp_id);
$rows[$k]['tagihans'] = [];
continue;
}
// ── Invoice branch ──────────────────────────────
$rows[$k]['chex'] = false;
$inv_id = $v['SupplierInvoiceID'];
$s_payment = $this->db_onedev->query("
SELECT
GROUP_CONCAT(SupplierPaymentNumber SEPARATOR ', ') as SupplierPaymentNumber,
SUM(IFNULL(SupplierPaymentAmount,0)) as SupplierPaymentAmount,
GROUP_CONCAT(
DATE_FORMAT(SupplierPaymentDate,'%d-%m-%Y')
SEPARATOR ', '
) as SupplierPaymentDate
FROM supplier_payment
WHERE SupplierPaymentIsActive = 'Y'
AND SupplierPaymentSupplierInvoiceID = ?",
[$inv_id]
)->row();
$s_jurnal = $this->db_onedev->query("
SELECT SUM(jurnalTxCredit) totalbill
FROM supplier_invoice si
JOIN jurnal_addon ja ON ja.jurnalAddOnValue = si.SupplierInvoiceNumber
JOIN jurnal_tx jt
ON jt.jurnalTxJurnalID = ja.jurnalAddOnJurnalID
AND jt.jurnalTxCredit <> 0
AND jt.jurnalTxCoaID <> 563
WHERE si.SupplierInvoiceID = ?
GROUP BY si.SupplierInvoiceID",
[$inv_id]
)->row();
$amount = $s_payment->SupplierPaymentAmount
? $s_payment->SupplierPaymentAmount
: "0.00";
$unpaid = (float)$s_jurnal->totalbill - (float)$amount;
$rows[$k]['SupplierPaymentNumber'] = $s_payment->SupplierPaymentNumber;
$rows[$k]['SupplierPaymentAmount'] = $amount;
$rows[$k]['SupplierPaymentDate'] = $s_payment->SupplierPaymentDate;
$rows[$k]['paid'] = $amount;
$rows[$k]['totalbill'] = $s_jurnal->totalbill
? $s_jurnal->totalbill
: "0.00";
$rows[$k]['unpaid'] = number_format($unpaid, 2, '.', '');
$rows[$k]['notes'] = $this->add_notes($inv_id);
$rows[$k]['tagihans'] = $this->add_tagihans($inv_id);
}
}
$result = array("total" => $tot_page, "records" => $rows);
$this->sys_ok($result);
exit;
}
}

View File

@@ -70,28 +70,14 @@ class PaymentV2 extends MY_Controller
}
# UPDATE status lunas supplier invoice #
if ($param['type'] == 'DP') {
$sql_updatedp = "UPDATE supplier_downpayment
SET SupplierDownpaymentIsLunas = 'Y'
WHERE SupplierDownpaymentID = ?";
$que_updatedp = $this->db->query($sql_updatedp, [
abs($param['SupplierInvoiceID'])
]);
if (!$que_updatedp) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] update status lunas downpayment");
exit;
}
} else {
$sql_suppinvoice = "UPDATE supplier_invoice
SET SupplierInvoiceIsLunas = 'Y'
WHERE SupplierInvoiceID = ?";
$que_suppinvoice = $this->db->query($sql_suppinvoice, [$param['SupplierInvoiceID']]);
if (!$que_suppinvoice) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] update status lunas invoice");
exit;
}
$sql_suppinvoice = "UPDATE supplier_invoice
SET SupplierInvoiceIsLunas = 'Y'
WHERE SupplierInvoiceID = ?";
$que_suppinvoice = $this->db->query($sql_suppinvoice, [$param['SupplierInvoiceID']]);
if (!$que_suppinvoice) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] update status lunas invoice");
exit;
}
# GET Latest data supplier payment #
@@ -103,33 +89,16 @@ class PaymentV2 extends MY_Controller
exit;
}
$suppayment_header = $que_suppayment->row_array();
$suppayment_detail = [];
if ($param['type'] == 'DP') {
$sql_suppaymentdetail = "SELECT supplier_downpayment.*
FROM supplier_payment
JOIN supplier_downpayment
ON SupplierPaymentSupplierDownpaymentID = SupplierDownpaymentID
AND SupplierDownpaymentIsActive = 'Y'
WHERE SupplierPaymentID = ?";
$que_suppaymentdetail = $this->db->query($sql_suppaymentdetail, [$param['orderid']]);
if (!$que_suppaymentdetail) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] get data latest supplier downpayment");
exit;
}
$suppayment_detail = $que_suppaymentdetail->result_array();
} else {
$sql_suppaymentdetail = "SELECT * FROM supplier_payment_detail
$sql_suppaymentdetail = "SELECT * FROM supplier_payment_detail
WHERE SupplierPaymentDetailSupplierPaymentID = ?";
$que_suppaymentdetail = $this->db->query($sql_suppaymentdetail, [$param['orderid']]);
if (!$que_suppaymentdetail) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] get data latest supplier payment detail");
exit;
}
$suppayment_detail = $que_suppaymentdetail->result_array();
$que_suppaymentdetail = $this->db->query($sql_suppaymentdetail, [$param['orderid']]);
if (!$que_suppaymentdetail) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] get data latest supplier payment detail");
exit;
}
$suppayment_detail = $que_suppaymentdetail->result_array();
$data_log = [
"header" => $suppayment_header,
@@ -152,85 +121,38 @@ class PaymentV2 extends MY_Controller
# INSERT JURNAL #
$detail_transac = [];
if ($param['type'] == "DP") {
$sql_coaDP = "SELECT
coaID,
coaDescription,
SupplierDownpaymentAmount,
M_ItemID,
SupplierPaymentNumber,
M_ItemID
FROM supplier_payment
JOIN supplier_downpayment
ON SupplierDownpaymentID = SupplierPaymentSupplierDownpaymentID
AND SupplierDownpaymentIsActive = 'Y'
JOIN purchase_order_detail
ON SupplierDownpaymentPurchasOrderID = PurchaseOrderDetailPurchaseOrderID
AND PurchaseOrderDetailIsActive = 'Y'
JOIN m_item
ON M_ItemID = PurchaseOrderDetailItemID
AND M_ItemIsActive = 'Y'
JOIN fa_class
ON Fa_ClassID = M_ItemFa_ClassID
AND M_ItemIsActive = 'Y'
JOIN coa
ON coaID = Fa_ClassDownPaymentCoaID
AND coaIsActive = 'Y'
WHERE SupplierPaymentID = ?";
$que_coaDP = $this->db->query($sql_coaDP, [
$param['orderid']
]);
if (!$que_coaDP) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] get data hutang item");
exit;
}
$data_dp = $que_coaDP->result_array();
foreach ($data_dp as $key => $dp) {
$detail_transac[] = [
"coaID" => $dp['coaID'],
"coaDescription" => $dp['coaDescription'],
"debit" => $dp['SupplierDownpaymentAmount'],
"credit" => 0,
"addoncode" => "DP-JFA",
"addonvalue" => $dp['SupplierPaymentNumber'],
"addonitemid" => $dp['M_ItemID']
];
}
} else {
# GET data hutang #
$sql_datahutang = "SELECT
SupplierPaymentNumber AS addonvalue,
SupplierPaymentDetailID,
jurnalTxCoaID AS coaID,
jurnalTxDescription AS coaDescription,
SupplierPaymentDetailAmount,
SupplierInvoiceDetailItemID
FROM supplier_payment
JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID
JOIN supplier_invoice_detail ON SupplierInvoiceDetailSupplierInvoiceID = SupplierPaymentSupplierInvoiceID
AND SupplierInvoiceDetailIsActive = 'Y'
JOIN jurnal_tx ON SupplierPaymentDetailSupplierInvoiceDetailID = jurnalTxID
WHERE SupplierPaymentID = ?
AND SupplierPaymentDetailIsActive = 'Y'";
$que_datahutang = $this->db->query($sql_datahutang, [$param['orderid']]);
if (!$que_datahutang) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] get data hutang item");
exit;
}
$data_hutang = $que_datahutang->result_array();
foreach ($data_hutang as $key => $debt) {
$detail_transac[] = [
"coaID" => $debt['coaID'],
"coaDescription" => $debt['coaDescription'],
"debit" => $debt['SupplierPaymentDetailAmount'],
"credit" => 0,
"addoncode" => "JFA",
"addonvalue" => $debt['addonvalue'],
"addonitemid" => $debt['SupplierInvoiceDetailItemID']
];
}
# GET data hutang #
$sql_datahutang = "SELECT
SupplierPaymentNumber AS addonvalue,
SupplierPaymentDetailID,
jurnalTxCoaID AS coaID,
jurnalTxDescription AS coaDescription,
SupplierPaymentDetailAmount,
SupplierInvoiceDetailItemID
FROM supplier_payment
JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID
JOIN supplier_invoice_detail ON SupplierInvoiceDetailSupplierInvoiceID = SupplierPaymentSupplierInvoiceID
AND SupplierInvoiceDetailIsActive = 'Y'
JOIN jurnal_tx ON SupplierPaymentDetailSupplierInvoiceDetailID = jurnalTxID
WHERE SupplierPaymentID = ?
AND SupplierPaymentDetailIsActive = 'Y'";
$que_datahutang = $this->db->query($sql_datahutang, [$param['orderid']]);
if (!$que_datahutang) {
$this->db->trans_rollback();
$this->sys_error_db("[Error] get data hutang item");
exit;
}
$data_hutang = $que_datahutang->result_array();
foreach ($data_hutang as $key => $debt) {
$detail_transac[] = [
"coaID" => $debt['coaID'],
"coaDescription" => $debt['coaDescription'],
"debit" => $debt['SupplierPaymentDetailAmount'],
"credit" => 0,
"addoncode" => "JFA",
"addonvalue" => $debt['addonvalue'],
"addonitemid" => $debt['SupplierInvoiceDetailItemID']
];
}
# GET data bayar #

View File

@@ -1,22 +1,20 @@
<?php
class Bill extends MY_Controller
{
var $db_onedev;
public function index()
{
echo "Bill API";
}
public function __construct()
{
parent::__construct();
$this->db_onedev = $this->load->database("onedev", true);
}
public function add_notes($orderid)
{
$sql = "SELECT SupplierPaymentSupplierInvoiceID as note_order_id,
SupplierPaymentID as note_id,
var $db_onedev;
public function index()
{
echo "Bill API";
}
public function __construct()
{
parent::__construct();
$this->db_onedev = $this->load->database("onedev", true);
}
public function add_notes($orderid){
$sql = " SELECT SupplierPaymentSupplierInvoiceID as note_order_id,
SupplierPaymentID as note_id,
SupplierPaymentDetailSupplierInvoiceDetailID as detail_id,
SupplierPaymentDate as note_date,
SupplierPaymentNumber as note_number,
@@ -43,80 +41,27 @@ class Bill extends MY_Controller
LEFT JOIN m_user a ON SupplierPaymentApprovedUserID = a.M_UserID
LEFT JOIN m_user b ON SupplierPaymentVerifUserID = b.M_UserID
WHERE
SupplierPaymentSupplierInvoiceID = {$orderid}
SupplierPaymentSupplierInvoiceID = {$orderid}
AND
SupplierPaymentIsActive = 'Y'
GROUP BY SupplierPaymentID";
$query = $this->db_onedev->query($sql);
if ($query) {
$rows = $query->result_array();
if ($rows) {
foreach ($rows as $k => $v) {
$rows[$k]['tests'] = $this->add_tests($v['note_id']);
}
}
return $rows;
} else {
$this->sys_error_db("get notes", $this->db_onedev);
exit;
}
}
public function add_notes_downpayment($orderid)
{
$sql = "SELECT SupplierPaymentSupplierDownpaymentID AS note_order_id,
SupplierPaymentID AS note_id,
SupplierDownpaymentID AS detail_id,
SupplierPaymentDate AS note_date,
SupplierPaymentNumber AS note_number,
GROUP_CONCAT(DISTINCT coaDescription separator ' , ') AS paymenttypes_name,
SUM(SupplierDownpaymentAmount) AS note_amount,
n.M_UserUsername AS note_user,
SupplierDownpaymentIsActive AS note_active,
'N' AS show_detail,
SupplierPaymentNote AS keterangan,
SupplierPaymentCoaID,
coaID,
coaDescription,
SupplierPaymentIsConfirm,
CONCAT(
'Confirmed by : ',c.M_UserUsername, ' ',
DATE_FORMAT(SupplierPaymentConfirmDate, '%d-%m-%Y %H:%i')
) AS d_confirm,
SupplierPaymentIsApproved,
CONCAT(
'Approved by : ',a.M_UserUsername, ' ',
DATE_FORMAT(SupplierPaymentApprovedDate,'%d-%m-%Y %H:%i')
) AS d_approved,
CONCAT(
'Verified by : ',b.M_UserUsername, ' ',
DATE_FORMAT(SupplierPaymentVerifDate,'%d-%m-%Y %H:%i')
) AS d_verif
FROM supplier_payment
JOIN supplier_downpayment
ON SupplierDownpaymentID = SupplierPaymentSupplierDownpaymentID
AND SupplierDownpaymentIsActive = 'Y'
LEFT JOIN coa ON SupplierPaymentCoaID = coaID
LEFT JOIN m_user n ON SupplierPaymentUserID = n.M_UserID
LEFT JOIN m_user c ON SupplierPaymentConfirmUserID = c.M_UserID
LEFT JOIN m_user a ON SupplierPaymentApprovedUserID = a.M_UserID
LEFT JOIN m_user b ON SupplierPaymentVerifUserID = b.M_UserID
WHERE SupplierPaymentSupplierDownpaymentID = {$orderid}
AND SupplierPaymentIsActive = 'Y'
GROUP BY SupplierPaymentID";
$query = $this->db_onedev->query($sql);
if ($query) {
$rows = $query->result_array();
return $rows ?: [];
} else {
$this->sys_error_db("get DP notes", $this->db_onedev);
exit;
}
}
public function add_tagihans($orderid)
{
$sql = "SELECT SupplierInvoiceID as tagihan_id,
$query = $this->db_onedev->query($sql);
if ($query) {
$rows = $query->result_array();
if($rows){
foreach($rows as $k => $v){
$rows[$k]['tests'] = $this->add_tests($v['note_id']);
}
}
return $rows;
} else {
$this->sys_error_db("get notes", $this->db_onedev);
exit;
}
}
public function add_tagihans($orderid){
$sql = "SELECT SupplierInvoiceID as tagihan_id,
PurchaseOrderNumber as tagihan_number,
jurnalTxDescription as pasien,
jurnalTxCredit as tagihan_total,
@@ -140,20 +85,19 @@ class Bill extends MY_Controller
SupplierInvoiceID = {$orderid}
GROUP BY jurnalTxID
";
$query = $this->db_onedev->query($sql);
if ($query) {
$rows = $query->result_array();
return $rows;
} else {
$this->sys_error_db("get notes", $this->db_onedev);
exit;
}
}
public function add_tests($orderid)
{
$sql = " SELECT SupplierPaymentSupplierInvoiceID as note_order_id,
SupplierPaymentID as note_id,
$query = $this->db_onedev->query($sql);
if ($query) {
$rows = $query->result_array();
return $rows;
} else {
$this->sys_error_db("get notes", $this->db_onedev);
exit;
}
}
public function add_tests($orderid){
$sql = " SELECT SupplierPaymentSupplierInvoiceID as note_order_id,
SupplierPaymentID as note_id,
SupplierPaymentDate as note_date,
SupplierPaymentNumber as note_number,
GROUP_CONCAT(coaDescription separator ' , ') as paymenttypes_name,
@@ -164,414 +108,150 @@ class Bill extends MY_Controller
SupplierInvoiceDetailTotal,
SupplierPaymentDetailAmount
FROM supplier_payment
JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID
JOIN supplier_payment_detail ON SupplierPaymentDetailSupplierPaymentID = SupplierPaymentID
LEFT JOIN supplier_invoice_detail ON SupplierPaymentDetailSupplierInvoiceDetailID = SupplierInvoiceDetailID
LEFT JOIN purchase_order ON SupplierInvoiceDetailPurchaseOrderID = PurchaseOrderID
LEFT JOIN coa ON SupplierPaymentCoaID = coaID
LEFT JOIN m_user ON SupplierPaymentDetailUserID = M_UserID
WHERE
SupplierPaymentID = {$orderid}
SupplierPaymentID = {$orderid}
GROUP BY SupplierPaymentDetailID";
$query = $this->db_onedev->query($sql);
if ($query) {
$rows = $query->result_array();
if ($rows) {
}
return $rows;
} else {
$this->sys_error_db("get notes", $this->db_onedev);
exit;
}
}
public function search_old()
{
//# cek token valid
if (! $this->isLogin) {
$this->sys_error("Invalid Token");
exit;
}
$prm = $this->sys_input;
$supplier = $prm["supplier"];
$search = $prm["search"];
$status = $prm["status"];
$startdate = $prm["startdate"];
$enddate = $prm["enddate"];
$regionalid = $this->sys_user['S_RegionalID'];
$number_limit = 10;
$number_offset = ($prm['current_page'] - 1) * $number_limit;
$where = "SupplierInvoiceIsActive = 'Y'
AND SupplierInvoiceStatus = 'Approved'
AND SupplierInvoiceGrandTotal > 0
AND IF(SupplierPaymentID IS NULL,'N','Y') = '{$status}'
AND (SupplierInvoiceNumber LIKE '%{$search}%' AND SupplierName LIKE '%{$supplier}%')
AND ReceiveOrderPoS_RegionalID = {$regionalid}
AND SupplierInvoiceDraftPaymentDate BETWEEN '{$startdate}' AND '{$enddate}'";
$sql = " SELECT count(*) as total
FROM supplier_invoice
JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber
LEFT JOIN supplier_payment ON SupplierInvoiceID = SupplierPaymentSupplierInvoiceID AND SupplierPaymentIsActive = 'Y'
LEFT JOIN supplier ON SupplierInvoiceSupplierID = SupplierID
JOIN receive_order_po ON SupplierInvoiceReceiveOrderPoID = ReceiveOrderPoID
WHERE
$where
";
// echo $sql;
$query = $this->db_onedev->query($sql, $sql_param);
$tot_count = 0;
$tot_page = 0;
if ($query) {
$tot_count = $query->result_array()[0]["total"];
$tot_page = ceil($tot_count / $number_limit);
} else {
$this->sys_error_db("supplier_invoice count", $this->db_onedev);
exit;
}
$sql = "SELECT supplier_invoice.*,
SupplierName,
'' M_MouName,
0 as totalbill,
0 as paid,
0 as unpaid,
SupplierInvoiceIsLunas as flaglunas,
0 as SupplierPaymentID,
'' as SupplierPaymentNumber,
0 as SupplierPaymentAmount,
'' as SupplierPaymentDate,
'' as SupplierInvoiceIssueRefNumber,
'' as notes,
'' as tagihans,
'N' as isbillterpusat,
DATE_FORMAT(SupplierInvoiceDraftPaymentDate,'%d-%m-%Y') as tanggalbayar,
DATE_FORMAT(SupplierInvoiceDraftPaymentDate,'%d%m%Y') as tanggalbayartext,
IF(SupplierPaymentID IS NULL,'N','Y') as status_invoice,
IFNULL(SupplierPaymentIsApproved,'N') as SupplierPaymentIsApproved,
IFNULL(SupplierPaymentIsVerif,'N') as SupplierPaymentIsVerif,
IFNULL(SupplierPaymentCashierNumber,'') SupplierPaymentCashierNumber
FROM supplier_invoice
LEFT JOIN supplier ON SupplierInvoiceSupplierID = SupplierID
JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber
JOIN receive_order_po ON SupplierInvoiceReceiveOrderPoID = ReceiveOrderPoID
LEFT JOIN supplier_payment ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID AND SupplierPaymentIsActive = 'Y'
WHERE
$where
GROUP BY SupplierInvoiceID
ORDER BY SupplierInvoiceID ASC
limit $number_limit offset $number_offset";
//echo $sql;
$query = $this->db_onedev->query($sql, $sql_param);
$rows = $query->result_array();
if ($rows) {
foreach ($rows as $k => $v) {
$s_payment = $this->db_onedev->query("SELECT GROUP_CONCAT(SupplierPaymentNumber SEPARATOR ', ') as SupplierPaymentNumber,
SUM(IFNULL(SupplierPaymentAmount,0)) as SupplierPaymentAmount,
IFNULL(SupplierPaymentID,0) SupplierPaymentID,
GROUP_CONCAT(DATE_FORMAT(SupplierPaymentDate,'%d-%m-%Y') SEPARATOR ', ') as SupplierPaymentDate
FROM supplier_payment
WHERE SupplierPaymentIsActive = 'Y' AND SupplierPaymentSupplierInvoiceID = {$v['SupplierInvoiceID']}")->row();
$s_jurnal = $this->db_onedev->query("SELECT SUM(jurnalTxCredit) totalbill
FROM supplier_invoice
JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber
JOIN jurnal_tx ON jurnalTxJurnalID = jurnalAddOnJurnalID AND jurnalTxCredit <> 0 AND jurnalTxCoaID <> 563
WHERE SupplierInvoiceID = {$v['SupplierInvoiceID']}
GROUP BY SupplierInvoiceID")->row();
$amount = $s_payment->SupplierPaymentAmount ? $s_payment->SupplierPaymentAmount : "0.00";
$unpaid = (float)$s_jurnal->totalbill - (float)$amount;
$rows[$k]['SupplierPaymentID'] = $s_payment->SupplierPaymentID ? $s_payment->SupplierPaymentID : '0';
$rows[$k]['SupplierPaymentNumber'] = $s_payment->SupplierPaymentNumber ? $s_payment->SupplierPaymentNumber : '';
$rows[$k]['SupplierPaymentAmount'] = $amount;
$rows[$k]['SupplierPaymentDate'] = $s_payment->SupplierPaymentDate;
$rows[$k]['paid'] = $amount;
$rows[$k]['totalbill'] = $s_jurnal->totalbill ? $s_jurnal->totalbill : "0.00";
$rows[$k]['unpaid'] = number_format($unpaid, 2, '.', '');
$rows[$k]['notes'] = $this->add_notes($v['SupplierInvoiceID']);
$rows[$k]['tagihans'] = $this->add_tagihans($v['SupplierInvoiceID']);
}
}
$result = array("total" => $tot_page, "records" => $rows, "sql" => $this->db_onedev->last_query());
$this->sys_ok($result);
exit;
}
/**
* search — unified invoice + downpayment list:
* - Only columns the frontend actually reads (no wildcard, no dead aliases)
* - UNION ALL merges supplier_invoice and supplier_downpayment
* - DP rows enriched via SupplierPaymentSupplierDownpaymentID FK
* - All queries use PDO parameterised placeholders
*/
public function search()
{
if (! $this->isLogin) {
$this->sys_error("Invalid Token");
exit;
}
$prm = $this->sys_input;
$supplier = $prm["supplier"];
$search = $prm["search"];
$status = $prm["status"];
$startdate = $prm["startdate"];
$enddate = $prm["enddate"];
$regionalid = $this->sys_user['S_RegionalID'];
$number_limit = 10;
$number_offset = ((int)$prm['current_page'] - 1) * $number_limit;
// ── INVOICE WHERE ──────────────────────────────────────────
$inv_where = " SupplierInvoiceIsActive = 'Y'
AND SupplierInvoiceStatus = 'Approved'
AND SupplierInvoiceGrandTotal > 0
AND SupplierInvoiceIsInstallment = 'N'
AND IF(SupplierPaymentID IS NULL,'N','Y') = ?
AND SupplierInvoiceNumber LIKE ?
AND SupplierName LIKE ?
AND ReceiveOrderPoS_RegionalID = ?
AND SupplierInvoiceDraftPaymentDate BETWEEN ? AND ? ";
$inv_params = [
$status,
'%' . $search . '%',
'%' . $supplier . '%',
$regionalid,
$startdate,
$enddate,
];
// ── DOWNPAYMENT WHERE ──────────────────────────────────────
$dp_where = " SupplierDownpaymentIsActive = 'Y'
AND IF(SupplierDownpaymentStatus = 'Paid','Y','N') = ?
AND PurchaseOrderNumber LIKE ?
AND SupplierName LIKE ?
AND PurchaseOrderS_RegionalID = ?
AND SupplierDownpaymentDueDate BETWEEN ? AND ? ";
$dp_params = [
$status,
'%' . $search . '%',
'%' . $supplier . '%',
$regionalid,
$startdate,
$enddate,
];
// ── COUNT query — UNION of both sources ────────────────────
$sql_count = "SELECT SUM(cnt) as total FROM (
SELECT count(*) as cnt
FROM supplier_invoice
JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber
LEFT JOIN supplier_payment
ON SupplierInvoiceID = SupplierPaymentSupplierInvoiceID
AND SupplierPaymentIsActive = 'Y'
LEFT JOIN supplier ON SupplierInvoiceSupplierID = SupplierID
JOIN receive_order_po ON SupplierInvoiceReceiveOrderPoID = ReceiveOrderPoID
WHERE $inv_where
UNION ALL
SELECT count(*) as cnt
FROM supplier_downpayment
JOIN purchase_order ON PurchaseOrderID = SupplierDownpaymentPurchasOrderID
JOIN supplier ON SupplierID = SupplierDownpaymentSupplierID
WHERE $dp_where
) AS combined";
$count_params = array_merge($inv_params, $dp_params);
$query = $this->db_onedev->query($sql_count, $count_params);
$tot_count = 0;
$tot_page = 0;
if ($query) {
$tot_count = $query->result_array()[0]["total"];
$tot_page = ceil($tot_count / $number_limit);
} else {
$this->sys_error_db("payment instructions count", $this->db_onedev);
exit;
}
// ── DATA query — UNION with identical columns ──────────────
$sql_data = "
SELECT * FROM (
SELECT
SupplierInvoiceID,
SupplierInvoiceNumber,
SupplierInvoiceDraftPaymentDate,
SupplierInvoiceIsLunas as flaglunas,
SupplierName,
DATE_FORMAT(SupplierInvoiceDraftPaymentDate,'%d-%m-%Y') as tanggalbayar,
IFNULL(SupplierPaymentIsApproved,'N') as SupplierPaymentIsApproved,
IFNULL(SupplierPaymentCashierNumber,'') as SupplierPaymentCashierNumber,
0 as totalbill,
0 as paid,
0 as unpaid,
0 as SupplierPaymentID,
'' as SupplierPaymentNumber,
0 as SupplierPaymentAmount,
'' as SupplierPaymentDate,
'' as notes,
'' as tagihans,
'INVOICE' as type
FROM supplier_invoice
LEFT JOIN supplier ON SupplierInvoiceSupplierID = SupplierID
JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber
JOIN receive_order_po ON SupplierInvoiceReceiveOrderPoID = ReceiveOrderPoID
LEFT JOIN supplier_payment
ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID
AND SupplierPaymentIsActive = 'Y'
WHERE $inv_where
GROUP BY SupplierInvoiceID
UNION ALL
SELECT
SupplierDownpaymentID * -1 as SupplierInvoiceID,
CONCAT('DP-', PurchaseOrderNumber) as SupplierInvoiceNumber,
SupplierDownpaymentDueDate as SupplierInvoiceDraftPaymentDate,
SupplierDownpaymentIsLunas as flaglunas,
SupplierName,
DATE_FORMAT(SupplierDownpaymentDueDate,'%d-%m-%Y') as tanggalbayar,
'N' as SupplierPaymentIsApproved,
'' as SupplierPaymentCashierNumber,
SupplierDownpaymentAmount as totalbill,
CASE WHEN SupplierDownpaymentStatus = 'Paid'
THEN SupplierDownpaymentAmount
ELSE 0 END as paid,
CASE WHEN SupplierDownpaymentStatus = 'Paid'
THEN 0
ELSE SupplierDownpaymentAmount END as unpaid,
0 as SupplierPaymentID,
'' as SupplierPaymentNumber,
0 as SupplierPaymentAmount,
'' as SupplierPaymentDate,
'' as notes,
'' as tagihans,
'DP' as type
FROM supplier_downpayment
JOIN purchase_order ON PurchaseOrderID = SupplierDownpaymentPurchasOrderID
JOIN supplier ON SupplierID = SupplierDownpaymentSupplierID
WHERE $dp_where
) AS combined
ORDER BY SupplierInvoiceID ASC
LIMIT ? OFFSET ?";
$data_params = array_merge($inv_params, $dp_params, [$number_limit, $number_offset]);
$query = $this->db_onedev->query($sql_data, $data_params);
$rows = $query->result_array();
// ── ENRICH — per-row sub-queries ───────────────────────────
if ($rows) {
foreach ($rows as $k => $v) {
// ── Downpayment branch ──────────────────────────
if ($v['type'] === 'DP') {
$dp_id = abs($v['SupplierInvoiceID']);
$s_payment = $this->db_onedev->query("
SELECT
GROUP_CONCAT(SupplierPaymentNumber SEPARATOR ', ') as SupplierPaymentNumber,
SUM(IFNULL(SupplierPaymentAmount,0)) as SupplierPaymentAmount,
IFNULL(SupplierPaymentID,0) as SupplierPaymentID,
GROUP_CONCAT(
DATE_FORMAT(SupplierPaymentDate,'%d-%m-%Y')
SEPARATOR ', '
) as SupplierPaymentDate
FROM supplier_payment
WHERE SupplierPaymentIsActive = 'Y'
AND SupplierPaymentSupplierDownpaymentID = ?",
[$dp_id]
)->row();
$amount = $s_payment->SupplierPaymentAmount
? $s_payment->SupplierPaymentAmount
: "0.00";
$rows[$k]['SupplierPaymentID'] = $s_payment->SupplierPaymentID
? $s_payment->SupplierPaymentID
: '0';
$rows[$k]['SupplierPaymentNumber'] = $s_payment->SupplierPaymentNumber
? $s_payment->SupplierPaymentNumber
: '';
$rows[$k]['SupplierPaymentAmount'] = $amount;
$rows[$k]['SupplierPaymentDate'] = $s_payment->SupplierPaymentDate;
$rows[$k]['paid'] = $amount;
$rows[$k]['notes'] = $this->add_notes_downpayment($dp_id);
$rows[$k]['tagihans'] = [];
// totalbill, unpaid already correct from UNION CASE
continue;
}
// ── Invoice branch ───────────────────────────────
$inv_id = $v['SupplierInvoiceID'];
$s_payment = $this->db_onedev->query("
SELECT
GROUP_CONCAT(SupplierPaymentNumber SEPARATOR ', ') as SupplierPaymentNumber,
SUM(IFNULL(SupplierPaymentAmount,0)) as SupplierPaymentAmount,
IFNULL(SupplierPaymentID,0) as SupplierPaymentID,
GROUP_CONCAT(
DATE_FORMAT(SupplierPaymentDate,'%d-%m-%Y')
SEPARATOR ', '
) as SupplierPaymentDate
FROM supplier_payment
WHERE SupplierPaymentIsActive = 'Y'
AND SupplierPaymentSupplierInvoiceID = ?",
[$inv_id]
)->row();
$s_jurnal = $this->db_onedev->query("
SELECT SUM(jurnalTxCredit) totalbill
FROM supplier_invoice
JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber
JOIN jurnal_tx
ON jurnalTxJurnalID = jurnalAddOnJurnalID
AND jurnalTxCredit <> 0
AND jurnalTxCoaID <> 563
WHERE SupplierInvoiceID = ?
GROUP BY SupplierInvoiceID",
[$inv_id]
)->row();
$amount = $s_payment->SupplierPaymentAmount
? $s_payment->SupplierPaymentAmount
: "0.00";
$unpaid = (float)$s_jurnal->totalbill - (float)$amount;
$rows[$k]['SupplierPaymentID'] = $s_payment->SupplierPaymentID
? $s_payment->SupplierPaymentID
: '0';
$rows[$k]['SupplierPaymentNumber'] = $s_payment->SupplierPaymentNumber
? $s_payment->SupplierPaymentNumber
: '';
$rows[$k]['SupplierPaymentAmount'] = $amount;
$rows[$k]['SupplierPaymentDate'] = $s_payment->SupplierPaymentDate;
$rows[$k]['paid'] = $amount;
$rows[$k]['totalbill'] = $s_jurnal->totalbill
? $s_jurnal->totalbill
: "0.00";
$rows[$k]['unpaid'] = number_format($unpaid, 2, '.', '');
$rows[$k]['notes'] = $this->add_notes($inv_id);
$rows[$k]['tagihans'] = $this->add_tagihans($inv_id);
}
}
$result = array("total" => $tot_page, "records" => $rows);
$this->sys_ok($result);
exit;
}
$query = $this->db_onedev->query($sql);
if ($query) {
$rows = $query->result_array();
if($rows){
}
return $rows;
} else {
$this->sys_error_db("get notes", $this->db_onedev);
exit;
}
}
public function search()
{
//# cek token valid
if (! $this->isLogin) {
$this->sys_error("Invalid Token");
exit;
}
$prm = $this->sys_input;
$supplier = $prm["supplier"];
$search = $prm["search"];
$status = $prm["status"];
$startdate = $prm["startdate"];
$enddate = $prm["enddate"];
$regionalid = $this->sys_user['S_RegionalID'];
$number_limit = 10;
$number_offset = ($prm['current_page'] - 1) * $number_limit ;
$where = "SupplierInvoiceIsActive = 'Y'
AND SupplierInvoiceStatus = 'Approved'
AND SupplierInvoiceGrandTotal > 0
AND IF(SupplierPaymentID IS NULL,'N','Y') = '{$status}'
AND (SupplierInvoiceNumber LIKE '%{$search}%' AND SupplierName LIKE '%{$supplier}%')
AND ReceiveOrderPoS_RegionalID = {$regionalid}
AND SupplierInvoiceDraftPaymentDate BETWEEN '{$startdate}' AND '{$enddate}'";
$sql = " SELECT count(*) as total
FROM supplier_invoice
JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber
LEFT JOIN supplier_payment ON SupplierInvoiceID = SupplierPaymentSupplierInvoiceID AND SupplierPaymentIsActive = 'Y'
LEFT JOIN supplier ON SupplierInvoiceSupplierID = SupplierID
JOIN receive_order_po ON SupplierInvoiceReceiveOrderPoID = ReceiveOrderPoID
WHERE
$where
";
// echo $sql;
$query = $this->db_onedev->query($sql, $sql_param);
$tot_count = 0;
$tot_page = 0;
if ($query) {
$tot_count = $query->result_array()[0]["total"];
$tot_page = ceil($tot_count/$number_limit);
} else {
$this->sys_error_db("supplier_invoice count", $this->db_onedev);
exit;
}
$sql = "SELECT supplier_invoice.*,
SupplierName,
'' M_MouName,
0 as totalbill,
0 as paid,
0 as unpaid,
SupplierInvoiceIsLunas as flaglunas,
0 as SupplierPaymentID,
'' as SupplierPaymentNumber,
0 as SupplierPaymentAmount,
'' as SupplierPaymentDate,
'' as SupplierInvoiceIssueRefNumber,
'' as notes,
'' as tagihans,
'N' as isbillterpusat,
DATE_FORMAT(SupplierInvoiceDraftPaymentDate,'%d-%m-%Y') as tanggalbayar,
DATE_FORMAT(SupplierInvoiceDraftPaymentDate,'%d%m%Y') as tanggalbayartext,
IF(SupplierPaymentID IS NULL,'N','Y') as status_invoice,
IFNULL(SupplierPaymentIsApproved,'N') as SupplierPaymentIsApproved,
IFNULL(SupplierPaymentIsVerif,'N') as SupplierPaymentIsVerif,
IFNULL(SupplierPaymentCashierNumber,'') SupplierPaymentCashierNumber
FROM supplier_invoice
LEFT JOIN supplier ON SupplierInvoiceSupplierID = SupplierID
JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber
JOIN receive_order_po ON SupplierInvoiceReceiveOrderPoID = ReceiveOrderPoID
LEFT JOIN supplier_payment ON SupplierPaymentSupplierInvoiceID = SupplierInvoiceID AND SupplierPaymentIsActive = 'Y'
WHERE
$where
GROUP BY SupplierInvoiceID
ORDER BY SupplierInvoiceID ASC
limit $number_limit offset $number_offset";
//echo $sql;
$query = $this->db_onedev->query($sql, $sql_param);
$rows = $query->result_array();
if($rows){
foreach($rows as $k => $v){
$s_payment = $this->db_onedev->query("SELECT GROUP_CONCAT(SupplierPaymentNumber SEPARATOR ', ') as SupplierPaymentNumber,
SUM(IFNULL(SupplierPaymentAmount,0)) as SupplierPaymentAmount,
IFNULL(SupplierPaymentID,0) SupplierPaymentID,
GROUP_CONCAT(DATE_FORMAT(SupplierPaymentDate,'%d-%m-%Y') SEPARATOR ', ') as SupplierPaymentDate
FROM supplier_payment
WHERE SupplierPaymentIsActive = 'Y' AND SupplierPaymentSupplierInvoiceID = {$v['SupplierInvoiceID']}")->row();
$s_jurnal = $this->db_onedev->query("SELECT SUM(jurnalTxCredit) totalbill
FROM supplier_invoice
JOIN jurnal_addon ON jurnalAddOnValue = SupplierInvoiceNumber
JOIN jurnal_tx ON jurnalTxJurnalID = jurnalAddOnJurnalID AND jurnalTxCredit <> 0 AND jurnalTxCoaID <> 563
WHERE SupplierInvoiceID = {$v['SupplierInvoiceID']}
GROUP BY SupplierInvoiceID")->row();
$amount = $s_payment->SupplierPaymentAmount ? $s_payment->SupplierPaymentAmount : "0.00";
$unpaid = (float)$s_jurnal->totalbill - (float)$amount;
$rows[$k]['SupplierPaymentID'] = $s_payment->SupplierPaymentID ? $s_payment->SupplierPaymentID : '0';
$rows[$k]['SupplierPaymentNumber'] = $s_payment->SupplierPaymentNumber ? $s_payment->SupplierPaymentNumber : '';
$rows[$k]['SupplierPaymentAmount'] = $amount;
$rows[$k]['SupplierPaymentDate'] = $s_payment->SupplierPaymentDate;
$rows[$k]['paid'] = $amount;
$rows[$k]['totalbill'] = $s_jurnal->totalbill ? $s_jurnal->totalbill : "0.00";
$rows[$k]['unpaid'] = number_format($unpaid, 2, '.', '');
$rows[$k]['notes'] = $this->add_notes($v['SupplierInvoiceID']);
$rows[$k]['tagihans'] = $this->add_tagihans($v['SupplierInvoiceID']);
}
}
$result = array("total" => $tot_page, "records" => $rows, "sql"=> $this->db_onedev->last_query());
$this->sys_ok($result);
exit;
}
}

File diff suppressed because it is too large Load Diff