|
@@ -52,29 +52,26 @@ class AccountCode
|
52
|
52
|
public static function generate(int $companyId, string $subtypeId): string
|
53
|
53
|
{
|
54
|
54
|
$subtype = AccountSubtype::find($subtypeId);
|
55
|
|
- $type = $subtype->type;
|
|
55
|
+ $subtypeName = $subtype->name;
|
|
56
|
+ $typeEnum = $subtype->type;
|
|
57
|
+ $typeValue = $typeEnum->value;
|
56
|
58
|
|
57
|
|
- $range = self::getRangeForType($type);
|
|
59
|
+ $baseCode = config("chart-of-accounts.default.{$typeValue}.{$subtypeName}.base_code");
|
|
60
|
+ $range = self::getRangeForType($typeEnum);
|
58
|
61
|
|
59
|
62
|
$lastAccount = Account::where('subtype_id', $subtypeId)
|
60
|
63
|
->where('company_id', $companyId)
|
|
64
|
+ ->whereNotNull('code')
|
61
|
65
|
->orderBy('code', 'desc')
|
62
|
|
- ->first(); // maybe handle subaccounts (parent-child) in the future (not using max() because of subaccounts)
|
|
66
|
+ ->first();
|
63
|
67
|
|
64
|
|
- if ($lastAccount) {
|
65
|
|
- $lastCode = $lastAccount->code;
|
66
|
|
- $lastAccountPart = explode('-', $lastCode)[0]; // possibly handle subaccounts (parent-child) in the future
|
67
|
|
- $numericValue = (int) $lastAccountPart;
|
68
|
|
- $numericValue++;
|
69
|
|
- } else {
|
70
|
|
- $numericValue = $range[0];
|
71
|
|
- }
|
|
68
|
+ $numericValue = $lastAccount ? (int) explode('-', $lastAccount->code)[0] + 1 : (int) $baseCode;
|
72
|
69
|
|
|
70
|
+ // Ensure the new code does not exist and is within the acceptable range
|
73
|
71
|
while (Account::where('company_id', $companyId)->where('code', '=', (string) $numericValue)->exists() || $numericValue > $range[1]) {
|
74
|
72
|
if ($numericValue > $range[1]) {
|
75
|
|
- throw new RuntimeException('No more account codes available for this type.');
|
|
73
|
+ throw new RuntimeException('No more account codes available within the allowed range for this type.');
|
76
|
74
|
}
|
77
|
|
-
|
78
|
75
|
$numericValue++;
|
79
|
76
|
}
|
80
|
77
|
|