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.

InvoiceResource.php 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales;
  3. use App\Collections\Accounting\DocumentCollection;
  4. use App\Enums\Accounting\AdjustmentCategory;
  5. use App\Enums\Accounting\AdjustmentStatus;
  6. use App\Enums\Accounting\AdjustmentType;
  7. use App\Enums\Accounting\DocumentDiscountMethod;
  8. use App\Enums\Accounting\DocumentType;
  9. use App\Enums\Accounting\InvoiceStatus;
  10. use App\Enums\Accounting\PaymentMethod;
  11. use App\Filament\Company\Resources\Sales\ClientResource\RelationManagers\InvoicesRelationManager;
  12. use App\Filament\Company\Resources\Sales\InvoiceResource\Pages;
  13. use App\Filament\Company\Resources\Sales\InvoiceResource\RelationManagers;
  14. use App\Filament\Company\Resources\Sales\InvoiceResource\Widgets;
  15. use App\Filament\Forms\Components\CreateAdjustmentSelect;
  16. use App\Filament\Forms\Components\CreateCurrencySelect;
  17. use App\Filament\Forms\Components\DocumentFooterSection;
  18. use App\Filament\Forms\Components\DocumentHeaderSection;
  19. use App\Filament\Forms\Components\DocumentTotals;
  20. use App\Filament\Tables\Actions\ReplicateBulkAction;
  21. use App\Filament\Tables\Columns;
  22. use App\Filament\Tables\Filters\DateRangeFilter;
  23. use App\Models\Accounting\Adjustment;
  24. use App\Models\Accounting\DocumentLineItem;
  25. use App\Models\Accounting\Invoice;
  26. use App\Models\Banking\BankAccount;
  27. use App\Models\Common\Client;
  28. use App\Models\Common\Offering;
  29. use App\Utilities\Currency\CurrencyAccessor;
  30. use App\Utilities\Currency\CurrencyConverter;
  31. use App\Utilities\RateCalculator;
  32. use Awcodes\TableRepeater\Components\TableRepeater;
  33. use Awcodes\TableRepeater\Header;
  34. use Closure;
  35. use Filament\Forms;
  36. use Filament\Forms\Form;
  37. use Filament\Notifications\Notification;
  38. use Filament\Resources\Resource;
  39. use Filament\Support\Enums\Alignment;
  40. use Filament\Support\Enums\MaxWidth;
  41. use Filament\Tables;
  42. use Filament\Tables\Table;
  43. use Illuminate\Database\Eloquent\Builder;
  44. use Illuminate\Database\Eloquent\Collection;
  45. use Illuminate\Support\Facades\Auth;
  46. class InvoiceResource extends Resource
  47. {
  48. protected static ?string $model = Invoice::class;
  49. public static function form(Form $form): Form
  50. {
  51. $company = Auth::user()->currentCompany;
  52. $settings = $company->defaultInvoice;
  53. return $form
  54. ->schema([
  55. DocumentHeaderSection::make('Invoice Header')
  56. ->defaultHeader($settings->header)
  57. ->defaultSubheader($settings->subheader),
  58. Forms\Components\Section::make('Invoice Details')
  59. ->schema([
  60. Forms\Components\Split::make([
  61. Forms\Components\Group::make([
  62. Forms\Components\Select::make('client_id')
  63. ->relationship('client', 'name')
  64. ->preload()
  65. ->searchable()
  66. ->required()
  67. ->live()
  68. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  69. if (! $state) {
  70. return;
  71. }
  72. $currencyCode = Client::find($state)?->currency_code;
  73. if ($currencyCode) {
  74. $set('currency_code', $currencyCode);
  75. }
  76. }),
  77. CreateCurrencySelect::make('currency_code')
  78. ->disabled(function (?Invoice $record) {
  79. return $record?->hasPayments();
  80. }),
  81. ]),
  82. Forms\Components\Group::make([
  83. Forms\Components\TextInput::make('invoice_number')
  84. ->label('Invoice number')
  85. ->default(static fn () => Invoice::getNextDocumentNumber()),
  86. Forms\Components\TextInput::make('order_number')
  87. ->label('P.O/S.O Number'),
  88. Forms\Components\DatePicker::make('date')
  89. ->label('Invoice date')
  90. ->live()
  91. ->default(now())
  92. ->disabled(function (?Invoice $record) {
  93. return $record?->hasPayments();
  94. })
  95. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  96. $date = $state;
  97. $dueDate = $get('due_date');
  98. if ($date && $dueDate && $date > $dueDate) {
  99. $set('due_date', $date);
  100. }
  101. }),
  102. Forms\Components\DatePicker::make('due_date')
  103. ->label('Payment due')
  104. ->default(function () use ($settings) {
  105. return now()->addDays($settings->payment_terms->getDays());
  106. })
  107. ->minDate(static function (Forms\Get $get) {
  108. return $get('date') ?? now();
  109. }),
  110. Forms\Components\Select::make('discount_method')
  111. ->label('Discount method')
  112. ->options(DocumentDiscountMethod::class)
  113. ->selectablePlaceholder(false)
  114. ->default(DocumentDiscountMethod::PerLineItem)
  115. ->afterStateUpdated(function ($state, Forms\Set $set) {
  116. $discountMethod = DocumentDiscountMethod::parse($state);
  117. if ($discountMethod->isPerDocument()) {
  118. $set('lineItems.*.salesDiscounts', []);
  119. }
  120. })
  121. ->live(),
  122. ])->grow(true),
  123. ])->from('md'),
  124. TableRepeater::make('lineItems')
  125. ->relationship()
  126. ->saveRelationshipsUsing(null)
  127. ->dehydrated(true)
  128. ->headers(function (Forms\Get $get) use ($settings) {
  129. $hasDiscounts = DocumentDiscountMethod::parse($get('discount_method'))->isPerLineItem();
  130. $headers = [
  131. Header::make($settings->resolveColumnLabel('item_name', 'Items'))
  132. ->width($hasDiscounts ? '15%' : '20%'),
  133. Header::make('Description')
  134. ->width($hasDiscounts ? '15%' : '20%'),
  135. Header::make($settings->resolveColumnLabel('unit_name', 'Quantity'))
  136. ->width('10%'),
  137. Header::make($settings->resolveColumnLabel('price_name', 'Price'))
  138. ->width('10%'),
  139. Header::make('Taxes')
  140. ->width($hasDiscounts ? '20%' : '30%'),
  141. ];
  142. if ($hasDiscounts) {
  143. $headers[] = Header::make('Discounts')->width('20%');
  144. }
  145. $headers[] = Header::make($settings->resolveColumnLabel('amount_name', 'Amount'))
  146. ->width('10%')
  147. ->align('right');
  148. return $headers;
  149. })
  150. ->schema([
  151. Forms\Components\Select::make('offering_id')
  152. ->relationship('sellableOffering', 'name')
  153. ->preload()
  154. ->searchable()
  155. ->required()
  156. ->live()
  157. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state, ?DocumentLineItem $record) {
  158. $offeringId = $state;
  159. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  160. $isPerLineItem = $discountMethod->isPerLineItem();
  161. $existingTaxIds = [];
  162. $existingDiscountIds = [];
  163. if ($record) {
  164. $existingTaxIds = $record->salesTaxes()->pluck('adjustments.id')->toArray();
  165. if ($isPerLineItem) {
  166. $existingDiscountIds = $record->salesDiscounts()->pluck('adjustments.id')->toArray();
  167. }
  168. }
  169. $with = [
  170. 'salesTaxes' => static function ($query) use ($existingTaxIds) {
  171. $query->where(static function ($query) use ($existingTaxIds) {
  172. $query->where('status', AdjustmentStatus::Active)
  173. ->orWhereIn('adjustments.id', $existingTaxIds);
  174. });
  175. },
  176. ];
  177. if ($isPerLineItem) {
  178. $with['salesDiscounts'] = static function ($query) use ($existingDiscountIds) {
  179. $query->where(static function ($query) use ($existingDiscountIds) {
  180. $query->where('status', AdjustmentStatus::Active)
  181. ->orWhereIn('adjustments.id', $existingDiscountIds);
  182. });
  183. };
  184. }
  185. $offeringRecord = Offering::with($with)->find($offeringId);
  186. if (! $offeringRecord) {
  187. return;
  188. }
  189. $unitPrice = CurrencyConverter::convertToFloat($offeringRecord->price, $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency());
  190. $set('description', $offeringRecord->description);
  191. $set('unit_price', $unitPrice);
  192. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  193. if ($isPerLineItem) {
  194. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  195. }
  196. }),
  197. Forms\Components\TextInput::make('description'),
  198. Forms\Components\TextInput::make('quantity')
  199. ->required()
  200. ->numeric()
  201. ->live()
  202. ->maxValue(9999999999.99)
  203. ->default(1),
  204. Forms\Components\TextInput::make('unit_price')
  205. ->hiddenLabel()
  206. ->numeric()
  207. ->live()
  208. ->maxValue(9999999999.99)
  209. ->default(0),
  210. CreateAdjustmentSelect::make('salesTaxes')
  211. ->label('Taxes')
  212. ->category(AdjustmentCategory::Tax)
  213. ->type(AdjustmentType::Sales)
  214. ->adjustmentsRelationship('salesTaxes')
  215. ->saveRelationshipsUsing(null)
  216. ->dehydrated(true)
  217. ->preload()
  218. ->multiple()
  219. ->live()
  220. ->searchable(),
  221. CreateAdjustmentSelect::make('salesDiscounts')
  222. ->label('Discounts')
  223. ->category(AdjustmentCategory::Discount)
  224. ->type(AdjustmentType::Sales)
  225. ->adjustmentsRelationship('salesDiscounts')
  226. ->saveRelationshipsUsing(null)
  227. ->dehydrated(true)
  228. ->multiple()
  229. ->live()
  230. ->hidden(function (Forms\Get $get) {
  231. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  232. return $discountMethod->isPerDocument();
  233. })
  234. ->searchable(),
  235. Forms\Components\Placeholder::make('total')
  236. ->hiddenLabel()
  237. ->extraAttributes(['class' => 'text-left sm:text-right'])
  238. ->content(function (Forms\Get $get) {
  239. $quantity = max((float) ($get('quantity') ?? 0), 0);
  240. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  241. $salesTaxes = $get('salesTaxes') ?? [];
  242. $salesDiscounts = $get('salesDiscounts') ?? [];
  243. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  244. $subtotal = $quantity * $unitPrice;
  245. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  246. $taxAmountInCents = Adjustment::whereIn('id', $salesTaxes)
  247. ->get()
  248. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  249. if ($adjustment->computation->isPercentage()) {
  250. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  251. } else {
  252. return $adjustment->getRawOriginal('rate');
  253. }
  254. });
  255. $discountAmountInCents = Adjustment::whereIn('id', $salesDiscounts)
  256. ->get()
  257. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  258. if ($adjustment->computation->isPercentage()) {
  259. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  260. } else {
  261. return $adjustment->getRawOriginal('rate');
  262. }
  263. });
  264. // Final total
  265. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  266. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  267. }),
  268. ]),
  269. DocumentTotals::make()
  270. ->type(DocumentType::Invoice),
  271. Forms\Components\Textarea::make('terms')
  272. ->default($settings->terms)
  273. ->columnSpanFull(),
  274. ]),
  275. DocumentFooterSection::make('Invoice Footer')
  276. ->defaultFooter($settings->footer),
  277. ]);
  278. }
  279. public static function table(Table $table): Table
  280. {
  281. return $table
  282. ->defaultSort('due_date')
  283. ->modifyQueryUsing(function (Builder $query, Tables\Contracts\HasTable $livewire) {
  284. if (property_exists($livewire, 'recurringInvoice')) {
  285. $recurringInvoiceId = $livewire->recurringInvoice;
  286. if (! empty($recurringInvoiceId)) {
  287. $query->where('recurring_invoice_id', $recurringInvoiceId);
  288. }
  289. }
  290. return $query;
  291. })
  292. ->columns([
  293. Columns::id(),
  294. Tables\Columns\TextColumn::make('status')
  295. ->badge()
  296. ->searchable(),
  297. Tables\Columns\TextColumn::make('due_date')
  298. ->label('Due')
  299. ->asRelativeDay()
  300. ->sortable()
  301. ->hideOnTabs(['draft']),
  302. Tables\Columns\TextColumn::make('date')
  303. ->date()
  304. ->sortable(),
  305. Tables\Columns\TextColumn::make('invoice_number')
  306. ->label('Number')
  307. ->searchable()
  308. ->description(function (Invoice $record) {
  309. return $record->source_type?->getLabel();
  310. })
  311. ->sortable(),
  312. Tables\Columns\TextColumn::make('client.name')
  313. ->sortable()
  314. ->searchable()
  315. ->hiddenOn(InvoicesRelationManager::class),
  316. Tables\Columns\TextColumn::make('total')
  317. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  318. ->sortable()
  319. ->toggleable()
  320. ->alignEnd(),
  321. Tables\Columns\TextColumn::make('amount_paid')
  322. ->label('Amount paid')
  323. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  324. ->sortable()
  325. ->alignEnd()
  326. ->showOnTabs(['unpaid']),
  327. Tables\Columns\TextColumn::make('amount_due')
  328. ->label('Amount due')
  329. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  330. ->sortable()
  331. ->alignEnd()
  332. ->hideOnTabs(['draft']),
  333. ])
  334. ->filters([
  335. Tables\Filters\SelectFilter::make('client')
  336. ->relationship('client', 'name')
  337. ->searchable()
  338. ->preload()
  339. ->hiddenOn(InvoicesRelationManager::class),
  340. Tables\Filters\SelectFilter::make('status')
  341. ->options(InvoiceStatus::class)
  342. ->multiple(),
  343. Tables\Filters\TernaryFilter::make('has_payments')
  344. ->label('Has payments')
  345. ->queries(
  346. true: fn (Builder $query) => $query->whereHas('payments'),
  347. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  348. ),
  349. Tables\Filters\SelectFilter::make('source_type')
  350. ->label('Source type')
  351. ->options([
  352. DocumentType::Estimate->value => DocumentType::Estimate->getLabel(),
  353. DocumentType::RecurringInvoice->value => DocumentType::RecurringInvoice->getLabel(),
  354. ])
  355. ->native(false)
  356. ->query(function (Builder $query, array $data) {
  357. $sourceType = $data['value'] ?? null;
  358. return match ($sourceType) {
  359. DocumentType::Estimate->value => $query->whereNotNull('estimate_id'),
  360. DocumentType::RecurringInvoice->value => $query->whereNotNull('recurring_invoice_id'),
  361. default => $query,
  362. };
  363. }),
  364. DateRangeFilter::make('date')
  365. ->fromLabel('From date')
  366. ->untilLabel('To date')
  367. ->indicatorLabel('Date'),
  368. DateRangeFilter::make('due_date')
  369. ->fromLabel('From due date')
  370. ->untilLabel('To due date')
  371. ->indicatorLabel('Due'),
  372. ])
  373. ->actions([
  374. Tables\Actions\ActionGroup::make([
  375. Tables\Actions\ActionGroup::make([
  376. Tables\Actions\EditAction::make()
  377. ->url(static fn (Invoice $record) => Pages\EditInvoice::getUrl(['record' => $record])),
  378. Tables\Actions\ViewAction::make()
  379. ->url(static fn (Invoice $record) => Pages\ViewInvoice::getUrl(['record' => $record])),
  380. Invoice::getReplicateAction(Tables\Actions\ReplicateAction::class),
  381. Invoice::getApproveDraftAction(Tables\Actions\Action::class),
  382. Invoice::getMarkAsSentAction(Tables\Actions\Action::class),
  383. Tables\Actions\Action::make('recordPayment')
  384. ->label(fn (Invoice $record) => $record->status === InvoiceStatus::Overpaid ? 'Refund Overpayment' : 'Record Payment')
  385. ->stickyModalHeader()
  386. ->stickyModalFooter()
  387. ->modalFooterActionsAlignment(Alignment::End)
  388. ->modalWidth(MaxWidth::TwoExtraLarge)
  389. ->icon('heroicon-o-credit-card')
  390. ->visible(function (Invoice $record) {
  391. return $record->canRecordPayment();
  392. })
  393. ->mountUsing(function (Invoice $record, Form $form) {
  394. $form->fill([
  395. 'posted_at' => now(),
  396. 'amount' => $record->status === InvoiceStatus::Overpaid ? ltrim($record->amount_due, '-') : $record->amount_due,
  397. ]);
  398. })
  399. ->databaseTransaction()
  400. ->successNotificationTitle('Payment recorded')
  401. ->form([
  402. Forms\Components\DatePicker::make('posted_at')
  403. ->label('Date'),
  404. Forms\Components\TextInput::make('amount')
  405. ->label('Amount')
  406. ->required()
  407. ->money(fn (Invoice $record) => $record->currency_code)
  408. ->live(onBlur: true)
  409. ->helperText(function (Invoice $record, $state) {
  410. $invoiceCurrency = $record->currency_code;
  411. if (! CurrencyConverter::isValidAmount($state, $invoiceCurrency)) {
  412. return null;
  413. }
  414. $amountDue = $record->getRawOriginal('amount_due');
  415. $amount = CurrencyConverter::convertToCents($state, $invoiceCurrency);
  416. if ($amount <= 0) {
  417. return 'Please enter a valid positive amount';
  418. }
  419. if ($record->status === InvoiceStatus::Overpaid) {
  420. $newAmountDue = $amountDue + $amount;
  421. } else {
  422. $newAmountDue = $amountDue - $amount;
  423. }
  424. return match (true) {
  425. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $invoiceCurrency),
  426. $newAmountDue === 0 => 'Invoice will be fully paid',
  427. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $invoiceCurrency),
  428. };
  429. })
  430. ->rules([
  431. static fn (Invoice $record): Closure => static function (string $attribute, $value, Closure $fail) use ($record) {
  432. if (! CurrencyConverter::isValidAmount($value, $record->currency_code)) {
  433. $fail('Please enter a valid amount');
  434. }
  435. },
  436. ]),
  437. Forms\Components\Select::make('payment_method')
  438. ->label('Payment method')
  439. ->required()
  440. ->options(PaymentMethod::class),
  441. Forms\Components\Select::make('bank_account_id')
  442. ->label('Account')
  443. ->required()
  444. ->options(function () {
  445. return BankAccount::query()
  446. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  447. ->select(['bank_accounts.id', 'accounts.name'])
  448. ->pluck('accounts.name', 'bank_accounts.id')
  449. ->toArray();
  450. })
  451. ->searchable(),
  452. Forms\Components\Textarea::make('notes')
  453. ->label('Notes'),
  454. ])
  455. ->action(function (Invoice $record, Tables\Actions\Action $action, array $data) {
  456. $record->recordPayment($data);
  457. $action->success();
  458. }),
  459. ])->dropdown(false),
  460. Tables\Actions\DeleteAction::make(),
  461. ]),
  462. ])
  463. ->bulkActions([
  464. Tables\Actions\BulkActionGroup::make([
  465. Tables\Actions\DeleteBulkAction::make(),
  466. ReplicateBulkAction::make()
  467. ->label('Replicate')
  468. ->modalWidth(MaxWidth::Large)
  469. ->modalDescription('Replicating invoices will also replicate their line items. Are you sure you want to proceed?')
  470. ->successNotificationTitle('Invoices replicated successfully')
  471. ->failureNotificationTitle('Failed to replicate invoices')
  472. ->databaseTransaction()
  473. ->deselectRecordsAfterCompletion()
  474. ->excludeAttributes([
  475. 'status',
  476. 'amount_paid',
  477. 'amount_due',
  478. 'created_by',
  479. 'updated_by',
  480. 'created_at',
  481. 'updated_at',
  482. 'invoice_number',
  483. 'date',
  484. 'due_date',
  485. 'approved_at',
  486. 'paid_at',
  487. 'last_sent_at',
  488. 'last_viewed_at',
  489. ])
  490. ->beforeReplicaSaved(function (Invoice $replica) {
  491. $replica->status = InvoiceStatus::Draft;
  492. $replica->invoice_number = Invoice::getNextDocumentNumber();
  493. $replica->date = now();
  494. $replica->due_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  495. })
  496. ->withReplicatedRelationships(['lineItems'])
  497. ->withExcludedRelationshipAttributes('lineItems', [
  498. 'subtotal',
  499. 'total',
  500. 'created_by',
  501. 'updated_by',
  502. 'created_at',
  503. 'updated_at',
  504. ]),
  505. Tables\Actions\BulkAction::make('approveDrafts')
  506. ->label('Approve')
  507. ->icon('heroicon-o-check-circle')
  508. ->databaseTransaction()
  509. ->successNotificationTitle('Invoices approved')
  510. ->failureNotificationTitle('Failed to Approve Invoices')
  511. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  512. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeApproved());
  513. if ($isInvalid) {
  514. Notification::make()
  515. ->title('Approval failed')
  516. ->body('Only draft invoices can be approved. Please adjust your selection and try again.')
  517. ->persistent()
  518. ->danger()
  519. ->send();
  520. $action->cancel(true);
  521. }
  522. })
  523. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  524. $records->each(function (Invoice $record) {
  525. $record->approveDraft();
  526. });
  527. $action->success();
  528. }),
  529. Tables\Actions\BulkAction::make('markAsSent')
  530. ->label('Mark as sent')
  531. ->icon('heroicon-o-paper-airplane')
  532. ->databaseTransaction()
  533. ->successNotificationTitle('Invoices sent')
  534. ->failureNotificationTitle('Failed to Mark Invoices as Sent')
  535. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  536. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeMarkedAsSent());
  537. if ($isInvalid) {
  538. Notification::make()
  539. ->title('Sending failed')
  540. ->body('Only unsent invoices can be marked as sent. Please adjust your selection and try again.')
  541. ->persistent()
  542. ->danger()
  543. ->send();
  544. $action->cancel(true);
  545. }
  546. })
  547. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  548. $records->each(function (Invoice $record) {
  549. $record->markAsSent();
  550. });
  551. $action->success();
  552. }),
  553. Tables\Actions\BulkAction::make('recordPayments')
  554. ->label('Record payments')
  555. ->icon('heroicon-o-credit-card')
  556. ->stickyModalHeader()
  557. ->stickyModalFooter()
  558. ->modalFooterActionsAlignment(Alignment::End)
  559. ->modalWidth(MaxWidth::TwoExtraLarge)
  560. ->databaseTransaction()
  561. ->successNotificationTitle('Payments recorded')
  562. ->failureNotificationTitle('Failed to Record Payments')
  563. ->deselectRecordsAfterCompletion()
  564. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  565. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBulkRecordPayment());
  566. if ($isInvalid) {
  567. Notification::make()
  568. ->title('Payment recording failed')
  569. ->body('Invoices that are either draft, paid, overpaid, voided, or are in a foreign currency cannot be processed through bulk payments. Please adjust your selection and try again.')
  570. ->persistent()
  571. ->danger()
  572. ->send();
  573. $action->cancel(true);
  574. }
  575. })
  576. ->mountUsing(function (DocumentCollection $records, Form $form) {
  577. $totalAmountDue = $records->sumMoneyFormattedSimple('amount_due');
  578. $form->fill([
  579. 'posted_at' => now(),
  580. 'amount' => $totalAmountDue,
  581. ]);
  582. })
  583. ->form([
  584. Forms\Components\DatePicker::make('posted_at')
  585. ->label('Date'),
  586. Forms\Components\TextInput::make('amount')
  587. ->label('Amount')
  588. ->required()
  589. ->money()
  590. ->rules([
  591. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  592. if (! CurrencyConverter::isValidAmount($value)) {
  593. $fail('Please enter a valid amount');
  594. }
  595. },
  596. ]),
  597. Forms\Components\Select::make('payment_method')
  598. ->label('Payment method')
  599. ->required()
  600. ->options(PaymentMethod::class),
  601. Forms\Components\Select::make('bank_account_id')
  602. ->label('Account')
  603. ->required()
  604. ->options(function () {
  605. return BankAccount::query()
  606. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  607. ->select(['bank_accounts.id', 'accounts.name'])
  608. ->pluck('accounts.name', 'bank_accounts.id')
  609. ->toArray();
  610. })
  611. ->searchable(),
  612. Forms\Components\Textarea::make('notes')
  613. ->label('Notes'),
  614. ])
  615. ->before(function (DocumentCollection $records, Tables\Actions\BulkAction $action, array $data) {
  616. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  617. $totalAmountDue = $records->sumMoneyInCents('amount_due');
  618. if ($totalPaymentAmount > $totalAmountDue) {
  619. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  620. Notification::make()
  621. ->title('Excess payment amount')
  622. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  623. ->persistent()
  624. ->warning()
  625. ->send();
  626. $action->halt(true);
  627. }
  628. })
  629. ->action(function (DocumentCollection $records, Tables\Actions\BulkAction $action, array $data) {
  630. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  631. $remainingAmount = $totalPaymentAmount;
  632. $records->each(function (Invoice $record) use (&$remainingAmount, $data) {
  633. $amountDue = $record->getRawOriginal('amount_due');
  634. if ($amountDue <= 0 || $remainingAmount <= 0) {
  635. return;
  636. }
  637. $paymentAmount = min($amountDue, $remainingAmount);
  638. $data['amount'] = CurrencyConverter::convertCentsToFormatSimple($paymentAmount);
  639. $record->recordPayment($data);
  640. $remainingAmount -= $paymentAmount;
  641. });
  642. $action->success();
  643. }),
  644. ]),
  645. ]);
  646. }
  647. public static function getRelations(): array
  648. {
  649. return [
  650. RelationManagers\PaymentsRelationManager::class,
  651. ];
  652. }
  653. public static function getPages(): array
  654. {
  655. return [
  656. 'index' => Pages\ListInvoices::route('/'),
  657. 'create' => Pages\CreateInvoice::route('/create'),
  658. 'view' => Pages\ViewInvoice::route('/{record}'),
  659. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  660. ];
  661. }
  662. public static function getWidgets(): array
  663. {
  664. return [
  665. Widgets\InvoiceOverview::class,
  666. ];
  667. }
  668. }