Files
html/api/invoice-api.php

56 lines
2.6 KiB
PHP

<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
$action = $_GET["action"] ?? $_POST["action"] ?? "list";
$db_file = "/opt/weval-data/invoices.json";
if (!file_exists(dirname($db_file))) @mkdir(dirname($db_file), 0755, true);
if (!file_exists($db_file)) file_put_contents($db_file, "[]");
$invoices = json_decode(file_get_contents($db_file), true) ?: [];
switch ($action) {
case "list":
echo json_encode(["ok"=>true,"count"=>count($invoices),"invoices"=>$invoices]);
break;
case "create":
$seq = count($invoices) + 1;
$inv = [
"id" => "FAC-" . date("Y") . "-" . str_pad($seq, 4, "0", STR_PAD_LEFT),
"client" => $_POST["client"] ?? "",
"entity" => $_POST["entity"] ?? "WEVAL Consulting SARL",
"ice" => $_POST["entity"] === "LLC" ? "" : "003267890000012",
"if_code" => "50429871",
"lines" => json_decode($_POST["lines"] ?? "[]", true) ?: [],
"subtotal_ht" => floatval($_POST["subtotal_ht"] ?? 0),
"tva_rate" => 20,
"tva_amount" => floatval($_POST["subtotal_ht"] ?? 0) * 0.20,
"total_ttc" => floatval($_POST["subtotal_ht"] ?? 0) * 1.20,
"currency" => $_POST["currency"] ?? "MAD",
"status" => "draft", // draft, sent, paid, overdue, cancelled
"due_date" => $_POST["due_date"] ?? date("Y-m-d", strtotime("+30 days")),
"payment_terms" => $_POST["payment_terms"] ?? "30 jours fin de mois",
"bank" => "BMCE Bank, Agence Casablanca, RIB: 011780000017820000784",
"created_at" => date("c"),
];
$invoices[] = $inv;
file_put_contents($db_file, json_encode($invoices, JSON_PRETTY_PRINT));
echo json_encode(["ok"=>true,"invoice"=>$inv]);
break;
case "stats":
$total_ht = 0; $total_paid = 0; $total_pending = 0; $overdue = 0;
foreach ($invoices as $inv) {
$total_ht += $inv["subtotal_ht"];
if ($inv["status"] === "paid") $total_paid += $inv["total_ttc"];
elseif ($inv["status"] === "sent") $total_pending += $inv["total_ttc"];
if ($inv["status"] === "sent" && strtotime($inv["due_date"]) < time()) $overdue++;
}
echo json_encode(["ok"=>true,"total"=>count($invoices),"total_ht"=>$total_ht,
"total_paid"=>$total_paid,"total_pending"=>$total_pending,"overdue"=>$overdue,
"by_status"=>array_count_values(array_column($invoices,"status"))]);
break;
default:
echo json_encode(["ok"=>false,"actions"=>["list","create","stats"]]);
}
?>