accounting workflows

This commit is contained in:
Thanakorn S
2026-05-20 10:17:02 +07:00
parent 04a683bd02
commit 7396db6ffc
199 changed files with 23539 additions and 5345 deletions
@@ -0,0 +1,183 @@
<?php
/**
* BasePosting
*
* Shared build() logic for all six posting types.
* Subclasses implement fetchDocument(), getAmounts(), getDocType(), getDocDate().
*
* build() returns:
* ['formula_id' => int, 'period' => 'YYYY-MM', 'doc_date' => 'YYYY-MM-DD', 'lines' => [...]]
*
* Amount keys understood by formulas:
* grand_total — full document total (abs value used)
* total — pre-tax amount (grand_total - tax)
* tax — tax portion
* amount — used by receipt and payment
*/
abstract class BasePosting
{
protected PDO $pdo;
protected int $companyId;
public function __construct(PDO $pdo, int $company_id)
{
$this->pdo = $pdo;
$this->companyId = $company_id;
}
abstract protected function fetchDocument(int $id): array;
abstract protected function getAmounts(array $doc): array;
abstract protected function getDocType(): string;
abstract protected function getDocDate(array $doc): string;
public function build(int $id, ?int $formula_id = null): array
{
$doc = $this->fetchDocument($id);
$formula = $this->resolveFormula($this->getDocType(), $formula_id);
$amounts = $this->getAmounts($doc);
$doc_date = $this->getDocDate($doc);
$period = substr($doc_date, 0, 7);
$dept_id = (int)($doc['department_id'] ?? 0);
$lines = [];
foreach ($formula['items'] as $item) {
$amount = abs((float)($amounts[$item['amount_key']] ?? 0));
if ($amount == 0) continue;
if ($item['amount_key'] === 'total') {
$split_lines = $this->buildSkuTotalLines($doc, $item, $amount, $dept_id);
if ($split_lines) {
$lines = array_merge($lines, $split_lines);
continue;
}
}
$lines[] = [
'account_code' => $item['account_code'],
'department_id' => $dept_id,
'debit' => $item['drcr'] === 'D' ? $amount : 0.0,
'credit' => $item['drcr'] === 'C' ? $amount : 0.0,
'description' => (string)($item['description'] ?? ''),
];
}
return [
'formula_id' => (int)$formula['id'],
'period' => $period,
'doc_date' => $doc_date,
'lines' => $lines,
];
}
protected function resolveFormula(string $doc_type, ?int $formula_id): array
{
if ($formula_id) {
$sth = $this->pdo->prepare(
"SELECT * FROM md_account_formula
WHERE company_id = :cid AND id = :id AND status = 1
LIMIT 1"
);
$sth->execute([':cid' => $this->companyId, ':id' => $formula_id]);
} else {
$sth = $this->pdo->prepare(
"SELECT * FROM md_account_formula
WHERE company_id = :cid
AND document_type = :doc_type
AND is_default = 1
AND status = 1
LIMIT 1"
);
$sth->execute([':cid' => $this->companyId, ':doc_type' => $doc_type]);
}
$formula = $sth->fetch(PDO::FETCH_ASSOC);
if (!$formula) throw new Exception("No active formula found for '{$doc_type}'.");
$sth = $this->pdo->prepare(
"SELECT * FROM md_account_formula_item
WHERE company_id = :cid AND formula_id = :formula_id
ORDER BY sort_order ASC"
);
$sth->execute([':cid' => $this->companyId, ':formula_id' => $formula['id']]);
$formula['items'] = $sth->fetchAll(PDO::FETCH_ASSOC);
return $formula;
}
protected function getSkuTotalAccountColumn(): string
{
return '';
}
private function buildSkuTotalLines(array $doc, array $formula_item, float $amount, int $dept_id): array
{
$column = $this->getSkuTotalAccountColumn();
if ($column === '' || !in_array($column, ['sales_account_code', 'purchase_account_code'], true)) {
return [];
}
$invoice_id = (int)($doc['id'] ?? 0);
if ($invoice_id <= 0) return [];
$sth = $this->pdo->prepare("
SELECT
i.product_sku,
i.product_name,
i.total_price,
COALESCE(NULLIF(p.{$column}, ''), '') AS mapped_account_code
FROM td_invoice_item i
LEFT JOIN md_product p
ON p.company_id = i.company_id
AND p.sku = i.product_sku
WHERE i.company_id = :cid
AND i.invoice_id = :invoice_id
ORDER BY i.item_id ASC, i.id ASC
");
$sth->execute([':cid' => $this->companyId, ':invoice_id' => $invoice_id]);
$items = array_values(array_filter($sth->fetchAll(PDO::FETCH_ASSOC), function($row) {
return abs((float)($row['total_price'] ?? 0)) > 0.0000001;
}));
if (!$items) return [];
$base_total = array_reduce($items, function($carry, $row) {
return $carry + abs((float)($row['total_price'] ?? 0));
}, 0.0);
if ($base_total <= 0) return [];
$remaining = round($amount, 4);
$last = count($items) - 1;
$lines = [];
foreach ($items as $idx => $row) {
$line_amount = $idx === $last
? $remaining
: round($amount * (abs((float)$row['total_price']) / $base_total), 4);
$remaining = round($remaining - $line_amount, 4);
if (abs($line_amount) <= 0.0000001) continue;
$account_code = trim((string)($row['mapped_account_code'] ?? ''));
if ($account_code === '') {
$account_code = (string)$formula_item['account_code'];
}
$desc = trim((string)($formula_item['description'] ?? ''));
$sku = trim((string)($row['product_sku'] ?? ''));
$name = trim((string)($row['product_name'] ?? ''));
$item_desc = trim($sku . ($name !== '' ? ' - ' . $name : ''));
if ($item_desc !== '') {
$desc = $desc !== '' ? $desc . ': ' . $item_desc : $item_desc;
}
$lines[] = [
'account_code' => $account_code,
'department_id' => $dept_id,
'debit' => $formula_item['drcr'] === 'D' ? $line_amount : 0.0,
'credit' => $formula_item['drcr'] === 'C' ? $line_amount : 0.0,
'description' => $desc,
];
}
return $lines;
}
}
@@ -0,0 +1,43 @@
<?php
require_once __DIR__ . '/BasePosting.php';
class CreditNotePosting extends BasePosting
{
protected function getDocType(): string { return 'credit_note'; }
protected function getSkuTotalAccountColumn(): string { return 'sales_account_code'; }
protected function fetchDocument(int $id): array
{
$sth = $this->pdo->prepare(
"SELECT i.*, COALESCE(c.contact_name, '') AS contact_name
FROM td_invoice i
LEFT JOIN md_contact c
ON c.company_id = i.company_id AND c.id = i.contact_id
WHERE i.company_id = :cid AND i.id = :id AND i.doc_type = 'credit_note'
LIMIT 1"
);
$sth->execute([':cid' => $this->companyId, ':id' => $id]);
$doc = $sth->fetch(PDO::FETCH_ASSOC);
if (!$doc) throw new Exception("Credit note #{$id} not found.");
return $doc;
}
protected function getAmounts(array $doc): array
{
// grand_total is negative in DB for credit notes — use abs()
$grand_total = abs((float)$doc['grand_total']);
$tax = abs((float)$doc['tax']);
return [
'grand_total' => $grand_total,
'tax' => $tax,
'total' => $grand_total - $tax,
'amount' => $grand_total,
];
}
protected function getDocDate(array $doc): string
{
return $doc['issued_date'] ?? date('Y-m-d');
}
}
@@ -1,21 +1,42 @@
<?php
/**
* InvoicePosting
*
* Builds the journal entry for a posted sales invoice.
* DR: Accounts Receivable
* CR: Revenue + Output VAT
*/
class InvoicePosting
{
private PDO $pdo;
private int $companyId;
require_once __DIR__ . '/BasePosting.php';
public function __construct(PDO $pdo, int $company_id)
class InvoicePosting extends BasePosting
{
protected function getDocType(): string { return 'invoice'; }
protected function getSkuTotalAccountColumn(): string { return 'sales_account_code'; }
protected function fetchDocument(int $id): array
{
$this->pdo = $pdo;
$this->companyId = $company_id;
$sth = $this->pdo->prepare(
"SELECT i.*, COALESCE(c.contact_name, '') AS contact_name
FROM td_invoice i
LEFT JOIN md_contact c
ON c.company_id = i.company_id AND c.id = i.contact_id
WHERE i.company_id = :cid AND i.id = :id AND i.doc_type = 'invoice'
LIMIT 1"
);
$sth->execute([':cid' => $this->companyId, ':id' => $id]);
$doc = $sth->fetch(PDO::FETCH_ASSOC);
if (!$doc) throw new Exception("Invoice #{$id} not found.");
return $doc;
}
// TODO: build(int $invoice_id): array — returns [header, lines] ready for JournalManager
protected function getAmounts(array $doc): array
{
$grand_total = abs((float)$doc['grand_total']);
$tax = abs((float)$doc['tax']);
return [
'grand_total' => $grand_total,
'tax' => $tax,
'total' => $grand_total - $tax,
'amount' => $grand_total,
];
}
protected function getDocDate(array $doc): string
{
return $doc['issued_date'] ?? date('Y-m-d');
}
}
@@ -1,21 +1,109 @@
<?php
/**
* PaymentPosting
*
* Builds the journal entry when a supplier payment is recorded.
* DR: Accounts Payable
* CR: Bank / Cash
*/
class PaymentPosting
{
private PDO $pdo;
private int $companyId;
require_once __DIR__ . '/BasePosting.php';
public function __construct(PDO $pdo, int $company_id)
class PaymentPosting extends BasePosting
{
protected function getDocType(): string { return 'payment'; }
public function build(int $id, ?int $formula_id = null): array
{
$this->pdo = $pdo;
$this->companyId = $company_id;
$doc = $this->fetchDocument($id);
$formula = $this->resolveFormula($this->getDocType(), $formula_id);
$doc_date = $this->getDocDate($doc);
$period = substr($doc_date, 0, 7);
$dept_amounts = $this->getDepartmentAmounts($id);
$lines = [];
foreach ($dept_amounts as $dept_id => $amount) {
if (abs($amount) <= 0.0001) continue;
$is_negative = $amount < 0;
$line_amount = abs($amount);
foreach ($formula['items'] as $item) {
if ($item['amount_key'] === 'tax') continue;
$drcr = $item['drcr'];
if ($is_negative) {
$drcr = $drcr === 'D' ? 'C' : 'D';
}
$lines[] = [
'account_code' => $item['account_code'],
'department_id' => (int)$dept_id,
'debit' => $drcr === 'D' ? $line_amount : 0.0,
'credit' => $drcr === 'C' ? $line_amount : 0.0,
'description' => (string)($item['description'] ?? ''),
];
}
}
return [
'formula_id' => (int)$formula['id'],
'period' => $period,
'doc_date' => $doc_date,
'lines' => $lines,
];
}
// TODO: build(int $payment_id): array — returns [header, lines] ready for JournalManager
protected function fetchDocument(int $id): array
{
$sth = $this->pdo->prepare(
"SELECT r.*, COALESCE(c.contact_name, '') AS contact_name
FROM td_payment r
LEFT JOIN md_contact c
ON c.company_id = r.company_id AND c.id = r.contact_id
WHERE r.company_id = :cid AND r.id = :id
LIMIT 1"
);
$sth->execute([':cid' => $this->companyId, ':id' => $id]);
$doc = $sth->fetch(PDO::FETCH_ASSOC);
if (!$doc) throw new Exception("Payment #{$id} not found.");
return $doc;
}
protected function getAmounts(array $doc): array
{
$amount = abs((float)$doc['amount']);
return [
'amount' => $amount,
'grand_total' => $amount,
'total' => $amount,
'tax' => 0.0,
];
}
protected function getDocDate(array $doc): string
{
return $doc['payment_date'] ?? date('Y-m-d');
}
private function getDepartmentAmounts(int $payment_id): array
{
$sth = $this->pdo->prepare(
"SELECT pi.department_id,
pi.doc_type,
pi.amount
FROM td_payment_item pi
WHERE pi.company_id = :cid
AND pi.payment_id = :payment_id"
);
$sth->execute([
':cid' => $this->companyId,
':payment_id' => $payment_id,
]);
$dept_amounts = [];
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $line) {
$dept_id = (int)($line['department_id'] ?? 0);
$amount = abs((float)($line['amount'] ?? 0));
if ($line['doc_type'] === 'supplier_credit_note') {
$amount *= -1;
}
$dept_amounts[$dept_id] = ($dept_amounts[$dept_id] ?? 0) + $amount;
}
if (!$dept_amounts) throw new Exception("Payment #{$payment_id} has no allocation lines for GL posting.");
return $dept_amounts;
}
}
@@ -0,0 +1,42 @@
<?php
require_once __DIR__ . '/BasePosting.php';
class PurchaseInvoicePosting extends BasePosting
{
protected function getDocType(): string { return 'purchase_invoice'; }
protected function getSkuTotalAccountColumn(): string { return 'purchase_account_code'; }
protected function fetchDocument(int $id): array
{
$sth = $this->pdo->prepare(
"SELECT i.*, COALESCE(c.contact_name, '') AS contact_name
FROM td_invoice i
LEFT JOIN md_contact c
ON c.company_id = i.company_id AND c.id = i.contact_id
WHERE i.company_id = :cid AND i.id = :id AND i.doc_type = 'purchase_invoice'
LIMIT 1"
);
$sth->execute([':cid' => $this->companyId, ':id' => $id]);
$doc = $sth->fetch(PDO::FETCH_ASSOC);
if (!$doc) throw new Exception("Purchase invoice #{$id} not found.");
return $doc;
}
protected function getAmounts(array $doc): array
{
$grand_total = abs((float)$doc['grand_total']);
$tax = abs((float)$doc['tax']);
return [
'grand_total' => $grand_total,
'tax' => $tax,
'total' => $grand_total - $tax,
'amount' => $grand_total,
];
}
protected function getDocDate(array $doc): string
{
return $doc['issued_date'] ?? date('Y-m-d');
}
}
@@ -1,21 +1,162 @@
<?php
require_once __DIR__ . '/BasePosting.php';
/**
* PurchasePosting
*
* Builds the journal entry when a Purchase Order is received (GRN).
* DR: Inventory
* CR: Accounts Payable
* Builds the GL journal entry for a Purchase Order (GRN).
* Typical formula: DR Inventory (per SKU) + DR Input VAT / CR Accounts Payable.
*
* Amount keys:
* grand_total — full PO total (used for AP credit line)
* tax — VAT portion
* total — pre-tax (grand_total - tax), split per SKU via purchase_account_code
* amount — alias of grand_total
*/
class PurchasePosting
class PurchasePosting extends BasePosting
{
private PDO $pdo;
private int $companyId;
protected function getDocType(): string { return 'purchase_order'; }
public function __construct(PDO $pdo, int $company_id)
protected function fetchDocument(int $id): array
{
$this->pdo = $pdo;
$this->companyId = $company_id;
$sth = $this->pdo->prepare(
"SELECT p.*, COALESCE(c.contact_name, '') AS contact_name
FROM td_purchase_order p
LEFT JOIN md_contact c
ON c.company_id = p.company_id AND c.id = p.contact_id
WHERE p.company_id = :cid AND p.id = :id
LIMIT 1"
);
$sth->execute([':cid' => $this->companyId, ':id' => $id]);
$doc = $sth->fetch(PDO::FETCH_ASSOC);
if (!$doc) throw new Exception("Purchase order #{$id} not found.");
$sth2 = $this->pdo->prepare(
"SELECT * FROM td_purchase_order_item
WHERE company_id = :cid AND order_id = :id
ORDER BY item_id ASC"
);
$sth2->execute([':cid' => $this->companyId, ':id' => $id]);
$doc['items'] = $sth2->fetchAll(PDO::FETCH_ASSOC);
return $doc;
}
// TODO: build(int $po_id): array — returns [header, lines] ready for JournalManager
protected function getAmounts(array $doc): array
{
$grand_total = abs((float)$doc['grand_total']);
$tax = abs((float)$doc['tax']);
return [
'grand_total' => $grand_total,
'tax' => $tax,
'total' => $grand_total - $tax,
'amount' => $grand_total,
];
}
protected function getDocDate(array $doc): string
{
return $doc['po_date'] ?? date('Y-m-d');
}
public function build(int $id, ?int $formula_id = null): array
{
$doc = $this->fetchDocument($id);
$formula = $this->resolveFormula($this->getDocType(), $formula_id);
$amounts = $this->getAmounts($doc);
$doc_date = $this->getDocDate($doc);
$period = substr($doc_date, 0, 7);
$dept_id = (int)($doc['department_id'] ?? 0);
$lines = [];
foreach ($formula['items'] as $item) {
$amount = abs((float)($amounts[$item['amount_key']] ?? 0));
if ($amount == 0) continue;
if ($item['amount_key'] === 'total') {
$split_lines = $this->buildSkuSplitLines($doc['items'], $item, $amount, $dept_id);
if ($split_lines) {
$lines = array_merge($lines, $split_lines);
continue;
}
}
$lines[] = [
'account_code' => $item['account_code'],
'department_id' => $dept_id,
'debit' => $item['drcr'] === 'D' ? $amount : 0.0,
'credit' => $item['drcr'] === 'C' ? $amount : 0.0,
'description' => (string)($item['description'] ?? ''),
];
}
return [
'formula_id' => (int)$formula['id'],
'period' => $period,
'doc_date' => $doc_date,
'lines' => $lines,
];
}
private function buildSkuSplitLines(array $items, array $formula_item, float $amount, int $dept_id): array
{
$items = array_values(array_filter($items, function($row) {
return abs((float)($row['total_price'] ?? 0)) > 0.0000001;
}));
if (!$items) return [];
$skus = array_values(array_unique(array_filter(array_column($items, 'product_sku'))));
$account_map = [];
if ($skus) {
$placeholders = implode(',', array_fill(0, count($skus), '?'));
$sth = $this->pdo->prepare(
"SELECT sku, purchase_account_code FROM md_product
WHERE company_id = ? AND sku IN ({$placeholders})"
);
$sth->execute(array_merge([$this->companyId], $skus));
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
$account_map[$row['sku']] = trim((string)($row['purchase_account_code'] ?? ''));
}
}
$base_total = array_reduce($items, function($carry, $row) {
return $carry + abs((float)($row['total_price'] ?? 0));
}, 0.0);
if ($base_total <= 0) return [];
$remaining = round($amount, 4);
$last = count($items) - 1;
$lines = [];
foreach ($items as $idx => $row) {
$line_amount = $idx === $last
? $remaining
: round($amount * (abs((float)$row['total_price']) / $base_total), 4);
$remaining = round($remaining - $line_amount, 4);
if (abs($line_amount) <= 0.0000001) continue;
$sku = trim((string)($row['product_sku'] ?? ''));
$account_code = ($sku !== '' && ($account_map[$sku] ?? '') !== '')
? $account_map[$sku]
: (string)$formula_item['account_code'];
$name = trim((string)($row['product_name'] ?? ''));
$desc = trim((string)($formula_item['description'] ?? ''));
$item_desc = trim($sku . ($name !== '' ? ' - ' . $name : ''));
if ($item_desc !== '') {
$desc = $desc !== '' ? $desc . ': ' . $item_desc : $item_desc;
}
$lines[] = [
'account_code' => $account_code,
'department_id' => $dept_id,
'debit' => $formula_item['drcr'] === 'D' ? $line_amount : 0.0,
'credit' => $formula_item['drcr'] === 'C' ? $line_amount : 0.0,
'description' => $desc,
];
}
return $lines;
}
}
@@ -1,21 +1,109 @@
<?php
/**
* ReceiptPosting
*
* Builds the journal entry when a customer receipt is recorded.
* DR: Bank / Cash
* CR: Accounts Receivable
*/
class ReceiptPosting
{
private PDO $pdo;
private int $companyId;
require_once __DIR__ . '/BasePosting.php';
public function __construct(PDO $pdo, int $company_id)
class ReceiptPosting extends BasePosting
{
protected function getDocType(): string { return 'receipt'; }
public function build(int $id, ?int $formula_id = null): array
{
$this->pdo = $pdo;
$this->companyId = $company_id;
$doc = $this->fetchDocument($id);
$formula = $this->resolveFormula($this->getDocType(), $formula_id);
$doc_date = $this->getDocDate($doc);
$period = substr($doc_date, 0, 7);
$dept_amounts = $this->getDepartmentAmounts($id);
$lines = [];
foreach ($dept_amounts as $dept_id => $amount) {
if (abs($amount) <= 0.0001) continue;
$is_negative = $amount < 0;
$line_amount = abs($amount);
foreach ($formula['items'] as $item) {
if ($item['amount_key'] === 'tax') continue;
$drcr = $item['drcr'];
if ($is_negative) {
$drcr = $drcr === 'D' ? 'C' : 'D';
}
$lines[] = [
'account_code' => $item['account_code'],
'department_id' => (int)$dept_id,
'debit' => $drcr === 'D' ? $line_amount : 0.0,
'credit' => $drcr === 'C' ? $line_amount : 0.0,
'description' => (string)($item['description'] ?? ''),
];
}
}
return [
'formula_id' => (int)$formula['id'],
'period' => $period,
'doc_date' => $doc_date,
'lines' => $lines,
];
}
// TODO: build(int $receipt_id): array — returns [header, lines] ready for JournalManager
protected function fetchDocument(int $id): array
{
$sth = $this->pdo->prepare(
"SELECT r.*, COALESCE(c.contact_name, '') AS contact_name
FROM td_receipt r
LEFT JOIN md_contact c
ON c.company_id = r.company_id AND c.id = r.contact_id
WHERE r.company_id = :cid AND r.id = :id
LIMIT 1"
);
$sth->execute([':cid' => $this->companyId, ':id' => $id]);
$doc = $sth->fetch(PDO::FETCH_ASSOC);
if (!$doc) throw new Exception("Receipt #{$id} not found.");
return $doc;
}
protected function getAmounts(array $doc): array
{
$amount = abs((float)$doc['amount']);
return [
'amount' => $amount,
'grand_total' => $amount,
'total' => $amount,
'tax' => 0.0,
];
}
protected function getDocDate(array $doc): string
{
return $doc['receipt_date'] ?? date('Y-m-d');
}
private function getDepartmentAmounts(int $receipt_id): array
{
$sth = $this->pdo->prepare(
"SELECT ri.department_id,
ri.doc_type,
ri.amount
FROM td_receipt_item ri
WHERE ri.company_id = :cid
AND ri.receipt_id = :receipt_id"
);
$sth->execute([
':cid' => $this->companyId,
':receipt_id' => $receipt_id,
]);
$dept_amounts = [];
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $line) {
$dept_id = (int)($line['department_id'] ?? 0);
$amount = abs((float)($line['amount'] ?? 0));
if ($line['doc_type'] === 'credit_note') {
$amount *= -1;
}
$dept_amounts[$dept_id] = ($dept_amounts[$dept_id] ?? 0) + $amount;
}
if (!$dept_amounts) throw new Exception("Receipt #{$receipt_id} has no allocation lines for GL posting.");
return $dept_amounts;
}
}
@@ -0,0 +1,42 @@
<?php
require_once __DIR__ . '/BasePosting.php';
class SupplierCreditNotePosting extends BasePosting
{
protected function getDocType(): string { return 'supplier_credit_note'; }
protected function getSkuTotalAccountColumn(): string { return 'purchase_account_code'; }
protected function fetchDocument(int $id): array
{
$sth = $this->pdo->prepare(
"SELECT i.*, COALESCE(c.contact_name, '') AS contact_name
FROM td_invoice i
LEFT JOIN md_contact c
ON c.company_id = i.company_id AND c.id = i.contact_id
WHERE i.company_id = :cid AND i.id = :id AND i.doc_type = 'supplier_credit_note'
LIMIT 1"
);
$sth->execute([':cid' => $this->companyId, ':id' => $id]);
$doc = $sth->fetch(PDO::FETCH_ASSOC);
if (!$doc) throw new Exception("Supplier credit note #{$id} not found.");
return $doc;
}
protected function getAmounts(array $doc): array
{
$grand_total = abs((float)$doc['grand_total']);
$tax = abs((float)$doc['tax']);
return [
'grand_total' => $grand_total,
'tax' => $tax,
'total' => $grand_total - $tax,
'amount' => $grand_total,
];
}
protected function getDocDate(array $doc): string
{
return $doc['issued_date'] ?? date('Y-m-d');
}
}