Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

InvoiceResource.php 44KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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::convertCentsToFloat($offeringRecord->price, CurrencyAccessor::getDefaultCurrency());
  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. ->numeric()
  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 = max((float) ($get('unit_price') ?? 0), 0);
  311. $salesTaxes = $get('salesTaxes') ?? [];
  312. $salesDiscounts = $get('salesDiscounts') ?? [];
  313. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  314. $subtotal = $quantity * $unitPrice;
  315. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  316. $taxAmountInCents = Adjustment::whereIn('id', $salesTaxes)
  317. ->get()
  318. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  319. if ($adjustment->computation->isPercentage()) {
  320. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  321. } else {
  322. return $adjustment->getRawOriginal('rate');
  323. }
  324. });
  325. $discountAmountInCents = Adjustment::whereIn('id', $salesDiscounts)
  326. ->get()
  327. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  328. if ($adjustment->computation->isPercentage()) {
  329. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  330. } else {
  331. return $adjustment->getRawOriginal('rate');
  332. }
  333. });
  334. // Final total
  335. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  336. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  337. }),
  338. ]),
  339. DocumentTotals::make()
  340. ->type(DocumentType::Invoice),
  341. Forms\Components\Textarea::make('terms')
  342. ->default($settings->terms)
  343. ->columnSpanFull(),
  344. ]),
  345. DocumentFooterSection::make('Invoice Footer')
  346. ->defaultFooter($settings->footer),
  347. ]);
  348. }
  349. public static function table(Table $table): Table
  350. {
  351. return $table
  352. ->defaultSort('due_date')
  353. ->modifyQueryUsing(function (Builder $query, Tables\Contracts\HasTable $livewire) {
  354. if (property_exists($livewire, 'recurringInvoice')) {
  355. $recurringInvoiceId = $livewire->recurringInvoice;
  356. if (! empty($recurringInvoiceId)) {
  357. $query->where('recurring_invoice_id', $recurringInvoiceId);
  358. }
  359. }
  360. return $query;
  361. })
  362. ->columns([
  363. Columns::id(),
  364. Tables\Columns\TextColumn::make('status')
  365. ->badge()
  366. ->searchable(),
  367. Tables\Columns\TextColumn::make('due_date')
  368. ->label('Due')
  369. ->asRelativeDay()
  370. ->sortable()
  371. ->hideOnTabs(['draft']),
  372. Tables\Columns\TextColumn::make('date')
  373. ->date()
  374. ->sortable(),
  375. Tables\Columns\TextColumn::make('invoice_number')
  376. ->label('Number')
  377. ->searchable()
  378. ->description(function (Invoice $record) {
  379. return $record->source_type?->getLabel();
  380. })
  381. ->sortable(),
  382. Tables\Columns\TextColumn::make('client.name')
  383. ->sortable()
  384. ->searchable()
  385. ->hiddenOn(InvoicesRelationManager::class),
  386. Tables\Columns\TextColumn::make('total')
  387. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  388. ->sortable()
  389. ->toggleable()
  390. ->alignEnd(),
  391. Tables\Columns\TextColumn::make('amount_paid')
  392. ->label('Amount paid')
  393. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  394. ->sortable()
  395. ->alignEnd()
  396. ->showOnTabs(['unpaid']),
  397. Tables\Columns\TextColumn::make('amount_due')
  398. ->label('Amount due')
  399. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  400. ->sortable()
  401. ->alignEnd()
  402. ->hideOnTabs(['draft']),
  403. ])
  404. ->filters([
  405. Tables\Filters\SelectFilter::make('client')
  406. ->relationship('client', 'name')
  407. ->searchable()
  408. ->preload()
  409. ->hiddenOn(InvoicesRelationManager::class),
  410. Tables\Filters\SelectFilter::make('status')
  411. ->options(InvoiceStatus::class)
  412. ->multiple(),
  413. Tables\Filters\TernaryFilter::make('has_payments')
  414. ->label('Has payments')
  415. ->queries(
  416. true: fn (Builder $query) => $query->whereHas('payments'),
  417. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  418. ),
  419. Tables\Filters\SelectFilter::make('source_type')
  420. ->label('Source type')
  421. ->options([
  422. DocumentType::Estimate->value => DocumentType::Estimate->getLabel(),
  423. DocumentType::RecurringInvoice->value => DocumentType::RecurringInvoice->getLabel(),
  424. ])
  425. ->native(false)
  426. ->query(function (Builder $query, array $data) {
  427. $sourceType = $data['value'] ?? null;
  428. return match ($sourceType) {
  429. DocumentType::Estimate->value => $query->whereNotNull('estimate_id'),
  430. DocumentType::RecurringInvoice->value => $query->whereNotNull('recurring_invoice_id'),
  431. default => $query,
  432. };
  433. }),
  434. DateRangeFilter::make('date')
  435. ->fromLabel('From date')
  436. ->untilLabel('To date')
  437. ->indicatorLabel('Date'),
  438. DateRangeFilter::make('due_date')
  439. ->fromLabel('From due date')
  440. ->untilLabel('To due date')
  441. ->indicatorLabel('Due'),
  442. ])
  443. ->actions([
  444. Tables\Actions\ActionGroup::make([
  445. Tables\Actions\ActionGroup::make([
  446. Tables\Actions\EditAction::make()
  447. ->url(static fn (Invoice $record) => Pages\EditInvoice::getUrl(['record' => $record])),
  448. Tables\Actions\ViewAction::make()
  449. ->url(static fn (Invoice $record) => Pages\ViewInvoice::getUrl(['record' => $record])),
  450. Invoice::getReplicateAction(Tables\Actions\ReplicateAction::class),
  451. Invoice::getApproveDraftAction(Tables\Actions\Action::class),
  452. Invoice::getMarkAsSentAction(Tables\Actions\Action::class),
  453. Tables\Actions\Action::make('recordPayment')
  454. ->label(fn (Invoice $record) => $record->status === InvoiceStatus::Overpaid ? 'Refund Overpayment' : 'Record Payment')
  455. ->stickyModalHeader()
  456. ->stickyModalFooter()
  457. ->modalFooterActionsAlignment(Alignment::End)
  458. ->modalWidth(MaxWidth::TwoExtraLarge)
  459. ->icon('heroicon-o-credit-card')
  460. ->visible(function (Invoice $record) {
  461. return $record->canRecordPayment();
  462. })
  463. ->mountUsing(function (Invoice $record, Form $form) {
  464. $form->fill([
  465. 'posted_at' => now(),
  466. 'amount' => $record->status === InvoiceStatus::Overpaid ? ltrim($record->amount_due, '-') : $record->amount_due,
  467. ]);
  468. })
  469. ->databaseTransaction()
  470. ->successNotificationTitle('Payment recorded')
  471. ->form([
  472. Forms\Components\DatePicker::make('posted_at')
  473. ->label('Date'),
  474. Forms\Components\TextInput::make('amount')
  475. ->label('Amount')
  476. ->required()
  477. ->money(fn (Invoice $record) => $record->currency_code)
  478. ->live(onBlur: true)
  479. ->helperText(function (Invoice $record, $state) {
  480. $invoiceCurrency = $record->currency_code;
  481. if (! CurrencyConverter::isValidAmount($state, $invoiceCurrency)) {
  482. return null;
  483. }
  484. $amountDue = $record->getRawOriginal('amount_due');
  485. $amount = CurrencyConverter::convertToCents($state, $invoiceCurrency);
  486. if ($amount <= 0) {
  487. return 'Please enter a valid positive amount';
  488. }
  489. if ($record->status === InvoiceStatus::Overpaid) {
  490. $newAmountDue = $amountDue + $amount;
  491. } else {
  492. $newAmountDue = $amountDue - $amount;
  493. }
  494. return match (true) {
  495. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $invoiceCurrency),
  496. $newAmountDue === 0 => 'Invoice will be fully paid',
  497. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $invoiceCurrency),
  498. };
  499. })
  500. ->rules([
  501. static fn (Invoice $record): Closure => static function (string $attribute, $value, Closure $fail) use ($record) {
  502. if (! CurrencyConverter::isValidAmount($value, $record->currency_code)) {
  503. $fail('Please enter a valid amount');
  504. }
  505. },
  506. ]),
  507. Forms\Components\Select::make('payment_method')
  508. ->label('Payment method')
  509. ->required()
  510. ->options(PaymentMethod::class),
  511. Forms\Components\Select::make('bank_account_id')
  512. ->label('Account')
  513. ->required()
  514. ->options(function () {
  515. return BankAccount::query()
  516. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  517. ->select(['bank_accounts.id', 'accounts.name'])
  518. ->pluck('accounts.name', 'bank_accounts.id')
  519. ->toArray();
  520. })
  521. ->searchable(),
  522. Forms\Components\Textarea::make('notes')
  523. ->label('Notes'),
  524. ])
  525. ->action(function (Invoice $record, Tables\Actions\Action $action, array $data) {
  526. $record->recordPayment($data);
  527. $action->success();
  528. }),
  529. ])->dropdown(false),
  530. Tables\Actions\DeleteAction::make(),
  531. ]),
  532. ])
  533. ->bulkActions([
  534. Tables\Actions\BulkActionGroup::make([
  535. Tables\Actions\DeleteBulkAction::make(),
  536. ReplicateBulkAction::make()
  537. ->label('Replicate')
  538. ->modalWidth(MaxWidth::Large)
  539. ->modalDescription('Replicating invoices will also replicate their line items. Are you sure you want to proceed?')
  540. ->successNotificationTitle('Invoices replicated successfully')
  541. ->failureNotificationTitle('Failed to replicate invoices')
  542. ->databaseTransaction()
  543. ->excludeAttributes([
  544. 'status',
  545. 'amount_paid',
  546. 'amount_due',
  547. 'created_by',
  548. 'updated_by',
  549. 'created_at',
  550. 'updated_at',
  551. 'invoice_number',
  552. 'date',
  553. 'due_date',
  554. 'approved_at',
  555. 'paid_at',
  556. 'last_sent_at',
  557. 'last_viewed_at',
  558. ])
  559. ->beforeReplicaSaved(function (Invoice $replica) {
  560. $replica->status = InvoiceStatus::Draft;
  561. $replica->invoice_number = Invoice::getNextDocumentNumber();
  562. $replica->date = now();
  563. $replica->due_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  564. })
  565. ->withReplicatedRelationships(['lineItems'])
  566. ->withExcludedRelationshipAttributes('lineItems', [
  567. 'subtotal',
  568. 'total',
  569. 'created_by',
  570. 'updated_by',
  571. 'created_at',
  572. 'updated_at',
  573. ]),
  574. Tables\Actions\BulkAction::make('approveDrafts')
  575. ->label('Approve')
  576. ->icon('heroicon-o-check-circle')
  577. ->databaseTransaction()
  578. ->successNotificationTitle('Invoices approved')
  579. ->failureNotificationTitle('Failed to Approve Invoices')
  580. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  581. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeApproved());
  582. if ($isInvalid) {
  583. Notification::make()
  584. ->title('Approval failed')
  585. ->body('Only draft invoices can be approved. Please adjust your selection and try again.')
  586. ->persistent()
  587. ->danger()
  588. ->send();
  589. $action->cancel(true);
  590. }
  591. })
  592. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  593. $records->each(function (Invoice $record) {
  594. $record->approveDraft();
  595. });
  596. $action->success();
  597. }),
  598. Tables\Actions\BulkAction::make('markAsSent')
  599. ->label('Mark as sent')
  600. ->icon('heroicon-o-paper-airplane')
  601. ->databaseTransaction()
  602. ->successNotificationTitle('Invoices sent')
  603. ->failureNotificationTitle('Failed to Mark Invoices as Sent')
  604. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  605. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeMarkedAsSent());
  606. if ($isInvalid) {
  607. Notification::make()
  608. ->title('Sending failed')
  609. ->body('Only unsent invoices can be marked as sent. Please adjust your selection and try again.')
  610. ->persistent()
  611. ->danger()
  612. ->send();
  613. $action->cancel(true);
  614. }
  615. })
  616. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  617. $records->each(function (Invoice $record) {
  618. $record->markAsSent();
  619. });
  620. $action->success();
  621. }),
  622. Tables\Actions\BulkAction::make('recordPayments')
  623. ->label('Record payments')
  624. ->icon('heroicon-o-credit-card')
  625. ->stickyModalHeader()
  626. ->stickyModalFooter()
  627. ->modalFooterActionsAlignment(Alignment::End)
  628. ->modalWidth(MaxWidth::TwoExtraLarge)
  629. ->databaseTransaction()
  630. ->successNotificationTitle('Payments recorded')
  631. ->failureNotificationTitle('Failed to Record Payments')
  632. ->deselectRecordsAfterCompletion()
  633. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  634. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBulkRecordPayment());
  635. if ($isInvalid) {
  636. Notification::make()
  637. ->title('Payment recording failed')
  638. ->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.')
  639. ->persistent()
  640. ->danger()
  641. ->send();
  642. $action->cancel(true);
  643. }
  644. })
  645. ->mountUsing(function (DocumentCollection $records, Form $form) {
  646. $totalAmountDue = $records->sum('amount_due');
  647. $form->fill([
  648. 'posted_at' => now(),
  649. 'amount' => $totalAmountDue,
  650. ]);
  651. })
  652. ->form([
  653. Forms\Components\DatePicker::make('posted_at')
  654. ->label('Date'),
  655. Forms\Components\TextInput::make('amount')
  656. ->label('Amount')
  657. ->required()
  658. ->money()
  659. ->rules([
  660. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  661. if (! CurrencyConverter::isValidAmount($value)) {
  662. $fail('Please enter a valid amount');
  663. }
  664. },
  665. ]),
  666. Forms\Components\Select::make('payment_method')
  667. ->label('Payment method')
  668. ->required()
  669. ->options(PaymentMethod::class),
  670. Forms\Components\Select::make('bank_account_id')
  671. ->label('Account')
  672. ->required()
  673. ->options(function () {
  674. return BankAccount::query()
  675. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  676. ->select(['bank_accounts.id', 'accounts.name'])
  677. ->pluck('accounts.name', 'bank_accounts.id')
  678. ->toArray();
  679. })
  680. ->searchable(),
  681. Forms\Components\Textarea::make('notes')
  682. ->label('Notes'),
  683. ])
  684. ->before(function (DocumentCollection $records, Tables\Actions\BulkAction $action, array $data) {
  685. $totalPaymentAmount = $data['amount'] ?? 0;
  686. $totalAmountDue = $records->sum('amount_due');
  687. if ($totalPaymentAmount > $totalAmountDue) {
  688. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  689. Notification::make()
  690. ->title('Excess payment amount')
  691. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  692. ->persistent()
  693. ->warning()
  694. ->send();
  695. $action->halt(true);
  696. }
  697. })
  698. ->action(function (DocumentCollection $records, Tables\Actions\BulkAction $action, array $data) {
  699. $totalPaymentAmount = $data['amount'] ?? 0;
  700. $remainingAmount = $totalPaymentAmount;
  701. $records->each(function (Invoice $record) use (&$remainingAmount, $data) {
  702. $amountDue = $record->amount_due;
  703. if ($amountDue <= 0 || $remainingAmount <= 0) {
  704. return;
  705. }
  706. $paymentAmount = min($amountDue, $remainingAmount);
  707. $data['amount'] = $paymentAmount;
  708. $record->recordPayment($data);
  709. $remainingAmount -= $paymentAmount;
  710. });
  711. $action->success();
  712. }),
  713. ]),
  714. ]);
  715. }
  716. public static function getPages(): array
  717. {
  718. return [
  719. 'index' => Pages\ListInvoices::route('/'),
  720. 'create' => Pages\CreateInvoice::route('/create'),
  721. 'view' => Pages\ViewInvoice::route('/{record}'),
  722. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  723. ];
  724. }
  725. public static function getWidgets(): array
  726. {
  727. return [
  728. Widgets\InvoiceOverview::class,
  729. ];
  730. }
  731. }