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

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