refactor: extract transaction creation and account syncing to actions

- Introduce CreateRecordTransactionsAction to handle transaction creation for any model
- Introduce SyncAccountsAction to encapsulate account synchronization logic
- Refactor CreateSaleAction to use new actions and handle full sale creation flow
- Simplify CreateExpense and CreateSale pages by delegating to actions
- Ensure proper transaction handling with database rollback on failure
This commit is contained in:
Jp
2026-02-16 01:48:25 +08:00
parent e04689acca
commit 7bcfaff311
5 changed files with 90 additions and 65 deletions

View File

@@ -2,21 +2,54 @@
namespace App\Actions\Sales;
use App\Actions\Transactions\CreateRecordTransactionsAction;
use App\Commands\Sales\CreateSaleCommand;
use App\Commands\Series\CreateSeriesCommand;
use App\Models\Sale;
use Illuminate\Support\Facades\DB;
class CreateSaleAction
{
/**
* Create a new class instance.
*/
public function __construct(private CreateSaleCommand $createSaleCommand)
{
//
}
public function __construct(
private CreateSaleCommand $createSaleCommand,
private CreateSeriesCommand $createSeriesCommand,
){ }
public function __invoke(array $data): Sale
public function __invoke(array $data, array $transactions): Sale
{
return $this->createSaleCommand->execute($data);
$record = $this->createSaleCommand->execute($data);
try {
DB::beginTransaction();
//create transactions for the sale
app(CreateRecordTransactionsAction::class)($record, $transactions);
$accountIds = collect($transactions)
->pluck('account_id')
->filter()
->unique()
->values()
->all();
//sync accounts to sale
app(SyncAccountsAction::class)($record, $accountIds);
//increment current_series
$this->createSeriesCommand->execute([
'branch_id' => $record->branch_id,
'series' => $record->reference_number,
]);
DB::commit();
} catch (\Exception $exception) {
DB::rollBack();
throw new \Exception('Failed to save transactions : '.$exception->getMessage());
}
return $record;
}
}