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 44KB

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