InvoicePosting::class, 'credit_note' => CreditNotePosting::class, 'purchase_invoice' => PurchaseInvoicePosting::class, 'supplier_credit_note' => SupplierCreditNotePosting::class, 'receipt' => ReceiptPosting::class, 'payment' => PaymentPosting::class, 'purchase_order' => PurchasePosting::class, ]; if (!isset($posting_map[$doc_type]) || $id <= 0) { http_response_code(400); $answer['message'] = 'Invalid doc_type or id.'; exit(json_encode($answer)); } try { $posting_class = $posting_map[$doc_type]; $posting = new $posting_class($pdo2, $company_id); $built = $posting->build($id, $formula_id); $guard = new PostingWindowGuard($pdo1, $company_id); $gl = new GlManager($pdo2, $company_id, $guard); $meta = ['journal_date' => $built['doc_date'] ?? null]; $pdo2->beginTransaction(); $existing = $gl->getBySource($doc_type, $id); if ($existing) { $gl->replace($doc_type, $id, $built['formula_id'], $built['period'], $built['lines'], $meta); } else { $gl->post($doc_type, $id, $built['formula_id'], $built['period'], $built['lines'], $meta); } $pdo2->commit(); $answer['success'] = 1; $answer['message'] = $existing ? 'GL entry replaced.' : 'GL entry posted.'; $has_revenue = false; $has_expense = false; foreach ($built['lines'] as $line) { $code = (int)($line['account_code'] ?? 0); if ($code >= 4000 && $code < 5000) $has_revenue = true; if ($code >= 5000) $has_expense = true; } notify_node('gl_posted', [ 'doc_type' => $doc_type, 'id' => $id, 'action' => $existing ? 'replaced' : 'posted', 'has_revenue' => $has_revenue, 'has_expense' => $has_expense, ], $company_id); } catch (PDOException $e) { if ($pdo2->inTransaction()) $pdo2->rollBack(); error_log('[' . basename(__FILE__) . '] ' . $e->getMessage()); $answer['message'] = 'Database error, please try again.'; http_response_code(500); } catch (Exception $e) { if ($pdo2->inTransaction()) $pdo2->rollBack(); $answer['message'] = $e->getMessage(); http_response_code(400); } exit(json_encode($answer));