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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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. ->reorderAtStart()
  183. ->cloneable()
  184. ->addActionLabel('Add an item')
  185. ->headers(function (Forms\Get $get) use ($settings) {
  186. $hasDiscounts = DocumentDiscountMethod::parse($get('discount_method'))->isPerLineItem();
  187. $headers = [
  188. Header::make($settings->resolveColumnLabel('item_name', 'Items'))
  189. ->width('30%'),
  190. Header::make($settings->resolveColumnLabel('unit_name', 'Quantity'))
  191. ->width('10%'),
  192. Header::make($settings->resolveColumnLabel('price_name', 'Price'))
  193. ->width('10%'),
  194. ];
  195. if ($hasDiscounts) {
  196. $headers[] = Header::make('Adjustments')->width('30%');
  197. } else {
  198. $headers[] = Header::make('Taxes')->width('30%');
  199. }
  200. $headers[] = Header::make($settings->resolveColumnLabel('amount_name', 'Amount'))
  201. ->width('10%')
  202. ->align('right');
  203. return $headers;
  204. })
  205. ->schema([
  206. Forms\Components\Group::make([
  207. CreateOfferingSelect::make('offering_id')
  208. ->label('Item')
  209. ->hiddenLabel()
  210. ->placeholder('Select item')
  211. ->required()
  212. ->live()
  213. ->inlineSuffix()
  214. ->sellable()
  215. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state, ?DocumentLineItem $record) {
  216. $offeringId = $state;
  217. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  218. $isPerLineItem = $discountMethod->isPerLineItem();
  219. $existingTaxIds = [];
  220. $existingDiscountIds = [];
  221. if ($record) {
  222. $existingTaxIds = $record->salesTaxes()->pluck('adjustments.id')->toArray();
  223. if ($isPerLineItem) {
  224. $existingDiscountIds = $record->salesDiscounts()->pluck('adjustments.id')->toArray();
  225. }
  226. }
  227. $with = [
  228. 'salesTaxes' => static function ($query) use ($existingTaxIds) {
  229. $query->where(static function ($query) use ($existingTaxIds) {
  230. $query->where('status', AdjustmentStatus::Active)
  231. ->orWhereIn('adjustments.id', $existingTaxIds);
  232. });
  233. },
  234. ];
  235. if ($isPerLineItem) {
  236. $with['salesDiscounts'] = static function ($query) use ($existingDiscountIds) {
  237. $query->where(static function ($query) use ($existingDiscountIds) {
  238. $query->where('status', AdjustmentStatus::Active)
  239. ->orWhereIn('adjustments.id', $existingDiscountIds);
  240. });
  241. };
  242. }
  243. $offeringRecord = Offering::with($with)->find($offeringId);
  244. if (! $offeringRecord) {
  245. return;
  246. }
  247. $unitPrice = CurrencyConverter::convertToFloat($offeringRecord->price, $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency());
  248. $set('description', $offeringRecord->description);
  249. $set('unit_price', $unitPrice);
  250. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  251. if ($isPerLineItem) {
  252. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  253. }
  254. }),
  255. Forms\Components\TextInput::make('description')
  256. ->placeholder('Enter item description')
  257. ->hiddenLabel(),
  258. ])->columnSpan(1),
  259. Forms\Components\TextInput::make('quantity')
  260. ->required()
  261. ->numeric()
  262. ->live()
  263. ->maxValue(9999999999.99)
  264. ->default(1),
  265. Forms\Components\TextInput::make('unit_price')
  266. ->hiddenLabel()
  267. ->numeric()
  268. ->live()
  269. ->maxValue(9999999999.99)
  270. ->default(0),
  271. Forms\Components\Group::make([
  272. CreateAdjustmentSelect::make('salesTaxes')
  273. ->label('Taxes')
  274. ->hiddenLabel()
  275. ->placeholder('Select taxes')
  276. ->category(AdjustmentCategory::Tax)
  277. ->type(AdjustmentType::Sales)
  278. ->adjustmentsRelationship('salesTaxes')
  279. ->saveRelationshipsUsing(null)
  280. ->dehydrated(true)
  281. ->inlineSuffix()
  282. ->preload()
  283. ->multiple()
  284. ->live()
  285. ->searchable(),
  286. CreateAdjustmentSelect::make('salesDiscounts')
  287. ->label('Discounts')
  288. ->hiddenLabel()
  289. ->placeholder('Select discounts')
  290. ->category(AdjustmentCategory::Discount)
  291. ->type(AdjustmentType::Sales)
  292. ->adjustmentsRelationship('salesDiscounts')
  293. ->saveRelationshipsUsing(null)
  294. ->dehydrated(true)
  295. ->inlineSuffix()
  296. ->multiple()
  297. ->live()
  298. ->hidden(function (Forms\Get $get) {
  299. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  300. return $discountMethod->isPerDocument();
  301. })
  302. ->searchable(),
  303. ])->columnSpan(1),
  304. Forms\Components\Placeholder::make('total')
  305. ->hiddenLabel()
  306. ->extraAttributes(['class' => 'text-left sm:text-right'])
  307. ->content(function (Forms\Get $get) {
  308. $quantity = max((float) ($get('quantity') ?? 0), 0);
  309. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  310. $salesTaxes = $get('salesTaxes') ?? [];
  311. $salesDiscounts = $get('salesDiscounts') ?? [];
  312. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  313. $subtotal = $quantity * $unitPrice;
  314. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  315. $taxAmountInCents = Adjustment::whereIn('id', $salesTaxes)
  316. ->get()
  317. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  318. if ($adjustment->computation->isPercentage()) {
  319. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  320. } else {
  321. return $adjustment->getRawOriginal('rate');
  322. }
  323. });
  324. $discountAmountInCents = Adjustment::whereIn('id', $salesDiscounts)
  325. ->get()
  326. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  327. if ($adjustment->computation->isPercentage()) {
  328. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  329. } else {
  330. return $adjustment->getRawOriginal('rate');
  331. }
  332. });
  333. // Final total
  334. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  335. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  336. }),
  337. ]),
  338. DocumentTotals::make()
  339. ->type(DocumentType::Invoice),
  340. Forms\Components\Textarea::make('terms')
  341. ->default($settings->terms)
  342. ->columnSpanFull(),
  343. ]),
  344. DocumentFooterSection::make('Invoice Footer')
  345. ->defaultFooter($settings->footer),
  346. ]);
  347. }
  348. public static function table(Table $table): Table
  349. {
  350. return $table
  351. ->defaultSort('due_date')
  352. ->modifyQueryUsing(function (Builder $query, Tables\Contracts\HasTable $livewire) {
  353. if (property_exists($livewire, 'recurringInvoice')) {
  354. $recurringInvoiceId = $livewire->recurringInvoice;
  355. if (! empty($recurringInvoiceId)) {
  356. $query->where('recurring_invoice_id', $recurringInvoiceId);
  357. }
  358. }
  359. return $query;
  360. })
  361. ->columns([
  362. Columns::id(),
  363. Tables\Columns\TextColumn::make('status')
  364. ->badge()
  365. ->searchable(),
  366. Tables\Columns\TextColumn::make('due_date')
  367. ->label('Due')
  368. ->asRelativeDay()
  369. ->sortable()
  370. ->hideOnTabs(['draft']),
  371. Tables\Columns\TextColumn::make('date')
  372. ->date()
  373. ->sortable(),
  374. Tables\Columns\TextColumn::make('invoice_number')
  375. ->label('Number')
  376. ->searchable()
  377. ->description(function (Invoice $record) {
  378. return $record->source_type?->getLabel();
  379. })
  380. ->sortable(),
  381. Tables\Columns\TextColumn::make('client.name')
  382. ->sortable()
  383. ->searchable()
  384. ->hiddenOn(InvoicesRelationManager::class),
  385. Tables\Columns\TextColumn::make('total')
  386. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  387. ->sortable()
  388. ->toggleable()
  389. ->alignEnd(),
  390. Tables\Columns\TextColumn::make('amount_paid')
  391. ->label('Amount paid')
  392. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  393. ->sortable()
  394. ->alignEnd()
  395. ->showOnTabs(['unpaid']),
  396. Tables\Columns\TextColumn::make('amount_due')
  397. ->label('Amount due')
  398. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  399. ->sortable()
  400. ->alignEnd()
  401. ->hideOnTabs(['draft']),
  402. ])
  403. ->filters([
  404. Tables\Filters\SelectFilter::make('client')
  405. ->relationship('client', 'name')
  406. ->searchable()
  407. ->preload()
  408. ->hiddenOn(InvoicesRelationManager::class),
  409. Tables\Filters\SelectFilter::make('status')
  410. ->options(InvoiceStatus::class)
  411. ->multiple(),
  412. Tables\Filters\TernaryFilter::make('has_payments')
  413. ->label('Has payments')
  414. ->queries(
  415. true: fn (Builder $query) => $query->whereHas('payments'),
  416. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  417. ),
  418. Tables\Filters\SelectFilter::make('source_type')
  419. ->label('Source type')
  420. ->options([
  421. DocumentType::Estimate->value => DocumentType::Estimate->getLabel(),
  422. DocumentType::RecurringInvoice->value => DocumentType::RecurringInvoice->getLabel(),
  423. ])
  424. ->native(false)
  425. ->query(function (Builder $query, array $data) {
  426. $sourceType = $data['value'] ?? null;
  427. return match ($sourceType) {
  428. DocumentType::Estimate->value => $query->whereNotNull('estimate_id'),
  429. DocumentType::RecurringInvoice->value => $query->whereNotNull('recurring_invoice_id'),
  430. default => $query,
  431. };
  432. }),
  433. DateRangeFilter::make('date')
  434. ->fromLabel('From date')
  435. ->untilLabel('To date')
  436. ->indicatorLabel('Date'),
  437. DateRangeFilter::make('due_date')
  438. ->fromLabel('From due date')
  439. ->untilLabel('To due date')
  440. ->indicatorLabel('Due'),
  441. ])
  442. ->actions([
  443. Tables\Actions\ActionGroup::make([
  444. Tables\Actions\ActionGroup::make([
  445. Tables\Actions\EditAction::make()
  446. ->url(static fn (Invoice $record) => Pages\EditInvoice::getUrl(['record' => $record])),
  447. Tables\Actions\ViewAction::make()
  448. ->url(static fn (Invoice $record) => Pages\ViewInvoice::getUrl(['record' => $record])),
  449. Invoice::getReplicateAction(Tables\Actions\ReplicateAction::class),
  450. Invoice::getApproveDraftAction(Tables\Actions\Action::class),
  451. Invoice::getMarkAsSentAction(Tables\Actions\Action::class),
  452. Tables\Actions\Action::make('recordPayment')
  453. ->label(fn (Invoice $record) => $record->status === InvoiceStatus::Overpaid ? 'Refund Overpayment' : 'Record Payment')
  454. ->stickyModalHeader()
  455. ->stickyModalFooter()
  456. ->modalFooterActionsAlignment(Alignment::End)
  457. ->modalWidth(MaxWidth::TwoExtraLarge)
  458. ->icon('heroicon-o-credit-card')
  459. ->visible(function (Invoice $record) {
  460. return $record->canRecordPayment();
  461. })
  462. ->mountUsing(function (Invoice $record, Form $form) {
  463. $form->fill([
  464. 'posted_at' => now(),
  465. 'amount' => $record->status === InvoiceStatus::Overpaid ? ltrim($record->amount_due, '-') : $record->amount_due,
  466. ]);
  467. })
  468. ->databaseTransaction()
  469. ->successNotificationTitle('Payment recorded')
  470. ->form([
  471. Forms\Components\DatePicker::make('posted_at')
  472. ->label('Date'),
  473. Forms\Components\TextInput::make('amount')
  474. ->label('Amount')
  475. ->required()
  476. ->money(fn (Invoice $record) => $record->currency_code)
  477. ->live(onBlur: true)
  478. ->helperText(function (Invoice $record, $state) {
  479. $invoiceCurrency = $record->currency_code;
  480. if (! CurrencyConverter::isValidAmount($state, $invoiceCurrency)) {
  481. return null;
  482. }
  483. $amountDue = $record->getRawOriginal('amount_due');
  484. $amount = CurrencyConverter::convertToCents($state, $invoiceCurrency);
  485. if ($amount <= 0) {
  486. return 'Please enter a valid positive amount';
  487. }
  488. if ($record->status === InvoiceStatus::Overpaid) {
  489. $newAmountDue = $amountDue + $amount;
  490. } else {
  491. $newAmountDue = $amountDue - $amount;
  492. }
  493. return match (true) {
  494. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $invoiceCurrency),
  495. $newAmountDue === 0 => 'Invoice will be fully paid',
  496. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $invoiceCurrency),
  497. };
  498. })
  499. ->rules([
  500. static fn (Invoice $record): Closure => static function (string $attribute, $value, Closure $fail) use ($record) {
  501. if (! CurrencyConverter::isValidAmount($value, $record->currency_code)) {
  502. $fail('Please enter a valid amount');
  503. }
  504. },
  505. ]),
  506. Forms\Components\Select::make('payment_method')
  507. ->label('Payment method')
  508. ->required()
  509. ->options(PaymentMethod::class),
  510. Forms\Components\Select::make('bank_account_id')
  511. ->label('Account')
  512. ->required()
  513. ->options(function () {
  514. return BankAccount::query()
  515. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  516. ->select(['bank_accounts.id', 'accounts.name'])
  517. ->pluck('accounts.name', 'bank_accounts.id')
  518. ->toArray();
  519. })
  520. ->searchable(),
  521. Forms\Components\Textarea::make('notes')
  522. ->label('Notes'),
  523. ])
  524. ->action(function (Invoice $record, Tables\Actions\Action $action, array $data) {
  525. $record->recordPayment($data);
  526. $action->success();
  527. }),
  528. ])->dropdown(false),
  529. Tables\Actions\DeleteAction::make(),
  530. ]),
  531. ])
  532. ->bulkActions([
  533. Tables\Actions\BulkActionGroup::make([
  534. Tables\Actions\DeleteBulkAction::make(),
  535. ReplicateBulkAction::make()
  536. ->label('Replicate')
  537. ->modalWidth(MaxWidth::Large)
  538. ->modalDescription('Replicating invoices will also replicate their line items. Are you sure you want to proceed?')
  539. ->successNotificationTitle('Invoices replicated successfully')
  540. ->failureNotificationTitle('Failed to replicate invoices')
  541. ->databaseTransaction()
  542. ->excludeAttributes([
  543. 'status',
  544. 'amount_paid',
  545. 'amount_due',
  546. 'created_by',
  547. 'updated_by',
  548. 'created_at',
  549. 'updated_at',
  550. 'invoice_number',
  551. 'date',
  552. 'due_date',
  553. 'approved_at',
  554. 'paid_at',
  555. 'last_sent_at',
  556. 'last_viewed_at',
  557. ])
  558. ->beforeReplicaSaved(function (Invoice $replica) {
  559. $replica->status = InvoiceStatus::Draft;
  560. $replica->invoice_number = Invoice::getNextDocumentNumber();
  561. $replica->date = now();
  562. $replica->due_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  563. })
  564. ->withReplicatedRelationships(['lineItems'])
  565. ->withExcludedRelationshipAttributes('lineItems', [
  566. 'subtotal',
  567. 'total',
  568. 'created_by',
  569. 'updated_by',
  570. 'created_at',
  571. 'updated_at',
  572. ]),
  573. Tables\Actions\BulkAction::make('approveDrafts')
  574. ->label('Approve')
  575. ->icon('heroicon-o-check-circle')
  576. ->databaseTransaction()
  577. ->successNotificationTitle('Invoices approved')
  578. ->failureNotificationTitle('Failed to Approve Invoices')
  579. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  580. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeApproved());
  581. if ($isInvalid) {
  582. Notification::make()
  583. ->title('Approval failed')
  584. ->body('Only draft invoices can be approved. Please adjust your selection and try again.')
  585. ->persistent()
  586. ->danger()
  587. ->send();
  588. $action->cancel(true);
  589. }
  590. })
  591. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  592. $records->each(function (Invoice $record) {
  593. $record->approveDraft();
  594. });
  595. $action->success();
  596. }),
  597. Tables\Actions\BulkAction::make('markAsSent')
  598. ->label('Mark as sent')
  599. ->icon('heroicon-o-paper-airplane')
  600. ->databaseTransaction()
  601. ->successNotificationTitle('Invoices sent')
  602. ->failureNotificationTitle('Failed to Mark Invoices as Sent')
  603. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  604. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeMarkedAsSent());
  605. if ($isInvalid) {
  606. Notification::make()
  607. ->title('Sending failed')
  608. ->body('Only unsent invoices can be marked as sent. Please adjust your selection and try again.')
  609. ->persistent()
  610. ->danger()
  611. ->send();
  612. $action->cancel(true);
  613. }
  614. })
  615. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  616. $records->each(function (Invoice $record) {
  617. $record->markAsSent();
  618. });
  619. $action->success();
  620. }),
  621. Tables\Actions\BulkAction::make('recordPayments')
  622. ->label('Record payments')
  623. ->icon('heroicon-o-credit-card')
  624. ->stickyModalHeader()
  625. ->stickyModalFooter()
  626. ->modalFooterActionsAlignment(Alignment::End)
  627. ->modalWidth(MaxWidth::TwoExtraLarge)
  628. ->databaseTransaction()
  629. ->successNotificationTitle('Payments recorded')
  630. ->failureNotificationTitle('Failed to Record Payments')
  631. ->deselectRecordsAfterCompletion()
  632. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  633. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBulkRecordPayment());
  634. if ($isInvalid) {
  635. Notification::make()
  636. ->title('Payment recording failed')
  637. ->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.')
  638. ->persistent()
  639. ->danger()
  640. ->send();
  641. $action->cancel(true);
  642. }
  643. })
  644. ->mountUsing(function (DocumentCollection $records, Form $form) {
  645. $totalAmountDue = $records->sumMoneyFormattedSimple('amount_due');
  646. $form->fill([
  647. 'posted_at' => now(),
  648. 'amount' => $totalAmountDue,
  649. ]);
  650. })
  651. ->form([
  652. Forms\Components\DatePicker::make('posted_at')
  653. ->label('Date'),
  654. Forms\Components\TextInput::make('amount')
  655. ->label('Amount')
  656. ->required()
  657. ->money()
  658. ->rules([
  659. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  660. if (! CurrencyConverter::isValidAmount($value)) {
  661. $fail('Please enter a valid amount');
  662. }
  663. },
  664. ]),
  665. Forms\Components\Select::make('payment_method')
  666. ->label('Payment method')
  667. ->required()
  668. ->options(PaymentMethod::class),
  669. Forms\Components\Select::make('bank_account_id')
  670. ->label('Account')
  671. ->required()
  672. ->options(function () {
  673. return BankAccount::query()
  674. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  675. ->select(['bank_accounts.id', 'accounts.name'])
  676. ->pluck('accounts.name', 'bank_accounts.id')
  677. ->toArray();
  678. })
  679. ->searchable(),
  680. Forms\Components\Textarea::make('notes')
  681. ->label('Notes'),
  682. ])
  683. ->before(function (DocumentCollection $records, Tables\Actions\BulkAction $action, array $data) {
  684. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  685. $totalAmountDue = $records->sumMoneyInCents('amount_due');
  686. if ($totalPaymentAmount > $totalAmountDue) {
  687. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  688. Notification::make()
  689. ->title('Excess payment amount')
  690. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  691. ->persistent()
  692. ->warning()
  693. ->send();
  694. $action->halt(true);
  695. }
  696. })
  697. ->action(function (DocumentCollection $records, Tables\Actions\BulkAction $action, array $data) {
  698. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  699. $remainingAmount = $totalPaymentAmount;
  700. $records->each(function (Invoice $record) use (&$remainingAmount, $data) {
  701. $amountDue = $record->getRawOriginal('amount_due');
  702. if ($amountDue <= 0 || $remainingAmount <= 0) {
  703. return;
  704. }
  705. $paymentAmount = min($amountDue, $remainingAmount);
  706. $data['amount'] = CurrencyConverter::convertCentsToFormatSimple($paymentAmount);
  707. $record->recordPayment($data);
  708. $remainingAmount -= $paymentAmount;
  709. });
  710. $action->success();
  711. }),
  712. ]),
  713. ]);
  714. }
  715. public static function getPages(): array
  716. {
  717. return [
  718. 'index' => Pages\ListInvoices::route('/'),
  719. 'create' => Pages\CreateInvoice::route('/create'),
  720. 'view' => Pages\ViewInvoice::route('/{record}'),
  721. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  722. ];
  723. }
  724. public static function getWidgets(): array
  725. {
  726. return [
  727. Widgets\InvoiceOverview::class,
  728. ];
  729. }
  730. }