WIP Contract/Billing/Invoice 2024-06-28

This commit is contained in:
Frank Schubert
2024-07-01 11:44:19 +02:00
parent 4589e61ab8
commit ae298a0665
30 changed files with 1898 additions and 212 deletions
+60
View File
@@ -0,0 +1,60 @@
<?php
class Invoice extends mfBaseModel {
private $positions;
public function getProperty($name) {
if($this->$name == null) {
if(!$this->id) {
return null;
}
if($name == "positions") {
$positions = InvoicepositionModel::search(["invoice_id" => $this->id]);
$this->positions = $positions;
return $this->positions;
}
if($name == "creator") {
$this->creator = mfValuecache::singleton()->get("Worker-id-".$this->create_by);
if($this->creator === null) {
$this->creator = new User($this->create_by);
if($this->creator->id) {
mfValuecache::singleton()->set("Worker-id-".$this->create_by, $this->creator);
}
}
return $this->creator;
}
if($name == "editor") {
$this->editor = mfValuecache::singleton()->get("Worker-id-".$this->edit_by);
if($this->editor === null) {
$this->editor = new User($this->edit_by);
if($this->editor->id) {
mfValuecache::singleton()->set("Worker-id-".$this->edit_by, $this->editor);
}
}
return $this->editor;
}
$classname = ucfirst($name);
$idfield = $name."_id";
$this->$name = mfValuecache::singleton()->get("mfObjectmodel-$name-".$this->$idfield);
if(!$this->$name) {
$this->$name = new $classname($this->$idfield);
}
if($this->$name->id) {
mfValuecache::singleton()->set("mfObjectmodel-$name-".$this->$name->id, $this->$name);
return $this->$name;
} else {
return null;
}
}
return $this->$name;
}
}
+345
View File
@@ -0,0 +1,345 @@
<?php
class InvoiceController extends mfBaseController {
protected function init()
{
$this->needlogin = true;
$me = new User();
$me->loadMe();
$this->me = $me;
$this->layout()->set("me", $me);
if (!$me->is(["Admin"])) {
$this->redirect("Dashboard");
}
}
protected function indexAction() {
$this->layout()->setTemplate("Invoice/Index");
if ($this->request->resetFilter) {
unset($_SESSION[MFAPPNAME . '-Invoice-filter']);
}
$filter = [];
if (is_array($this->request->filter)) {
$filter = $this->request->filter;
$_SESSION[MFAPPNAME . '-Invoice-filter'] = $filter;
} else {
if (array_key_exists(MFAPPNAME . '-Invoice-filter', $_SESSION) && count($_SESSION[MFAPPNAME . '-Invoice-filter'])) {
$filter = $_SESSION[MFAPPNAME . '-Invoice-filter'];
}
}
$this->layout->set("filter", $filter);
$filter = $this->getPreparedFilter($filter);
// pagination defaults
$pagination = [];
$pagination['start'] = 0;
$pagination['count'] = 50;
$pagination['maxItems'] = 0;
if(is_numeric($this->request->s)) {
$pagination['start'] = intval($this->request->s);
}
//var_dump($filter);exit;
$pagination['maxItems'] = InvoiceModel::count($filter);
$billings = InvoiceModel::search($filter, $pagination);
$this->layout()->set("invoices", $billings);
$this->layout()->set("pagination", $pagination);
}
private function getPreparedFilter($filter)
{
$new_filter = [];
if(array_key_exists("customer", $filter)) {
if(array_key_exists("customer", $filter) && $filter["customer"]) {
$kunde = $this->db()->escape($filter['customer']);
if(!array_key_exists("add-where", $new_filter)) $new_filter["add-where"] = "";
$new_filter['add-where'] .= " AND (company like '%$kunde%' OR firstname like '%$kunde%' OR lastname like '%$kunde%' OR concat(firstname, ' ', lastname) like '%$kunde%' OR concat(lastname, ' ', firstname) like '%$kunde%')";
}
}
if(array_key_exists("address", $filter)) {
if(array_key_exists("address", $filter) && $filter["address"]) {
$search = $this->db()->escape($filter['address']);
if(!array_key_exists("add-where", $new_filter)) $new_filter["add-where"] = "";
$new_filter['add-where'] .= " AND (street like '%$search%' OR zip like '%$search%' OR city like '%$search%' OR country like '%$search%')";
}
}
if (is_array($filter) && count($filter)) {
foreach ($filter as $name => $value) {
$new_filter[$name] = $value;
}
}
return $new_filter;
}
protected function downloadInvoice() {
$id = $this->request->id;
if (!is_numeric($id) || !$id) {
$this->layout()->setFlash("Rechnung nicht gefunden", "error");
$this->redirect("Invoice");
}
$invoice = new Invoice($id);
if (!$invoice->id) {
$this->layout()->setFlash("Rechnung nicht gefunden", "error");
$this->redirect("Rechnung");
}
$vat = [];
foreach($invoice->positions as $p) {
if(!array_key_exists($p->vatrate, $vat)) {
$vat[$p->vatrate] = 0;
}
$vat[$p->vatrate] += $p->price_gross - $p->price;
}
$pdf_vars = [
"invoice" => $invoice,
"vat" => $vat
];
/*$this->layout()->setTemplate("Invoice/Print.pdf");
$this->layout()->set("invoice", $invoice);
$this->layout()->set("vat", $vat);
$this->layout()->set("ressourcePathPrefix", MFFANCYBASEURL."/");
return true;*/
$pdf = new PdfForm("Invoice/Print.pdf", $pdf_vars);
//$pdfpath = $pdf->render();
$pdf->download($invoice->invoice_number.".pdf");
}
protected function runInvoicingAction() {
$i = 0;
$p = 0;
// get pairs of owner_id and billingaddress_id, so each will be its own invoice
foreach(BillingModel::getInvoiceBaseData(['invoice_id' => null]) as $base) {
//var_dump($base); continue;
$owner_id = $base["owner_id"];
$billingaddress_id = $base["billingaddress_id"];
$billing_type = $base["billing_type"];
$billing_delivery = $base["billing_delivery"];
$bill_positions = [];
$credit_positions = [];
$billing_rows = BillingModel::search([
"owner_id" => $owner_id,
"billingaddress_id" => $billingaddress_id,
"billing_type" => $billing_type,
"billing_delivery" => $billing_delivery,
"invoice_id" => null]);
if(!count($billing_rows)) {
die("Keine nicht verrechneten Billing records für billingaddress_id");
}
//var_dump($owner_id, $billingaddress_id, $bills);exit;
$invoice_data = [];
foreach($billing_rows as $bill) {
$vatrate = $bill->vatrate;
$price = $bill->price;
$price_total = $bill->price * $bill->amount;
$price_gross = ($vatrate) ? $price_total + ($price_total / 100) * $vatrate : $price_total;
$price_setup = $bill->price_setup;
$price_setup_total = $bill->price_setup * $bill->amount;
$price_setup_gross = ($vatrate) ? $price_setup_total + ($price_setup_total / 100) * $vatrate : $price_setup_total;
$add_setup_position = ($price > 0 && $price_setup > 0);
$is_setup_only = ($price < 0.00001 && $price_setup > 0);
$position_data = [];
$position_data["billing_id"] = $bill->id;
$position_data["contract_id"] = $bill->contract_id;
$position_data["start_date"] = $bill->start_date;
$position_data["end_date"] = $bill->end_date;
$position_data["matchcode"] = $bill->matchcode;
$position_data["product_id"] = $bill->product_id;
$position_data["product_name"] = $bill->product_name;
$position_data["product_info"] = $bill->product_info;
$position_data["amount"] = $bill->amount;
$position_data["billing_period"] = $bill->billing_period;
if($is_setup_only) {
$this->log->debug("Contract ID ". $bill->contract_id." is setup only");
$position_data["price"] = $price_setup;
$position_data["price_total"] = $price_setup_total;
$position_data["price_gross"] = $price_setup_gross;
$position_data["vatrate"] = $vatrate;
$position_data["end_date"] = $position_data["start_date"];
} else {
$position_data["price"] = $price;
$position_data["price_total"] = $price_total;
$position_data["price_gross"] = $price_gross;
$position_data["vatrate"] = $vatrate;
}
$new_position = InvoicepositionModel::create($position_data);
$bill_positions[] = $new_position;
if($add_setup_position) {
$this->log->debug("Adding Setup Invoiceposition for Contract ID ". $bill->contract_id);
$setup_data = $position_data;
$setup_data["product_name"] = "Herstellungskosten ".$bill->product_name;
$setup_data["product_info"] = "";
$setup_data["price"] = $price_setup;
$setup_data["price_total"] = $price_setup * $bill->amount;
$setup_data["price_gross"] = $price_setup_gross;
$setup_data["vatrate"] = $vatrate;
$setup_data["end_date"] = $setup_data["start_date"];
$setup_position = InvoicepositionModel::create($setup_data);
$bill_positions[] = $setup_position;
}
/*if($bill->price >= 0 || $bill->price_setup >= 0) {
$bill_positions[] = InvoicepositionModel::create($position_data);
} else {
$credit_positions[] = InvoicepositionModel::create($position_data);;
}*/
$invoice_data["owner_id"] = $owner_id;
$invoice_data["billingaddress_id"] = $billingaddress_id;
$invoice_data["customer_number"] = $bill->customer_number;
$invoice_data["company"] = $bill->company;
$invoice_data["firstname"] = $bill->firstname;
$invoice_data["lastname"] = $bill->lastname;
$invoice_data["street"] = $bill->street;
$invoice_data["zip"] = $bill->zip;
$invoice_data["city"] = $bill->city;
$invoice_data["country"] = $bill->country;
$invoice_data["email"] = $bill->email;
$invoice_data["uid"] = $bill->uid;
$invoice_data["billing_type"] = $billing_type;
$invoice_data["billing_delivery"] = $billing_delivery;
$invoice_data["bank_account_bank"] = $bill->bank_account_bank;
$invoice_data["bank_account_owner"] = $bill->bank_account_owner;
$invoice_data["bank_account_iban"] = $bill->bank_account_iban;
$invoice_data["bank_account_bic"] = $bill->bank_account_bic;
$invoice_data["total"] = 0;
$invoice_data["total_gross"] = 0;
$invoice_data["total_vat"] = 0;
}
//var_dump($bill_positions, $credit_positions);exit;
// create Invoice
$invoice = InvoiceModel::create($invoice_data);
$invoice->startTransaction();
try {
if(!$invoice->save()) {
$invoice->rollbackTransaction();
die("Error saving Invoice");
}
$total_net = 0;
$total_gross = 0;
$total_vat = 0;
foreach($bill_positions as $position) {
// on error: rollback transaction
// add Invoice::id to Invoiceposition
$position->invoice_id = $invoice->id;
if(!$position->vatrate) {
$total_net += $position->price_total;
} else {
$total_vat += ($position->price_total / 100) * $position->vatrate;
$total_net += $position->price_total;
$total_gross += $position->price_gross;
}
// save Invoiceposition
if(!$position->save()) {
$invoice->rollbackTransaction();
die("Error saving Invoiceposition");
}
// ad Invoice::id to Bill
$bill = new Billing($position->billing_id);
if(!$bill->id) {
$invoice->rollbackTransaction();
die("Bill for Invoiceposition not found");
}
$bill->invoice_id = $invoice->id;
if(!$bill->save()) {
$invoice->rollbackTransaction();
die("error saving invoice_id to bill");
}
$p++;
}
$invoice->total = $total_net;
$invoice->total_gross = $total_gross;
$invoice->total_vat = $total_vat;
if(!$invoice->save()) {
$invoice->rollbackTransaction();
die("Error saving totals in Invoice");
}
// generate Invoice number
$new_num = InvoiceModel::getNextInvoiceNUmber();
$invoice->invoice_number = $new_num;
$invoice->invoice_date = date("U");
if(!$invoice->save()) {
$invoice->rollbackTransaction();
die("Error saving Invoice number and date");
}
// commit transaction
$invoice->commitTransaction();
$i++;
} catch (Exception $e) {
if($invoice) {
$invoice->rollbackTransaction();
}
die("Error saving Invoice!\n");
}
// Create Invoice PDF
// if billing_delivery == paper -> add to pdf collection
// else -> send by email
//var_dump($invoice);
//exit;
}
$this->layout()->setFlash("$i Rechnungen mit $p Rechnungspositionen erstellt");
$this->redirect("Invoice");
}
}
+340
View File
@@ -0,0 +1,340 @@
<?php
class InvoiceModel {
public $invoice_number;
public $invoice_date;
public $billingaddress_id;
public $customer_number;
public $company;
public $firstname;
public $lastname;
public $street;
public $zip;
public $city;
public $country;
public $email;
public $uid;
public $billing_type;
public $billing_delivery;
public $bank_account_bank;
public $bank_account_owner;
public $bank_account_iban;
public $bank_account_bic;
public $total;
public $total_gross;
public $total_vat;
public $create_by;
public $edit_by;
public $create;
public $edit;
public static function create(Array $data) {
$model = new Invoice();
foreach($data as $field => $value) {
if(property_exists(get_called_class(), $field)) {
$model ->$field = $value;
}
}
$me = new User();
$me->loadMe();
if($model->create_by === null) {
$model->create_by = $me->id;
}
if($model->edit_by === null) {
$model->edit_by = $me->id;
}
return $model;
}
public static function getNextInvoiceNUmber() {
$last_invoice_num = self::getLastInvoiceNumber();
if(!$last_invoice_num) {
return TT_FIRST_INVOICE_NUM;
}
$year_part = 0;
$num_part = 0;
$m = [];
if(preg_match('/^RN(\d+)-X(\d+)$/', $last_invoice_num, $m)) {
if(array_key_exists(1, $m)) {
$year_part = $m[1];
if(array_key_exists(2, $m)) {
$num_part = $m[2];
}
}
}
if(!$year_part || !$num_part) {
die("NO LAST INVOICE NUMBER!!!");
}
//var_dump($year_part, $num_part);exit;
if(date("Y") == $year_part) {
$new_year_part = $year_part;
$new_num_part = $num_part + 1;
} else {
$new_year_part = date("Y");
$new_num_part = 1;
}
$new_invoice_num = "RN$new_year_part-X".str_pad($new_num_part,"6", "0", STR_PAD_LEFT);
return $new_invoice_num;
}
public static function getLastInvoiceNumber() {
$last_invoice = self::getLast(["invoice_number" => true]);
if(!$last_invoice || !$last_invoice->invoice_number) {
return false;
}
return $last_invoice->invoice_number;
}
public static function getAll() {
$items = [];
$db = FronkDB::singleton();
$res = $db->select("Invoice", "*", "1 = 1 ORDER BY invoice_number");
if($db->num_rows($res)) {
while($data = $db->fetch_object($res)) {
$items[] = new Invoice($data);
}
}
return $items;
}
public static function getFirst($filter) {
$db = FronkDB::singleton();
$where = self::getSqlFilter($filter);
$sql = "SELECT * FROM Invoice
WHERE $where
ORDER BY invoice_number LIMIT 1";
//var_dump($sql);exit;
$res = $db->query($sql);
if($db->num_rows($res)) {
$data = $db->fetch_object($res);
$item = new Invoice($data);
if($item->id) {
return $item;
} else {
return null;
}
}
return null;
}
public static function getLast($filter) {
$db = FronkDB::singleton();
$where = self::getSqlFilter($filter);
$sql = "SELECT * FROM Invoice
WHERE $where
ORDER BY invoice_number DESC LIMIT 1";
//mfLoghandler::singleton()->debug($sql);
$res = $db->query($sql);
if($db->num_rows($res)) {
$data = $db->fetch_object($res);
$item = new Invoice($data);
if($item->id) {
return $item;
} else {
return null;
}
}
return null;
}
public static function count($filter) {
$db = FronkDB::singleton();
$where = self::getSqlFilter($filter);
$sql = "SELECT COUNT(*) as cnt FROM Invoice
WHERE $where";
//mfLoghandler::singleton()->debug($sql);
$res = $db->query($sql);
if($db->num_rows($res)) {
$data = $db->fetch_object($res);
return $data->cnt;
}
return 0;
}
public static function search($filter, $limit = false, $order = false) {
//var_dump($filter);exit;
$items = [];
if(!$order) {
$order = "invoice_number ASC";
}
$db = FronkDB::singleton();
$where = self::getSqlFilter($filter);
$sql = "SELECT * FROM Invoice
WHERE $where
ORDER BY $order";
if(is_array($limit) && count($limit)) {
if(is_numeric($limit['start']) && is_numeric($limit['count'])) {
$sql .= " LIMIT ".$limit['start'].", ".$limit['count'];
} elseif(is_numeric($limit['count'])) {
$sql .= " LIMIT ".$limit['count'];
}
}
mfLoghandler::singleton()->debug($sql);
$res = $db->query($sql);
if($db->num_rows($res)) {
while($data = $db->fetch_object($res)) {
$items[$data->id] = new Invoice($data);
}
}
return $items;
}
private static function getSqlFilter($filter) {
$where = "1=1 ";
$db = FronkDB::singleton();
//var_dump($filter);exit;
if(array_key_exists("id", $filter)) {
$id = $filter['id'];
if(is_numeric($id)) {
$where .= " AND Invoice.id like '%$id%'";
}
}
if(array_key_exists("invoice_number", $filter)) {
$invoice_number = $filter['invoice_number'];
if($invoice_number === true) {
$where .= " AND Invoice.invoice_number IS NOT NULL AND Invoice.invoice_number <> ''";
} elseif($invoice_number) {
$invoice_number = $db->escape($invoice_number);
$where .= " AND Invoice.invoice_number='$invoice_number'";
} elseif($invoice_number === null || $invoice_number === false) {
$where .= " AND Invoice.invoice_number IS NULL";
}
}
if(array_key_exists("invoice_date", $filter)) {
$invoice_date = $filter['invoice_date'];
if($invoice_date) {
$where .= " AND Invoice.invoice_date='$invoice_date'";
} elseif($invoice_date === null || $invoice_date === false) {
$where .= " AND Invoice.invoice_date IS NULL";
}
}
if(array_key_exists("billingaddress_id", $filter)) {
$Invoiceaddress_id = $filter['billingaddress_id'];
if(is_numeric($Invoiceaddress_id)) {
$where .= " AND Invoice.billingaddress_id=$Invoiceaddress_id";
}
}
if(array_key_exists("customer_number", $filter)) {
$customer_number = $filter['customer_number'];
if(is_numeric($customer_number)) {
$where .= " AND Invoice.customer_number LIKE $customer_number";
}
}
if (array_key_exists("company", $filter)) {
$company = FronkDB::singleton()->escape($filter["company"]);
if ($company) {
$where .= " AND company like '%$company%'";
}
}
if (array_key_exists("firstname", $filter)) {
$firstname = FronkDB::singleton()->escape($filter["firstname"]);
if ($firstname) {
$where .= " AND firstname like '%$firstname%'";
}
}
if (array_key_exists("lastname", $filter)) {
$lastname = FronkDB::singleton()->escape($filter["lastname"]);
if ($lastname) {
$where .= " AND lastname like '%$lastname%'";
}
}
if (array_key_exists("mergedName", $filter)) {
$name = FronkDB::singleton()->escape($filter["mergedName"]);
if ($name) {
$where .= " AND (CONCAT(firstname, ' ', lastname) like '%$name%' OR CONCAT(lastname, ' ', firstname) like '%$name%' )";
}
}
if (array_key_exists("street", $filter)) {
$street = FronkDB::singleton()->escape($filter["street"]);
if ($street) {
$where .= " AND street like '%$street%'";
}
}
if (array_key_exists("zip", $filter)) {
$zip = FronkDB::singleton()->escape($filter["zip"]);
if ($zip) {
$where .= " AND zip like '%$zip%'";
}
}
if (array_key_exists("city", $filter)) {
$city = FronkDB::singleton()->escape($filter["city"]);
if ($city) {
$where .= " AND city like '%$city%'";
}
}
if (array_key_exists("country", $filter)) {
$country = FronkDB::singleton()->escape($filter["country"]);
if ($country) {
$where .= " AND country like '%$country%'";
}
}
if (array_key_exists("email", $filter)) {
$email = FronkDB::singleton()->escape($filter["email"]);
if ($email) {
$where .= " AND email like '%$email%'";
}
}
if(array_key_exists("add-where", $filter)) {
$where .= " ".$filter['add-where'];
}
if(array_key_exists("Invoice_period", $filter)) {
$Invoice_period = $filter['Invoice_period'];
if(is_numeric($Invoice_period)) {
$where .= " AND Invoice.Invoice_period = $Invoice_period";
}
}
//var_dump($filter, $where);exit;
return $where;
}
}