Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

InvoiceResource.php 47KB

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