You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BillResource.php 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. <?php
  2. namespace App\Filament\Company\Resources\Purchases;
  3. use App\Enums\Accounting\BillStatus;
  4. use App\Enums\Accounting\PaymentMethod;
  5. use App\Filament\Company\Resources\Purchases\BillResource\Pages;
  6. use App\Filament\Tables\Actions\ReplicateBulkAction;
  7. use App\Filament\Tables\Filters\DateRangeFilter;
  8. use App\Models\Accounting\Adjustment;
  9. use App\Models\Accounting\Bill;
  10. use App\Models\Accounting\DocumentLineItem;
  11. use App\Models\Banking\BankAccount;
  12. use App\Models\Common\Offering;
  13. use App\Utilities\Currency\CurrencyConverter;
  14. use Awcodes\TableRepeater\Components\TableRepeater;
  15. use Awcodes\TableRepeater\Header;
  16. use Carbon\CarbonInterface;
  17. use Closure;
  18. use Filament\Forms;
  19. use Filament\Forms\Form;
  20. use Filament\Notifications\Notification;
  21. use Filament\Resources\Resource;
  22. use Filament\Support\Enums\Alignment;
  23. use Filament\Support\Enums\MaxWidth;
  24. use Filament\Tables;
  25. use Filament\Tables\Table;
  26. use Illuminate\Database\Eloquent\Builder;
  27. use Illuminate\Database\Eloquent\Collection;
  28. use Illuminate\Database\Eloquent\Model;
  29. use Illuminate\Support\Carbon;
  30. use Illuminate\Support\Facades\Auth;
  31. class BillResource extends Resource
  32. {
  33. protected static ?string $model = Bill::class;
  34. protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
  35. public static function form(Form $form): Form
  36. {
  37. $company = Auth::user()->currentCompany;
  38. return $form
  39. ->schema([
  40. Forms\Components\Section::make('Bill Details')
  41. ->schema([
  42. Forms\Components\Split::make([
  43. Forms\Components\Group::make([
  44. Forms\Components\Select::make('vendor_id')
  45. ->relationship('vendor', 'name')
  46. ->preload()
  47. ->searchable()
  48. ->required(),
  49. ]),
  50. Forms\Components\Group::make([
  51. Forms\Components\TextInput::make('bill_number')
  52. ->label('Bill Number')
  53. ->default(fn () => Bill::getNextDocumentNumber()),
  54. Forms\Components\TextInput::make('order_number')
  55. ->label('P.O/S.O Number'),
  56. Forms\Components\DatePicker::make('date')
  57. ->label('Bill Date')
  58. ->default(now()),
  59. Forms\Components\DatePicker::make('due_date')
  60. ->label('Due Date')
  61. ->default(function () use ($company) {
  62. return now()->addDays($company->defaultBill->payment_terms->getDays());
  63. }),
  64. ])->grow(true),
  65. ])->from('md'),
  66. TableRepeater::make('lineItems')
  67. ->relationship()
  68. ->saveRelationshipsUsing(function (TableRepeater $component, Forms\Contracts\HasForms $livewire, ?array $state) {
  69. if (! is_array($state)) {
  70. $state = [];
  71. }
  72. $relationship = $component->getRelationship();
  73. $existingRecords = $component->getCachedExistingRecords();
  74. $recordsToDelete = [];
  75. foreach ($existingRecords->pluck($relationship->getRelated()->getKeyName()) as $keyToCheckForDeletion) {
  76. if (array_key_exists("record-{$keyToCheckForDeletion}", $state)) {
  77. continue;
  78. }
  79. $recordsToDelete[] = $keyToCheckForDeletion;
  80. $existingRecords->forget("record-{$keyToCheckForDeletion}");
  81. }
  82. $relationship
  83. ->whereKey($recordsToDelete)
  84. ->get()
  85. ->each(static fn (Model $record) => $record->delete());
  86. $childComponentContainers = $component->getChildComponentContainers(
  87. withHidden: $component->shouldSaveRelationshipsWhenHidden(),
  88. );
  89. $itemOrder = 1;
  90. $orderColumn = $component->getOrderColumn();
  91. $translatableContentDriver = $livewire->makeFilamentTranslatableContentDriver();
  92. foreach ($childComponentContainers as $itemKey => $item) {
  93. $itemData = $item->getState(shouldCallHooksBefore: false);
  94. if ($orderColumn) {
  95. $itemData[$orderColumn] = $itemOrder;
  96. $itemOrder++;
  97. }
  98. if ($record = ($existingRecords[$itemKey] ?? null)) {
  99. $itemData = $component->mutateRelationshipDataBeforeSave($itemData, record: $record);
  100. if ($itemData === null) {
  101. continue;
  102. }
  103. $translatableContentDriver ?
  104. $translatableContentDriver->updateRecord($record, $itemData) :
  105. $record->fill($itemData)->save();
  106. continue;
  107. }
  108. $relatedModel = $component->getRelatedModel();
  109. $itemData = $component->mutateRelationshipDataBeforeCreate($itemData);
  110. if ($itemData === null) {
  111. continue;
  112. }
  113. if ($translatableContentDriver) {
  114. $record = $translatableContentDriver->makeRecord($relatedModel, $itemData);
  115. } else {
  116. $record = new $relatedModel;
  117. $record->fill($itemData);
  118. }
  119. $record = $relationship->save($record);
  120. $item->model($record)->saveRelationships();
  121. $existingRecords->push($record);
  122. }
  123. $component->getRecord()->setRelation($component->getRelationshipName(), $existingRecords);
  124. /** @var Bill $bill */
  125. $bill = $component->getRecord();
  126. // Recalculate totals for line items
  127. $bill->lineItems()->each(function (DocumentLineItem $lineItem) {
  128. $lineItem->updateQuietly([
  129. 'tax_total' => $lineItem->calculateTaxTotal()->getAmount(),
  130. 'discount_total' => $lineItem->calculateDiscountTotal()->getAmount(),
  131. ]);
  132. });
  133. $subtotal = $bill->lineItems()->sum('subtotal') / 100;
  134. $taxTotal = $bill->lineItems()->sum('tax_total') / 100;
  135. $discountTotal = $bill->lineItems()->sum('discount_total') / 100;
  136. $grandTotal = $subtotal + $taxTotal - $discountTotal;
  137. $bill->updateQuietly([
  138. 'subtotal' => $subtotal,
  139. 'tax_total' => $taxTotal,
  140. 'discount_total' => $discountTotal,
  141. 'total' => $grandTotal,
  142. ]);
  143. })
  144. ->headers([
  145. Header::make('Items')->width('15%'),
  146. Header::make('Description')->width('25%'),
  147. Header::make('Quantity')->width('10%'),
  148. Header::make('Price')->width('10%'),
  149. Header::make('Taxes')->width('15%'),
  150. Header::make('Discounts')->width('15%'),
  151. Header::make('Amount')->width('10%')->align('right'),
  152. ])
  153. ->schema([
  154. Forms\Components\Select::make('offering_id')
  155. ->relationship('purchasableOffering', 'name')
  156. ->preload()
  157. ->searchable()
  158. ->required()
  159. ->live()
  160. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  161. $offeringId = $state;
  162. $offeringRecord = Offering::with(['purchaseTaxes', 'purchaseDiscounts'])->find($offeringId);
  163. if ($offeringRecord) {
  164. $set('description', $offeringRecord->description);
  165. $set('unit_price', $offeringRecord->price);
  166. $set('purchaseTaxes', $offeringRecord->purchaseTaxes->pluck('id')->toArray());
  167. $set('purchaseDiscounts', $offeringRecord->purchaseDiscounts->pluck('id')->toArray());
  168. }
  169. }),
  170. Forms\Components\TextInput::make('description'),
  171. Forms\Components\TextInput::make('quantity')
  172. ->required()
  173. ->numeric()
  174. ->live()
  175. ->default(1),
  176. Forms\Components\TextInput::make('unit_price')
  177. ->hiddenLabel()
  178. ->numeric()
  179. ->live()
  180. ->default(0),
  181. Forms\Components\Select::make('purchaseTaxes')
  182. ->relationship('purchaseTaxes', 'name')
  183. ->preload()
  184. ->multiple()
  185. ->live()
  186. ->searchable(),
  187. Forms\Components\Select::make('purchaseDiscounts')
  188. ->relationship('purchaseDiscounts', 'name')
  189. ->preload()
  190. ->multiple()
  191. ->live()
  192. ->searchable(),
  193. Forms\Components\Placeholder::make('total')
  194. ->hiddenLabel()
  195. ->content(function (Forms\Get $get) {
  196. $quantity = max((float) ($get('quantity') ?? 0), 0);
  197. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  198. $purchaseTaxes = $get('purchaseTaxes') ?? [];
  199. $purchaseDiscounts = $get('purchaseDiscounts') ?? [];
  200. $subtotal = $quantity * $unitPrice;
  201. // Calculate tax amount based on subtotal
  202. $taxAmount = 0;
  203. if (! empty($purchaseTaxes)) {
  204. $taxRates = Adjustment::whereIn('id', $purchaseTaxes)->pluck('rate');
  205. $taxAmount = collect($taxRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  206. }
  207. // Calculate discount amount based on subtotal
  208. $discountAmount = 0;
  209. if (! empty($purchaseDiscounts)) {
  210. $discountRates = Adjustment::whereIn('id', $purchaseDiscounts)->pluck('rate');
  211. $discountAmount = collect($discountRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  212. }
  213. // Final total
  214. $total = $subtotal + ($taxAmount - $discountAmount);
  215. return CurrencyConverter::formatToMoney($total);
  216. }),
  217. ]),
  218. Forms\Components\Grid::make(6)
  219. ->schema([
  220. Forms\Components\ViewField::make('totals')
  221. ->columnStart(5)
  222. ->columnSpan(2)
  223. ->view('filament.forms.components.bill-totals'),
  224. ]),
  225. ]),
  226. ]);
  227. }
  228. public static function table(Table $table): Table
  229. {
  230. return $table
  231. ->columns([
  232. Tables\Columns\TextColumn::make('status')
  233. ->badge()
  234. ->searchable(),
  235. Tables\Columns\TextColumn::make('due_date')
  236. ->label('Due')
  237. ->formatStateUsing(function (Tables\Columns\TextColumn $column, mixed $state) {
  238. if (blank($state)) {
  239. return null;
  240. }
  241. $date = Carbon::parse($state)
  242. ->setTimezone($timezone ?? $column->getTimezone());
  243. if ($date->isToday()) {
  244. return 'Today';
  245. }
  246. return $date->diffForHumans([
  247. 'options' => CarbonInterface::ONE_DAY_WORDS,
  248. ]);
  249. })
  250. ->sortable(),
  251. Tables\Columns\TextColumn::make('date')
  252. ->date()
  253. ->sortable(),
  254. Tables\Columns\TextColumn::make('bill_number')
  255. ->label('Number')
  256. ->searchable(),
  257. Tables\Columns\TextColumn::make('vendor.name')
  258. ->sortable(),
  259. Tables\Columns\TextColumn::make('total')
  260. ->currency(),
  261. Tables\Columns\TextColumn::make('amount_paid')
  262. ->label('Amount Paid')
  263. ->currency(),
  264. Tables\Columns\TextColumn::make('amount_due')
  265. ->label('Amount Due')
  266. ->currency(),
  267. ])
  268. ->filters([
  269. Tables\Filters\SelectFilter::make('vendor')
  270. ->relationship('vendor', 'name')
  271. ->searchable()
  272. ->preload(),
  273. Tables\Filters\SelectFilter::make('status')
  274. ->options(BillStatus::class)
  275. ->native(false),
  276. Tables\Filters\TernaryFilter::make('has_payments')
  277. ->label('Has Payments')
  278. ->queries(
  279. true: fn (Builder $query) => $query->whereHas('payments'),
  280. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  281. ),
  282. DateRangeFilter::make('date')
  283. ->fromLabel('From Date')
  284. ->untilLabel('To Date')
  285. ->indicatorLabel('Date'),
  286. DateRangeFilter::make('due_date')
  287. ->fromLabel('From Due Date')
  288. ->untilLabel('To Due Date')
  289. ->indicatorLabel('Due'),
  290. ])
  291. ->actions([
  292. Tables\Actions\ActionGroup::make([
  293. Tables\Actions\EditAction::make(),
  294. Tables\Actions\ViewAction::make(),
  295. Tables\Actions\DeleteAction::make(),
  296. Bill::getReplicateAction(Tables\Actions\ReplicateAction::class),
  297. Tables\Actions\Action::make('recordPayment')
  298. ->label('Record Payment')
  299. ->stickyModalHeader()
  300. ->stickyModalFooter()
  301. ->modalFooterActionsAlignment(Alignment::End)
  302. ->modalWidth(MaxWidth::TwoExtraLarge)
  303. ->icon('heroicon-o-credit-card')
  304. ->visible(function (Bill $record) {
  305. return $record->canRecordPayment();
  306. })
  307. ->mountUsing(function (Bill $record, Form $form) {
  308. $form->fill([
  309. 'posted_at' => now(),
  310. 'amount' => $record->amount_due,
  311. ]);
  312. })
  313. ->databaseTransaction()
  314. ->successNotificationTitle('Payment Recorded')
  315. ->form([
  316. Forms\Components\DatePicker::make('posted_at')
  317. ->label('Date'),
  318. Forms\Components\TextInput::make('amount')
  319. ->label('Amount')
  320. ->required()
  321. ->money()
  322. ->live(onBlur: true)
  323. ->helperText(function (Bill $record, $state) {
  324. if (! CurrencyConverter::isValidAmount($state)) {
  325. return null;
  326. }
  327. $amountDue = $record->getRawOriginal('amount_due');
  328. $amount = CurrencyConverter::convertToCents($state);
  329. if ($amount <= 0) {
  330. return 'Please enter a valid positive amount';
  331. }
  332. $newAmountDue = $amountDue - $amount;
  333. return match (true) {
  334. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue),
  335. $newAmountDue === 0 => 'Bill will be fully paid',
  336. default => 'Amount exceeds bill total by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue)),
  337. };
  338. })
  339. ->rules([
  340. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  341. if (! CurrencyConverter::isValidAmount($value)) {
  342. $fail('Please enter a valid amount');
  343. }
  344. },
  345. ]),
  346. Forms\Components\Select::make('payment_method')
  347. ->label('Payment Method')
  348. ->required()
  349. ->options(PaymentMethod::class),
  350. Forms\Components\Select::make('bank_account_id')
  351. ->label('Account')
  352. ->required()
  353. ->options(BankAccount::query()
  354. ->get()
  355. ->pluck('account.name', 'id'))
  356. ->searchable(),
  357. Forms\Components\Textarea::make('notes')
  358. ->label('Notes'),
  359. ])
  360. ->action(function (Bill $record, Tables\Actions\Action $action, array $data) {
  361. $record->recordPayment($data);
  362. $action->success();
  363. }),
  364. ]),
  365. ])
  366. ->bulkActions([
  367. Tables\Actions\BulkActionGroup::make([
  368. Tables\Actions\DeleteBulkAction::make(),
  369. ReplicateBulkAction::make()
  370. ->label('Replicate')
  371. ->modalWidth(MaxWidth::Large)
  372. ->modalDescription('Replicating bills will also replicate their line items. Are you sure you want to proceed?')
  373. ->successNotificationTitle('Bills Replicated Successfully')
  374. ->failureNotificationTitle('Failed to Replicate Bills')
  375. ->databaseTransaction()
  376. ->deselectRecordsAfterCompletion()
  377. ->excludeAttributes([
  378. 'status',
  379. 'amount_paid',
  380. 'amount_due',
  381. 'created_by',
  382. 'updated_by',
  383. 'created_at',
  384. 'updated_at',
  385. 'bill_number',
  386. 'date',
  387. 'due_date',
  388. 'paid_at',
  389. ])
  390. ->beforeReplicaSaved(function (Bill $replica) {
  391. $replica->status = BillStatus::Unpaid;
  392. $replica->bill_number = Bill::getNextDocumentNumber();
  393. $replica->date = now();
  394. $replica->due_date = now()->addDays($replica->company->defaultBill->payment_terms->getDays());
  395. })
  396. ->withReplicatedRelationships(['lineItems'])
  397. ->withExcludedRelationshipAttributes('lineItems', [
  398. 'subtotal',
  399. 'total',
  400. 'created_by',
  401. 'updated_by',
  402. 'created_at',
  403. 'updated_at',
  404. ]),
  405. Tables\Actions\BulkAction::make('recordPayments')
  406. ->label('Record Payments')
  407. ->icon('heroicon-o-credit-card')
  408. ->stickyModalHeader()
  409. ->stickyModalFooter()
  410. ->modalFooterActionsAlignment(Alignment::End)
  411. ->modalWidth(MaxWidth::TwoExtraLarge)
  412. ->databaseTransaction()
  413. ->successNotificationTitle('Payments Recorded')
  414. ->failureNotificationTitle('Failed to Record Payments')
  415. ->deselectRecordsAfterCompletion()
  416. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  417. $cantRecordPayments = $records->contains(fn (Bill $bill) => ! $bill->canRecordPayment());
  418. if ($cantRecordPayments) {
  419. Notification::make()
  420. ->title('Payment Recording Failed')
  421. ->body('Bills that are either paid or voided cannot be processed through bulk payments. Please adjust your selection and try again.')
  422. ->persistent()
  423. ->danger()
  424. ->send();
  425. $action->cancel(true);
  426. }
  427. })
  428. ->mountUsing(function (Collection $records, Form $form) {
  429. $totalAmountDue = $records->sum(fn (Bill $bill) => $bill->getRawOriginal('amount_due'));
  430. $form->fill([
  431. 'posted_at' => now(),
  432. 'amount' => CurrencyConverter::convertCentsToFormatSimple($totalAmountDue),
  433. ]);
  434. })
  435. ->form([
  436. Forms\Components\DatePicker::make('posted_at')
  437. ->label('Date'),
  438. Forms\Components\TextInput::make('amount')
  439. ->label('Amount')
  440. ->required()
  441. ->money()
  442. ->rules([
  443. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  444. if (! CurrencyConverter::isValidAmount($value)) {
  445. $fail('Please enter a valid amount');
  446. }
  447. },
  448. ]),
  449. Forms\Components\Select::make('payment_method')
  450. ->label('Payment Method')
  451. ->required()
  452. ->options(PaymentMethod::class),
  453. Forms\Components\Select::make('bank_account_id')
  454. ->label('Account')
  455. ->required()
  456. ->options(BankAccount::query()
  457. ->get()
  458. ->pluck('account.name', 'id'))
  459. ->searchable(),
  460. Forms\Components\Textarea::make('notes')
  461. ->label('Notes'),
  462. ])
  463. ->before(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  464. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  465. $totalAmountDue = $records->sum(fn (Bill $bill) => $bill->getRawOriginal('amount_due'));
  466. if ($totalPaymentAmount > $totalAmountDue) {
  467. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  468. Notification::make()
  469. ->title('Excess Payment Amount')
  470. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  471. ->persistent()
  472. ->warning()
  473. ->send();
  474. $action->halt(true);
  475. }
  476. })
  477. ->action(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  478. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  479. $remainingAmount = $totalPaymentAmount;
  480. $records->each(function (Bill $record) use (&$remainingAmount, $data) {
  481. $amountDue = $record->getRawOriginal('amount_due');
  482. if ($amountDue <= 0 || $remainingAmount <= 0) {
  483. return;
  484. }
  485. $paymentAmount = min($amountDue, $remainingAmount);
  486. $data['amount'] = CurrencyConverter::convertCentsToFormatSimple($paymentAmount);
  487. $record->recordPayment($data);
  488. $remainingAmount -= $paymentAmount;
  489. });
  490. $action->success();
  491. }),
  492. ]),
  493. ]);
  494. }
  495. public static function getRelations(): array
  496. {
  497. return [
  498. //
  499. ];
  500. }
  501. public static function getPages(): array
  502. {
  503. return [
  504. 'index' => Pages\ListBills::route('/'),
  505. 'create' => Pages\CreateBill::route('/create'),
  506. 'edit' => Pages\EditBill::route('/{record}/edit'),
  507. ];
  508. }
  509. public static function getWidgets(): array
  510. {
  511. return [
  512. BillResource\Widgets\BillOverview::class,
  513. ];
  514. }
  515. }