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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales;
  3. use App\Collections\Accounting\InvoiceCollection;
  4. use App\Enums\Accounting\InvoiceStatus;
  5. use App\Enums\Accounting\PaymentMethod;
  6. use App\Filament\Company\Resources\Sales\InvoiceResource\Pages;
  7. use App\Filament\Company\Resources\Sales\InvoiceResource\RelationManagers;
  8. use App\Filament\Company\Resources\Sales\InvoiceResource\Widgets;
  9. use App\Filament\Tables\Actions\ReplicateBulkAction;
  10. use App\Filament\Tables\Filters\DateRangeFilter;
  11. use App\Models\Accounting\Adjustment;
  12. use App\Models\Accounting\DocumentLineItem;
  13. use App\Models\Accounting\Invoice;
  14. use App\Models\Banking\BankAccount;
  15. use App\Models\Common\Offering;
  16. use App\Utilities\Currency\CurrencyAccessor;
  17. use App\Utilities\Currency\CurrencyConverter;
  18. use Awcodes\TableRepeater\Components\TableRepeater;
  19. use Awcodes\TableRepeater\Header;
  20. use Carbon\CarbonInterface;
  21. use Closure;
  22. use Filament\Forms;
  23. use Filament\Forms\Components\FileUpload;
  24. use Filament\Forms\Form;
  25. use Filament\Notifications\Notification;
  26. use Filament\Resources\Resource;
  27. use Filament\Support\Enums\Alignment;
  28. use Filament\Support\Enums\MaxWidth;
  29. use Filament\Tables;
  30. use Filament\Tables\Table;
  31. use Illuminate\Database\Eloquent\Builder;
  32. use Illuminate\Database\Eloquent\Collection;
  33. use Illuminate\Database\Eloquent\Model;
  34. use Illuminate\Support\Carbon;
  35. use Illuminate\Support\Facades\Auth;
  36. use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
  37. class InvoiceResource extends Resource
  38. {
  39. protected static ?string $model = Invoice::class;
  40. protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
  41. public static function form(Form $form): Form
  42. {
  43. $company = Auth::user()->currentCompany;
  44. return $form
  45. ->schema([
  46. Forms\Components\Section::make('Invoice Header')
  47. ->collapsible()
  48. ->schema([
  49. Forms\Components\Split::make([
  50. Forms\Components\Group::make([
  51. FileUpload::make('logo')
  52. ->openable()
  53. ->maxSize(1024)
  54. ->localizeLabel()
  55. ->visibility('public')
  56. ->disk('public')
  57. ->directory('logos/document')
  58. ->imageResizeMode('contain')
  59. ->imageCropAspectRatio('3:2')
  60. ->panelAspectRatio('3:2')
  61. ->maxWidth(MaxWidth::ExtraSmall)
  62. ->panelLayout('integrated')
  63. ->removeUploadedFileButtonPosition('center bottom')
  64. ->uploadButtonPosition('center bottom')
  65. ->uploadProgressIndicatorPosition('center bottom')
  66. ->getUploadedFileNameForStorageUsing(
  67. static fn (TemporaryUploadedFile $file): string => (string) str($file->getClientOriginalName())
  68. ->prepend(Auth::user()->currentCompany->id . '_'),
  69. )
  70. ->acceptedFileTypes(['image/png', 'image/jpeg', 'image/gif']),
  71. ]),
  72. Forms\Components\Group::make([
  73. Forms\Components\TextInput::make('header')
  74. ->default(fn () => $company->defaultInvoice->header),
  75. Forms\Components\TextInput::make('subheader')
  76. ->default(fn () => $company->defaultInvoice->subheader),
  77. Forms\Components\View::make('filament.forms.components.company-info')
  78. ->viewData([
  79. 'company_name' => $company->name,
  80. 'company_address' => $company->profile->address,
  81. 'company_city' => $company->profile->city?->name,
  82. 'company_state' => $company->profile->state?->name,
  83. 'company_zip' => $company->profile->zip_code,
  84. 'company_country' => $company->profile->state?->country->name,
  85. ]),
  86. ])->grow(true),
  87. ])->from('md'),
  88. ]),
  89. Forms\Components\Section::make('Invoice Details')
  90. ->schema([
  91. Forms\Components\Split::make([
  92. Forms\Components\Group::make([
  93. Forms\Components\Select::make('client_id')
  94. ->relationship('client', 'name')
  95. ->preload()
  96. ->searchable()
  97. ->required(),
  98. ]),
  99. Forms\Components\Group::make([
  100. Forms\Components\TextInput::make('invoice_number')
  101. ->label('Invoice Number')
  102. ->default(fn () => Invoice::getNextDocumentNumber()),
  103. Forms\Components\TextInput::make('order_number')
  104. ->label('P.O/S.O Number'),
  105. Forms\Components\DatePicker::make('date')
  106. ->label('Invoice Date')
  107. ->live()
  108. ->default(now())
  109. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  110. $date = $state;
  111. $dueDate = $get('due_date');
  112. if ($date && $dueDate && $date > $dueDate) {
  113. $set('due_date', $date);
  114. }
  115. }),
  116. Forms\Components\DatePicker::make('due_date')
  117. ->label('Payment Due')
  118. ->default(function () use ($company) {
  119. return now()->addDays($company->defaultInvoice->payment_terms->getDays());
  120. })
  121. ->minDate(static function (Forms\Get $get) {
  122. return $get('date') ?? now();
  123. }),
  124. ])->grow(true),
  125. ])->from('md'),
  126. TableRepeater::make('lineItems')
  127. ->relationship()
  128. ->saveRelationshipsUsing(function (TableRepeater $component, Forms\Contracts\HasForms $livewire, ?array $state) {
  129. if (! is_array($state)) {
  130. $state = [];
  131. }
  132. $relationship = $component->getRelationship();
  133. $existingRecords = $component->getCachedExistingRecords();
  134. $recordsToDelete = [];
  135. foreach ($existingRecords->pluck($relationship->getRelated()->getKeyName()) as $keyToCheckForDeletion) {
  136. if (array_key_exists("record-{$keyToCheckForDeletion}", $state)) {
  137. continue;
  138. }
  139. $recordsToDelete[] = $keyToCheckForDeletion;
  140. $existingRecords->forget("record-{$keyToCheckForDeletion}");
  141. }
  142. $relationship
  143. ->whereKey($recordsToDelete)
  144. ->get()
  145. ->each(static fn (Model $record) => $record->delete());
  146. $childComponentContainers = $component->getChildComponentContainers(
  147. withHidden: $component->shouldSaveRelationshipsWhenHidden(),
  148. );
  149. $itemOrder = 1;
  150. $orderColumn = $component->getOrderColumn();
  151. $translatableContentDriver = $livewire->makeFilamentTranslatableContentDriver();
  152. foreach ($childComponentContainers as $itemKey => $item) {
  153. $itemData = $item->getState(shouldCallHooksBefore: false);
  154. if ($orderColumn) {
  155. $itemData[$orderColumn] = $itemOrder;
  156. $itemOrder++;
  157. }
  158. if ($record = ($existingRecords[$itemKey] ?? null)) {
  159. $itemData = $component->mutateRelationshipDataBeforeSave($itemData, record: $record);
  160. if ($itemData === null) {
  161. continue;
  162. }
  163. $translatableContentDriver ?
  164. $translatableContentDriver->updateRecord($record, $itemData) :
  165. $record->fill($itemData)->save();
  166. continue;
  167. }
  168. $relatedModel = $component->getRelatedModel();
  169. $itemData = $component->mutateRelationshipDataBeforeCreate($itemData);
  170. if ($itemData === null) {
  171. continue;
  172. }
  173. if ($translatableContentDriver) {
  174. $record = $translatableContentDriver->makeRecord($relatedModel, $itemData);
  175. } else {
  176. $record = new $relatedModel;
  177. $record->fill($itemData);
  178. }
  179. $record = $relationship->save($record);
  180. $item->model($record)->saveRelationships();
  181. $existingRecords->push($record);
  182. }
  183. $component->getRecord()->setRelation($component->getRelationshipName(), $existingRecords);
  184. /** @var Invoice $invoice */
  185. $invoice = $component->getRecord();
  186. // Recalculate totals for line items
  187. $invoice->lineItems()->each(function (DocumentLineItem $lineItem) {
  188. $lineItem->updateQuietly([
  189. 'tax_total' => $lineItem->calculateTaxTotal()->getAmount(),
  190. 'discount_total' => $lineItem->calculateDiscountTotal()->getAmount(),
  191. ]);
  192. });
  193. $subtotal = $invoice->lineItems()->sum('subtotal') / 100;
  194. $taxTotal = $invoice->lineItems()->sum('tax_total') / 100;
  195. $discountTotal = $invoice->lineItems()->sum('discount_total') / 100;
  196. $grandTotal = $subtotal + $taxTotal - $discountTotal;
  197. $invoice->updateQuietly([
  198. 'subtotal' => $subtotal,
  199. 'tax_total' => $taxTotal,
  200. 'discount_total' => $discountTotal,
  201. 'total' => $grandTotal,
  202. ]);
  203. })
  204. ->headers([
  205. Header::make('Items')->width('15%'),
  206. Header::make('Description')->width('25%'),
  207. Header::make('Quantity')->width('10%'),
  208. Header::make('Price')->width('10%'),
  209. Header::make('Taxes')->width('15%'),
  210. Header::make('Discounts')->width('15%'),
  211. Header::make('Amount')->width('10%')->align('right'),
  212. ])
  213. ->schema([
  214. Forms\Components\Select::make('offering_id')
  215. ->relationship('sellableOffering', 'name')
  216. ->preload()
  217. ->searchable()
  218. ->required()
  219. ->live()
  220. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  221. $offeringId = $state;
  222. $offeringRecord = Offering::with(['salesTaxes', 'salesDiscounts'])->find($offeringId);
  223. if ($offeringRecord) {
  224. $set('description', $offeringRecord->description);
  225. $set('unit_price', $offeringRecord->price);
  226. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  227. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  228. }
  229. }),
  230. Forms\Components\TextInput::make('description'),
  231. Forms\Components\TextInput::make('quantity')
  232. ->required()
  233. ->numeric()
  234. ->live()
  235. ->default(1),
  236. Forms\Components\TextInput::make('unit_price')
  237. ->hiddenLabel()
  238. ->numeric()
  239. ->live()
  240. ->default(0),
  241. Forms\Components\Select::make('salesTaxes')
  242. ->relationship('salesTaxes', 'name')
  243. ->preload()
  244. ->multiple()
  245. ->live()
  246. ->searchable(),
  247. Forms\Components\Select::make('salesDiscounts')
  248. ->relationship('salesDiscounts', 'name')
  249. ->preload()
  250. ->multiple()
  251. ->live()
  252. ->searchable(),
  253. Forms\Components\Placeholder::make('total')
  254. ->hiddenLabel()
  255. ->content(function (Forms\Get $get) {
  256. $quantity = max((float) ($get('quantity') ?? 0), 0);
  257. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  258. $salesTaxes = $get('salesTaxes') ?? [];
  259. $salesDiscounts = $get('salesDiscounts') ?? [];
  260. $subtotal = $quantity * $unitPrice;
  261. // Calculate tax amount based on subtotal
  262. $taxAmount = 0;
  263. if (! empty($salesTaxes)) {
  264. $taxRates = Adjustment::whereIn('id', $salesTaxes)->pluck('rate');
  265. $taxAmount = collect($taxRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  266. }
  267. // Calculate discount amount based on subtotal
  268. $discountAmount = 0;
  269. if (! empty($salesDiscounts)) {
  270. $discountRates = Adjustment::whereIn('id', $salesDiscounts)->pluck('rate');
  271. $discountAmount = collect($discountRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  272. }
  273. // Final total
  274. $total = $subtotal + ($taxAmount - $discountAmount);
  275. return money($total, CurrencyAccessor::getDefaultCurrency(), true)->format();
  276. }),
  277. ]),
  278. Forms\Components\Grid::make(6)
  279. ->schema([
  280. Forms\Components\ViewField::make('totals')
  281. ->columnStart(5)
  282. ->columnSpan(2)
  283. ->view('filament.forms.components.invoice-totals'),
  284. ]),
  285. // Forms\Components\Repeater::make('lineItems')
  286. // ->relationship()
  287. // ->columns(8)
  288. // ->schema([
  289. // Forms\Components\Select::make('offering_id')
  290. // ->relationship('offering', 'name')
  291. // ->preload()
  292. // ->columnSpan(2)
  293. // ->searchable()
  294. // ->required()
  295. // ->live()
  296. // ->afterStateUpdated(function (Forms\Set $set, $state) {
  297. // $offeringId = $state;
  298. // $offeringRecord = Offering::with('salesTaxes')->find($offeringId);
  299. //
  300. // if ($offeringRecord) {
  301. // $set('description', $offeringRecord->description);
  302. // $set('unit_price', $offeringRecord->price);
  303. // $set('total', $offeringRecord->price);
  304. //
  305. // $salesTaxes = $offeringRecord->salesTaxes->map(function ($tax) {
  306. // return [
  307. // 'id' => $tax->id,
  308. // 'amount' => null, // Amount will be calculated dynamically
  309. // ];
  310. // })->toArray();
  311. //
  312. // $set('taxes', $salesTaxes);
  313. // }
  314. // }),
  315. // Forms\Components\TextInput::make('description')
  316. // ->columnSpan(3)
  317. // ->required(),
  318. // Forms\Components\TextInput::make('quantity')
  319. // ->required()
  320. // ->numeric()
  321. // ->live()
  322. // ->default(1),
  323. // Forms\Components\TextInput::make('unit_price')
  324. // ->live()
  325. // ->numeric()
  326. // ->default(0),
  327. // Forms\Components\Placeholder::make('total')
  328. // ->content(function (Forms\Get $get) {
  329. // $quantity = $get('quantity');
  330. // $unitPrice = $get('unit_price');
  331. //
  332. // if ($quantity && $unitPrice) {
  333. // return $quantity * $unitPrice;
  334. // }
  335. // }),
  336. // TableRepeater::make('taxes')
  337. // ->relationship()
  338. // ->columnSpanFull()
  339. // ->columnStart(6)
  340. // ->headers([
  341. // Header::make('')->width('200px'),
  342. // Header::make('')->width('50px')->align('right'),
  343. // ])
  344. // ->defaultItems(0)
  345. // ->schema([
  346. // Forms\Components\Select::make('id') // The ID of the adjustment being attached.
  347. // ->label('Tax Adjustment')
  348. // ->options(
  349. // Adjustment::query()
  350. // ->where('category', AdjustmentCategory::Tax)
  351. // ->pluck('name', 'id')
  352. // )
  353. // ->preload()
  354. // ->searchable()
  355. // ->required()
  356. // ->live(),
  357. // Forms\Components\Placeholder::make('amount')
  358. // ->hiddenLabel()
  359. // ->content(function (Forms\Get $get) {
  360. // $quantity = $get('../../quantity') ?? 0; // Get parent quantity
  361. // $unitPrice = $get('../../unit_price') ?? 0; // Get parent unit price
  362. // $rate = Adjustment::find($get('id'))->rate ?? 0;
  363. //
  364. // $total = $quantity * $unitPrice;
  365. //
  366. // return $total * ($rate / 100);
  367. // }),
  368. // ]),
  369. // ]),
  370. Forms\Components\Textarea::make('terms')
  371. ->columnSpanFull(),
  372. ]),
  373. Forms\Components\Section::make('Invoice Footer')
  374. ->collapsible()
  375. ->schema([
  376. Forms\Components\Textarea::make('footer')
  377. ->columnSpanFull(),
  378. ]),
  379. ]);
  380. }
  381. public static function table(Table $table): Table
  382. {
  383. return $table
  384. ->defaultSort('due_date')
  385. ->columns([
  386. Tables\Columns\TextColumn::make('status')
  387. ->badge()
  388. ->searchable(),
  389. Tables\Columns\TextColumn::make('due_date')
  390. ->label('Due')
  391. ->formatStateUsing(function (Tables\Columns\TextColumn $column, mixed $state) {
  392. if (blank($state)) {
  393. return null;
  394. }
  395. $date = Carbon::parse($state)
  396. ->setTimezone($timezone ?? $column->getTimezone());
  397. if ($date->isToday()) {
  398. return 'Today';
  399. }
  400. return $date->diffForHumans([
  401. 'options' => CarbonInterface::ONE_DAY_WORDS,
  402. ]);
  403. })
  404. ->sortable(),
  405. Tables\Columns\TextColumn::make('date')
  406. ->date()
  407. ->sortable(),
  408. Tables\Columns\TextColumn::make('invoice_number')
  409. ->label('Number')
  410. ->searchable()
  411. ->sortable(),
  412. Tables\Columns\TextColumn::make('client.name')
  413. ->sortable()
  414. ->searchable(),
  415. Tables\Columns\TextColumn::make('total')
  416. ->currency()
  417. ->sortable(),
  418. Tables\Columns\TextColumn::make('amount_paid')
  419. ->label('Amount Paid')
  420. ->currency()
  421. ->sortable(),
  422. Tables\Columns\TextColumn::make('amount_due')
  423. ->label('Amount Due')
  424. ->currency()
  425. ->sortable(),
  426. ])
  427. ->filters([
  428. Tables\Filters\SelectFilter::make('client')
  429. ->relationship('client', 'name')
  430. ->searchable()
  431. ->preload(),
  432. Tables\Filters\SelectFilter::make('status')
  433. ->options(InvoiceStatus::class)
  434. ->native(false),
  435. Tables\Filters\TernaryFilter::make('has_payments')
  436. ->label('Has Payments')
  437. ->queries(
  438. true: fn (Builder $query) => $query->whereHas('payments'),
  439. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  440. ),
  441. DateRangeFilter::make('date')
  442. ->fromLabel('From Date')
  443. ->untilLabel('To Date')
  444. ->indicatorLabel('Date'),
  445. DateRangeFilter::make('due_date')
  446. ->fromLabel('From Due Date')
  447. ->untilLabel('To Due Date')
  448. ->indicatorLabel('Due'),
  449. ])
  450. ->actions([
  451. Tables\Actions\ActionGroup::make([
  452. Tables\Actions\EditAction::make(),
  453. Tables\Actions\ViewAction::make(),
  454. Tables\Actions\DeleteAction::make(),
  455. Tables\Actions\ReplicateAction::make()
  456. ->label('Duplicate')
  457. ->excludeAttributes(['status', 'amount_paid', 'amount_due', 'created_by', 'updated_by', 'created_at', 'updated_at', 'invoice_number', 'date', 'due_date'])
  458. ->modal(false)
  459. ->beforeReplicaSaved(function (Invoice $original, Invoice $replica) {
  460. $replica->status = InvoiceStatus::Draft;
  461. $replica->invoice_number = Invoice::getNextDocumentNumber();
  462. $replica->date = now();
  463. $replica->due_date = now()->addDays($original->company->defaultInvoice->payment_terms->getDays());
  464. })
  465. ->databaseTransaction()
  466. ->after(function (Invoice $original, Invoice $replica) {
  467. $original->lineItems->each(function (DocumentLineItem $lineItem) use ($replica) {
  468. $replicaLineItem = $lineItem->replicate([
  469. 'documentable_id',
  470. 'documentable_type',
  471. 'subtotal',
  472. 'total',
  473. 'created_by',
  474. 'updated_by',
  475. 'created_at',
  476. 'updated_at',
  477. ]);
  478. $replicaLineItem->documentable_id = $replica->id;
  479. $replicaLineItem->documentable_type = $replica->getMorphClass();
  480. $replicaLineItem->save();
  481. $replicaLineItem->adjustments()->sync($lineItem->adjustments->pluck('id'));
  482. });
  483. })
  484. ->successRedirectUrl(function (Invoice $replica) {
  485. return InvoiceResource::getUrl('edit', ['record' => $replica]);
  486. }),
  487. Tables\Actions\Action::make('approveDraft')
  488. ->label('Approve')
  489. ->icon('heroicon-o-check-circle')
  490. ->visible(function (Invoice $record) {
  491. return $record->isDraft();
  492. })
  493. ->databaseTransaction()
  494. ->successNotificationTitle('Invoice Approved')
  495. ->action(function (Invoice $record, Tables\Actions\Action $action) {
  496. $record->approveDraft();
  497. $action->success();
  498. }),
  499. Tables\Actions\Action::make('markAsSent')
  500. ->label('Mark as Sent')
  501. ->icon('heroicon-o-paper-airplane')
  502. ->visible(function (Invoice $record) {
  503. return $record->status === InvoiceStatus::Unsent;
  504. })
  505. ->successNotificationTitle('Invoice Sent')
  506. ->action(function (Invoice $record, Tables\Actions\Action $action) {
  507. $record->update([
  508. 'status' => InvoiceStatus::Sent,
  509. ]);
  510. $action->success();
  511. }),
  512. Tables\Actions\Action::make('recordPayment')
  513. ->label(fn (Invoice $record) => $record->status === InvoiceStatus::Overpaid ? 'Refund Overpayment' : 'Record Payment')
  514. ->stickyModalHeader()
  515. ->stickyModalFooter()
  516. ->modalFooterActionsAlignment(Alignment::End)
  517. ->modalWidth(MaxWidth::TwoExtraLarge)
  518. ->icon('heroicon-o-credit-card')
  519. ->visible(function (Invoice $record) {
  520. return $record->canRecordPayment();
  521. })
  522. ->mountUsing(function (Invoice $record, Form $form) {
  523. $form->fill([
  524. 'posted_at' => now(),
  525. 'amount' => $record->status === InvoiceStatus::Overpaid ? ltrim($record->amount_due, '-') : $record->amount_due,
  526. ]);
  527. })
  528. ->databaseTransaction()
  529. ->successNotificationTitle('Payment Recorded')
  530. ->form([
  531. Forms\Components\DatePicker::make('posted_at')
  532. ->label('Date'),
  533. Forms\Components\TextInput::make('amount')
  534. ->label('Amount')
  535. ->required()
  536. ->money()
  537. ->live(onBlur: true)
  538. ->helperText(function (Invoice $record, $state) {
  539. if (! CurrencyConverter::isValidAmount($state)) {
  540. return null;
  541. }
  542. $amountDue = $record->getRawOriginal('amount_due');
  543. $amount = CurrencyConverter::convertToCents($state);
  544. if ($amount <= 0) {
  545. return 'Please enter a valid positive amount';
  546. }
  547. if ($record->status === InvoiceStatus::Overpaid) {
  548. $newAmountDue = $amountDue + $amount;
  549. } else {
  550. $newAmountDue = $amountDue - $amount;
  551. }
  552. return match (true) {
  553. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue),
  554. $newAmountDue === 0 => 'Invoice will be fully paid',
  555. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue)),
  556. };
  557. })
  558. ->rules([
  559. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  560. if (! CurrencyConverter::isValidAmount($value)) {
  561. $fail('Please enter a valid amount');
  562. }
  563. },
  564. ]),
  565. Forms\Components\Select::make('payment_method')
  566. ->label('Payment Method')
  567. ->required()
  568. ->options(PaymentMethod::class),
  569. Forms\Components\Select::make('bank_account_id')
  570. ->label('Account')
  571. ->required()
  572. ->options(BankAccount::query()
  573. ->get()
  574. ->pluck('account.name', 'id'))
  575. ->searchable(),
  576. Forms\Components\Textarea::make('notes')
  577. ->label('Notes'),
  578. ])
  579. ->action(function (Invoice $record, Tables\Actions\Action $action, array $data) {
  580. $record->recordPayment($data);
  581. $action->success();
  582. }),
  583. ]),
  584. ])
  585. ->bulkActions([
  586. Tables\Actions\BulkActionGroup::make([
  587. Tables\Actions\DeleteBulkAction::make(),
  588. ReplicateBulkAction::make()
  589. ->label('Replicate')
  590. ->modalWidth(MaxWidth::Large)
  591. ->modalDescription('Replicating invoices will also replicate their line items. Are you sure you want to proceed?')
  592. ->successNotificationTitle('Invoices Replicated Successfully')
  593. ->failureNotificationTitle('Failed to Replicate Invoices')
  594. ->databaseTransaction()
  595. ->deselectRecordsAfterCompletion()
  596. ->excludeAttributes([
  597. 'status',
  598. 'amount_paid',
  599. 'amount_due',
  600. 'created_by',
  601. 'updated_by',
  602. 'created_at',
  603. 'updated_at',
  604. 'invoice_number',
  605. 'date',
  606. 'due_date',
  607. ])
  608. ->beforeReplicaSaved(function (Invoice $replica) {
  609. $replica->status = InvoiceStatus::Draft;
  610. $replica->invoice_number = Invoice::getNextDocumentNumber();
  611. $replica->date = now();
  612. $replica->due_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  613. })
  614. ->withReplicatedRelationships(['lineItems'])
  615. ->withExcludedRelationshipAttributes('lineItems', [
  616. 'subtotal',
  617. 'total',
  618. 'created_by',
  619. 'updated_by',
  620. 'created_at',
  621. 'updated_at',
  622. ]),
  623. Tables\Actions\BulkAction::make('approveDrafts')
  624. ->label('Approve')
  625. ->icon('heroicon-o-check-circle')
  626. ->databaseTransaction()
  627. ->successNotificationTitle('Invoices Approved')
  628. ->failureNotificationTitle('Failed to Approve Invoices')
  629. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  630. $containsNonDrafts = $records->contains(fn (Invoice $record) => ! $record->isDraft());
  631. if ($containsNonDrafts) {
  632. Notification::make()
  633. ->title('Approval Failed')
  634. ->body('Only draft invoices can be approved. Please adjust your selection and try again.')
  635. ->persistent()
  636. ->danger()
  637. ->send();
  638. $action->cancel(true);
  639. }
  640. })
  641. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  642. $records->each(function (Invoice $record) {
  643. $record->approveDraft();
  644. });
  645. $action->success();
  646. }),
  647. Tables\Actions\BulkAction::make('markAsSent')
  648. ->label('Mark as Sent')
  649. ->icon('heroicon-o-paper-airplane')
  650. ->databaseTransaction()
  651. ->successNotificationTitle('Invoices Sent')
  652. ->failureNotificationTitle('Failed to Mark Invoices as Sent')
  653. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  654. $doesntContainUnsent = $records->contains(fn (Invoice $record) => $record->status !== InvoiceStatus::Unsent);
  655. if ($doesntContainUnsent) {
  656. Notification::make()
  657. ->title('Sending Failed')
  658. ->body('Only unsent invoices can be marked as sent. Please adjust your selection and try again.')
  659. ->persistent()
  660. ->danger()
  661. ->send();
  662. $action->cancel(true);
  663. }
  664. })
  665. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  666. $records->each(function (Invoice $record) {
  667. $record->updateQuietly([
  668. 'status' => InvoiceStatus::Sent,
  669. ]);
  670. });
  671. $action->success();
  672. }),
  673. Tables\Actions\BulkAction::make('recordPayments')
  674. ->label('Record Payments')
  675. ->icon('heroicon-o-credit-card')
  676. ->stickyModalHeader()
  677. ->stickyModalFooter()
  678. ->modalFooterActionsAlignment(Alignment::End)
  679. ->modalWidth(MaxWidth::TwoExtraLarge)
  680. ->databaseTransaction()
  681. ->successNotificationTitle('Payments Recorded')
  682. ->failureNotificationTitle('Failed to Record Payments')
  683. ->deselectRecordsAfterCompletion()
  684. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  685. $cantRecordPayments = $records->contains(fn (Invoice $record) => ! $record->canBulkRecordPayment());
  686. if ($cantRecordPayments) {
  687. Notification::make()
  688. ->title('Payment Recording Failed')
  689. ->body('Invoices that are either draft, paid, overpaid, or voided cannot be processed through bulk payments. Please adjust your selection and try again.')
  690. ->persistent()
  691. ->danger()
  692. ->send();
  693. $action->cancel(true);
  694. }
  695. })
  696. ->mountUsing(function (InvoiceCollection $records, Form $form) {
  697. $totalAmountDue = $records->sumMoneyFormattedSimple('amount_due');
  698. $form->fill([
  699. 'posted_at' => now(),
  700. 'amount' => $totalAmountDue,
  701. ]);
  702. })
  703. ->form([
  704. Forms\Components\DatePicker::make('posted_at')
  705. ->label('Date'),
  706. Forms\Components\TextInput::make('amount')
  707. ->label('Amount')
  708. ->required()
  709. ->money()
  710. ->rules([
  711. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  712. if (! CurrencyConverter::isValidAmount($value)) {
  713. $fail('Please enter a valid amount');
  714. }
  715. },
  716. ]),
  717. Forms\Components\Select::make('payment_method')
  718. ->label('Payment Method')
  719. ->required()
  720. ->options(PaymentMethod::class),
  721. Forms\Components\Select::make('bank_account_id')
  722. ->label('Account')
  723. ->required()
  724. ->options(BankAccount::query()
  725. ->get()
  726. ->pluck('account.name', 'id'))
  727. ->searchable(),
  728. Forms\Components\Textarea::make('notes')
  729. ->label('Notes'),
  730. ])
  731. ->before(function (InvoiceCollection $records, Tables\Actions\BulkAction $action, array $data) {
  732. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  733. $totalAmountDue = $records->sumMoneyInCents('amount_due');
  734. if ($totalPaymentAmount > $totalAmountDue) {
  735. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  736. Notification::make()
  737. ->title('Excess Payment Amount')
  738. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  739. ->persistent()
  740. ->warning()
  741. ->send();
  742. $action->halt(true);
  743. }
  744. })
  745. ->action(function (InvoiceCollection $records, Tables\Actions\BulkAction $action, array $data) {
  746. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  747. $remainingAmount = $totalPaymentAmount;
  748. $records->each(function (Invoice $record) use (&$remainingAmount, $data) {
  749. $amountDue = $record->getRawOriginal('amount_due');
  750. if ($amountDue <= 0 || $remainingAmount <= 0) {
  751. return;
  752. }
  753. $paymentAmount = min($amountDue, $remainingAmount);
  754. $data['amount'] = CurrencyConverter::convertCentsToFormatSimple($paymentAmount);
  755. $record->recordPayment($data);
  756. $remainingAmount -= $paymentAmount;
  757. });
  758. $action->success();
  759. }),
  760. ]),
  761. ]);
  762. }
  763. public static function getRelations(): array
  764. {
  765. return [
  766. RelationManagers\PaymentsRelationManager::class,
  767. ];
  768. }
  769. public static function getPages(): array
  770. {
  771. return [
  772. 'index' => Pages\ListInvoices::route('/'),
  773. 'create' => Pages\CreateInvoice::route('/create'),
  774. 'view' => Pages\ViewInvoice::route('/{record}'),
  775. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  776. ];
  777. }
  778. public static function getWidgets(): array
  779. {
  780. return [
  781. Widgets\InvoiceOverview::class,
  782. ];
  783. }
  784. }