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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. $bill->refresh();
  144. $bill->createInitialTransaction();
  145. })
  146. ->headers([
  147. Header::make('Items')->width('15%'),
  148. Header::make('Description')->width('25%'),
  149. Header::make('Quantity')->width('10%'),
  150. Header::make('Price')->width('10%'),
  151. Header::make('Taxes')->width('15%'),
  152. Header::make('Discounts')->width('15%'),
  153. Header::make('Amount')->width('10%')->align('right'),
  154. ])
  155. ->schema([
  156. Forms\Components\Select::make('offering_id')
  157. ->relationship('purchasableOffering', 'name')
  158. ->preload()
  159. ->searchable()
  160. ->required()
  161. ->live()
  162. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  163. $offeringId = $state;
  164. $offeringRecord = Offering::with(['purchaseTaxes', 'purchaseDiscounts'])->find($offeringId);
  165. if ($offeringRecord) {
  166. $set('description', $offeringRecord->description);
  167. $set('unit_price', $offeringRecord->price);
  168. $set('purchaseTaxes', $offeringRecord->purchaseTaxes->pluck('id')->toArray());
  169. $set('purchaseDiscounts', $offeringRecord->purchaseDiscounts->pluck('id')->toArray());
  170. }
  171. }),
  172. Forms\Components\TextInput::make('description'),
  173. Forms\Components\TextInput::make('quantity')
  174. ->required()
  175. ->numeric()
  176. ->live()
  177. ->default(1),
  178. Forms\Components\TextInput::make('unit_price')
  179. ->hiddenLabel()
  180. ->numeric()
  181. ->live()
  182. ->default(0),
  183. Forms\Components\Select::make('purchaseTaxes')
  184. ->relationship('purchaseTaxes', 'name')
  185. ->preload()
  186. ->multiple()
  187. ->live()
  188. ->searchable(),
  189. Forms\Components\Select::make('purchaseDiscounts')
  190. ->relationship('purchaseDiscounts', 'name')
  191. ->preload()
  192. ->multiple()
  193. ->live()
  194. ->searchable(),
  195. Forms\Components\Placeholder::make('total')
  196. ->hiddenLabel()
  197. ->content(function (Forms\Get $get) {
  198. $quantity = max((float) ($get('quantity') ?? 0), 0);
  199. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  200. $purchaseTaxes = $get('purchaseTaxes') ?? [];
  201. $purchaseDiscounts = $get('purchaseDiscounts') ?? [];
  202. $subtotal = $quantity * $unitPrice;
  203. // Calculate tax amount based on subtotal
  204. $taxAmount = 0;
  205. if (! empty($purchaseTaxes)) {
  206. $taxRates = Adjustment::whereIn('id', $purchaseTaxes)->pluck('rate');
  207. $taxAmount = collect($taxRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  208. }
  209. // Calculate discount amount based on subtotal
  210. $discountAmount = 0;
  211. if (! empty($purchaseDiscounts)) {
  212. $discountRates = Adjustment::whereIn('id', $purchaseDiscounts)->pluck('rate');
  213. $discountAmount = collect($discountRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  214. }
  215. // Final total
  216. $total = $subtotal + ($taxAmount - $discountAmount);
  217. return CurrencyConverter::formatToMoney($total);
  218. }),
  219. ]),
  220. Forms\Components\Grid::make(6)
  221. ->schema([
  222. Forms\Components\ViewField::make('totals')
  223. ->columnStart(5)
  224. ->columnSpan(2)
  225. ->view('filament.forms.components.bill-totals'),
  226. ]),
  227. ]),
  228. ]);
  229. }
  230. public static function table(Table $table): Table
  231. {
  232. return $table
  233. ->columns([
  234. Tables\Columns\TextColumn::make('status')
  235. ->badge()
  236. ->searchable(),
  237. Tables\Columns\TextColumn::make('due_date')
  238. ->label('Due')
  239. ->formatStateUsing(function (Tables\Columns\TextColumn $column, mixed $state) {
  240. if (blank($state)) {
  241. return null;
  242. }
  243. $date = Carbon::parse($state)
  244. ->setTimezone($timezone ?? $column->getTimezone());
  245. if ($date->isToday()) {
  246. return 'Today';
  247. }
  248. return $date->diffForHumans([
  249. 'options' => CarbonInterface::ONE_DAY_WORDS,
  250. ]);
  251. })
  252. ->sortable(),
  253. Tables\Columns\TextColumn::make('date')
  254. ->date()
  255. ->sortable(),
  256. Tables\Columns\TextColumn::make('bill_number')
  257. ->label('Number')
  258. ->searchable(),
  259. Tables\Columns\TextColumn::make('vendor.name')
  260. ->sortable(),
  261. Tables\Columns\TextColumn::make('total')
  262. ->currency(),
  263. Tables\Columns\TextColumn::make('amount_paid')
  264. ->label('Amount Paid')
  265. ->currency(),
  266. Tables\Columns\TextColumn::make('amount_due')
  267. ->label('Amount Due')
  268. ->currency(),
  269. ])
  270. ->filters([
  271. Tables\Filters\SelectFilter::make('vendor')
  272. ->relationship('vendor', 'name')
  273. ->searchable()
  274. ->preload(),
  275. Tables\Filters\SelectFilter::make('status')
  276. ->options(BillStatus::class)
  277. ->native(false),
  278. Tables\Filters\TernaryFilter::make('has_payments')
  279. ->label('Has Payments')
  280. ->queries(
  281. true: fn (Builder $query) => $query->whereHas('payments'),
  282. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  283. ),
  284. DateRangeFilter::make('date')
  285. ->fromLabel('From Date')
  286. ->untilLabel('To Date')
  287. ->indicatorLabel('Date'),
  288. DateRangeFilter::make('due_date')
  289. ->fromLabel('From Due Date')
  290. ->untilLabel('To Due Date')
  291. ->indicatorLabel('Due'),
  292. ])
  293. ->actions([
  294. Tables\Actions\ActionGroup::make([
  295. Tables\Actions\EditAction::make(),
  296. Tables\Actions\ViewAction::make(),
  297. Tables\Actions\DeleteAction::make(),
  298. Bill::getReplicateAction(Tables\Actions\ReplicateAction::class),
  299. Tables\Actions\Action::make('recordPayment')
  300. ->label('Record Payment')
  301. ->stickyModalHeader()
  302. ->stickyModalFooter()
  303. ->modalFooterActionsAlignment(Alignment::End)
  304. ->modalWidth(MaxWidth::TwoExtraLarge)
  305. ->icon('heroicon-o-credit-card')
  306. ->visible(function (Bill $record) {
  307. return $record->canRecordPayment();
  308. })
  309. ->mountUsing(function (Bill $record, Form $form) {
  310. $form->fill([
  311. 'posted_at' => now(),
  312. 'amount' => $record->amount_due,
  313. ]);
  314. })
  315. ->databaseTransaction()
  316. ->successNotificationTitle('Payment Recorded')
  317. ->form([
  318. Forms\Components\DatePicker::make('posted_at')
  319. ->label('Date'),
  320. Forms\Components\TextInput::make('amount')
  321. ->label('Amount')
  322. ->required()
  323. ->money()
  324. ->live(onBlur: true)
  325. ->helperText(function (Bill $record, $state) {
  326. if (! CurrencyConverter::isValidAmount($state)) {
  327. return null;
  328. }
  329. $amountDue = $record->getRawOriginal('amount_due');
  330. $amount = CurrencyConverter::convertToCents($state);
  331. if ($amount <= 0) {
  332. return 'Please enter a valid positive amount';
  333. }
  334. $newAmountDue = $amountDue - $amount;
  335. return match (true) {
  336. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue),
  337. $newAmountDue === 0 => 'Bill will be fully paid',
  338. default => 'Amount exceeds bill total by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue)),
  339. };
  340. })
  341. ->rules([
  342. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  343. if (! CurrencyConverter::isValidAmount($value)) {
  344. $fail('Please enter a valid amount');
  345. }
  346. },
  347. ]),
  348. Forms\Components\Select::make('payment_method')
  349. ->label('Payment Method')
  350. ->required()
  351. ->options(PaymentMethod::class),
  352. Forms\Components\Select::make('bank_account_id')
  353. ->label('Account')
  354. ->required()
  355. ->options(BankAccount::query()
  356. ->get()
  357. ->pluck('account.name', 'id'))
  358. ->searchable(),
  359. Forms\Components\Textarea::make('notes')
  360. ->label('Notes'),
  361. ])
  362. ->action(function (Bill $record, Tables\Actions\Action $action, array $data) {
  363. $record->recordPayment($data);
  364. $action->success();
  365. }),
  366. ]),
  367. ])
  368. ->bulkActions([
  369. Tables\Actions\BulkActionGroup::make([
  370. Tables\Actions\DeleteBulkAction::make(),
  371. ReplicateBulkAction::make()
  372. ->label('Replicate')
  373. ->modalWidth(MaxWidth::Large)
  374. ->modalDescription('Replicating bills will also replicate their line items. Are you sure you want to proceed?')
  375. ->successNotificationTitle('Bills Replicated Successfully')
  376. ->failureNotificationTitle('Failed to Replicate Bills')
  377. ->databaseTransaction()
  378. ->deselectRecordsAfterCompletion()
  379. ->excludeAttributes([
  380. 'status',
  381. 'amount_paid',
  382. 'amount_due',
  383. 'created_by',
  384. 'updated_by',
  385. 'created_at',
  386. 'updated_at',
  387. 'bill_number',
  388. 'date',
  389. 'due_date',
  390. 'paid_at',
  391. ])
  392. ->beforeReplicaSaved(function (Bill $replica) {
  393. $replica->status = BillStatus::Unpaid;
  394. $replica->bill_number = Bill::getNextDocumentNumber();
  395. $replica->date = now();
  396. $replica->due_date = now()->addDays($replica->company->defaultBill->payment_terms->getDays());
  397. })
  398. ->withReplicatedRelationships(['lineItems'])
  399. ->withExcludedRelationshipAttributes('lineItems', [
  400. 'subtotal',
  401. 'total',
  402. 'created_by',
  403. 'updated_by',
  404. 'created_at',
  405. 'updated_at',
  406. ]),
  407. Tables\Actions\BulkAction::make('recordPayments')
  408. ->label('Record Payments')
  409. ->icon('heroicon-o-credit-card')
  410. ->stickyModalHeader()
  411. ->stickyModalFooter()
  412. ->modalFooterActionsAlignment(Alignment::End)
  413. ->modalWidth(MaxWidth::TwoExtraLarge)
  414. ->databaseTransaction()
  415. ->successNotificationTitle('Payments Recorded')
  416. ->failureNotificationTitle('Failed to Record Payments')
  417. ->deselectRecordsAfterCompletion()
  418. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  419. $cantRecordPayments = $records->contains(fn (Bill $bill) => ! $bill->canRecordPayment());
  420. if ($cantRecordPayments) {
  421. Notification::make()
  422. ->title('Payment Recording Failed')
  423. ->body('Bills that are either paid or voided cannot be processed through bulk payments. Please adjust your selection and try again.')
  424. ->persistent()
  425. ->danger()
  426. ->send();
  427. $action->cancel(true);
  428. }
  429. })
  430. ->mountUsing(function (Collection $records, Form $form) {
  431. $totalAmountDue = $records->sum(fn (Bill $bill) => $bill->getRawOriginal('amount_due'));
  432. $form->fill([
  433. 'posted_at' => now(),
  434. 'amount' => CurrencyConverter::convertCentsToFormatSimple($totalAmountDue),
  435. ]);
  436. })
  437. ->form([
  438. Forms\Components\DatePicker::make('posted_at')
  439. ->label('Date'),
  440. Forms\Components\TextInput::make('amount')
  441. ->label('Amount')
  442. ->required()
  443. ->money()
  444. ->rules([
  445. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  446. if (! CurrencyConverter::isValidAmount($value)) {
  447. $fail('Please enter a valid amount');
  448. }
  449. },
  450. ]),
  451. Forms\Components\Select::make('payment_method')
  452. ->label('Payment Method')
  453. ->required()
  454. ->options(PaymentMethod::class),
  455. Forms\Components\Select::make('bank_account_id')
  456. ->label('Account')
  457. ->required()
  458. ->options(BankAccount::query()
  459. ->get()
  460. ->pluck('account.name', 'id'))
  461. ->searchable(),
  462. Forms\Components\Textarea::make('notes')
  463. ->label('Notes'),
  464. ])
  465. ->before(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  466. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  467. $totalAmountDue = $records->sum(fn (Bill $bill) => $bill->getRawOriginal('amount_due'));
  468. if ($totalPaymentAmount > $totalAmountDue) {
  469. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  470. Notification::make()
  471. ->title('Excess Payment Amount')
  472. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  473. ->persistent()
  474. ->warning()
  475. ->send();
  476. $action->halt(true);
  477. }
  478. })
  479. ->action(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  480. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  481. $remainingAmount = $totalPaymentAmount;
  482. $records->each(function (Bill $record) use (&$remainingAmount, $data) {
  483. $amountDue = $record->getRawOriginal('amount_due');
  484. if ($amountDue <= 0 || $remainingAmount <= 0) {
  485. return;
  486. }
  487. $paymentAmount = min($amountDue, $remainingAmount);
  488. $data['amount'] = CurrencyConverter::convertCentsToFormatSimple($paymentAmount);
  489. $record->recordPayment($data);
  490. $remainingAmount -= $paymentAmount;
  491. });
  492. $action->success();
  493. }),
  494. ]),
  495. ]);
  496. }
  497. public static function getRelations(): array
  498. {
  499. return [
  500. //
  501. ];
  502. }
  503. public static function getPages(): array
  504. {
  505. return [
  506. 'index' => Pages\ListBills::route('/'),
  507. 'create' => Pages\CreateBill::route('/create'),
  508. 'edit' => Pages\EditBill::route('/{record}/edit'),
  509. ];
  510. }
  511. public static function getWidgets(): array
  512. {
  513. return [
  514. BillResource\Widgets\BillOverview::class,
  515. ];
  516. }
  517. }