Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewdwallo committed Dec 15, 2024
1 parent 98707e8 commit 4926a07
Show file tree
Hide file tree
Showing 16 changed files with 205 additions and 135 deletions.
17 changes: 9 additions & 8 deletions app/Concerns/ManagesLineItems.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Concerns;

use App\Enums\Accounting\AdjustmentComputation;
use App\Enums\Accounting\DocumentDiscountMethod;
use App\Models\Accounting\DocumentLineItem;
use App\Models\Accounting\Invoice;
use App\Utilities\Currency\CurrencyConverter;
Expand Down Expand Up @@ -49,22 +50,22 @@ protected function deleteRemovedLineItems(Invoice $record, Collection $lineItems
}
}

protected function handleLineItemAdjustments(DocumentLineItem $lineItem, array $itemData, string $discountMethod): void
protected function handleLineItemAdjustments(DocumentLineItem $lineItem, array $itemData, DocumentDiscountMethod $discountMethod): void
{
$adjustmentIds = collect($itemData['salesTaxes'] ?? [])
->merge($discountMethod === 'line_items' ? ($itemData['salesDiscounts'] ?? []) : [])
->merge($discountMethod->isPerLineItem() ? ($itemData['salesDiscounts'] ?? []) : [])
->filter()
->unique();

$lineItem->adjustments()->sync($adjustmentIds);
$lineItem->refresh();
}

protected function updateLineItemTotals(DocumentLineItem $lineItem, string $discountMethod): void
protected function updateLineItemTotals(DocumentLineItem $lineItem, DocumentDiscountMethod $discountMethod): void
{
$lineItem->updateQuietly([
'tax_total' => $lineItem->calculateTaxTotal()->getAmount(),
'discount_total' => $discountMethod === 'line_items'
'discount_total' => $discountMethod->isPerLineItem()
? $lineItem->calculateDiscountTotal()->getAmount()
: 0,
]);
Expand All @@ -75,7 +76,7 @@ protected function updateInvoiceTotals(Invoice $record, array $data): array
$subtotalCents = $record->lineItems()->sum('subtotal');
$taxTotalCents = $record->lineItems()->sum('tax_total');
$discountTotalCents = $this->calculateDiscountTotal(
$data['discount_method'],
DocumentDiscountMethod::parse($data['discount_method']),
AdjustmentComputation::parse($data['discount_computation']),
$data['discount_rate'] ?? null,
$subtotalCents,
Expand All @@ -93,17 +94,17 @@ protected function updateInvoiceTotals(Invoice $record, array $data): array
}

protected function calculateDiscountTotal(
string $discountMethod,
DocumentDiscountMethod $discountMethod,
?AdjustmentComputation $discountComputation,
?string $discountRate,
int $subtotalCents,
Invoice $record
): int {
if ($discountMethod === 'line_items') {
if ($discountMethod->isPerLineItem()) {
return $record->lineItems()->sum('discount_total');
}

if ($discountComputation === AdjustmentComputation::Percentage) {
if ($discountComputation?->isPercentage()) {
return (int) ($subtotalCents * ((float) $discountRate / 100));
}

Expand Down
10 changes: 10 additions & 0 deletions app/Enums/Accounting/AdjustmentComputation.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,14 @@ public function getLabel(): ?string
{
return translate($this->name);
}

public function isPercentage(): bool
{
return $this == self::Percentage;
}

public function isFixed(): bool
{
return $this == self::Fixed;
}
}
32 changes: 32 additions & 0 deletions app/Enums/Accounting/DocumentDiscountMethod.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace App\Enums\Accounting;

use App\Enums\Concerns\ParsesEnum;
use Filament\Support\Contracts\HasLabel;

enum DocumentDiscountMethod: string implements HasLabel
{
use ParsesEnum;

case PerLineItem = 'per_line_item';
case PerDocument = 'per_document';

public function getLabel(): string
{
return match ($this) {
self::PerLineItem => 'Per Line Item',
self::PerDocument => 'Per Document',
};
}

public function isPerLineItem(): bool
{
return $this == self::PerLineItem;
}

public function isPerDocument(): bool
{
return $this == self::PerDocument;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public static function form(Form $form): Form
ToggleButton::make('recoverable')
->label('Recoverable')
->default(false)
->visible(fn (Forms\Get $get) => AdjustmentCategory::parse($get('category')) === AdjustmentCategory::Tax && AdjustmentType::parse($get('type')) === AdjustmentType::Purchase),
->visible(fn (Forms\Get $get) => AdjustmentCategory::parse($get('category'))->isTax() && AdjustmentType::parse($get('type'))->isPurchase()),
])
->columns()
->visibleOn('create'),
Expand All @@ -80,7 +80,7 @@ public static function form(Form $form): Form
Forms\Components\DateTimePicker::make('end_date'),
])
->columns()
->visible(fn (Forms\Get $get) => AdjustmentCategory::parse($get('category')) === AdjustmentCategory::Discount),
->visible(fn (Forms\Get $get) => AdjustmentCategory::parse($get('category'))->isDiscount()),
]);
}

Expand Down
22 changes: 10 additions & 12 deletions app/Filament/Company/Resources/Sales/InvoiceResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Filament\Company\Resources\Sales;

use App\Collections\Accounting\InvoiceCollection;
use App\Enums\Accounting\DocumentDiscountMethod;
use App\Enums\Accounting\InvoiceStatus;
use App\Enums\Accounting\PaymentMethod;
use App\Filament\Company\Resources\Sales\InvoiceResource\Pages;
Expand Down Expand Up @@ -129,16 +130,13 @@ public static function form(Form $form): Form
}),
Forms\Components\Select::make('discount_method')
->label('Discount Method')
->options([
'line_items' => 'Per Line Item Discounts',
'invoice' => 'Invoice Level Discount',
])
->options(DocumentDiscountMethod::class)
->selectablePlaceholder(false)
->default('line_items')
->default(DocumentDiscountMethod::PerLineItem)
->afterStateUpdated(function ($state, Forms\Set $set) {
$discountMethod = $state;
$discountMethod = DocumentDiscountMethod::parse($state);

if ($discountMethod === 'invoice') {
if ($discountMethod->isPerDocument()) {
$set('lineItems.*.salesDiscounts', []);
}
})
Expand All @@ -150,7 +148,7 @@ public static function form(Form $form): Form
->saveRelationshipsUsing(null)
->dehydrated(true)
->headers(function (Forms\Get $get) {
$hasDiscounts = $get('discount_method') === 'line_items';
$hasDiscounts = DocumentDiscountMethod::parse($get('discount_method'))->isPerLineItem();

$headers = [
Header::make('Items')->width($hasDiscounts ? '15%' : '20%'),
Expand Down Expand Up @@ -184,8 +182,8 @@ public static function form(Form $form): Form
$set('unit_price', $offeringRecord->price);
$set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());

$discountMethod = $get('../../discount_method');
if ($discountMethod === 'line_items') {
$discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
if ($discountMethod->isPerLineItem()) {
$set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
}
}
Expand Down Expand Up @@ -217,9 +215,9 @@ public static function form(Form $form): Form
->multiple()
->live()
->hidden(function (Forms\Get $get) {
$discountMethod = $get('../../discount_method');
$discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));

return $discountMethod === 'invoice';
return $discountMethod->isPerDocument();
})
->searchable(),
Forms\Components\Placeholder::make('total')
Expand Down
9 changes: 9 additions & 0 deletions app/Models/Accounting/Bill.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
namespace App\Models\Accounting;

use App\Casts\MoneyCast;
use App\Casts\RateCast;
use App\Concerns\Blamable;
use App\Concerns\CompanyOwned;
use App\Enums\Accounting\AdjustmentComputation;
use App\Enums\Accounting\BillStatus;
use App\Enums\Accounting\DocumentDiscountMethod;
use App\Enums\Accounting\JournalEntryType;
use App\Enums\Accounting\TransactionType;
use App\Filament\Company\Resources\Purchases\BillResource;
Expand Down Expand Up @@ -42,6 +45,9 @@ class Bill extends Model
'paid_at',
'status',
'currency_code',
'discount_method',
'discount_computation',
'discount_rate',
'subtotal',
'tax_total',
'discount_total',
Expand All @@ -57,6 +63,9 @@ class Bill extends Model
'due_date' => 'date',
'paid_at' => 'datetime',
'status' => BillStatus::class,
'discount_method' => DocumentDiscountMethod::class,
'discount_computation' => AdjustmentComputation::class,
'discount_rate' => RateCast::class,
'subtotal' => MoneyCast::class,
'tax_total' => MoneyCast::class,
'discount_total' => MoneyCast::class,
Expand Down
4 changes: 3 additions & 1 deletion app/Models/Accounting/Invoice.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use App\Concerns\Blamable;
use App\Concerns\CompanyOwned;
use App\Enums\Accounting\AdjustmentComputation;
use App\Enums\Accounting\DocumentDiscountMethod;
use App\Enums\Accounting\InvoiceStatus;
use App\Enums\Accounting\JournalEntryType;
use App\Enums\Accounting\TransactionType;
Expand Down Expand Up @@ -75,6 +76,7 @@ class Invoice extends Model
'paid_at' => 'datetime',
'last_sent' => 'datetime',
'status' => InvoiceStatus::class,
'discount_method' => DocumentDiscountMethod::class,
'discount_computation' => AdjustmentComputation::class,
'discount_rate' => RateCast::class,
'subtotal' => MoneyCast::class,
Expand Down Expand Up @@ -293,7 +295,7 @@ public function createApprovalTransaction(): void
]);
}

if ($this->discount_method === 'invoice' && $totalLineItemSubtotal > 0) {
if ($this->discount_method->isPerDocument() && $totalLineItemSubtotal > 0) {
$lineItemSubtotalCents = (int) $lineItem->getRawOriginal('subtotal');

if ($index === $this->lineItems->count() - 1) {
Expand Down
13 changes: 11 additions & 2 deletions app/Services/ReportService.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,8 @@ public function buildAccountTransactionsReport(string $startDate, string $endDat

$accountTransactions = [];
$currentBalance = $account->starting_balance;
$periodDebitTotal = 0;
$periodCreditTotal = 0;

$accountTransactions[] = new AccountTransactionDTO(
id: null,
Expand All @@ -192,6 +194,13 @@ public function buildAccountTransactionsReport(string $startDate, string $endDat
foreach ($account->journalEntries as $journalEntry) {
$transaction = $journalEntry->transaction;
$signedAmount = $journalEntry->signed_amount;
$amount = $journalEntry->getRawOriginal('amount');

if ($journalEntry->type->isDebit()) {
$periodDebitTotal += $amount;
} else {
$periodCreditTotal += $amount;
}

if ($account->category->isNormalDebitBalance()) {
$currentBalance += $signedAmount;
Expand Down Expand Up @@ -219,8 +228,8 @@ public function buildAccountTransactionsReport(string $startDate, string $endDat
id: null,
date: 'Totals and Ending Balance',
description: '',
debit: money($account->total_debit, $defaultCurrency)->format(),
credit: money($account->total_credit, $defaultCurrency)->format(),
debit: money($periodDebitTotal, $defaultCurrency)->format(),
credit: money($periodCreditTotal, $defaultCurrency)->format(),
balance: money($currentBalance, $defaultCurrency)->format(),
type: null,
tableAction: null
Expand Down
9 changes: 5 additions & 4 deletions app/View/Models/InvoiceTotalViewModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\View\Models;

use App\Enums\Accounting\AdjustmentComputation;
use App\Enums\Accounting\DocumentDiscountMethod;
use App\Models\Accounting\Adjustment;
use App\Models\Accounting\Invoice;
use App\Utilities\Currency\CurrencyConverter;
Expand Down Expand Up @@ -39,9 +40,9 @@ public function buildViewData(): array
}, 0);

// Calculate discount based on method
$discountMethod = $this->data['discount_method'] ?? 'line_items';
$discountMethod = DocumentDiscountMethod::parse($this->data['discount_method']) ?? DocumentDiscountMethod::PerLineItem;

if ($discountMethod === 'line_items') {
if ($discountMethod->isPerLineItem()) {
$discountTotal = $lineItems->reduce(function ($carry, $item) {
$quantity = max((float) ($item['quantity'] ?? 0), 0);
$unitPrice = max((float) ($item['unit_price'] ?? 0), 0);
Expand All @@ -55,10 +56,10 @@ public function buildViewData(): array
return $carry + $discountAmount;
}, 0);
} else {
$discountComputation = $this->data['discount_computation'] ?? AdjustmentComputation::Percentage;
$discountComputation = AdjustmentComputation::parse($this->data['discount_computation']) ?? AdjustmentComputation::Percentage;
$discountRate = (float) ($this->data['discount_rate'] ?? 0);

if (AdjustmentComputation::parse($discountComputation) === AdjustmentComputation::Percentage) {
if ($discountComputation->isPercentage()) {
$discountTotal = $subtotal * ($discountRate / 100);
} else {
$discountTotal = $discountRate;
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"andrewdwallo/transmatic": "^1.1",
"awcodes/filament-table-repeater": "^3.0",
"barryvdh/laravel-snappy": "^1.0",
"filament/filament": "^3.2.115",
"filament/filament": "v3.2.129",
"guava/filament-clusters": "^1.1",
"guzzlehttp/guzzle": "^7.8",
"jaocero/radio-deck": "^1.2",
Expand Down
Loading

0 comments on commit 4926a07

Please sign in to comment.