HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers10/farmfun.komma.pro/app/Komma/Shop/Orders/CreditInvoiceNumberSequence.php
<?php

namespace App\Komma\Shop\Orders;

use App\Komma\Kms\Core\Sequence\Parts\NumberPart;
use App\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;
    }
}