gruene-seele/app/Repositories/InvoiceRepository.php
2022-04-14 13:21:17 +02:00

103 lines
No EOL
3.5 KiB
PHP

<?php
namespace App\Repositories;
use PDF;
use Storage;
use App\Models\ShoppingOrder;
use App\Services\Invoice;
use App\Services\MyPDFMerger;
class InvoiceRepository extends BaseRepository {
private $invoice_date;
private $invoice_number;
private $filename;
private $dir;
public function __construct(ShoppingOrder $model)
{
$this->model = $model;
}
public function create($request = [])
{
//need invoice $data
$number = Invoice::getInvoiceNumber();
$this->invoice_date = isset($request['invoice_date']) ? $request['invoice_date'] : $this->model->created_at->format("d.m.Y");
$invoice_send_mail = isset($request['invoice_send_mail']) ? true: false;
$this->invoice_number = Invoice::createInvoiceNumber($number, $this->invoice_date);
$this->dir = Invoice::getInvoiceStorageDir($this->invoice_date);
$this->filename = Invoice::makeInvoiceFilename($this->invoice_number);
$this->makePDF();
$data_file = [
'filename' => $this->filename,
'dir' => $this->dir,
'disk' => 'public',
'invoice_number' => $this->invoice_number,
'invoice_date' => $this->invoice_date,
];
$this->model->invoice = $data_file;
$this->model->invoice_number = $this->invoice_number;
$this->model->save();
Invoice::makeNextInvoiceNumber();
if($invoice_send_mail){
Invoice::sendInvoiceMail($this->model);
}
return true;
}
public function update($request = []){
if(isset($this->model->invoice['filename'])){
$this->invoice_date = isset($request['invoice_date']) ? $request['invoice_date'] : Invoice::getDate($this->model);
$invoice_send_mail = isset($request['invoice_send_mail']) ? true: false;
$this->invoice_number = Invoice::getNumber($this->model);
$this->dir = Invoice::getDir($this->model);
$this->filename = Invoice::getFilename($this->model);
$this->makePDF();
$data_file = [
'filename' => $this->filename,
'dir' => $this->dir,
'disk' => 'public',
'invoice_number' => $this->invoice_number,
'invoice_date' => $this->invoice_date,
];
$this->model->invoice = $data_file;
$this->model->invoice_number = $this->invoice_number;
$this->model->save();
if($invoice_send_mail){
Invoice::sendInvoiceMail($this->model);
}
return true;
}
return null;
}
private function makePDF(){
$data = [
'shopping_order' => $this->model,
'invoice_date' => $this->invoice_date,
'invoice_number' => $this->invoice_number,
];
$pdf = PDF::loadView('pdf.invoice', $data);
$pdf->setPaper('A4', 'portrait');
if(!Storage::disk('public')->exists( $this->dir )){
Storage::disk('public')->makeDirectory($this->dir); //creates directory
}
$path = Storage::disk('public')->getAdapter()->getPathPrefix();
$pdf->save($path.$this->dir.$this->filename);
$pdfMerger = new MyPDFMerger();
$pdfMerger->addPDF($path.$this->dir.$this->filename);
$file = $pdfMerger->myMerge('string', $this->filename, 'template_invoice_de');
Storage::disk('public')->put($this->dir.$this->filename, $file);
}
}