getOpenDocuments($contact_id); $answer['success'] = 1; exit(json_encode($answer)); } if ($action === 'save_formula') { $id = (int)($data['id'] ?? 0); $formula_id = isset($data['formula_id']) && (int)$data['formula_id'] > 0 ? (int)$data['formula_id'] : null; $mgr->saveFormula($id, $formula_id); $answer['success'] = 1; exit(json_encode($answer)); } if ($action === 'retrieve') { $receipt_id = (int)($data['id'] ?? $data['receipt_id'] ?? 0); $answer['output'] = $mgr->getReceiptById($receipt_id); $answer['success'] = 1; exit(json_encode($answer)); } if ($action === 'void') { $receipt_id = (int)($data['id'] ?? $data['receipt_id'] ?? 0); dbTransaction($pdo2, function($pdo) use ($receipt_id, $company_id, $logging) { $mgr = new ReceiptManager($pdo, $company_id); $mgr->voidReceipt($receipt_id, $logging); }); $answer['success'] = 1; $answer['message'] = 'Receipt voided.'; exit(json_encode($answer)); } if ($action === 'create') { $new_id = null; dbTransaction($pdo2, function($pdo) use ($data, $company_id, $logging, &$new_id) { $mgr = new ReceiptManager($pdo, $company_id); $new_id = $mgr->createReceipt($data, $logging); }); $answer['success'] = 1; $answer['new_id'] = $new_id; $answer['message'] = 'Receipt posted.'; (new UsageGuard($pdo1, $company_id, $packages))->increment(); require_once '../../../assets/utils/notify_node.php'; notify_node('receipt_posted', ['id' => $new_id], $company_id); // Auto-post GL try { require_once '../../../assets/utils/classes_ac/posting/BasePosting.php'; require_once '../../../assets/utils/classes_ac/posting/ReceiptPosting.php'; $sth = $pdo2->prepare("SELECT formula_id FROM td_receipt WHERE company_id = :cid AND id = :id LIMIT 1"); $sth->execute([':cid' => $company_id, ':id' => $new_id]); $row = $sth->fetch(PDO::FETCH_ASSOC); $posting = new ReceiptPosting($pdo2, $company_id); $built = $posting->build($new_id, $row['formula_id'] ?: null); $guard = new PostingWindowGuard($pdo1, $company_id); $gl = new GlManager($pdo2, $company_id, $guard); $pdo2->beginTransaction(); $gl->post('receipt', $new_id, $built['formula_id'], $built['period'], $built['lines'], ['journal_date' => $built['doc_date']]); $pdo2->commit(); notify_node('gl_posted', gl_posted_payload('receipt', (int)$new_id, 'posted', $built['lines'] ?? []), $company_id); $answer['gl_posted'] = true; } catch (Exception $e) { if ($pdo2->inTransaction()) $pdo2->rollBack(); $answer['gl_posted'] = false; $answer['gl_message'] = $e->getMessage(); error_log("auto_gl [receipt#{$new_id}]: " . $e->getMessage()); } exit(json_encode($answer)); } $answer['output'] = $mgr->getReceiptList(); $answer['success'] = 1; } catch (PDOException $e) { $answer['message'] = 'Database error, please try again.'; http_response_code(500); } catch (Exception $e) { $answer['message'] = $e->getMessage(); http_response_code(400); } exit(json_encode($answer)); ?>