File: D:/HostingSpaces/SBogers10/shop.komma.nl/app/Orders/CreditInvoiceNumberSequence.php
<?php
namespace App\Orders;
use Komma\KMS\Core\Sequence\Parts\NumberPart;
use Komma\KMS\Core\Sequence\Sequence;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
/**
* Defines an credit invoice number
*/
class CreditInvoiceNumberSequence extends Sequence
{
public function __construct()
{
parent::__construct();
//Define how an invoice number looks like
$this->startsWith('C') //C to indicate that it is an credit invoice number
->followedBy(new NumberPart(4, 'year'))
->followedBy(new NumberPart(5, 'number'));
//Define its starting number when the orders table is empty
$this->startingAt('C'.Carbon::now()->year.'00001');
//The table and column the in this case "order number" is meant for. Checks uniqueness and starts the sequence from the latest order number if present
$this->uniqueForTable('orders', 'credit_invoice_number');
//Force the year part to be the current year, even if the latest order for the table is a different year
$this->getPartByName('year')->startingAt(Carbon::now()->year);
}
/**
* @param string $table
* @param string $column
* @return $this
*/
public function uniqueForTable(string $table, string $column) {
$this->table = $table;
$this->column = $column;
$latestRecords = DB::table($table)->whereNotNull($column)->orderBy($this->column, 'DESC')->limit(1)->get([$column]); //We cannot simply get the last one by id because not all orders will have a credit invoice number :).
if($latestRecords->count() == 1) {
$latestSequenceValueFromTable = $latestRecords[0]->$column;
$this->startingAt($latestSequenceValueFromTable);
}
return $this;
}
}