195 lines
10 KiB
PHP
195 lines
10 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Enums\PurchasingRole;
|
|
use App\Models\BusinessClient;
|
|
use App\Models\StockItem;
|
|
use App\Models\Tenant;
|
|
use App\Models\User;
|
|
use Brick\Math\BigDecimal;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Tempo\Finance\GeneralLedger\LedgerSchema;
|
|
use Tempo\Finance\GeneralLedger\Receivables;
|
|
use Tempo\Finance\GeneralLedger\ReceivablesSchema;
|
|
|
|
/** Native actor/catalogue adapter. All customer financial writes belong to the common core. */
|
|
final class CustomerSales
|
|
{
|
|
public function ready(): bool
|
|
{
|
|
if (config('third_party.sales_enabled') !== true || ! class_exists(Receivables::class, false)
|
|
|| ! Schema::hasTable('business_clients') || ! Schema::hasTable('cr_invoices')) {
|
|
return false;
|
|
}
|
|
$runtime = app(StandaloneRuntime::class);
|
|
if ($runtime->enabled()) {
|
|
return $runtime->feature('standalone-sales', DB::connection());
|
|
}
|
|
if (app()->environment('testing') && config('customer_sales.qa_enabled') === true && DB::getDriverName() === 'pgsql') {
|
|
LedgerSchema::assertSynthetic(DB::connection());
|
|
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private function actor(User $actor, bool $lock = false): User
|
|
{
|
|
abort_unless($this->ready() && auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
|
|
$fresh = $lock ? app(CurrentActor::class)->lock($actor) : User::query()->where('tenant_id', $actor->tenant_id)->findOrFail($actor->id);
|
|
abort_if(app(OrganizationAccess::class)->maintenanceOnly($fresh), 403);
|
|
$contexts = app(WorkContext::class);
|
|
if ($contexts->enforced($fresh)) {
|
|
abort_unless(app()->bound('request') && request()->hasSession() && $contexts->active(request()) === 'procurement.sales', 403,
|
|
'Seleccione Venda para terceiros no Painel Inicial.');
|
|
}
|
|
|
|
return $fresh;
|
|
}
|
|
|
|
private function person(User $actor): string
|
|
{
|
|
if (Schema::hasTable('pa_access')) {
|
|
$people = DB::table('pa_access')->where(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $actor->id])
|
|
->distinct()->pluck('person')->all();
|
|
abort_if(count($people) > 1, 409, 'A identidade financeira do operador tem correspondências divergentes.');
|
|
if ($people !== []) {
|
|
abort_unless(is_string($people[0]) && trim($people[0]) !== '', 409);
|
|
|
|
return $people[0];
|
|
}
|
|
}
|
|
|
|
return 'compras-user:'.$actor->tenant_id.':'.$actor->id;
|
|
}
|
|
|
|
public function can(User $actor, string $action): bool
|
|
{
|
|
$roles = match ($action) {
|
|
'series' => [PurchasingRole::Admin],
|
|
'invoice_prepare', 'invoice_issue' => [PurchasingRole::Procurement],
|
|
'invoice_review', 'receipts_view', 'receipt_prepare', 'receipt_decide', 'allocation_prepare', 'allocation_decide', 'reversal_prepare', 'reversal_decide' => [PurchasingRole::Finance],
|
|
'delivery_view', 'delivery' => [PurchasingRole::Warehouse],
|
|
'view' => [PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::Admin],
|
|
default => [],
|
|
};
|
|
|
|
return $roles !== [] && $actor->hasFunctions($roles) && ! app(OrganizationAccess::class)->maintenanceOnly($actor);
|
|
}
|
|
|
|
public function assertCan(User $actor, string $action): User
|
|
{
|
|
$current = $this->actor($actor);
|
|
abort_unless($this->can($current, $action), 403);
|
|
|
|
return $current;
|
|
}
|
|
|
|
public function engine(User $actor): Receivables
|
|
{
|
|
$fresh = $this->actor($actor);
|
|
$person = $this->person($fresh);
|
|
$scope = ['tenant_id' => (int) $fresh->tenant_id, 'company_id' => 0, 'unit_id' => 0];
|
|
|
|
return new Receivables(DB::connection(), $scope, $fresh->id, $person,
|
|
function (string $action) use ($fresh, $person): void {
|
|
$current = $this->actor($fresh, ! in_array($action, ['view', 'receipts_view', 'delivery_view'], true));
|
|
abort_unless($this->person($current) === $person, 409, 'A identidade do operador mudou; reabra o documento.');
|
|
abort_unless($this->can($current, $action), 403);
|
|
}, fn () => app(ConflictGuard::class)->lockCompany($fresh),
|
|
fn (string $kind, array $input) => $this->source($fresh, $kind, $input));
|
|
}
|
|
|
|
/** @return array{actor:User,scope:array<string,int>,person:string} */
|
|
public function financialContext(User $actor): array
|
|
{
|
|
$fresh = $this->actor($actor);
|
|
abort_unless($fresh->hasFunctions([PurchasingRole::Finance, PurchasingRole::Admin]), 403);
|
|
$scope = ['tenant_id' => (int) $fresh->tenant_id, 'company_id' => 0, 'unit_id' => 0];
|
|
$person = $this->person($fresh);
|
|
abort_unless(DB::table('pa_access')->where($scope)->where(['user_id' => $fresh->id, 'action' => 'view', 'person' => $person])->exists(), 403);
|
|
|
|
return ['actor' => $fresh, 'scope' => $scope, 'person' => $person];
|
|
}
|
|
|
|
/** @param array<string,mixed> $input
|
|
* @return array<string,mixed> */
|
|
private function source(User $actor, string $kind, array $input): array
|
|
{
|
|
abort_unless(in_array($kind, ['invoice', 'receipt'], true), 403);
|
|
$client = BusinessClient::query()->where('tenant_id', $actor->tenant_id)->whereKey($input['client_id'])->lockForUpdate()->firstOrFail();
|
|
abort_unless($client->version === $input['client_version'] && ($kind !== 'invoice' || $client->active), 409,
|
|
'O cliente mudou ou deixou de aceitar novas operações; actualize a selecção.');
|
|
$snapshot = $client->only(['id', 'code', 'name', 'tax_number', 'address', 'version']);
|
|
if ($kind === 'receipt') {
|
|
return ['client' => $snapshot];
|
|
}
|
|
$lines = [];
|
|
foreach ($input['lines'] as $line) {
|
|
$item = StockItem::query()->where('tenant_id', $actor->tenant_id)->whereKey($line['stock_item_id'])->lockForUpdate()->firstOrFail();
|
|
$lines[] = [...$line, ...$item->only(['id', 'code', 'name', 'unit']), 'stock_item_id' => $item->getKey()];
|
|
}
|
|
$company = Tenant::query()->findOrFail($actor->tenant_id);
|
|
|
|
return ['client' => $snapshot, 'lines' => $lines, 'issuer' => ['id' => $company->id, 'name' => $company->name,
|
|
...array_intersect_key($company->company_details ?? [], array_flip(['legal_name', 'nuit', 'address', 'phone', 'email']))]];
|
|
}
|
|
|
|
/** @param array<string,mixed> $input
|
|
* @return array<string,mixed> */
|
|
public function command(User $actor, string $action, array $input): array
|
|
{
|
|
$this->assertCan($actor, $action);
|
|
$rules = match ($action) {
|
|
'series' => ['series_key' => 'required|string|max:80', 'prefix' => 'required|string|max:80', 'starts_on' => 'required|date_format:Y-m-d',
|
|
'ends_on' => 'required|date_format:Y-m-d|after_or_equal:starts_on', 'first_number' => 'required|integer|min:1'],
|
|
'invoice_prepare' => ['client_id' => 'required|integer|min:1', 'client_version' => 'required|integer|min:1',
|
|
'series_key' => 'required|string|max:80', 'issued_on' => 'required|date_format:Y-m-d', 'due_on' => 'required|date_format:Y-m-d|after_or_equal:issued_on',
|
|
'lines' => 'required|array|min:1|max:50', 'lines.*.stock_item_id' => 'required|integer|min:1',
|
|
'lines.*.quantity' => 'required|string|regex:/^[0-9]{1,6}(\.[0-9]{1,3})?$/D',
|
|
'lines.*.unit_price' => 'required|string|regex:/^[0-9]{1,9}(\.[0-9]{1,2})?$/D',
|
|
'lines.*.tax_rate' => 'required|string|regex:/^[0-9]{1,3}(\.[0-9]{1,4})?$/D', 'lines.*.tax_basis' => 'required|string|max:1000'],
|
|
'invoice_review' => ['proposal_id' => 'required|integer|min:1', 'revision' => 'required|string|size:64', 'decision' => 'required|in:approved,rejected'],
|
|
'invoice_issue' => ['proposal_id' => 'required|integer|min:1', 'revision' => 'required|string|size:64'],
|
|
'receipt_prepare' => ['client_id' => 'required|integer|min:1', 'client_version' => 'required|integer|min:1',
|
|
'amount' => 'required|string|regex:/^[0-9]{1,12}(\.[0-9]{1,2})?$/D', 'received_on' => 'required|date_format:Y-m-d', 'reference' => 'required|string|max:180'],
|
|
'allocation_prepare' => ['invoice_id' => 'required|integer|min:1', 'receipt_id' => 'required|integer|min:1',
|
|
'amount' => 'required|string|regex:/^[0-9]{1,12}(\.[0-9]{1,2})?$/D'],
|
|
'reversal_prepare' => ['allocation_id' => 'required|integer|min:1'],
|
|
'receipt_decide', 'allocation_decide', 'reversal_decide' => ['proposal_id' => 'required|integer|min:1', 'revision' => 'required|string|size:64', 'decision' => 'required|in:confirmed,rejected'],
|
|
default => throw new \InvalidArgumentException('Comando de venda desconhecido.'),
|
|
};
|
|
$data = Validator::make($input, $rules + ['operation_key' => 'required|uuid', 'reason' => 'required|string|min:10|max:2000'])->validate();
|
|
$key = $data['operation_key'];
|
|
unset($data['operation_key']);
|
|
foreach (['client_id', 'client_version', 'first_number', 'proposal_id', 'invoice_id', 'receipt_id', 'allocation_id'] as $field) {
|
|
if (isset($data[$field])) {
|
|
$data[$field] = (int) $data[$field];
|
|
}
|
|
}
|
|
if (isset($data['amount'])) {
|
|
$data['amount_minor'] = BigDecimal::of($data['amount'])->multipliedBy(100)->toInt();
|
|
unset($data['amount']);
|
|
}
|
|
if (isset($data['lines'])) {
|
|
$data['lines'] = array_map(fn ($line) => ['stock_item_id' => (int) $line['stock_item_id'],
|
|
'quantity_milli' => ReceiptWorkflow::milli($line['quantity']),
|
|
'unit_price_minor' => BigDecimal::of($line['unit_price'])->multipliedBy(100)->toInt(),
|
|
'tax_rate' => $line['tax_rate'], 'tax_basis' => trim($line['tax_basis'])], $data['lines']);
|
|
}
|
|
|
|
return DB::transaction(function () use ($actor, $action, $data, $key): array {
|
|
$result = $this->engine($actor)->command($action, $data, $key);
|
|
if (! $result['replayed']) {
|
|
app(RequisitionWorkflow::class)->audit($actor, 'sales.'.$action, null, null, ['result' => $result, 'reason' => $data['reason']]);
|
|
}
|
|
|
|
return $result;
|
|
});
|
|
}
|
|
}
|