Просмотр исходного кода

Add Quickbooks customer export

Alan Lam 7 лет назад
Родитель
Сommit
f20a4cb7ba

+ 7 - 2
controllers/project_export.php

@@ -44,8 +44,13 @@ switch($type) {
 		$template->exportTestsCSV("project_customer_csv.php", $tests);
 		break;
 
-	case "quickbooks":
-		Test::exportCSV("project_quickbooks_csv.php", $tests);
+	case "quickbooks-customer":
+		Project::exportCSV("project_quickbooks_customer_csv.php", $projects);
+		break;
+
+	case "quickbooks-tester":
+		Test::exportCSV("project_quickbooks_tester_csv.php", $tests);
+		break;
 
 	case "kml":
 		// TODO

+ 12 - 83
controllers/project_invoice.php

@@ -7,55 +7,19 @@ if(!$project) throw new Exception(__("Project not found."));
 if(!$project->dts_finished) throw new Exception(__("An invoice cannot be generated for this project as it has not been marked as finished."));
 if(!Core::$user->canAdmin()) throw new Exception(__("You do not have permission to access this resource."));
 
-$customer = $project->getCustomer();
-$template = $project->getTemplate();
-$invoice_fields = $template->getCustomerInvoiceFields();
-
-// Calculation
-$default_customer_fee = $project->default_customer_fee;
-$tests = $project->getTests();
-
-$invoice_field_totals = [];
-$test_fee_invoice_counts = [];
-
-$test_costs = 0;
-foreach($tests as $test) {
-
-	$values = $test->getValues(true);
-
-	$fee = $test->customer_fee ?? $default_customer_fee;
-	$test_costs += $fee;
-
-	$count = $test_fee_invoice_counts[$fee] ?? 0;
-	++$count;
-	$test_fee_invoice_counts[$fee] = $count;
+$invoice = $project->getCustomerInvoice();
 
-	foreach($invoice_fields as $field) {
-		if(!isset($invoice_field_totals[$field->name])) {
-			$invoice_field_totals[$field->name] = 0;
-		}
+$line_items = $invoice->getLineItems();
 
-		$invoice_field_totals[$field->name] += (float) ($values[$field->name] ?? 0);
-	}
-}
-
-$total_ex_vat = $test_costs + array_sum($invoice_field_totals);
-$vat = round($total_ex_vat * 0.20, 2);
-
-$total_inc_vat = $total_ex_vat + $vat;
+$customer = $project->getCustomer();
 
-// Processing
-usort($tests, function($a, $b) {
-	return $a->dts_start <=> $b->dts_start;
-});
+$total_ex_vat = $invoice->getTotal();
+$vat = $invoice->getTax();
 
-Location::load(array_column($tests, "location_id"));
-Template::load(array_column($tests, "template_id"));
+$total_inc_vat = $invoice->getTotalIncTax();
 
 // Filename
-$reference =
-	"P" . str_pad($project->id, 3, "0", STR_PAD_LEFT) .
-	"/C" . str_pad($customer->id, 3, "0", STR_PAD_LEFT);
+$reference = $invoice->getReference();
 
 $download_filename = str_replace("/", "_", $reference) . " - " . $project->name . " - Invoice.pdf";
 
@@ -190,53 +154,18 @@ ob_start();
 				</tr>
 
 				<?php
-				/*
-				foreach($tests as $test) {
-					$location = $test->getLocation();
-					$location_address = $location->getDisplayAddress(["address_1", "address_2", "city", "county", "postal_code"]);
-					?>
-
-					<tr>
-						<td>
-							<strong><?=htmlspecialchars($location->name)?></strong><br />
-							<?=nl2br(htmlspecialchars("{$location_address}\n" . date("d/m/Y H:i", strtotime($test->dts_start . " UTC"))))?>
-						</td>
-						<td align="right" valign="top">1</td>
-						<td align="right" valign="top">£<?=number_format($default_customer_fee, 2)?></td>
-						<td align="right" valign="top">£<?=number_format($default_customer_fee, 2)?></td>
-					</tr>
-					<?php
-				}
-				*/
-
-				foreach($test_fee_invoice_counts as $fee => $count) {
-					?>
-					<tr>
-						<td>
-							<strong><?=htmlspecialchars($template->name)?> Testing</strong>
-						</td>
-						<td align="right" valign="top"><?=number_format($count)?></td>
-						<td align="right" valign="top">£<?=number_format($fee, 2)?></td>
-						<td align="right" valign="top">£<?=number_format($fee * $count, 2)?></td>
-					</tr>
-					<?php
-				}
-
-				foreach($invoice_fields as $field) {
-					$total = $invoice_field_totals[$field->name] ?? 0;
-					if(!$total) continue;
+				foreach($line_items as $item) {
 					?>
 					<tr>
 						<td>
-							<strong><?=htmlspecialchars($field->label)?></strong>
+							<strong><?=htmlspecialchars($item->getName())?></strong>
 						</td>
-						<td align="center" valign="top">-</td>
-						<td align="center" valign="top">-</td>
-						<td align="right" valign="top">£<?=number_format($total, 2)?></td>
+						<td align="right" valign="top"><?=htmlspecialchars($item->getDisplayQuantity())?></td>
+						<td align="right" valign="top"><?=htmlspecialchars($item->getDisplayPrice())?></td>
+						<td align="right" valign="top"><?=htmlspecialchars($item->getDisplayTotal())?></td>
 					</tr>
 					<?php
 				}
-
 				?>
 
 				<tr>

+ 62 - 0
engine/invoice.php

@@ -0,0 +1,62 @@
+<?php
+
+/**
+ * @property InvoiceLineItem[] $lineItems
+ */
+
+class Invoice {
+
+    private $lineItems = [];
+    private $taxRate = 0.2;
+    private $reference = "";
+
+    public function addLineItem(InvoiceLineItem $item) {
+        $this->lineItems[] = $item;
+    }
+
+    public function addLineItems(array $items) {
+        foreach($items as $item) {
+            $this->addLineItem($item);
+        }
+    }
+
+    /**
+     * @return InvoiceLineItem[]
+     */
+    public function getLineItems(): array {
+        return $this->lineItems;
+    }
+
+    public function getTotal() {
+        $total = 0;
+        foreach($this->lineItems as $item) {
+            $total += $item->getTotal();
+        }
+        return $total;
+    }
+
+    public function getTaxRate(): float {
+        return $this->taxRate;
+    }
+
+    public function setTaxRate(float $tax_rate): void {
+        $this->taxRate = $tax_rate;
+    }
+
+    public function getTax() {
+        return round($this->getTotal() * $this->taxRate);
+    }
+
+    public function getTotalIncTax() {
+        return $this->getTotal() + $this->getTax();
+    }
+
+    public function setReference(string $reference): void {
+        $this->reference = $reference;
+    }
+
+    public function getReference(): string {
+        return $this->reference;
+    }
+
+}

+ 74 - 0
engine/invoice_line_item.php

@@ -0,0 +1,74 @@
+<?php
+
+/**
+ * @property string $name
+ * @property int $quantity
+ * @property float $price
+ */
+
+class InvoiceLineItem {
+
+    private $name = "Untitled Item";
+    private $quantity = 0;
+    private $price = 0;
+
+    // Static methods
+
+    // Object methods
+    public function __construct(string $name) {
+        $this->name = $name;
+    }
+
+    public function getName(): string {
+        return $this->name;
+    }
+
+    public function setName(string $name): void {
+        $this->name = $name;
+    }
+
+    public function incrementQuantity(): void {
+        ++$this->quantity;
+    }
+
+    public function getQuantity(): int {
+        return $this->quantity;
+    }
+
+    public function setQuantity(int $quantity): void {
+        $this->quantity = $quantity;
+    }
+
+    public function getDisplayQuantity(): string {
+        if($this->quantity == 0) return "-";
+        return $this->quantity;
+    }
+
+    public function addPrice(float $price): void {
+        $this->price += $price;
+    }
+
+    public function getPrice(): float {
+        return $this->price;
+    }
+
+    public function setPrice(float $price): void {
+        $this->price = $price;
+    }
+
+    public function getDisplayPrice(): string {
+        if($this->quantity == 0) return "-";
+        return "£" . number_format($this->getPrice(), 2);
+    }
+
+    public function getTotal(): float {
+        if($this->quantity == 0) return $this->price;
+        return $this->quantity * $this->price;
+    }
+
+    public function getDisplayTotal(): string {
+        return "£" . number_format($this->getTotal(), 2);
+    }
+
+
+}

+ 96 - 0
engine/project.php

@@ -39,6 +39,21 @@ class Project extends Model {
 	 */
 	protected $tests = null;
 
+	// Static methods
+	public static function exportCSV($processing_file, $projects = []) {
+
+		// Get processing file
+		$processing_file_path = ROOT_DIR . "/export_processing/{$processing_file}";
+		if(!file_exists($processing_file_path)) throw new Exception("Processing file not found.");
+
+		// Output
+		HTTP::setDownloadHeaders("export.csv");
+
+		$handle = fopen("php://output", "w");
+		require $processing_file_path;
+		fclose($handle);
+	}
+
 	// Object methods
 	/**
 	 * @return Customer
@@ -268,4 +283,85 @@ class Project extends Model {
 		return "/account/test-results/{$customer_slug}/{$project_slug}";
 	}
 
+	public function getCustomerInvoice(): Invoice {
+
+		$invoice = new Invoice;
+		$invoice->setReference($this->getInvoiceReference());
+
+		$test_line_items = $this->getTestInvoiceLineItems();
+		$field_line_items = $this->getFieldInvoiceLineItems();
+
+
+		$invoice->addLineItems($test_line_items);
+		$invoice->addLineItems($field_line_items);
+
+		return $invoice;
+
+	}
+
+	private function getInvoiceReference(): string {
+
+		$customer = $this->getCustomer();
+
+		return
+			"P" . str_pad($this->id, 3, "0", STR_PAD_LEFT) .
+			"/C" . str_pad($customer->id, 3, "0", STR_PAD_LEFT);
+	}
+
+
+	private function getTestInvoiceLineItems(): array {
+
+		/**
+		 * @var InvoiceLineItem[] $items
+		 */
+
+		$template = $this->getTemplate();
+
+		$default_customer_fee = $this->default_customer_fee;
+		$tests = $this->getTests();
+
+		$items = [];
+
+		foreach($tests as $test) {
+
+			$fee = $test->customer_fee ?? $default_customer_fee;
+
+			$item = $items[$fee] ?? null;
+
+			if(!$item) {
+				$item = new InvoiceLineItem(__("%s Testing", $template->name));
+				$item->setPrice($fee);
+			}
+
+			$item->incrementQuantity();
+
+			$items[$fee] = $item;
+
+		}
+
+		return array_values($items);
+	}
+
+	private function getFieldInvoiceLineItems(): array {
+
+		$template = $this->getTemplate();
+		$invoice_fields = $template->getCustomerInvoiceFields();
+
+		$tests = $this->getTests();
+
+		$items = [];
+
+		foreach($tests as $test) {
+			$values = $test->getValues(true);
+
+			foreach($invoice_fields as $field) {
+				$item = $items[$field->name] ?? (new InvoiceLineItem($field->label));
+				$item->addPrice((float) $values[$field->name] ?? 0);
+				$items[$field->name] = $item;
+			}
+		}
+
+		return $items;
+	}
+
 }

+ 71 - 0
export_processing/project_quickbooks_customer_csv.php

@@ -0,0 +1,71 @@
+<?php
+
+/**
+ * @var Project[] $projects
+ */
+
+$utc_timezone = new DateTimeZone("UTC");
+$invoice_interval = new DateInterval("P30D");
+
+$current_dt = new DateTime();
+$date = $current_dt->format("d/m/Y");
+
+$field_names = [
+	"Invoice No",
+	"Customer",
+	"Invoice Date",
+	"Due Date",
+	"Terms",
+	"Location",
+	"Memo",
+	"Item (Product/Service)",
+	"Item Description",
+	"Item Quantity",
+	"Item Rate",
+	"Item Amount",
+	"Item Tax Code",
+	"Item Tax Amount",
+	"Service Date",
+];
+
+fputcsv($handle, $field_names);
+
+foreach($projects as $project) {
+
+    if($project->dts_finished === null) continue;
+
+    $customer = $project->getCustomer();
+
+    $invoice = $project->getCustomerInvoice();
+    $line_items = $invoice->getLineItems();
+
+    $invoice_generated_dt = new DateTime($project->dts_finished, $utc_timezone);
+    $invoice_date = $invoice_generated_dt->format("d/m/Y");
+
+    $invoice_generated_dt->add($invoice_interval);
+	$invoice_due_date = $invoice_generated_dt->format("d/m/Y");
+
+    foreach($line_items as $item) {
+
+		$output = [];
+
+		$output[] = $invoice->getReference(); // "Invoice No",
+		$output[] = $customer->name; // "Customer",
+		$output[] = $invoice_date; // "Invoice Date",
+		$output[] = $invoice_due_date; // "Due Date",
+		$output[] = "Net 30"; // "Terms",
+		$output[] = ""; // "Location",
+		$output[] = "{$project->id} {$project->name}"; // "Memo",
+		$output[] = $item->getName(); // "Item (Product/Service)",
+		$output[] = ""; // "Item Description",
+		$output[] = $item->getQuantity() ?: "1"; // "Item Quantity",
+		$output[] = $item->getPrice(); // "Item Rate",
+		$output[] = $item->getTotal(); // "Item Amount",
+		$output[] = ($invoice->getTaxRate() * 100) . "%"; // "Item Tax Code",
+		$output[] = $invoice->getTaxRate() * $item->getTotal(); // "Item Tax Amount",
+		$output[] = $date; // "Service Date",
+
+		fputcsv($handle, $output);
+
+    }
+}

+ 0 - 0
export_processing/project_quickbooks_csv.php → export_processing/project_quickbooks_tester_csv.php


+ 7 - 2
public/js/app-projects.js

@@ -23,9 +23,14 @@ $(function() {
 				$("#type").val("customer");
 				break;
 
-			case "export-quickbooks-csv":
+			case "export-quickbooks-customer-csv":
 				$("#projects-form").attr("action", "/account/projects/export-csv");
-				$("#type").val("quickbooks");
+				$("#type").val("quickbooks-customer");
+				break;
+
+			case "export-quickbooks-tester-csv":
+				$("#projects-form").attr("action", "/account/projects/export-csv");
+				$("#type").val("quickbooks-tester");
 				break;
 		}
 	});

+ 2 - 1
views/projects.php

@@ -91,7 +91,8 @@
 						<option value="">Select Action</option>
 						<option value="export-admin-csv">Export CSV</option>
 						<option value="export-customer-csv">Export Customer CSV</option>
-						<option value="export-quickbooks-csv">Export Quickbooks CSV</option>
+						<option value="export-quickbooks-customer-csv">Export Quickbooks Customer CSV</option>
+						<option value="export-quickbooks-tester-csv">Export Quickbooks Tester CSV</option>
 					</select>
 					<div class="input-group-append">
 						<button type="submit" class="btn btn-primary" name="submit" value="<?=htmlspecialchars($_SESSION["csrf_token"])?>">