Package system sms
This commit is contained in:
parent
266af6595e
commit
369af34ad4
10
app/Enums/PersonPhoneType.php
Normal file
10
app/Enums/PersonPhoneType.php
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
enum PersonPhoneType: string
|
||||||
|
{
|
||||||
|
case Mobile = 'mobile';
|
||||||
|
case Landline = 'landline';
|
||||||
|
case Voip = 'voip';
|
||||||
|
}
|
||||||
470
app/Http/Controllers/Admin/PackageController.php
Normal file
470
app/Http/Controllers/Admin/PackageController.php
Normal file
|
|
@ -0,0 +1,470 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Admin;
|
||||||
|
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use App\Http\Requests\StorePackageFromContractsRequest;
|
||||||
|
use App\Http\Requests\StorePackageRequest;
|
||||||
|
use App\Jobs\PackageItemSmsJob;
|
||||||
|
use App\Models\Contract;
|
||||||
|
use App\Models\Package;
|
||||||
|
use App\Models\PackageItem;
|
||||||
|
use App\Models\SmsTemplate;
|
||||||
|
use App\Services\Contact\PhoneSelector;
|
||||||
|
use App\Services\Sms\SmsService;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Bus;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Inertia\Response;
|
||||||
|
|
||||||
|
class PackageController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request): Response
|
||||||
|
{
|
||||||
|
$packages = Package::query()
|
||||||
|
->latest('id')
|
||||||
|
->paginate(20);
|
||||||
|
// Minimal lookups for create form (active only)
|
||||||
|
$profiles = \App\Models\SmsProfile::query()
|
||||||
|
->where('active', true)
|
||||||
|
->orderBy('name')
|
||||||
|
->get(['id', 'name']);
|
||||||
|
$senders = \App\Models\SmsSender::query()
|
||||||
|
->where('active', true)
|
||||||
|
->orderBy('sname')
|
||||||
|
->get(['id', 'profile_id', 'sname', 'phone_number']);
|
||||||
|
$templates = \App\Models\SmsTemplate::query()
|
||||||
|
->orderBy('name')
|
||||||
|
->get(['id', 'name']);
|
||||||
|
$segments = \App\Models\Segment::query()
|
||||||
|
->where('active', true)
|
||||||
|
->orderBy('name')
|
||||||
|
->get(['id', 'name']);
|
||||||
|
// Provide a lightweight list of recent clients with person names for filtering
|
||||||
|
$clients = \App\Models\Client::query()
|
||||||
|
->with(['person' => function ($q) {
|
||||||
|
$q->select('id', 'uuid', 'full_name');
|
||||||
|
}])
|
||||||
|
->latest('id')
|
||||||
|
->get(['id', 'uuid', 'person_id'])
|
||||||
|
->map(function ($c) {
|
||||||
|
return [
|
||||||
|
'id' => $c->id,
|
||||||
|
'uuid' => $c->uuid,
|
||||||
|
'name' => $c->person?->full_name ?? ('Client #'.$c->id),
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->values();
|
||||||
|
|
||||||
|
return Inertia::render('Admin/Packages/Index', [
|
||||||
|
'packages' => $packages,
|
||||||
|
'profiles' => $profiles,
|
||||||
|
'senders' => $senders,
|
||||||
|
'templates' => $templates,
|
||||||
|
'segments' => $segments,
|
||||||
|
'clients' => $clients,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function show(Package $package, SmsService $sms): Response
|
||||||
|
{
|
||||||
|
$items = $package->items()->latest('id')->paginate(25);
|
||||||
|
|
||||||
|
// Preload contracts/accounts for current page items to compute per-item previews
|
||||||
|
$contractIds = collect($items->items())
|
||||||
|
->map(fn ($it) => (array) ($it->target_json ?? []))
|
||||||
|
->map(fn ($t) => $t['contract_id'] ?? null)
|
||||||
|
->filter()
|
||||||
|
->unique()
|
||||||
|
->values();
|
||||||
|
$contracts = $contractIds->isNotEmpty()
|
||||||
|
? Contract::query()->with('account.type')->whereIn('id', $contractIds)->get()->keyBy('id')
|
||||||
|
: collect();
|
||||||
|
|
||||||
|
// Attach rendered_preview to each item
|
||||||
|
$collection = collect($items->items());
|
||||||
|
$collection = $collection->transform(function ($it) use ($sms, $contracts) {
|
||||||
|
$payload = (array) ($it->payload_json ?? []);
|
||||||
|
$tgt = (array) ($it->target_json ?? []);
|
||||||
|
$vars = (array) ($payload['variables'] ?? []);
|
||||||
|
if (! empty($tgt['contract_id']) && $contracts->has($tgt['contract_id'])) {
|
||||||
|
$c = $contracts->get($tgt['contract_id']);
|
||||||
|
$vars['contract'] = [
|
||||||
|
'id' => $c->id,
|
||||||
|
'uuid' => $c->uuid,
|
||||||
|
'reference' => $c->reference,
|
||||||
|
'start_date' => (string) ($c->start_date ?? ''),
|
||||||
|
'end_date' => (string) ($c->end_date ?? ''),
|
||||||
|
];
|
||||||
|
if ($c->account) {
|
||||||
|
$initialRaw = (string) $c->account->initial_amount;
|
||||||
|
$balanceRaw = (string) $c->account->balance_amount;
|
||||||
|
$vars['account'] = [
|
||||||
|
'id' => $c->account->id,
|
||||||
|
'reference' => $c->account->reference,
|
||||||
|
// Use EU formatted values for SMS previews
|
||||||
|
'initial_amount' => $sms->formatAmountEu($initialRaw),
|
||||||
|
'balance_amount' => $sms->formatAmountEu($balanceRaw),
|
||||||
|
// Also expose raw values
|
||||||
|
'initial_amount_raw' => $initialRaw,
|
||||||
|
'balance_amount_raw' => $balanceRaw,
|
||||||
|
'type' => $c->account->type?->name,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prefer recorded message from result_json if available (sent items)
|
||||||
|
$result = (array) ($it->result_json ?? []);
|
||||||
|
$rendered = $result['message'] ?? null;
|
||||||
|
if (! $rendered) {
|
||||||
|
$body = isset($payload['body']) ? trim((string) $payload['body']) : '';
|
||||||
|
if ($body !== '') {
|
||||||
|
$rendered = $body;
|
||||||
|
} elseif (! empty($payload['template_id'])) {
|
||||||
|
$tpl = \App\Models\SmsTemplate::find((int) $payload['template_id']);
|
||||||
|
if ($tpl) {
|
||||||
|
$rendered = $sms->renderContent($tpl->content, $vars);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$it->rendered_preview = $rendered;
|
||||||
|
|
||||||
|
return $it;
|
||||||
|
});
|
||||||
|
// Replace paginator collection
|
||||||
|
if (method_exists($items, 'setCollection')) {
|
||||||
|
$items->setCollection($collection);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build a preview of message content from the first item (shared payload across package)
|
||||||
|
$preview = null;
|
||||||
|
$firstItem = $package->items()->oldest('id')->first();
|
||||||
|
if ($firstItem) {
|
||||||
|
$payload = (array) ($firstItem->payload_json ?? []);
|
||||||
|
$body = isset($payload['body']) ? trim((string) $payload['body']) : '';
|
||||||
|
// Enrich variables with contract/account for preview if available
|
||||||
|
$vars = (array) ($payload['variables'] ?? []);
|
||||||
|
$tgt = (array) ($firstItem->target_json ?? []);
|
||||||
|
if (! empty($tgt['contract_id'])) {
|
||||||
|
$c = Contract::query()->with('account.type')->find($tgt['contract_id']);
|
||||||
|
if ($c) {
|
||||||
|
$vars['contract'] = [
|
||||||
|
'id' => $c->id,
|
||||||
|
'uuid' => $c->uuid,
|
||||||
|
'reference' => $c->reference,
|
||||||
|
'start_date' => (string) ($c->start_date ?? ''),
|
||||||
|
'end_date' => (string) ($c->end_date ?? ''),
|
||||||
|
];
|
||||||
|
if ($c->account) {
|
||||||
|
$initialRaw = (string) $c->account->initial_amount;
|
||||||
|
$balanceRaw = (string) $c->account->balance_amount;
|
||||||
|
$vars['account'] = [
|
||||||
|
'id' => $c->account->id,
|
||||||
|
'reference' => $c->account->reference,
|
||||||
|
'initial_amount' => $sms->formatAmountEu($initialRaw),
|
||||||
|
'balance_amount' => $sms->formatAmountEu($balanceRaw),
|
||||||
|
'initial_amount_raw' => $initialRaw,
|
||||||
|
'balance_amount_raw' => $balanceRaw,
|
||||||
|
'type' => $c->account->type?->name,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($body !== '') {
|
||||||
|
$preview = [
|
||||||
|
'source' => 'body',
|
||||||
|
'content' => $body,
|
||||||
|
];
|
||||||
|
} elseif (! empty($payload['template_id'])) {
|
||||||
|
/** @var SmsTemplate|null $tpl */
|
||||||
|
$tpl = SmsTemplate::find((int) $payload['template_id']);
|
||||||
|
if ($tpl) {
|
||||||
|
$content = $sms->renderContent($tpl->content, $vars);
|
||||||
|
$preview = [
|
||||||
|
'source' => 'template',
|
||||||
|
'template' => [
|
||||||
|
'id' => $tpl->id,
|
||||||
|
'name' => $tpl->name,
|
||||||
|
],
|
||||||
|
'content' => $content,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Inertia::render('Admin/Packages/Show', [
|
||||||
|
'package' => $package,
|
||||||
|
'items' => $items,
|
||||||
|
'preview' => $preview,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(StorePackageRequest $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$data = $request->validated();
|
||||||
|
|
||||||
|
$package = Package::query()->create([
|
||||||
|
'uuid' => (string) Str::uuid(),
|
||||||
|
'type' => $data['type'],
|
||||||
|
'status' => Package::STATUS_DRAFT,
|
||||||
|
'name' => $data['name'] ?? null,
|
||||||
|
'description' => $data['description'] ?? null,
|
||||||
|
'meta' => $data['meta'] ?? [],
|
||||||
|
'created_by' => optional($request->user())->id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$items = collect($data['items'])
|
||||||
|
->map(function (array $row) {
|
||||||
|
return new PackageItem([
|
||||||
|
'status' => 'queued',
|
||||||
|
'target_json' => [
|
||||||
|
'number' => (string) $row['number'],
|
||||||
|
'phone_id' => $row['phone_id'] ?? null,
|
||||||
|
],
|
||||||
|
'payload_json' => $row['payload'] ?? [],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
$package->items()->saveMany($items);
|
||||||
|
$package->total_items = $items->count();
|
||||||
|
$package->save();
|
||||||
|
|
||||||
|
return back()->with('success', 'Package created');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function dispatch(Package $package): RedirectResponse
|
||||||
|
{
|
||||||
|
if (! in_array($package->status, [Package::STATUS_DRAFT, Package::STATUS_FAILED], true)) {
|
||||||
|
return back()->with('error', 'Package not in a dispatchable state.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$jobs = $package->items()->whereIn('status', ['queued', 'failed'])->get()->map(function (PackageItem $item) {
|
||||||
|
return new PackageItemSmsJob($item->id);
|
||||||
|
})->all();
|
||||||
|
|
||||||
|
if (empty($jobs)) {
|
||||||
|
return back()->with('error', 'No items to dispatch.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$package->status = Package::STATUS_QUEUED;
|
||||||
|
$package->save();
|
||||||
|
|
||||||
|
Bus::batch($jobs)
|
||||||
|
->name('pkg:'.$package->id.' ('.$package->type.')')
|
||||||
|
->then(function () use ($package) {
|
||||||
|
// If finished counters not set by items (e.g., empty), finalize
|
||||||
|
$package->refresh();
|
||||||
|
if (($package->sent_count + $package->failed_count) >= $package->total_items) {
|
||||||
|
$finalStatus = $package->failed_count > 0 ? Package::STATUS_FAILED : Package::STATUS_COMPLETED;
|
||||||
|
$package->status = $finalStatus;
|
||||||
|
$package->finished_at = now();
|
||||||
|
$package->save();
|
||||||
|
} else {
|
||||||
|
$package->status = Package::STATUS_RUNNING;
|
||||||
|
$package->save();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
->onQueue('sms')
|
||||||
|
->dispatch();
|
||||||
|
|
||||||
|
return back()->with('success', 'Package dispatched');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function cancel(Package $package): RedirectResponse
|
||||||
|
{
|
||||||
|
$package->status = Package::STATUS_CANCELED;
|
||||||
|
$package->save();
|
||||||
|
|
||||||
|
return back()->with('success', 'Package canceled');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List contracts for a given segment and include selected phone per person.
|
||||||
|
*/
|
||||||
|
public function contracts(Request $request, PhoneSelector $selector): \Illuminate\Http\JsonResponse
|
||||||
|
{
|
||||||
|
$request->validate([
|
||||||
|
'segment_id' => ['required', 'integer', 'exists:segments,id'],
|
||||||
|
'q' => ['nullable', 'string'],
|
||||||
|
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||||
|
'client_id' => ['nullable', 'integer', 'exists:clients,id'],
|
||||||
|
'only_mobile' => ['nullable', 'boolean'],
|
||||||
|
'only_validated' => ['nullable', 'boolean'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$segmentId = (int) $request->input('segment_id');
|
||||||
|
$perPage = (int) ($request->input('per_page') ?? 25);
|
||||||
|
|
||||||
|
$query = Contract::query()
|
||||||
|
->join('contract_segment', function ($j) use ($segmentId) {
|
||||||
|
$j->on('contract_segment.contract_id', '=', 'contracts.id')
|
||||||
|
->where('contract_segment.segment_id', '=', $segmentId)
|
||||||
|
->where('contract_segment.active', true);
|
||||||
|
})
|
||||||
|
->with([
|
||||||
|
'clientCase.person.phones',
|
||||||
|
'clientCase.client.person',
|
||||||
|
])
|
||||||
|
->select('contracts.*')
|
||||||
|
->latest('contracts.id');
|
||||||
|
|
||||||
|
if ($q = trim((string) $request->input('q'))) {
|
||||||
|
$query->where(function ($w) use ($q) {
|
||||||
|
$w->where('contracts.reference', 'ILIKE', "%{$q}%");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($clientId = $request->integer('client_id')) {
|
||||||
|
$query->join('client_cases', 'client_cases.id', '=', 'contracts.client_case_id')
|
||||||
|
->where('client_cases.client_id', $clientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Optional phone filters
|
||||||
|
if ($request->boolean('only_mobile') || $request->boolean('only_validated')) {
|
||||||
|
$query->whereHas('clientCase.person.phones', function ($q) use ($request) {
|
||||||
|
if ($request->boolean('only_mobile')) {
|
||||||
|
$q->where('person_phones.phone_type', 'mobile');
|
||||||
|
}
|
||||||
|
if ($request->boolean('only_validated')) {
|
||||||
|
$q->where('person_phones.validated', true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
$contracts = $query->paginate($perPage);
|
||||||
|
|
||||||
|
$data = collect($contracts->items())->map(function (Contract $contract) use ($selector) {
|
||||||
|
$person = $contract->clientCase?->person;
|
||||||
|
$selected = $person ? $selector->selectForPerson($person) : ['phone' => null, 'reason' => 'no_person'];
|
||||||
|
$phone = $selected['phone'];
|
||||||
|
$clientPerson = $contract->clientCase?->client?->person;
|
||||||
|
|
||||||
|
return [
|
||||||
|
'id' => $contract->id,
|
||||||
|
'uuid' => $contract->uuid,
|
||||||
|
'reference' => $contract->reference,
|
||||||
|
'case' => [
|
||||||
|
'id' => $contract->clientCase?->id,
|
||||||
|
'uuid' => $contract->clientCase?->uuid,
|
||||||
|
],
|
||||||
|
// Primer: the case person
|
||||||
|
'person' => [
|
||||||
|
'id' => $person?->id,
|
||||||
|
'uuid' => $person?->uuid,
|
||||||
|
'full_name' => $person?->full_name,
|
||||||
|
],
|
||||||
|
// Stranka: the client person
|
||||||
|
'client' => $clientPerson ? [
|
||||||
|
'id' => $contract->clientCase?->client?->id,
|
||||||
|
'uuid' => $contract->clientCase?->client?->uuid,
|
||||||
|
'name' => $clientPerson->full_name,
|
||||||
|
] : null,
|
||||||
|
'selected_phone' => $phone ? [
|
||||||
|
'id' => $phone->id,
|
||||||
|
'number' => $phone->nu,
|
||||||
|
'validated' => $phone->validated,
|
||||||
|
'type' => $phone->phone_type?->value,
|
||||||
|
] : null,
|
||||||
|
'no_phone_reason' => $phone ? null : ($selected['reason'] ?? 'unknown'),
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'data' => $data,
|
||||||
|
'meta' => [
|
||||||
|
'current_page' => $contracts->currentPage(),
|
||||||
|
'last_page' => $contracts->lastPage(),
|
||||||
|
'per_page' => $contracts->perPage(),
|
||||||
|
'total' => $contracts->total(),
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an SMS package from a list of contracts by selecting recipient phones.
|
||||||
|
*/
|
||||||
|
public function storeFromContracts(StorePackageFromContractsRequest $request, PhoneSelector $selector): RedirectResponse
|
||||||
|
{
|
||||||
|
$data = $request->validated();
|
||||||
|
|
||||||
|
// Load contracts with people, phones and account (for template placeholders)
|
||||||
|
$contracts = Contract::query()
|
||||||
|
->with(['clientCase.person.phones', 'account.type'])
|
||||||
|
->whereIn('id', $data['contract_ids'])
|
||||||
|
->get();
|
||||||
|
|
||||||
|
$items = [];
|
||||||
|
$seen = collect(); // de-dup by phone_id or number
|
||||||
|
$skipped = 0;
|
||||||
|
foreach ($contracts as $contract) {
|
||||||
|
$person = $contract->clientCase?->person;
|
||||||
|
if (! $person) {
|
||||||
|
$skipped++;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$selected = $selector->selectForPerson($person);
|
||||||
|
/** @var ?\App\Models\Person\PersonPhone $phone */
|
||||||
|
$phone = $selected['phone'];
|
||||||
|
if (! $phone) {
|
||||||
|
$skipped++;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$key = $phone->id ? 'id:'.$phone->id : 'num:'.$phone->nu;
|
||||||
|
if ($seen->contains($key)) {
|
||||||
|
// skip duplicates across multiple contracts/persons
|
||||||
|
$skipped++;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$seen->push($key);
|
||||||
|
$items[] = [
|
||||||
|
'number' => (string) $phone->nu,
|
||||||
|
'phone_id' => $phone->id,
|
||||||
|
'payload' => $data['payload'] ?? [],
|
||||||
|
// Keep context for variable rendering during send
|
||||||
|
'contract_id' => $contract->id,
|
||||||
|
'account_id' => $contract->account?->id,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($items)) {
|
||||||
|
return back()->with('error', 'No recipients found for selected contracts.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$package = Package::query()->create([
|
||||||
|
'uuid' => (string) Str::uuid(),
|
||||||
|
'type' => $data['type'],
|
||||||
|
'status' => Package::STATUS_DRAFT,
|
||||||
|
'name' => $data['name'] ?? null,
|
||||||
|
'description' => $data['description'] ?? null,
|
||||||
|
'meta' => array_merge($data['meta'] ?? [], [
|
||||||
|
'source' => 'contracts',
|
||||||
|
'skipped' => $skipped,
|
||||||
|
]),
|
||||||
|
'created_by' => optional($request->user())->id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$packageItems = collect($items)->map(function (array $row) {
|
||||||
|
return new PackageItem([
|
||||||
|
'status' => 'queued',
|
||||||
|
'target_json' => [
|
||||||
|
'number' => $row['number'],
|
||||||
|
'phone_id' => $row['phone_id'],
|
||||||
|
'contract_id' => $row['contract_id'] ?? null,
|
||||||
|
'account_id' => $row['account_id'] ?? null,
|
||||||
|
],
|
||||||
|
'payload_json' => $row['payload'] ?? [],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
$package->items()->saveMany($packageItems);
|
||||||
|
$package->total_items = $packageItems->count();
|
||||||
|
$package->save();
|
||||||
|
|
||||||
|
return back()->with('success', 'Package created from contracts');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -7,6 +7,7 @@
|
||||||
use App\Models\ClientCase;
|
use App\Models\ClientCase;
|
||||||
use App\Models\Contract;
|
use App\Models\Contract;
|
||||||
use App\Models\Document;
|
use App\Models\Document;
|
||||||
|
use App\Services\Sms\SmsService;
|
||||||
use Exception;
|
use Exception;
|
||||||
use Illuminate\Database\QueryException;
|
use Illuminate\Database\QueryException;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
|
@ -1693,6 +1694,7 @@ public function sendSmsToPhone(ClientCase $clientCase, Request $request, int $ph
|
||||||
'template_id' => ['sometimes', 'nullable', 'integer', 'exists:sms_templates,id'],
|
'template_id' => ['sometimes', 'nullable', 'integer', 'exists:sms_templates,id'],
|
||||||
'profile_id' => ['sometimes', 'nullable', 'integer', 'exists:sms_profiles,id'],
|
'profile_id' => ['sometimes', 'nullable', 'integer', 'exists:sms_profiles,id'],
|
||||||
'sender_id' => ['sometimes', 'nullable', 'integer', 'exists:sms_senders,id'],
|
'sender_id' => ['sometimes', 'nullable', 'integer', 'exists:sms_senders,id'],
|
||||||
|
'contract_uuid' => ['sometimes', 'nullable', 'uuid'],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Ensure the phone belongs to the person of this case
|
// Ensure the phone belongs to the person of this case
|
||||||
|
|
@ -1801,4 +1803,93 @@ public function sendSmsToPhone(ClientCase $clientCase, Request $request, int $ph
|
||||||
return back()->with('error', 'SMS ni bil dodan v čakalno vrsto.');
|
return back()->with('error', 'SMS ni bil dodan v čakalno vrsto.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return contracts for the given client case (for SMS dialog dropdown).
|
||||||
|
*/
|
||||||
|
public function listContracts(ClientCase $clientCase)
|
||||||
|
{
|
||||||
|
$contracts = $clientCase->contracts()
|
||||||
|
->with('account.type')
|
||||||
|
->select('id', 'uuid', 'reference', 'active', 'start_date', 'end_date')
|
||||||
|
->latest('id')
|
||||||
|
->get()
|
||||||
|
->map(function ($c) {
|
||||||
|
/** @var SmsService $sms */
|
||||||
|
$sms = app(SmsService::class);
|
||||||
|
$acc = $c->account;
|
||||||
|
$initialRaw = $acc?->initial_amount !== null ? (string) $acc->initial_amount : null;
|
||||||
|
$balanceRaw = $acc?->balance_amount !== null ? (string) $acc->balance_amount : null;
|
||||||
|
|
||||||
|
return [
|
||||||
|
'uuid' => $c->uuid,
|
||||||
|
'reference' => $c->reference,
|
||||||
|
'active' => (bool) $c->active,
|
||||||
|
'start_date' => (string) ($c->start_date ?? ''),
|
||||||
|
'end_date' => (string) ($c->end_date ?? ''),
|
||||||
|
'account' => $acc ? [
|
||||||
|
'reference' => $acc->reference,
|
||||||
|
'type' => $acc->type?->name,
|
||||||
|
'initial_amount' => $initialRaw !== null ? $sms->formatAmountEu($initialRaw) : null,
|
||||||
|
'balance_amount' => $balanceRaw !== null ? $sms->formatAmountEu($balanceRaw) : null,
|
||||||
|
'initial_amount_raw' => $initialRaw,
|
||||||
|
'balance_amount_raw' => $balanceRaw,
|
||||||
|
] : null,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
return response()->json(['data' => $contracts]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render an SMS template preview with optional contract/account placeholders filled.
|
||||||
|
*/
|
||||||
|
public function previewSms(ClientCase $clientCase, Request $request, SmsService $sms)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'template_id' => ['required', 'integer', 'exists:sms_templates,id'],
|
||||||
|
'contract_uuid' => ['sometimes', 'nullable', 'uuid'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
/** @var \App\Models\SmsTemplate $template */
|
||||||
|
$template = \App\Models\SmsTemplate::findOrFail((int) $validated['template_id']);
|
||||||
|
|
||||||
|
$vars = [];
|
||||||
|
$contractUuid = $validated['contract_uuid'] ?? null;
|
||||||
|
if ($contractUuid) {
|
||||||
|
// Ensure the contract belongs to this client case
|
||||||
|
$contract = $clientCase->contracts()->where('uuid', $contractUuid)
|
||||||
|
->with('account.type')
|
||||||
|
->first();
|
||||||
|
if ($contract) {
|
||||||
|
$vars['contract'] = [
|
||||||
|
'id' => $contract->id,
|
||||||
|
'uuid' => $contract->uuid,
|
||||||
|
'reference' => $contract->reference,
|
||||||
|
'start_date' => (string) ($contract->start_date ?? ''),
|
||||||
|
'end_date' => (string) ($contract->end_date ?? ''),
|
||||||
|
];
|
||||||
|
if ($contract->account) {
|
||||||
|
$initialRaw = (string) $contract->account->initial_amount;
|
||||||
|
$balanceRaw = (string) $contract->account->balance_amount;
|
||||||
|
$vars['account'] = [
|
||||||
|
'id' => $contract->account->id,
|
||||||
|
'reference' => $contract->account->reference,
|
||||||
|
'initial_amount' => $sms->formatAmountEu($initialRaw),
|
||||||
|
'balance_amount' => $sms->formatAmountEu($balanceRaw),
|
||||||
|
'initial_amount_raw' => $initialRaw,
|
||||||
|
'balance_amount_raw' => $balanceRaw,
|
||||||
|
'type' => $contract->account->type?->name,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$content = $sms->renderContent($template->content, $vars);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'content' => $content,
|
||||||
|
'variables' => $vars,
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -112,6 +112,8 @@ public function createPhone(Person $person, Request $request)
|
||||||
'country_code' => 'nullable|integer',
|
'country_code' => 'nullable|integer',
|
||||||
'type_id' => 'required|integer|exists:phone_types,id',
|
'type_id' => 'required|integer|exists:phone_types,id',
|
||||||
'description' => 'nullable|string|max:125',
|
'description' => 'nullable|string|max:125',
|
||||||
|
'validated' => 'sometimes|boolean',
|
||||||
|
'phone_type' => 'nullable|in:mobile,landline,voip',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Dedup: avoid duplicate phone per person by (nu, country_code)
|
// Dedup: avoid duplicate phone per person by (nu, country_code)
|
||||||
|
|
@ -120,15 +122,9 @@ public function createPhone(Person $person, Request $request)
|
||||||
'country_code' => $attributes['country_code'] ?? null,
|
'country_code' => $attributes['country_code'] ?? null,
|
||||||
], $attributes);
|
], $attributes);
|
||||||
|
|
||||||
if ($request->header('X-Inertia')) {
|
|
||||||
return back()->with('success', 'Phone added successfully');
|
return back()->with('success', 'Phone added successfully');
|
||||||
}
|
}
|
||||||
|
|
||||||
return response()->json([
|
|
||||||
'phone' => \App\Models\Person\PersonPhone::with(['type'])->findOrFail($phone->id),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function updatePhone(Person $person, int $phone_id, Request $request)
|
public function updatePhone(Person $person, int $phone_id, Request $request)
|
||||||
{
|
{
|
||||||
$attributes = $request->validate([
|
$attributes = $request->validate([
|
||||||
|
|
@ -136,33 +132,25 @@ public function updatePhone(Person $person, int $phone_id, Request $request)
|
||||||
'country_code' => 'nullable|integer',
|
'country_code' => 'nullable|integer',
|
||||||
'type_id' => 'required|integer|exists:phone_types,id',
|
'type_id' => 'required|integer|exists:phone_types,id',
|
||||||
'description' => 'nullable|string|max:125',
|
'description' => 'nullable|string|max:125',
|
||||||
|
'validated' => 'sometimes|boolean',
|
||||||
|
'phone_type' => 'nullable|in:mobile,landline,voip',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$phone = $person->phones()->with(['type'])->findOrFail($phone_id);
|
$phone = $person->phones()->with(['type'])->findOrFail($phone_id);
|
||||||
|
|
||||||
$phone->update($attributes);
|
$phone->update($attributes);
|
||||||
|
|
||||||
if ($request->header('X-Inertia')) {
|
|
||||||
return back()->with('success', 'Phone updated successfully');
|
return back()->with('success', 'Phone updated successfully');
|
||||||
}
|
}
|
||||||
|
|
||||||
return response()->json([
|
|
||||||
'phone' => $phone,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function deletePhone(Person $person, int $phone_id, Request $request)
|
public function deletePhone(Person $person, int $phone_id, Request $request)
|
||||||
{
|
{
|
||||||
$phone = $person->phones()->findOrFail($phone_id);
|
$phone = $person->phones()->findOrFail($phone_id);
|
||||||
$phone->delete(); // soft delete
|
$phone->delete(); // soft delete
|
||||||
|
|
||||||
if ($request->header('X-Inertia')) {
|
|
||||||
return back()->with('success', 'Phone deleted');
|
return back()->with('success', 'Phone deleted');
|
||||||
}
|
}
|
||||||
|
|
||||||
return response()->json(['status' => 'ok']);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function createEmail(Person $person, Request $request)
|
public function createEmail(Person $person, Request $request)
|
||||||
{
|
{
|
||||||
$attributes = $request->validate([
|
$attributes = $request->validate([
|
||||||
|
|
|
||||||
36
app/Http/Requests/StorePackageFromContractsRequest.php
Normal file
36
app/Http/Requests/StorePackageFromContractsRequest.php
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class StorePackageFromContractsRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return $this->user()?->can('manage-settings') ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'type' => ['required', 'in:sms'],
|
||||||
|
'name' => ['nullable', 'string', 'max:255'],
|
||||||
|
'description' => ['nullable', 'string'],
|
||||||
|
'meta' => ['nullable', 'array'],
|
||||||
|
|
||||||
|
// Common payload for all items
|
||||||
|
'payload' => ['required', 'array'],
|
||||||
|
'payload.profile_id' => ['nullable', 'integer', 'exists:sms_profiles,id'],
|
||||||
|
'payload.sender_id' => ['nullable', 'integer', 'exists:sms_senders,id'],
|
||||||
|
'payload.template_id' => ['nullable', 'integer', 'exists:sms_templates,id'],
|
||||||
|
'payload.delivery_report' => ['nullable', 'boolean'],
|
||||||
|
'payload.variables' => ['nullable', 'array'],
|
||||||
|
'payload.body' => ['nullable', 'string'],
|
||||||
|
|
||||||
|
// Source contracts to derive items from
|
||||||
|
'contract_ids' => ['required', 'array', 'min:1'],
|
||||||
|
'contract_ids.*' => ['integer', 'exists:contracts,id'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
35
app/Http/Requests/StorePackageRequest.php
Normal file
35
app/Http/Requests/StorePackageRequest.php
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class StorePackageRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return $this->user()?->can('manage-settings') ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'type' => ['required', 'in:sms'],
|
||||||
|
'name' => ['nullable', 'string', 'max:255'],
|
||||||
|
'description' => ['nullable', 'string'],
|
||||||
|
'meta' => ['nullable', 'array'],
|
||||||
|
|
||||||
|
// items
|
||||||
|
'items' => ['required', 'array', 'min:1'],
|
||||||
|
'items.*.number' => ['required', 'string'],
|
||||||
|
'items.*.phone_id' => ['nullable', 'integer'],
|
||||||
|
'items.*.payload' => ['nullable', 'array'],
|
||||||
|
'items.*.payload.profile_id' => ['nullable', 'integer', 'exists:sms_profiles,id'],
|
||||||
|
'items.*.payload.sender_id' => ['nullable', 'integer', 'exists:sms_senders,id'],
|
||||||
|
'items.*.payload.template_id' => ['nullable', 'integer', 'exists:sms_templates,id'],
|
||||||
|
'items.*.payload.delivery_report' => ['nullable', 'boolean'],
|
||||||
|
'items.*.payload.variables' => ['nullable', 'array'],
|
||||||
|
'items.*.payload.body' => ['nullable', 'string'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
217
app/Jobs/PackageItemSmsJob.php
Normal file
217
app/Jobs/PackageItemSmsJob.php
Normal file
|
|
@ -0,0 +1,217 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Jobs;
|
||||||
|
|
||||||
|
use App\Models\Contract;
|
||||||
|
use App\Models\Package;
|
||||||
|
use App\Models\PackageItem;
|
||||||
|
use App\Models\SmsProfile;
|
||||||
|
use App\Models\SmsSender;
|
||||||
|
use App\Models\SmsTemplate;
|
||||||
|
use App\Services\Sms\SmsService;
|
||||||
|
use Illuminate\Bus\Queueable;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use Illuminate\Support\Facades\Redis;
|
||||||
|
|
||||||
|
class PackageItemSmsJob implements ShouldQueue
|
||||||
|
{
|
||||||
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
|
public function __construct(public int $packageItemId)
|
||||||
|
{
|
||||||
|
$this->onQueue('sms');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(SmsService $sms): void
|
||||||
|
{
|
||||||
|
/** @var PackageItem|null $item */
|
||||||
|
$item = PackageItem::query()->find($this->packageItemId);
|
||||||
|
if (! $item) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Package $package */
|
||||||
|
$package = $item->package;
|
||||||
|
if (! $package || $package->status === Package::STATUS_CANCELED) {
|
||||||
|
return; // canceled or missing
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip if already finalized to avoid double counting on retries
|
||||||
|
if (in_array($item->status, ['sent', 'failed', 'canceled', 'skipped'], true)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Mark processing on first entry
|
||||||
|
if ($item->status === 'queued') {
|
||||||
|
$item->status = 'processing';
|
||||||
|
$item->save();
|
||||||
|
$package->increment('processing_count');
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = (array) $item->payload_json;
|
||||||
|
$target = (array) $item->target_json;
|
||||||
|
|
||||||
|
$profileId = $payload['profile_id'] ?? null;
|
||||||
|
$senderId = $payload['sender_id'] ?? null;
|
||||||
|
$templateId = $payload['template_id'] ?? null;
|
||||||
|
$deliveryReport = (bool) ($payload['delivery_report'] ?? false);
|
||||||
|
$variables = (array) ($payload['variables'] ?? []);
|
||||||
|
// Enrich variables with contract/account context when available (contracts-based packages)
|
||||||
|
if (! empty($target['contract_id'])) {
|
||||||
|
$contract = Contract::query()->with('account.type')->find($target['contract_id']);
|
||||||
|
if ($contract) {
|
||||||
|
$variables['contract'] = [
|
||||||
|
'id' => $contract->id,
|
||||||
|
'uuid' => $contract->uuid,
|
||||||
|
'reference' => $contract->reference,
|
||||||
|
'start_date' => (string) ($contract->start_date ?? ''),
|
||||||
|
'end_date' => (string) ($contract->end_date ?? ''),
|
||||||
|
];
|
||||||
|
if ($contract->account) {
|
||||||
|
// Preserve raw values and provide EU-formatted versions for SMS rendering
|
||||||
|
$initialRaw = (string) $contract->account->initial_amount;
|
||||||
|
$balanceRaw = (string) $contract->account->balance_amount;
|
||||||
|
$variables['account'] = [
|
||||||
|
'id' => $contract->account->id,
|
||||||
|
'reference' => $contract->account->reference,
|
||||||
|
// Override placeholders with EU formatted values for SMS
|
||||||
|
'initial_amount' => $sms->formatAmountEu($initialRaw),
|
||||||
|
'balance_amount' => $sms->formatAmountEu($balanceRaw),
|
||||||
|
// Expose raw values too in case templates need them explicitly
|
||||||
|
'initial_amount_raw' => $initialRaw,
|
||||||
|
'balance_amount_raw' => $balanceRaw,
|
||||||
|
'type' => $contract->account->type?->name,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$bodyOverride = isset($payload['body']) ? trim((string) $payload['body']) : null;
|
||||||
|
if ($bodyOverride === '') {
|
||||||
|
$bodyOverride = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var SmsProfile|null $profile */
|
||||||
|
$profile = $profileId ? SmsProfile::find($profileId) : null;
|
||||||
|
/** @var SmsSender|null $sender */
|
||||||
|
$sender = $senderId ? SmsSender::find($senderId) : null;
|
||||||
|
/** @var SmsTemplate|null $template */
|
||||||
|
$template = $templateId ? SmsTemplate::find($templateId) : null;
|
||||||
|
|
||||||
|
$to = $target['number'] ?? null;
|
||||||
|
if (! is_string($to) || $to === '') {
|
||||||
|
$item->status = 'failed';
|
||||||
|
$item->last_error = 'Missing recipient number.';
|
||||||
|
$item->save();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compute throttle key
|
||||||
|
$scope = config('services.sms.throttle.scope', 'global');
|
||||||
|
$provider = config('services.sms.throttle.provider_key', 'smsapi_si');
|
||||||
|
$allow = (int) config('services.sms.throttle.allow', 30);
|
||||||
|
$every = (int) config('services.sms.throttle.every', 60);
|
||||||
|
$jitter = (int) config('services.sms.throttle.jitter_seconds', 2);
|
||||||
|
$key = $scope === 'per_profile' && $profile ? "sms:{$provider}:{$profile->id}" : "sms:{$provider}";
|
||||||
|
|
||||||
|
// Throttle
|
||||||
|
$sendClosure = function () use ($sms, $item, $package, $profile, $sender, $template, $to, $variables, $deliveryReport, $bodyOverride) {
|
||||||
|
// Idempotency key (optional external use)
|
||||||
|
if (empty($item->idempotency_key)) {
|
||||||
|
$hash = sha1(implode('|', [
|
||||||
|
'sms', (string) ($profile?->id ?? ''), (string) ($sender?->id ?? ''), (string) ($template?->id ?? ''), $to, (string) ($bodyOverride ?? ''), json_encode($variables),
|
||||||
|
]));
|
||||||
|
$item->idempotency_key = "pkgitem:{$item->id}:{$hash}";
|
||||||
|
$item->save();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decide whether to use template or raw content
|
||||||
|
$useTemplate = false;
|
||||||
|
if ($template) {
|
||||||
|
if ($bodyOverride) {
|
||||||
|
// If custom body is provided but template does not allow it, force template
|
||||||
|
$useTemplate = ! (bool) ($template->allow_custom_body ?? false);
|
||||||
|
} else {
|
||||||
|
// No custom body provided -> use template
|
||||||
|
$useTemplate = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($useTemplate) {
|
||||||
|
$log = $sms->sendFromTemplate(
|
||||||
|
template: $template,
|
||||||
|
to: $to,
|
||||||
|
variables: $variables,
|
||||||
|
profile: $profile,
|
||||||
|
sender: $sender,
|
||||||
|
countryCode: null,
|
||||||
|
deliveryReport: $deliveryReport,
|
||||||
|
clientReference: "pkg:{$item->package_id}:item:{$item->id}",
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Either explicit body override or no template
|
||||||
|
$effectiveBody = (string) ($bodyOverride ?? '');
|
||||||
|
if ($effectiveBody === '') {
|
||||||
|
// Avoid provider error for empty body
|
||||||
|
throw new \RuntimeException('Empty SMS body and no template provided.');
|
||||||
|
}
|
||||||
|
if (! $profile && $template) {
|
||||||
|
$profile = $template->defaultProfile;
|
||||||
|
}
|
||||||
|
if (! $profile) {
|
||||||
|
throw new \RuntimeException('Missing SMS profile for raw send.');
|
||||||
|
}
|
||||||
|
$log = $sms->sendRaw(
|
||||||
|
profile: $profile,
|
||||||
|
to: $to,
|
||||||
|
content: $effectiveBody,
|
||||||
|
sender: $sender,
|
||||||
|
countryCode: null,
|
||||||
|
deliveryReport: $deliveryReport,
|
||||||
|
clientReference: "pkg:{$item->package_id}:item:{$item->id}",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$newStatus = $log->status === 'sent' ? 'sent' : 'failed';
|
||||||
|
$item->status = $newStatus;
|
||||||
|
$item->provider_message_id = $log->provider_message_id;
|
||||||
|
$item->cost = $log->cost;
|
||||||
|
$item->currency = $log->currency;
|
||||||
|
// Persist useful result info including final rendered message for auditing
|
||||||
|
$result = $log->meta ?? [];
|
||||||
|
$result['message'] = $log->message ?? (($useTemplate && isset($template)) ? $sms->renderContent($template->content, $variables) : ($bodyOverride ?? null));
|
||||||
|
$result['template_id'] = $template?->id;
|
||||||
|
$result['render_source'] = $useTemplate ? 'template' : 'body';
|
||||||
|
$item->result_json = $result;
|
||||||
|
$item->last_error = $log->status === 'sent' ? null : ($log->meta['error_message'] ?? 'Failed');
|
||||||
|
$item->save();
|
||||||
|
|
||||||
|
// Update package counters atomically
|
||||||
|
if ($newStatus === 'sent') {
|
||||||
|
$package->increment('sent_count');
|
||||||
|
} else {
|
||||||
|
$package->increment('failed_count');
|
||||||
|
}
|
||||||
|
|
||||||
|
// If all items processed, finalize package
|
||||||
|
$package->refresh();
|
||||||
|
if (($package->sent_count + $package->failed_count) >= $package->total_items) {
|
||||||
|
$finalStatus = $package->failed_count > 0 ? Package::STATUS_FAILED : Package::STATUS_COMPLETED;
|
||||||
|
$package->status = $finalStatus;
|
||||||
|
$package->finished_at = now();
|
||||||
|
$package->save();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
Redis::throttle($key)->allow($allow)->every($every)->then($sendClosure, function () use ($jitter) {
|
||||||
|
return $this->release(max(1, rand(1, $jitter)));
|
||||||
|
});
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
// Fallback to direct send when Redis unavailable (e.g., test environment)
|
||||||
|
$sendClosure();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -12,6 +12,7 @@
|
||||||
use Illuminate\Foundation\Bus\Dispatchable;
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
use Illuminate\Queue\InteractsWithQueue;
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
use Illuminate\Queue\SerializesModels;
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use Illuminate\Support\Facades\Redis;
|
||||||
|
|
||||||
class SendSmsJob implements ShouldQueue
|
class SendSmsJob implements ShouldQueue
|
||||||
{
|
{
|
||||||
|
|
@ -49,6 +50,17 @@ public function handle(SmsService $sms): void
|
||||||
/** @var SmsSender|null $sender */
|
/** @var SmsSender|null $sender */
|
||||||
$sender = $this->senderId ? SmsSender::find($this->senderId) : null;
|
$sender = $this->senderId ? SmsSender::find($this->senderId) : null;
|
||||||
|
|
||||||
|
// Apply Redis throttle from config to avoid provider rate limits
|
||||||
|
$scope = config('services.sms.throttle.scope', 'global');
|
||||||
|
$provider = config('services.sms.throttle.provider_key', 'smsapi_si');
|
||||||
|
$allow = (int) config('services.sms.throttle.allow', 30);
|
||||||
|
$every = (int) config('services.sms.throttle.every', 60);
|
||||||
|
$jitter = (int) config('services.sms.throttle.jitter_seconds', 2);
|
||||||
|
$key = $scope === 'per_profile' && $profile ? "sms:{$provider}:{$profile->id}" : "sms:{$provider}";
|
||||||
|
|
||||||
|
$log = null;
|
||||||
|
try {
|
||||||
|
Redis::throttle($key)->allow($allow)->every($every)->then(function () use (&$log, $sms, $profile, $sender) {
|
||||||
// Send and get log (handles queued->sent/failed transitions internally)
|
// Send and get log (handles queued->sent/failed transitions internally)
|
||||||
$log = $sms->sendRaw(
|
$log = $sms->sendRaw(
|
||||||
profile: $profile,
|
profile: $profile,
|
||||||
|
|
@ -59,6 +71,21 @@ public function handle(SmsService $sms): void
|
||||||
deliveryReport: $this->deliveryReport,
|
deliveryReport: $this->deliveryReport,
|
||||||
clientReference: $this->clientReference,
|
clientReference: $this->clientReference,
|
||||||
);
|
);
|
||||||
|
}, function () use ($jitter) {
|
||||||
|
return $this->release(max(1, rand(1, $jitter)));
|
||||||
|
});
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
// Fallback if Redis is unavailable in test or local env
|
||||||
|
$log = $sms->sendRaw(
|
||||||
|
profile: $profile,
|
||||||
|
to: $this->to,
|
||||||
|
content: $this->content,
|
||||||
|
sender: $sender,
|
||||||
|
countryCode: $this->countryCode,
|
||||||
|
deliveryReport: $this->deliveryReport,
|
||||||
|
clientReference: $this->clientReference,
|
||||||
|
);
|
||||||
|
}
|
||||||
// If invoked from the case UI with a selected template, create an Activity
|
// If invoked from the case UI with a selected template, create an Activity
|
||||||
if ($this->templateId && $this->clientCaseId && $log) {
|
if ($this->templateId && $this->clientCaseId && $log) {
|
||||||
try {
|
try {
|
||||||
|
|
|
||||||
48
app/Models/Package.php
Normal file
48
app/Models/Package.php
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
class Package extends Model
|
||||||
|
{
|
||||||
|
use HasFactory;
|
||||||
|
|
||||||
|
protected $fillable = [
|
||||||
|
'uuid', 'type', 'status', 'name', 'description', 'meta',
|
||||||
|
'total_items', 'processing_count', 'sent_count', 'failed_count',
|
||||||
|
'created_by', 'finished_at',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'meta' => 'array',
|
||||||
|
'finished_at' => 'datetime',
|
||||||
|
'total_items' => 'integer',
|
||||||
|
'processing_count' => 'integer',
|
||||||
|
'sent_count' => 'integer',
|
||||||
|
'failed_count' => 'integer',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function items()
|
||||||
|
{
|
||||||
|
return $this->hasMany(PackageItem::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public const TYPE_SMS = 'sms';
|
||||||
|
|
||||||
|
public const STATUS_DRAFT = 'draft';
|
||||||
|
|
||||||
|
public const STATUS_QUEUED = 'queued';
|
||||||
|
|
||||||
|
public const STATUS_RUNNING = 'running';
|
||||||
|
|
||||||
|
public const STATUS_COMPLETED = 'completed';
|
||||||
|
|
||||||
|
public const STATUS_FAILED = 'failed';
|
||||||
|
|
||||||
|
public const STATUS_CANCELED = 'canceled';
|
||||||
|
}
|
||||||
31
app/Models/PackageItem.php
Normal file
31
app/Models/PackageItem.php
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
class PackageItem extends Model
|
||||||
|
{
|
||||||
|
use HasFactory;
|
||||||
|
|
||||||
|
protected $fillable = [
|
||||||
|
'package_id', 'status', 'target_json', 'payload_json', 'attempts', 'last_error', 'result_json', 'provider_message_id', 'cost', 'currency', 'idempotency_key',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'target_json' => 'array',
|
||||||
|
'payload_json' => 'array',
|
||||||
|
'result_json' => 'array',
|
||||||
|
'attempts' => 'integer',
|
||||||
|
'cost' => 'decimal:4',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function package()
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Package::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
namespace App\Models\Person;
|
namespace App\Models\Person;
|
||||||
|
|
||||||
use Blade;
|
use App\Enums\PersonPhoneType;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
@ -13,6 +13,7 @@ class PersonPhone extends Model
|
||||||
{
|
{
|
||||||
/** @use HasFactory<\Database\Factories\Person/PersonPhoneFactory> */
|
/** @use HasFactory<\Database\Factories\Person/PersonPhoneFactory> */
|
||||||
use HasFactory;
|
use HasFactory;
|
||||||
|
|
||||||
use Searchable;
|
use Searchable;
|
||||||
use SoftDeletes;
|
use SoftDeletes;
|
||||||
|
|
||||||
|
|
@ -22,25 +23,28 @@ class PersonPhone extends Model
|
||||||
'type_id',
|
'type_id',
|
||||||
'description',
|
'description',
|
||||||
'person_id',
|
'person_id',
|
||||||
'user_id'
|
'user_id',
|
||||||
|
'validated',
|
||||||
|
'phone_type',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected $hidden = [
|
protected $hidden = [
|
||||||
'user_id',
|
'user_id',
|
||||||
'person_id',
|
'person_id',
|
||||||
'deleted'
|
'deleted',
|
||||||
];
|
];
|
||||||
|
|
||||||
public function toSearchableArray(): array
|
public function toSearchableArray(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'nu' => $this->nu
|
'nu' => $this->nu,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
protected static function booted(){
|
protected static function booted()
|
||||||
|
{
|
||||||
static::creating(function (PersonPhone $personPhone) {
|
static::creating(function (PersonPhone $personPhone) {
|
||||||
if(!isset($personPhone->user_id)){
|
if (! isset($personPhone->user_id)) {
|
||||||
$personPhone->user_id = auth()->id();
|
$personPhone->user_id = auth()->id();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
@ -55,4 +59,12 @@ public function type(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->belongsTo(\App\Models\Person\PhoneType::class, 'type_id');
|
return $this->belongsTo(\App\Models\Person\PhoneType::class, 'type_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'validated' => 'boolean',
|
||||||
|
'phone_type' => PersonPhoneType::class,
|
||||||
|
];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
53
app/Services/Contact/PhoneSelector.php
Normal file
53
app/Services/Contact/PhoneSelector.php
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Contact;
|
||||||
|
|
||||||
|
use App\Enums\PersonPhoneType;
|
||||||
|
use App\Models\Person\Person;
|
||||||
|
use App\Models\Person\PersonPhone;
|
||||||
|
|
||||||
|
class PhoneSelector
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Select the best phone for a person following priority rules.
|
||||||
|
* Priority:
|
||||||
|
* 1) validated mobile
|
||||||
|
* 2) validated (any type)
|
||||||
|
* 3) mobile (any validation)
|
||||||
|
* 4) first active phone
|
||||||
|
*
|
||||||
|
* Returns an array shape: ['phone' => ?PersonPhone, 'reason' => ?string]
|
||||||
|
*/
|
||||||
|
public function selectForPerson(Person $person): array
|
||||||
|
{
|
||||||
|
// Load active phones only (Person relation already filters active=1)
|
||||||
|
$phones = $person->phones;
|
||||||
|
|
||||||
|
if ($phones->isEmpty()) {
|
||||||
|
return ['phone' => null, 'reason' => 'no_active_phones'];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1) validated mobile
|
||||||
|
$phone = $phones->first(function (PersonPhone $p) {
|
||||||
|
return ($p->validated === true) && ($p->phone_type === PersonPhoneType::Mobile);
|
||||||
|
});
|
||||||
|
if ($phone) {
|
||||||
|
return ['phone' => $phone, 'reason' => null];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) validated (any type)
|
||||||
|
$phone = $phones->first(fn (PersonPhone $p) => $p->validated === true);
|
||||||
|
if ($phone) {
|
||||||
|
return ['phone' => $phone, 'reason' => null];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3) mobile (any validation)
|
||||||
|
$phone = $phones->first(fn (PersonPhone $p) => $p->phone_type === PersonPhoneType::Mobile);
|
||||||
|
if ($phone) {
|
||||||
|
return ['phone' => $phone, 'reason' => null];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4) first active
|
||||||
|
return ['phone' => $phones->first(), 'reason' => null];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -79,16 +79,52 @@ public function sendFromTemplate(SmsTemplate $template, string $to, array $varia
|
||||||
return $log;
|
return $log;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function renderContent(string $content, array $vars): string
|
public function renderContent(string $content, array $vars): string
|
||||||
{
|
{
|
||||||
// Simple token replacement: {token}
|
// Support {token} and {nested.keys} using dot-notation lookup
|
||||||
return preg_replace_callback('/\{([a-zA-Z0-9_\.]+)\}/', function ($m) use ($vars) {
|
$resolver = function (array $arr, string $path) {
|
||||||
$key = $m[1];
|
if (array_key_exists($path, $arr)) {
|
||||||
|
return $arr[$path];
|
||||||
|
}
|
||||||
|
$segments = explode('.', $path);
|
||||||
|
$cur = $arr;
|
||||||
|
foreach ($segments as $seg) {
|
||||||
|
if (is_array($cur) && array_key_exists($seg, $cur)) {
|
||||||
|
$cur = $cur[$seg];
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return array_key_exists($key, $vars) ? (string) $vars[$key] : $m[0];
|
return $cur;
|
||||||
|
};
|
||||||
|
|
||||||
|
return preg_replace_callback('/\{([a-zA-Z0-9_\.]+)\}/', function ($m) use ($vars, $resolver) {
|
||||||
|
$key = $m[1];
|
||||||
|
$val = $resolver($vars, $key);
|
||||||
|
|
||||||
|
return $val !== null ? (string) $val : $m[0];
|
||||||
}, $content);
|
}, $content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format a number to EU style: thousands separated by '.', decimals by ','.
|
||||||
|
*/
|
||||||
|
public function formatAmountEu(mixed $value, int $decimals = 2): string
|
||||||
|
{
|
||||||
|
if ($value === null || $value === '') {
|
||||||
|
return number_format(0, $decimals, ',', '.');
|
||||||
|
}
|
||||||
|
$str = (string) $value;
|
||||||
|
// Normalize possible EU-style input like "1.234,56" to standard for float casting
|
||||||
|
if (str_contains($str, ',')) {
|
||||||
|
$str = str_replace(['.', ','], ['', '.'], $str);
|
||||||
|
}
|
||||||
|
$num = (float) $str;
|
||||||
|
|
||||||
|
return number_format($num, $decimals, ',', '.');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get current credit balance from provider.
|
* Get current credit balance from provider.
|
||||||
*/
|
*/
|
||||||
|
|
|
||||||
|
|
@ -50,6 +50,14 @@
|
||||||
'timeout' => (int) env('SMSAPI_SI_TIMEOUT', 10),
|
'timeout' => (int) env('SMSAPI_SI_TIMEOUT', 10),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
|
// Throttling defaults for queued SMS jobs (per provider or per profile)
|
||||||
|
'throttle' => [
|
||||||
|
'scope' => env('SMS_THROTTLE_SCOPE', 'global'), // global|per_profile
|
||||||
|
'allow' => (int) env('SMS_THROTTLE_ALLOW', 30), // requests allowed
|
||||||
|
'every' => (int) env('SMS_THROTTLE_EVERY', 60), // per seconds
|
||||||
|
'jitter_seconds' => (int) env('SMS_THROTTLE_JITTER', 2),
|
||||||
|
'provider_key' => env('SMS_THROTTLE_PROVIDER_KEY', 'smsapi_si'),
|
||||||
|
],
|
||||||
],
|
],
|
||||||
|
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
namespace Database\Factories\Person;
|
namespace Database\Factories\Person;
|
||||||
|
|
||||||
|
use App\Enums\PersonPhoneType;
|
||||||
use App\Models\Person\PhoneType;
|
use App\Models\Person\PhoneType;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||||
|
|
@ -22,6 +23,33 @@ public function definition(): array
|
||||||
'nu' => $this->faker->numerify('06########'),
|
'nu' => $this->faker->numerify('06########'),
|
||||||
'type_id' => PhoneType::factory(),
|
'type_id' => PhoneType::factory(),
|
||||||
'user_id' => User::factory(),
|
'user_id' => User::factory(),
|
||||||
|
'validated' => $this->faker->boolean(80),
|
||||||
|
'phone_type' => PersonPhoneType::Mobile->value,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function mobile(): self
|
||||||
|
{
|
||||||
|
return $this->state(fn () => ['phone_type' => PersonPhoneType::Mobile->value]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function landline(): self
|
||||||
|
{
|
||||||
|
return $this->state(fn () => ['phone_type' => PersonPhoneType::Landline->value]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function voip(): self
|
||||||
|
{
|
||||||
|
return $this->state(fn () => ['phone_type' => PersonPhoneType::Voip->value]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function validated(): self
|
||||||
|
{
|
||||||
|
return $this->state(fn () => ['validated' => true]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function notValidated(): self
|
||||||
|
{
|
||||||
|
return $this->state(fn () => ['validated' => false]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,37 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('packages', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->uuid('uuid')->unique();
|
||||||
|
$table->string('type'); // sms, email, archive, segment
|
||||||
|
$table->string('status')->default('draft'); // draft, queued, running, completed, failed, canceled
|
||||||
|
$table->string('name')->nullable();
|
||||||
|
$table->text('description')->nullable();
|
||||||
|
$table->json('meta')->nullable();
|
||||||
|
$table->unsignedInteger('total_items')->default(0);
|
||||||
|
$table->unsignedInteger('processing_count')->default(0);
|
||||||
|
$table->unsignedInteger('sent_count')->default(0);
|
||||||
|
$table->unsignedInteger('failed_count')->default(0);
|
||||||
|
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
|
||||||
|
$table->timestamp('finished_at')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->index(['type', 'status']);
|
||||||
|
$table->index(['created_by']);
|
||||||
|
$table->index(['finished_at']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('packages');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -0,0 +1,35 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('package_items', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('package_id')->constrained('packages')->cascadeOnDelete();
|
||||||
|
$table->string('status')->default('queued'); // queued, processing, sent, failed, canceled, skipped
|
||||||
|
$table->json('target_json'); // e.g., {"phone_id": 1, "number": "+386..."}
|
||||||
|
$table->json('payload_json')->nullable(); // per-item overrides and variables
|
||||||
|
$table->unsignedTinyInteger('attempts')->default(0);
|
||||||
|
$table->text('last_error')->nullable();
|
||||||
|
$table->json('result_json')->nullable();
|
||||||
|
$table->string('provider_message_id')->nullable();
|
||||||
|
$table->decimal('cost', 10, 4)->nullable();
|
||||||
|
$table->string('currency', 10)->nullable();
|
||||||
|
$table->string('idempotency_key')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->index(['package_id', 'status']);
|
||||||
|
$table->unique(['idempotency_key']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('package_items');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -0,0 +1,85 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
$driver = DB::getDriverName();
|
||||||
|
if ($driver === 'pgsql') {
|
||||||
|
// Create PostgreSQL enum type for phone_type if not exists
|
||||||
|
DB::statement(<<<'SQL'
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'phone_type_enum') THEN
|
||||||
|
CREATE TYPE phone_type_enum AS ENUM ('mobile', 'landline', 'voip');
|
||||||
|
END IF;
|
||||||
|
END$$;
|
||||||
|
SQL);
|
||||||
|
}
|
||||||
|
|
||||||
|
Schema::table('person_phones', function (Blueprint $table): void {
|
||||||
|
// validated flag (default false)
|
||||||
|
if (! Schema::hasColumn('person_phones', 'validated')) {
|
||||||
|
$table->boolean('validated')->default(false)->after('active');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add phone_type column depending on driver
|
||||||
|
$hasPhoneType = $driver === 'pgsql'
|
||||||
|
? (bool) DB::selectOne("SELECT 1 as exists FROM information_schema.columns WHERE table_name = 'person_phones' AND column_name = 'phone_type'")
|
||||||
|
: Schema::hasColumn('person_phones', 'phone_type');
|
||||||
|
if (! $hasPhoneType) {
|
||||||
|
if ($driver === 'pgsql') {
|
||||||
|
// enum-typed column for Postgres
|
||||||
|
DB::statement('ALTER TABLE person_phones ADD COLUMN phone_type phone_type_enum NULL');
|
||||||
|
} else {
|
||||||
|
// Fallback for sqlite/mysql in tests/dev: simple string column
|
||||||
|
Schema::table('person_phones', function (Blueprint $table): void {
|
||||||
|
$table->string('phone_type', 20)->nullable()->after('validated');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
$driver = DB::getDriverName();
|
||||||
|
// Drop column phone_type if exists
|
||||||
|
$hasPhoneType = $driver === 'pgsql'
|
||||||
|
? (bool) DB::selectOne("SELECT 1 as exists FROM information_schema.columns WHERE table_name = 'person_phones' AND column_name = 'phone_type'")
|
||||||
|
: Schema::hasColumn('person_phones', 'phone_type');
|
||||||
|
if ($hasPhoneType) {
|
||||||
|
if ($driver === 'pgsql') {
|
||||||
|
DB::statement('ALTER TABLE person_phones DROP COLUMN phone_type');
|
||||||
|
} else {
|
||||||
|
Schema::table('person_phones', function (Blueprint $table): void {
|
||||||
|
$table->dropColumn('phone_type');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Schema::table('person_phones', function (Blueprint $table): void {
|
||||||
|
if (Schema::hasColumn('person_phones', 'validated')) {
|
||||||
|
$table->dropColumn('validated');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if ($driver === 'pgsql') {
|
||||||
|
// Drop type if no longer used (best-effort)
|
||||||
|
DB::statement(<<<'SQL'
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM pg_type WHERE typname = 'phone_type_enum') THEN
|
||||||
|
-- ensure no remaining dependencies
|
||||||
|
EXECUTE 'DROP TYPE phone_type_enum';
|
||||||
|
END IF;
|
||||||
|
END$$;
|
||||||
|
SQL);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -1,68 +1,68 @@
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, watch } from 'vue';
|
import { ref, watch } from "vue";
|
||||||
import { useForm, router, usePage } from '@inertiajs/vue3';
|
import { useForm, router, usePage } from "@inertiajs/vue3";
|
||||||
import DialogModal from './DialogModal.vue';
|
import DialogModal from "./DialogModal.vue";
|
||||||
import InputLabel from './InputLabel.vue';
|
import InputLabel from "./InputLabel.vue";
|
||||||
import SectionTitle from './SectionTitle.vue';
|
import SectionTitle from "./SectionTitle.vue";
|
||||||
import TextInput from './TextInput.vue';
|
import TextInput from "./TextInput.vue";
|
||||||
import InputError from './InputError.vue';
|
import InputError from "./InputError.vue";
|
||||||
import PrimaryButton from './PrimaryButton.vue';
|
import PrimaryButton from "./PrimaryButton.vue";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
show: {
|
show: {
|
||||||
type: Boolean,
|
type: Boolean,
|
||||||
default: false
|
default: false,
|
||||||
},
|
},
|
||||||
person: Object,
|
person: Object,
|
||||||
types: Array,
|
types: Array,
|
||||||
edit: {
|
edit: {
|
||||||
type: Boolean,
|
type: Boolean,
|
||||||
default: false
|
default: false,
|
||||||
},
|
},
|
||||||
id: {
|
id: {
|
||||||
type: Number,
|
type: Number,
|
||||||
default: 0
|
default: 0,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const processing = ref(false);
|
const processing = ref(false);
|
||||||
const errors = ref({});
|
const errors = ref({});
|
||||||
|
|
||||||
const emit = defineEmits(['close']);
|
const emit = defineEmits(["close"]);
|
||||||
|
|
||||||
const close = () => {
|
const close = () => {
|
||||||
emit('close');
|
emit("close");
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
errors.value = {};
|
errors.value = {};
|
||||||
try { form.clearErrors && form.clearErrors(); } catch {}
|
try {
|
||||||
|
form.clearErrors && form.clearErrors();
|
||||||
|
} catch {}
|
||||||
}, 300);
|
}, 300);
|
||||||
}
|
};
|
||||||
|
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
address: '',
|
address: "",
|
||||||
country: '',
|
country: "",
|
||||||
post_code: '',
|
post_code: "",
|
||||||
city: '',
|
city: "",
|
||||||
type_id: props.types?.[0]?.id ?? null,
|
type_id: props.types?.[0]?.id ?? null,
|
||||||
description: ''
|
description: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
const resetForm = () => {
|
const resetForm = () => {
|
||||||
form.address = '';
|
form.address = "";
|
||||||
form.country = '';
|
form.country = "";
|
||||||
form.post_code = '';
|
form.post_code = "";
|
||||||
form.city = '';
|
form.city = "";
|
||||||
form.type_id = props.types?.[0]?.id ?? null;
|
form.type_id = props.types?.[0]?.id ?? null;
|
||||||
form.description = '';
|
form.description = "";
|
||||||
}
|
};
|
||||||
|
|
||||||
const create = async () => {
|
const create = async () => {
|
||||||
processing.value = true;
|
processing.value = true;
|
||||||
errors.value = {};
|
errors.value = {};
|
||||||
|
|
||||||
form.post(route('person.address.create', props.person), {
|
form.post(route("person.address.create", props.person), {
|
||||||
preserveScroll: true,
|
preserveScroll: true,
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
// Optimistically append from last created record in DB by refetch or expose via flash if needed.
|
// Optimistically append from last created record in DB by refetch or expose via flash if needed.
|
||||||
|
|
@ -76,13 +76,15 @@ const create = async () => {
|
||||||
processing.value = false;
|
processing.value = false;
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
const update = async () => {
|
const update = async () => {
|
||||||
processing.value = true;
|
processing.value = true;
|
||||||
errors.value = {};
|
errors.value = {};
|
||||||
|
|
||||||
form.put(route('person.address.update', {person: props.person, address_id: props.id}), {
|
form.put(
|
||||||
|
route("person.address.update", { person: props.person, address_id: props.id }),
|
||||||
|
{
|
||||||
preserveScroll: true,
|
preserveScroll: true,
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
processing.value = false;
|
processing.value = false;
|
||||||
|
|
@ -93,20 +95,21 @@ const update = async () => {
|
||||||
errors.value = e || {};
|
errors.value = e || {};
|
||||||
processing.value = false;
|
processing.value = false;
|
||||||
},
|
},
|
||||||
});
|
}
|
||||||
}
|
);
|
||||||
|
};
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => props.id,
|
() => props.id,
|
||||||
((id) => {
|
(id) => {
|
||||||
if (props.edit && id !== 0){
|
if (props.edit && id !== 0) {
|
||||||
console.log(props.edit)
|
console.log(props.edit);
|
||||||
props.person.addresses.filter((a) => {
|
props.person.addresses.filter((a) => {
|
||||||
if(a.id === props.id){
|
if (a.id === props.id) {
|
||||||
form.address = a.address;
|
form.address = a.address;
|
||||||
form.country = a.country;
|
form.country = a.country;
|
||||||
form.post_code = a.post_code || a.postal_code || '';
|
form.post_code = a.post_code || a.postal_code || "";
|
||||||
form.city = a.city || '';
|
form.city = a.city || "";
|
||||||
form.type_id = a.type_id;
|
form.type_id = a.type_id;
|
||||||
form.description = a.description;
|
form.description = a.description;
|
||||||
}
|
}
|
||||||
|
|
@ -114,24 +117,20 @@ watch(
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
resetForm();
|
resetForm();
|
||||||
})
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const callSubmit = () => {
|
const callSubmit = () => {
|
||||||
if( props.edit ) {
|
if (props.edit) {
|
||||||
update();
|
update();
|
||||||
} else {
|
} else {
|
||||||
create();
|
create();
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<DialogModal
|
<DialogModal :show="show" @close="close">
|
||||||
:show="show"
|
|
||||||
@close="close"
|
|
||||||
>
|
|
||||||
<template #title>
|
<template #title>
|
||||||
<span v-if="edit">Spremeni naslov</span>
|
<span v-if="edit">Spremeni naslov</span>
|
||||||
<span v-else>Dodaj novi naslov</span>
|
<span v-else>Dodaj novi naslov</span>
|
||||||
|
|
@ -139,9 +138,7 @@ const callSubmit = () => {
|
||||||
<template #content>
|
<template #content>
|
||||||
<form @submit.prevent="callSubmit">
|
<form @submit.prevent="callSubmit">
|
||||||
<SectionTitle class="border-b mb-4">
|
<SectionTitle class="border-b mb-4">
|
||||||
<template #title>
|
<template #title> Naslov </template>
|
||||||
Naslov
|
|
||||||
</template>
|
|
||||||
</SectionTitle>
|
</SectionTitle>
|
||||||
|
|
||||||
<div class="col-span-6 sm:col-span-4">
|
<div class="col-span-6 sm:col-span-4">
|
||||||
|
|
@ -155,7 +152,11 @@ const callSubmit = () => {
|
||||||
autocomplete="address"
|
autocomplete="address"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<InputError v-if="errors.address !== undefined" v-for="err in errors.address" :message="err" />
|
<InputError
|
||||||
|
v-if="errors.address !== undefined"
|
||||||
|
v-for="err in errors.address"
|
||||||
|
:message="err"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-span-6 sm:col-span-4">
|
<div class="col-span-6 sm:col-span-4">
|
||||||
<InputLabel for="cr_country" value="Država" />
|
<InputLabel for="cr_country" value="Država" />
|
||||||
|
|
@ -168,7 +169,11 @@ const callSubmit = () => {
|
||||||
autocomplete="country"
|
autocomplete="country"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<InputError v-if="errors.address !== undefined" v-for="err in errors.address" :message="err" />
|
<InputError
|
||||||
|
v-if="errors.address !== undefined"
|
||||||
|
v-for="err in errors.address"
|
||||||
|
:message="err"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-span-6 sm:col-span-4">
|
<div class="col-span-6 sm:col-span-4">
|
||||||
<InputLabel for="cr_post_code" value="Poštna številka" />
|
<InputLabel for="cr_post_code" value="Poštna številka" />
|
||||||
|
|
@ -179,7 +184,11 @@ const callSubmit = () => {
|
||||||
class="mt-1 block w-full"
|
class="mt-1 block w-full"
|
||||||
autocomplete="postal-code"
|
autocomplete="postal-code"
|
||||||
/>
|
/>
|
||||||
<InputError v-if="errors.post_code !== undefined" v-for="err in errors.post_code" :message="err" />
|
<InputError
|
||||||
|
v-if="errors.post_code !== undefined"
|
||||||
|
v-for="err in errors.post_code"
|
||||||
|
:message="err"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-span-6 sm:col-span-4">
|
<div class="col-span-6 sm:col-span-4">
|
||||||
<InputLabel for="cr_city" value="Mesto" />
|
<InputLabel for="cr_city" value="Mesto" />
|
||||||
|
|
@ -190,20 +199,25 @@ const callSubmit = () => {
|
||||||
class="mt-1 block w-full"
|
class="mt-1 block w-full"
|
||||||
autocomplete="address-level2"
|
autocomplete="address-level2"
|
||||||
/>
|
/>
|
||||||
<InputError v-if="errors.city !== undefined" v-for="err in errors.city" :message="err" />
|
<InputError
|
||||||
|
v-if="errors.city !== undefined"
|
||||||
|
v-for="err in errors.city"
|
||||||
|
:message="err"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-span-6 sm:col-span-4">
|
<div class="col-span-6 sm:col-span-4">
|
||||||
<InputLabel for="cr_type" value="Tip"/>
|
<InputLabel for="cr_type" value="Tip" />
|
||||||
<select
|
<select
|
||||||
class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
|
class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
|
||||||
id="cr_type"
|
id="cr_type"
|
||||||
v-model="form.type_id"
|
v-model="form.type_id"
|
||||||
>
|
>
|
||||||
<option v-for="type in types" :key="type.id" :value="type.id">{{ type.name }}</option>
|
<option v-for="type in types" :key="type.id" :value="type.id">
|
||||||
|
{{ type.name }}
|
||||||
|
</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex justify-end mt-4">
|
<div class="flex justify-end mt-4">
|
||||||
|
|
||||||
<PrimaryButton :class="{ 'opacity-25': processing }" :disabled="processing">
|
<PrimaryButton :class="{ 'opacity-25': processing }" :disabled="processing">
|
||||||
Shrani
|
Shrani
|
||||||
</PrimaryButton>
|
</PrimaryButton>
|
||||||
|
|
|
||||||
|
|
@ -228,12 +228,123 @@ const pageSmsTemplates = computed(() => {
|
||||||
: null;
|
: null;
|
||||||
return fromProps ?? pageProps.value?.sms_templates ?? [];
|
return fromProps ?? pageProps.value?.sms_templates ?? [];
|
||||||
});
|
});
|
||||||
|
// Helpers: EU formatter and token renderer
|
||||||
|
const formatEu = (value, decimals = 2) => {
|
||||||
|
if (value === null || value === undefined || value === "") {
|
||||||
|
return new Intl.NumberFormat("de-DE", {
|
||||||
|
minimumFractionDigits: decimals,
|
||||||
|
maximumFractionDigits: decimals,
|
||||||
|
}).format(0);
|
||||||
|
}
|
||||||
|
const num =
|
||||||
|
typeof value === "number"
|
||||||
|
? value
|
||||||
|
: parseFloat(String(value).replace(/\./g, "").replace(",", "."));
|
||||||
|
return new Intl.NumberFormat("de-DE", {
|
||||||
|
minimumFractionDigits: decimals,
|
||||||
|
maximumFractionDigits: decimals,
|
||||||
|
}).format(isNaN(num) ? 0 : num);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderTokens = (text, vars) => {
|
||||||
|
if (!text) return "";
|
||||||
|
const resolver = (obj, path) => {
|
||||||
|
if (!obj) return null;
|
||||||
|
if (Object.prototype.hasOwnProperty.call(obj, path)) return obj[path];
|
||||||
|
const segs = path.split(".");
|
||||||
|
let cur = obj;
|
||||||
|
for (const s of segs) {
|
||||||
|
if (cur && typeof cur === "object" && s in cur) {
|
||||||
|
cur = cur[s];
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cur;
|
||||||
|
};
|
||||||
|
return text.replace(/\{([a-zA-Z0-9_\.]+)\}/g, (_, key) => {
|
||||||
|
const val = resolver(vars, key);
|
||||||
|
return val !== null && val !== undefined ? String(val) : `{${key}}`;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildVarsFromSelectedContract = () => {
|
||||||
|
const uuid = selectedContractUuid.value;
|
||||||
|
if (!uuid) return {};
|
||||||
|
const c = (contractsForCase.value || []).find((x) => x.uuid === uuid);
|
||||||
|
if (!c) return {};
|
||||||
|
const vars = {
|
||||||
|
contract: {
|
||||||
|
uuid: c.uuid,
|
||||||
|
reference: c.reference,
|
||||||
|
start_date: c.start_date || "",
|
||||||
|
end_date: c.end_date || "",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if (c.account) {
|
||||||
|
vars.account = {
|
||||||
|
reference: c.account.reference,
|
||||||
|
type: c.account.type,
|
||||||
|
initial_amount:
|
||||||
|
c.account.initial_amount ??
|
||||||
|
(c.account.initial_amount_raw ? formatEu(c.account.initial_amount_raw) : null),
|
||||||
|
balance_amount:
|
||||||
|
c.account.balance_amount ??
|
||||||
|
(c.account.balance_amount_raw ? formatEu(c.account.balance_amount_raw) : null),
|
||||||
|
initial_amount_raw: c.account.initial_amount_raw ?? null,
|
||||||
|
balance_amount_raw: c.account.balance_amount_raw ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return vars;
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateSmsFromSelection = async () => {
|
||||||
|
if (!selectedTemplateId.value) return;
|
||||||
|
// Try server preview first
|
||||||
|
try {
|
||||||
|
const url = route("clientCase.sms.preview", { client_case: props.clientCaseUuid });
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"X-Requested-With": "XMLHttpRequest",
|
||||||
|
"X-CSRF-TOKEN":
|
||||||
|
document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") ||
|
||||||
|
"",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
template_id: selectedTemplateId.value,
|
||||||
|
contract_uuid: selectedContractUuid.value || null,
|
||||||
|
}),
|
||||||
|
credentials: "same-origin",
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
if (typeof data?.content === "string" && data.content.trim() !== "") {
|
||||||
|
smsMessage.value = data.content;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// ignore and fallback
|
||||||
|
}
|
||||||
|
// Fallback: client-side render using template content and selected contract vars
|
||||||
|
const tpl = (pageSmsTemplates.value || []).find(
|
||||||
|
(t) => t.id === selectedTemplateId.value
|
||||||
|
);
|
||||||
|
if (tpl && typeof tpl.content === "string") {
|
||||||
|
smsMessage.value = renderTokens(tpl.content, buildVarsFromSelectedContract());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Selections
|
// Selections
|
||||||
const selectedProfileId = ref(null);
|
const selectedProfileId = ref(null);
|
||||||
const selectedSenderId = ref(null);
|
const selectedSenderId = ref(null);
|
||||||
const deliveryReport = ref(false);
|
const deliveryReport = ref(false);
|
||||||
const selectedTemplateId = ref(null);
|
const selectedTemplateId = ref(null);
|
||||||
|
// Contract selection for placeholder rendering
|
||||||
|
const contractsForCase = ref([]);
|
||||||
|
const selectedContractUuid = ref(null);
|
||||||
|
|
||||||
const sendersForSelectedProfile = computed(() => {
|
const sendersForSelectedProfile = computed(() => {
|
||||||
if (!selectedProfileId.value) return pageSmsSenders.value;
|
if (!selectedProfileId.value) return pageSmsSenders.value;
|
||||||
|
|
@ -257,14 +368,49 @@ watch(sendersForSelectedProfile, (list) => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
watch(selectedTemplateId, () => {
|
const renderSmsPreview = async () => {
|
||||||
if (!selectedTemplateId.value) return;
|
if (!selectedTemplateId.value) return;
|
||||||
|
try {
|
||||||
|
const url = route("clientCase.sms.preview", { client_case: props.clientCaseUuid });
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"X-Requested-With": "XMLHttpRequest",
|
||||||
|
"X-CSRF-TOKEN":
|
||||||
|
document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") ||
|
||||||
|
"",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
template_id: selectedTemplateId.value,
|
||||||
|
contract_uuid: selectedContractUuid.value || null,
|
||||||
|
}),
|
||||||
|
credentials: "same-origin",
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error(`Preview failed: ${res.status}`);
|
||||||
|
const data = await res.json();
|
||||||
|
if (typeof data?.content === "string") {
|
||||||
|
smsMessage.value = data.content;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// If preview fails and template has inline content, fallback
|
||||||
const tpl = (pageSmsTemplates.value || []).find(
|
const tpl = (pageSmsTemplates.value || []).find(
|
||||||
(t) => t.id === selectedTemplateId.value
|
(t) => t.id === selectedTemplateId.value
|
||||||
);
|
);
|
||||||
if (tpl && typeof tpl.content === "string") {
|
if (tpl && typeof tpl.content === "string") {
|
||||||
smsMessage.value = tpl.content;
|
smsMessage.value = tpl.content;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
watch(selectedTemplateId, () => {
|
||||||
|
if (!selectedTemplateId.value) return;
|
||||||
|
updateSmsFromSelection();
|
||||||
|
});
|
||||||
|
|
||||||
|
watch(selectedContractUuid, () => {
|
||||||
|
if (!selectedTemplateId.value) return;
|
||||||
|
updateSmsFromSelection();
|
||||||
});
|
});
|
||||||
|
|
||||||
// If templates array changes and none is chosen, pick the first by default
|
// If templates array changes and none is chosen, pick the first by default
|
||||||
|
|
@ -304,6 +450,22 @@ const openSmsDialog = (phone) => {
|
||||||
// Default template selection to first available
|
// Default template selection to first available
|
||||||
selectedTemplateId.value =
|
selectedTemplateId.value =
|
||||||
(pageSmsTemplates.value && pageSmsTemplates.value[0]?.id) || null;
|
(pageSmsTemplates.value && pageSmsTemplates.value[0]?.id) || null;
|
||||||
|
// Load contracts for this case (for contract/account placeholders)
|
||||||
|
loadContractsForCase();
|
||||||
|
};
|
||||||
|
const loadContractsForCase = async () => {
|
||||||
|
try {
|
||||||
|
const url = route("clientCase.contracts.list", { client_case: props.clientCaseUuid });
|
||||||
|
const res = await fetch(url, {
|
||||||
|
headers: { "X-Requested-With": "XMLHttpRequest" },
|
||||||
|
credentials: "same-origin",
|
||||||
|
});
|
||||||
|
const json = await res.json();
|
||||||
|
contractsForCase.value = Array.isArray(json?.data) ? json.data : [];
|
||||||
|
// Do not auto-select a contract; let user pick explicitly
|
||||||
|
} catch (e) {
|
||||||
|
contractsForCase.value = [];
|
||||||
|
}
|
||||||
};
|
};
|
||||||
const closeSmsDialog = () => {
|
const closeSmsDialog = () => {
|
||||||
showSmsDialog.value = false;
|
showSmsDialog.value = false;
|
||||||
|
|
@ -323,6 +485,7 @@ const submitSms = () => {
|
||||||
{
|
{
|
||||||
message: smsMessage.value,
|
message: smsMessage.value,
|
||||||
template_id: selectedTemplateId.value,
|
template_id: selectedTemplateId.value,
|
||||||
|
contract_uuid: selectedContractUuid.value,
|
||||||
profile_id: selectedProfileId.value,
|
profile_id: selectedProfileId.value,
|
||||||
sender_id: selectedSenderId.value,
|
sender_id: selectedSenderId.value,
|
||||||
delivery_report: !!deliveryReport.value,
|
delivery_report: !!deliveryReport.value,
|
||||||
|
|
@ -710,6 +873,24 @@ const submitSms = () => {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Contract selector (for placeholders) -->
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700">Pogodba</label>
|
||||||
|
<select
|
||||||
|
v-model="selectedContractUuid"
|
||||||
|
class="mt-1 block w-full rounded border-gray-300 focus:border-indigo-500 focus:ring-indigo-500"
|
||||||
|
>
|
||||||
|
<option :value="null">—</option>
|
||||||
|
<option v-for="c in contractsForCase" :key="c.uuid" :value="c.uuid">
|
||||||
|
{{ c.reference || c.uuid }}
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
<p class="mt-1 text-xs text-gray-500">
|
||||||
|
Uporabi podatke pogodbe (in računa) za zapolnitev {contract.*} in {account.*}
|
||||||
|
mest.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Template selector -->
|
<!-- Template selector -->
|
||||||
<div>
|
<div>
|
||||||
<label class="block text-sm font-medium text-gray-700">Predloga</label>
|
<label class="block text-sm font-medium text-gray-700">Predloga</label>
|
||||||
|
|
|
||||||
|
|
@ -1,132 +1,121 @@
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref, watch } from 'vue';
|
import { ref, watch } from "vue";
|
||||||
import DialogModal from './DialogModal.vue';
|
import DialogModal from "./DialogModal.vue";
|
||||||
import InputLabel from './InputLabel.vue';
|
import InputLabel from "./InputLabel.vue";
|
||||||
import SectionTitle from './SectionTitle.vue';
|
import SectionTitle from "./SectionTitle.vue";
|
||||||
import TextInput from './TextInput.vue';
|
import TextInput from "./TextInput.vue";
|
||||||
import InputError from './InputError.vue';
|
import InputError from "./InputError.vue";
|
||||||
import PrimaryButton from './PrimaryButton.vue';
|
import PrimaryButton from "./PrimaryButton.vue";
|
||||||
import axios from 'axios';
|
import { useForm, router } from "@inertiajs/vue3";
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
show: {
|
show: {
|
||||||
type: Boolean,
|
type: Boolean,
|
||||||
default: false
|
default: false,
|
||||||
},
|
},
|
||||||
person: Object,
|
person: Object,
|
||||||
types: Array,
|
types: Array,
|
||||||
edit: {
|
edit: {
|
||||||
type: Boolean,
|
type: Boolean,
|
||||||
default: false
|
default: false,
|
||||||
},
|
},
|
||||||
id: {
|
id: {
|
||||||
type: Number,
|
type: Number,
|
||||||
default: 0
|
default: 0,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const processing = ref(false);
|
// Using Inertia useForm for state, errors and processing
|
||||||
const errors = ref({});
|
|
||||||
|
|
||||||
const emit = defineEmits(['close']);
|
const emit = defineEmits(["close"]);
|
||||||
|
|
||||||
const close = () => {
|
const close = () => {
|
||||||
emit('close');
|
emit("close");
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
errors.value = {};
|
try {
|
||||||
|
form.clearErrors && form.clearErrors();
|
||||||
|
} catch {}
|
||||||
}, 500);
|
}, 500);
|
||||||
}
|
};
|
||||||
|
|
||||||
const form = ref({
|
const form = useForm({
|
||||||
nu: '',
|
nu: "",
|
||||||
country_code: 386,
|
country_code: 386,
|
||||||
type_id: props.types[0].id,
|
type_id: props.types?.[0]?.id ?? null,
|
||||||
description: ''
|
description: "",
|
||||||
|
validated: false,
|
||||||
|
phone_type: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
const resetForm = () => {
|
const resetForm = () => {
|
||||||
form.value = {
|
form.nu = "";
|
||||||
nu: '',
|
form.country_code = 386;
|
||||||
country_code: 386,
|
form.type_id = props.types?.[0]?.id ?? null;
|
||||||
type_id: props.types[0].id,
|
form.description = "";
|
||||||
description: ''
|
form.validated = false;
|
||||||
}
|
form.phone_type = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const create = async () => {
|
const create = async () => {
|
||||||
processing.value = true;
|
router.post(route("person.phone.create", props.person), form, {
|
||||||
errors.value = {};
|
preserveScroll: true,
|
||||||
|
onSuccess: () => {
|
||||||
const data = await axios({
|
|
||||||
method: 'post',
|
|
||||||
url: route('person.phone.create', props.person),
|
|
||||||
data: form.value
|
|
||||||
}).then((response) => {
|
|
||||||
props.person.phones.push(response.data.phone);
|
|
||||||
|
|
||||||
processing.value = false;
|
|
||||||
|
|
||||||
close();
|
close();
|
||||||
resetForm();
|
form.reset();
|
||||||
}).catch((reason) => {
|
},
|
||||||
errors.value = reason.response.data.errors;
|
onError: (e) => {
|
||||||
processing.value = false;
|
// errors are available on form.errors
|
||||||
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const update = async () => {
|
const update = async () => {
|
||||||
processing.value = true;
|
router.put(
|
||||||
errors.value = {};
|
route("person.phone.update", { person: props.person, phone_id: props.id }),
|
||||||
|
form,
|
||||||
const data = await axios({
|
{
|
||||||
method: 'put',
|
preserveScroll: true,
|
||||||
url: route('person.phone.update', {person: props.person, phone_id: props.id}),
|
onSuccess: () => {
|
||||||
data: form.value
|
|
||||||
}).then((response) => {
|
|
||||||
const index = props.person.phones.findIndex( p => p.id === response.data.phone.id );
|
|
||||||
props.person.phones[index] = response.data.phone;
|
|
||||||
|
|
||||||
processing.value = false;
|
|
||||||
close();
|
close();
|
||||||
resetForm();
|
form.reset();
|
||||||
}).catch((reason) => {
|
},
|
||||||
errors.value = reason.response.data.errors;
|
onError: (e) => {
|
||||||
processing.value = false;
|
// errors are available on form.errors
|
||||||
});
|
},
|
||||||
}
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
watch(
|
function hydrateFromProps() {
|
||||||
() => props.id,
|
if (props.edit && props.id) {
|
||||||
((id) => {
|
const p = props.person?.phones?.find((x) => x.id === props.id);
|
||||||
if ( id !== 0 && props.edit ){
|
if (p) {
|
||||||
const index = props.person.phones.findIndex( p => p.id === id );
|
form.nu = p.nu || "";
|
||||||
form.value.nu = props.person.phones[index].nu;
|
form.country_code = p.country_code ?? 386;
|
||||||
form.value.country_code = props.person.phones[index].country_code;
|
form.type_id = p.type_id ?? (props.types?.[0]?.id ?? null);
|
||||||
form.value.type_id = props.person.phones[index].type_id;
|
form.description = p.description || "";
|
||||||
form.value.description = props.person.phones[index].description;
|
form.validated = !!p.validated;
|
||||||
|
form.phone_type = p.phone_type ?? null;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
resetForm();
|
resetForm();
|
||||||
|
}
|
||||||
|
|
||||||
})
|
watch(() => props.id, () => hydrateFromProps());
|
||||||
);
|
watch(() => props.show, (val) => { if (val) hydrateFromProps(); });
|
||||||
|
|
||||||
const submit = () => {
|
const submit = () => {
|
||||||
if( props.edit ) {
|
if (props.edit) {
|
||||||
update();
|
update();
|
||||||
} else {
|
} else {
|
||||||
create();
|
create();
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
<template>
|
<template>
|
||||||
<DialogModal
|
<DialogModal :show="show" @close="close">
|
||||||
:show="show"
|
|
||||||
@close="close"
|
|
||||||
>
|
|
||||||
<template #title>
|
<template #title>
|
||||||
<span v-if="edit">Spremeni telefon</span>
|
<span v-if="edit">Spremeni telefon</span>
|
||||||
<span v-else>Dodaj novi telefon</span>
|
<span v-else>Dodaj novi telefon</span>
|
||||||
|
|
@ -134,9 +123,7 @@ const submit = () => {
|
||||||
<template #content>
|
<template #content>
|
||||||
<form @submit.prevent="submit">
|
<form @submit.prevent="submit">
|
||||||
<SectionTitle class="border-b mb-4">
|
<SectionTitle class="border-b mb-4">
|
||||||
<template #title>
|
<template #title> Telefon </template>
|
||||||
Telefon
|
|
||||||
</template>
|
|
||||||
</SectionTitle>
|
</SectionTitle>
|
||||||
<div class="col-span-6 sm:col-span-4">
|
<div class="col-span-6 sm:col-span-4">
|
||||||
<InputLabel for="pp_nu" value="Številka" />
|
<InputLabel for="pp_nu" value="Številka" />
|
||||||
|
|
@ -149,7 +136,11 @@ const submit = () => {
|
||||||
autocomplete="nu"
|
autocomplete="nu"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<InputError v-if="errors.nu !== undefined" v-for="err in errors.nu" :message="err" />
|
<InputError
|
||||||
|
v-if="form.errors.nu !== undefined"
|
||||||
|
v-for="err in form.errors.nu"
|
||||||
|
:message="err"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-span-6 sm:col-span-4">
|
<div class="col-span-6 sm:col-span-4">
|
||||||
<InputLabel for="pp_countrycode" value="Koda države tel." />
|
<InputLabel for="pp_countrycode" value="Koda države tel." />
|
||||||
|
|
@ -169,21 +160,62 @@ const submit = () => {
|
||||||
<!-- ... -->
|
<!-- ... -->
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
<InputError v-if="errors.country_code !== undefined" v-for="err in errors.country_code" :message="err" />
|
<InputError
|
||||||
|
v-if="form.errors.country_code !== undefined"
|
||||||
|
v-for="err in form.errors.country_code"
|
||||||
|
:message="err"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-span-6 sm:col-span-4">
|
<div class="col-span-6 sm:col-span-4">
|
||||||
<InputLabel for="pp_type" value="Tip"/>
|
<InputLabel for="pp_type" value="Tip" />
|
||||||
<select
|
<select
|
||||||
class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
|
class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
|
||||||
id="pp_type"
|
id="pp_type"
|
||||||
v-model="form.type_id"
|
v-model="form.type_id"
|
||||||
>
|
>
|
||||||
<option v-for="type in types" :key="type.id" :value="type.id">{{ type.name }}</option>
|
<option v-for="type in types" :key="type.id" :value="type.id">
|
||||||
|
{{ type.name }}
|
||||||
|
</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="col-span-6 sm:col-span-4">
|
||||||
|
<InputLabel for="pp_phone_type" value="Vrsta telefona (enum)" />
|
||||||
|
<select
|
||||||
|
class="block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
|
||||||
|
id="pp_phone_type"
|
||||||
|
v-model="form.phone_type"
|
||||||
|
>
|
||||||
|
<option :value="null">—</option>
|
||||||
|
<option value="mobile">Mobilni</option>
|
||||||
|
<option value="landline">Stacionarni</option>
|
||||||
|
<option value="voip">VOIP</option>
|
||||||
|
</select>
|
||||||
|
<InputError
|
||||||
|
v-if="form.errors.phone_type !== undefined"
|
||||||
|
v-for="err in form.errors.phone_type"
|
||||||
|
:message="err"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="col-span-6 sm:col-span-4">
|
||||||
|
<label class="inline-flex items-center mt-6">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
v-model="form.validated"
|
||||||
|
class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
|
||||||
|
/>
|
||||||
|
<span class="ml-2">Potrjeno</span>
|
||||||
|
</label>
|
||||||
|
<InputError
|
||||||
|
v-if="form.errors.validated !== undefined"
|
||||||
|
v-for="err in form.errors.validated"
|
||||||
|
:message="err"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<div class="flex justify-end mt-4">
|
<div class="flex justify-end mt-4">
|
||||||
|
<PrimaryButton
|
||||||
<PrimaryButton :class="{ 'opacity-25': processing }" :disabled="processing">
|
:class="{ 'opacity-25': form.processing }"
|
||||||
|
:disabled="form.processing"
|
||||||
|
>
|
||||||
Shrani
|
Shrani
|
||||||
</PrimaryButton>
|
</PrimaryButton>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -172,6 +172,13 @@ const navGroups = computed(() => [
|
||||||
icon: faGears,
|
icon: faGears,
|
||||||
active: ["admin.sms-profiles.index"],
|
active: ["admin.sms-profiles.index"],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: "admin.packages.index",
|
||||||
|
label: "SMS paketi",
|
||||||
|
route: "admin.packages.index",
|
||||||
|
icon: faMessage,
|
||||||
|
active: ["admin.packages.index", "admin.packages.show"],
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
|
|
|
||||||
|
|
@ -1,103 +1,123 @@
|
||||||
<script setup>
|
<script setup>
|
||||||
import AdminLayout from '@/Layouts/AdminLayout.vue'
|
import AdminLayout from "@/Layouts/AdminLayout.vue";
|
||||||
import { Link } from '@inertiajs/vue3'
|
import { Link } from "@inertiajs/vue3";
|
||||||
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
|
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
|
||||||
import { faUserGroup, faKey, faGears, faFileWord, faEnvelopeOpenText, faInbox, faAt, faAddressBook, faFileLines } from '@fortawesome/free-solid-svg-icons'
|
import {
|
||||||
|
faUserGroup,
|
||||||
|
faKey,
|
||||||
|
faGears,
|
||||||
|
faFileWord,
|
||||||
|
faEnvelopeOpenText,
|
||||||
|
faInbox,
|
||||||
|
faAt,
|
||||||
|
faAddressBook,
|
||||||
|
faFileLines,
|
||||||
|
} from "@fortawesome/free-solid-svg-icons";
|
||||||
|
|
||||||
const cards = [
|
const cards = [
|
||||||
{
|
{
|
||||||
category: 'Uporabniki & Dovoljenja',
|
category: "Uporabniki & Dovoljenja",
|
||||||
items: [
|
items: [
|
||||||
{
|
{
|
||||||
title: 'Uporabniki',
|
title: "Uporabniki",
|
||||||
description: 'Upravljanje uporabnikov in njihovih vlog',
|
description: "Upravljanje uporabnikov in njihovih vlog",
|
||||||
route: 'admin.users.index',
|
route: "admin.users.index",
|
||||||
icon: faUserGroup,
|
icon: faUserGroup,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Novo dovoljenje',
|
title: "Novo dovoljenje",
|
||||||
description: 'Dodaj in konfiguriraj novo dovoljenje',
|
description: "Dodaj in konfiguriraj novo dovoljenje",
|
||||||
route: 'admin.permissions.create',
|
route: "admin.permissions.create",
|
||||||
icon: faKey,
|
icon: faKey,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
category: 'Dokumenti',
|
category: "Dokumenti",
|
||||||
items: [
|
items: [
|
||||||
{
|
{
|
||||||
title: 'Nastavitve dokumentov',
|
title: "Nastavitve dokumentov",
|
||||||
description: 'Privzete sistemske nastavitve za dokumente',
|
description: "Privzete sistemske nastavitve za dokumente",
|
||||||
route: 'admin.document-settings.index',
|
route: "admin.document-settings.index",
|
||||||
icon: faGears,
|
icon: faGears,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Predloge dokumentov',
|
title: "Predloge dokumentov",
|
||||||
description: 'Upravljanje in verzioniranje DOCX predlog',
|
description: "Upravljanje in verzioniranje DOCX predlog",
|
||||||
route: 'admin.document-templates.index',
|
route: "admin.document-templates.index",
|
||||||
icon: faFileWord,
|
icon: faFileWord,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
category: 'Email',
|
category: "Email",
|
||||||
items: [
|
items: [
|
||||||
{
|
{
|
||||||
title: 'Email predloge',
|
title: "Email predloge",
|
||||||
description: 'Upravljanje HTML / tekst email predlog',
|
description: "Upravljanje HTML / tekst email predlog",
|
||||||
route: 'admin.email-templates.index',
|
route: "admin.email-templates.index",
|
||||||
icon: faEnvelopeOpenText,
|
icon: faEnvelopeOpenText,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Email dnevniki',
|
title: "Email dnevniki",
|
||||||
description: 'Pregled poslanih emailov in statusov',
|
description: "Pregled poslanih emailov in statusov",
|
||||||
route: 'admin.email-logs.index',
|
route: "admin.email-logs.index",
|
||||||
icon: faInbox,
|
icon: faInbox,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Mail profili',
|
title: "Mail profili",
|
||||||
description: 'SMTP profili, nastavitve in testiranje povezave',
|
description: "SMTP profili, nastavitve in testiranje povezave",
|
||||||
route: 'admin.mail-profiles.index',
|
route: "admin.mail-profiles.index",
|
||||||
icon: faAt,
|
icon: faAt,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
category: 'Komunikacije',
|
category: "Komunikacije",
|
||||||
items: [
|
items: [
|
||||||
{
|
{
|
||||||
title: 'SMS profili',
|
title: "SMS profili",
|
||||||
description: 'Nastavitve SMS profilov, testno pošiljanje in stanje kreditov',
|
description: "Nastavitve SMS profilov, testno pošiljanje in stanje kreditov",
|
||||||
route: 'admin.sms-profiles.index',
|
route: "admin.sms-profiles.index",
|
||||||
icon: faGears,
|
icon: faGears,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'SMS pošiljatelji',
|
title: "SMS pošiljatelji",
|
||||||
description: 'Upravljanje nazivov pošiljateljev (Sender ID) za SMS profile',
|
description: "Upravljanje nazivov pošiljateljev (Sender ID) za SMS profile",
|
||||||
route: 'admin.sms-senders.index',
|
route: "admin.sms-senders.index",
|
||||||
icon: faAddressBook,
|
icon: faAddressBook,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'SMS predloge',
|
title: "SMS predloge",
|
||||||
description: 'Tekstovne predloge za SMS obvestila in opomnike',
|
description: "Tekstovne predloge za SMS obvestila in opomnike",
|
||||||
route: 'admin.sms-templates.index',
|
route: "admin.sms-templates.index",
|
||||||
icon: faFileLines,
|
icon: faFileLines,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'SMS dnevniki',
|
title: "SMS dnevniki",
|
||||||
description: 'Pregled poslanih SMSov in statusov',
|
description: "Pregled poslanih SMSov in statusov",
|
||||||
route: 'admin.sms-logs.index',
|
route: "admin.sms-logs.index",
|
||||||
|
icon: faInbox,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "SMS paketi",
|
||||||
|
description: "Kreiranje in pošiljanje serijskih SMS paketov",
|
||||||
|
route: "admin.packages.index",
|
||||||
icon: faInbox,
|
icon: faInbox,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
]
|
];
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<AdminLayout title="Administrator">
|
<AdminLayout title="Administrator">
|
||||||
<div class="space-y-14">
|
<div class="space-y-14">
|
||||||
<section v-for="(group, i) in cards" :key="group.category" :class="[ i>0 ? 'pt-6 border-t border-gray-200/70' : '' ]">
|
<section
|
||||||
|
v-for="(group, i) in cards"
|
||||||
|
:key="group.category"
|
||||||
|
:class="[i > 0 ? 'pt-6 border-t border-gray-200/70' : '']"
|
||||||
|
>
|
||||||
<h2 class="text-xs font-semibold tracking-wider uppercase text-gray-500 mb-4">
|
<h2 class="text-xs font-semibold tracking-wider uppercase text-gray-500 mb-4">
|
||||||
{{ group.category }}
|
{{ group.category }}
|
||||||
</h2>
|
</h2>
|
||||||
|
|
@ -109,15 +129,22 @@ const cards = [
|
||||||
class="group relative overflow-hidden p-5 rounded-lg border bg-white hover:border-indigo-300 hover:shadow transition focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
class="group relative overflow-hidden p-5 rounded-lg border bg-white hover:border-indigo-300 hover:shadow transition focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||||
>
|
>
|
||||||
<div class="flex items-start gap-4">
|
<div class="flex items-start gap-4">
|
||||||
<span class="inline-flex items-center justify-center w-10 h-10 rounded-md bg-indigo-50 text-indigo-600 group-hover:bg-indigo-100">
|
<span
|
||||||
|
class="inline-flex items-center justify-center w-10 h-10 rounded-md bg-indigo-50 text-indigo-600 group-hover:bg-indigo-100"
|
||||||
|
>
|
||||||
<FontAwesomeIcon :icon="item.icon" class="w-5 h-5" />
|
<FontAwesomeIcon :icon="item.icon" class="w-5 h-5" />
|
||||||
</span>
|
</span>
|
||||||
<div class="flex-1 min-w-0">
|
<div class="flex-1 min-w-0">
|
||||||
<h3 class="font-semibold text-sm mb-1 flex items-center gap-2">
|
<h3 class="font-semibold text-sm mb-1 flex items-center gap-2">
|
||||||
{{ item.title }}
|
{{ item.title }}
|
||||||
<span class="opacity-0 group-hover:opacity-100 transition text-indigo-500 text-[10px] font-medium">→</span>
|
<span
|
||||||
|
class="opacity-0 group-hover:opacity-100 transition text-indigo-500 text-[10px] font-medium"
|
||||||
|
>→</span
|
||||||
|
>
|
||||||
</h3>
|
</h3>
|
||||||
<p class="text-xs text-gray-500 leading-relaxed line-clamp-3">{{ item.description }}</p>
|
<p class="text-xs text-gray-500 leading-relaxed line-clamp-3">
|
||||||
|
{{ item.description }}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</Link>
|
||||||
|
|
|
||||||
359
resources/js/Pages/Admin/Packages/Index.vue
Normal file
359
resources/js/Pages/Admin/Packages/Index.vue
Normal file
|
|
@ -0,0 +1,359 @@
|
||||||
|
<script setup>
|
||||||
|
import AdminLayout from '@/Layouts/AdminLayout.vue'
|
||||||
|
import { Link, router, useForm } from '@inertiajs/vue3'
|
||||||
|
import { ref, computed } from 'vue'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
packages: { type: Object, required: true },
|
||||||
|
profiles: { type: Array, default: () => [] },
|
||||||
|
senders: { type: Array, default: () => [] },
|
||||||
|
templates: { type: Array, default: () => [] },
|
||||||
|
segments: { type: Array, default: () => [] },
|
||||||
|
clients: { type: Array, default: () => [] },
|
||||||
|
})
|
||||||
|
|
||||||
|
function goShow(id) {
|
||||||
|
router.visit(route('admin.packages.show', id))
|
||||||
|
}
|
||||||
|
|
||||||
|
const showCreate = ref(false)
|
||||||
|
const createMode = ref('numbers') // 'numbers' | 'contracts'
|
||||||
|
const form = useForm({
|
||||||
|
type: 'sms',
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
profile_id: null,
|
||||||
|
sender_id: null,
|
||||||
|
template_id: null,
|
||||||
|
delivery_report: false,
|
||||||
|
body: '',
|
||||||
|
numbers: '', // one per line
|
||||||
|
})
|
||||||
|
|
||||||
|
const filteredSenders = computed(() => {
|
||||||
|
if (!form.profile_id) return props.senders
|
||||||
|
return props.senders.filter(s => s.profile_id === form.profile_id)
|
||||||
|
})
|
||||||
|
|
||||||
|
function submitCreate() {
|
||||||
|
const lines = (form.numbers || '').split(/\r?\n/).map(s => s.trim()).filter(Boolean)
|
||||||
|
if (!lines.length) return
|
||||||
|
if (!form.profile_id && !form.template_id) {
|
||||||
|
// require profile if no template/default profile resolution available
|
||||||
|
alert('Izberi SMS profil ali predlogo.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!form.template_id && !form.body) {
|
||||||
|
alert('Vnesi vsebino sporočila ali izberi predlogo.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
type: 'sms',
|
||||||
|
name: form.name || `SMS paket ${new Date().toLocaleString()}`,
|
||||||
|
description: form.description || '',
|
||||||
|
items: lines.map(number => ({
|
||||||
|
number,
|
||||||
|
payload: {
|
||||||
|
profile_id: form.profile_id,
|
||||||
|
sender_id: form.sender_id,
|
||||||
|
template_id: form.template_id,
|
||||||
|
delivery_report: !!form.delivery_report,
|
||||||
|
body: (form.body && form.body.trim()) ? form.body.trim() : null,
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
|
||||||
|
router.post(route('admin.packages.store'), payload, {
|
||||||
|
onSuccess: () => {
|
||||||
|
form.reset()
|
||||||
|
showCreate.value = false
|
||||||
|
router.reload({ only: ['packages'] })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Contracts mode state & actions
|
||||||
|
const contracts = ref({ data: [], meta: { current_page: 1, last_page: 1, per_page: 25, total: 0 } })
|
||||||
|
const segmentId = ref(null)
|
||||||
|
const search = ref('')
|
||||||
|
const clientId = ref(null)
|
||||||
|
const onlyMobile = ref(false)
|
||||||
|
const onlyValidated = ref(false)
|
||||||
|
const loadingContracts = ref(false)
|
||||||
|
const selectedContractIds = ref(new Set())
|
||||||
|
|
||||||
|
async function loadContracts(url = null) {
|
||||||
|
if (!segmentId.value) {
|
||||||
|
contracts.value = { data: [], meta: { current_page: 1, last_page: 1, per_page: 25, total: 0 } }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
loadingContracts.value = true
|
||||||
|
try {
|
||||||
|
const target = url || `${route('admin.packages.contracts')}?segment_id=${encodeURIComponent(segmentId.value)}${search.value ? `&q=${encodeURIComponent(search.value)}` : ''}${clientId.value ? `&client_id=${encodeURIComponent(clientId.value)}` : ''}${onlyMobile.value ? `&only_mobile=1` : ''}${onlyValidated.value ? `&only_validated=1` : ''}`
|
||||||
|
const res = await fetch(target, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
|
||||||
|
const json = await res.json()
|
||||||
|
contracts.value = { data: json.data || [], meta: json.meta || { current_page: 1, last_page: 1, per_page: 25, total: 0 } }
|
||||||
|
} finally {
|
||||||
|
loadingContracts.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleSelectContract(id) {
|
||||||
|
const s = selectedContractIds.value
|
||||||
|
if (s.has(id)) { s.delete(id) } else { s.add(id) }
|
||||||
|
// force reactivity
|
||||||
|
selectedContractIds.value = new Set(Array.from(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearSelection() {
|
||||||
|
selectedContractIds.value = new Set()
|
||||||
|
}
|
||||||
|
|
||||||
|
function goContractsPage(delta) {
|
||||||
|
const { current_page } = contracts.value.meta
|
||||||
|
const nextPage = current_page + delta
|
||||||
|
if (nextPage < 1 || nextPage > contracts.value.meta.last_page) return
|
||||||
|
const base = `${route('admin.packages.contracts')}?segment_id=${encodeURIComponent(segmentId.value)}${search.value ? `&q=${encodeURIComponent(search.value)}` : ''}${clientId.value ? `&client_id=${encodeURIComponent(clientId.value)}` : ''}${onlyMobile.value ? `&only_mobile=1` : ''}${onlyValidated.value ? `&only_validated=1` : ''}&page=${nextPage}`
|
||||||
|
loadContracts(base)
|
||||||
|
}
|
||||||
|
|
||||||
|
function submitCreateFromContracts() {
|
||||||
|
const ids = Array.from(selectedContractIds.value)
|
||||||
|
if (!ids.length) return
|
||||||
|
const payload = {
|
||||||
|
type: 'sms',
|
||||||
|
name: form.name || `SMS paket (segment) ${new Date().toLocaleString()}`,
|
||||||
|
description: form.description || '',
|
||||||
|
payload: {
|
||||||
|
profile_id: form.profile_id,
|
||||||
|
sender_id: form.sender_id,
|
||||||
|
template_id: form.template_id,
|
||||||
|
delivery_report: !!form.delivery_report,
|
||||||
|
body: (form.body && form.body.trim()) ? form.body.trim() : null,
|
||||||
|
},
|
||||||
|
contract_ids: ids,
|
||||||
|
}
|
||||||
|
|
||||||
|
router.post(route('admin.packages.store-from-contracts'), payload, {
|
||||||
|
onSuccess: () => {
|
||||||
|
clearSelection()
|
||||||
|
showCreate.value = false
|
||||||
|
router.reload({ only: ['packages'] })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<AdminLayout title="SMS paketi">
|
||||||
|
<div class="flex items-center justify-between mb-4">
|
||||||
|
<h2 class="text-base font-semibold text-gray-800">Seznam paketov</h2>
|
||||||
|
<button @click="showCreate = !showCreate" class="px-3 py-1.5 rounded bg-indigo-600 text-white text-sm">{{ showCreate ? 'Zapri' : 'Nov paket' }}</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="showCreate" class="mb-6 rounded border bg-white p-4">
|
||||||
|
<div class="mb-4 flex items-center gap-4 text-sm">
|
||||||
|
<label class="inline-flex items-center gap-2">
|
||||||
|
<input type="radio" value="numbers" v-model="createMode"> Vnos številk
|
||||||
|
</label>
|
||||||
|
<label class="inline-flex items-center gap-2">
|
||||||
|
<input type="radio" value="contracts" v-model="createMode"> Iz pogodb (segment)
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid sm:grid-cols-3 gap-4">
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs text-gray-500 mb-1">Profil</label>
|
||||||
|
<select v-model.number="form.profile_id" class="w-full rounded border-gray-300 text-sm">
|
||||||
|
<option :value="null">—</option>
|
||||||
|
<option v-for="p in profiles" :key="p.id" :value="p.id">{{ p.name }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs text-gray-500 mb-1">Pošiljatelj</label>
|
||||||
|
<select v-model.number="form.sender_id" class="w-full rounded border-gray-300 text-sm">
|
||||||
|
<option :value="null">—</option>
|
||||||
|
<option v-for="s in filteredSenders" :key="s.id" :value="s.id">{{ s.sname }} <span v-if="s.phone_number">({{ s.phone_number }})</span></option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs text-gray-500 mb-1">Predloga</label>
|
||||||
|
<select v-model.number="form.template_id" class="w-full rounded border-gray-300 text-sm">
|
||||||
|
<option :value="null">—</option>
|
||||||
|
<option v-for="t in templates" :key="t.id" :value="t.id">{{ t.name }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="sm:col-span-3">
|
||||||
|
<label class="block text-xs text-gray-500 mb-1">Vsebina (če ni predloge)</label>
|
||||||
|
<textarea v-model="form.body" rows="3" class="w-full rounded border-gray-300 text-sm" placeholder="Sporočilo..."></textarea>
|
||||||
|
<label class="inline-flex items-center gap-2 mt-2 text-sm text-gray-600">
|
||||||
|
<input type="checkbox" v-model="form.delivery_report" /> Zahtevaj delivery report
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Numbers mode -->
|
||||||
|
<template v-if="createMode === 'numbers'">
|
||||||
|
<div class="sm:col-span-3">
|
||||||
|
<label class="block text-xs text-gray-500 mb-1">Telefonske številke (ena na vrstico)</label>
|
||||||
|
<textarea v-model="form.numbers" rows="4" class="w-full rounded border-gray-300 text-sm" placeholder="+38640123456
|
||||||
|
+38640123457"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="sm:col-span-3 flex items-center justify-end gap-2">
|
||||||
|
<button @click="submitCreate" class="px-3 py-1.5 rounded bg-emerald-600 text-white text-sm">Ustvari paket</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Contracts mode -->
|
||||||
|
<template v-else>
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs text-gray-500 mb-1">Segment</label>
|
||||||
|
<select v-model.number="segmentId" @change="loadContracts()" class="w-full rounded border-gray-300 text-sm">
|
||||||
|
<option :value="null">—</option>
|
||||||
|
<option v-for="s in segments" :key="s.id" :value="s.id">{{ s.name }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs text-gray-500 mb-1">Stranka</label>
|
||||||
|
<select v-model.number="clientId" @change="loadContracts()" class="w-full rounded border-gray-300 text-sm">
|
||||||
|
<option :value="null">—</option>
|
||||||
|
<option v-for="c in clients" :key="c.id" :value="c.id">{{ c.name }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="sm:col-span-2">
|
||||||
|
<label class="block text-xs text-gray-500 mb-1">Iskanje</label>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<input v-model="search" @keyup.enter="loadContracts()" type="text" class="w-full rounded border-gray-300 text-sm" placeholder="referenca...">
|
||||||
|
<button @click="loadContracts()" class="px-3 py-1.5 rounded border text-sm">Išči</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="sm:col-span-3 flex items-center gap-6 text-sm text-gray-700">
|
||||||
|
<label class="inline-flex items-center gap-2">
|
||||||
|
<input type="checkbox" v-model="onlyMobile" @change="loadContracts()"> Samo s mobilno številko
|
||||||
|
</label>
|
||||||
|
<label class="inline-flex items-center gap-2">
|
||||||
|
<input type="checkbox" v-model="onlyValidated" @change="loadContracts()"> Telefonska številka mora biti potrjena
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="sm:col-span-3">
|
||||||
|
<div class="overflow-hidden rounded border bg-white">
|
||||||
|
<table class="min-w-full divide-y divide-gray-200">
|
||||||
|
<thead class="bg-gray-50">
|
||||||
|
<tr class="text-xs text-gray-500">
|
||||||
|
<th class="px-3 py-2"></th>
|
||||||
|
<th class="px-3 py-2 text-left">Pogodba</th>
|
||||||
|
<th class="px-3 py-2 text-left">Primer</th>
|
||||||
|
<th class="px-3 py-2 text-left">Stranka</th>
|
||||||
|
<th class="px-3 py-2 text-left">Izbrana številka</th>
|
||||||
|
<th class="px-3 py-2 text-left">Opomba</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody class="divide-y divide-gray-200" v-if="!loadingContracts">
|
||||||
|
<tr v-for="c in contracts.data" :key="c.id" class="text-sm">
|
||||||
|
<td class="px-3 py-2">
|
||||||
|
<input type="checkbox" :checked="selectedContractIds.has(c.id)" @change="toggleSelectContract(c.id)">
|
||||||
|
</td>
|
||||||
|
<td class="px-3 py-2">
|
||||||
|
<div class="font-mono text-xs text-gray-600">{{ c.uuid }}</div>
|
||||||
|
<div class="text-xs text-gray-800">{{ c.reference }}</div>
|
||||||
|
</td>
|
||||||
|
<td class="px-3 py-2">
|
||||||
|
<div class="text-xs text-gray-800">{{ c.person?.full_name || '—' }}</div>
|
||||||
|
</td>
|
||||||
|
<td class="px-3 py-2">
|
||||||
|
<div class="text-xs text-gray-800">{{ c.client?.name || '—' }}</div>
|
||||||
|
</td>
|
||||||
|
<td class="px-3 py-2">
|
||||||
|
<div v-if="c.selected_phone" class="text-xs">
|
||||||
|
{{ c.selected_phone.number }}
|
||||||
|
<span class="ml-2 inline-flex items-center px-1.5 py-0.5 rounded bg-gray-100 text-gray-600 text-[10px]">{{ c.selected_phone.validated ? 'validated' : 'unverified' }} / {{ c.selected_phone.type || 'unknown' }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-else class="text-xs text-gray-500">—</div>
|
||||||
|
</td>
|
||||||
|
<td class="px-3 py-2 text-xs text-gray-500">{{ c.no_phone_reason || '—' }}</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-if="!contracts.data?.length">
|
||||||
|
<td colspan="6" class="px-3 py-8 text-center text-sm text-gray-500">Ni rezultatov.</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
<tbody v-else>
|
||||||
|
<tr><td colspan="6" class="px-3 py-6 text-center text-sm text-gray-500">Nalaganje...</td></tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="mt-3 flex items-center justify-between text-sm">
|
||||||
|
<div class="text-gray-600">
|
||||||
|
Prikazano stran {{ contracts.meta.current_page }} od {{ contracts.meta.last_page }} (skupaj {{ contracts.meta.total }})
|
||||||
|
</div>
|
||||||
|
<div class="space-x-2">
|
||||||
|
<button @click="goContractsPage(-1)" :disabled="contracts.meta.current_page <= 1" class="px-3 py-1.5 rounded border text-sm disabled:opacity-50">Nazaj</button>
|
||||||
|
<button @click="goContractsPage(1)" :disabled="contracts.meta.current_page >= contracts.meta.last_page" class="px-3 py-1.5 rounded border text-sm disabled:opacity-50">Naprej</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="sm:col-span-3 flex items-center justify-end gap-2">
|
||||||
|
<div class="text-sm text-gray-600 mr-auto">Izbrano: {{ selectedContractIds.size }}</div>
|
||||||
|
<button @click="submitCreateFromContracts" :disabled="selectedContractIds.size === 0" class="px-3 py-1.5 rounded bg-emerald-600 text-white text-sm disabled:opacity-50">Ustvari paket</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="overflow-hidden rounded-md border bg-white">
|
||||||
|
<table class="min-w-full divide-y divide-gray-200">
|
||||||
|
<thead class="bg-gray-50">
|
||||||
|
<tr class="text-xs text-gray-500">
|
||||||
|
<th class="px-3 py-2 text-left font-medium">ID</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">UUID</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Ime</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Tip</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Status</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Skupaj</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Poslano</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Neuspešno</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Zaključeno</th>
|
||||||
|
<th class="px-3 py-2"></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody class="divide-y divide-gray-200">
|
||||||
|
<tr v-for="p in packages.data" :key="p.id" class="text-sm">
|
||||||
|
<td class="px-3 py-2">{{ p.id }}</td>
|
||||||
|
<td class="px-3 py-2 font-mono text-xs text-gray-500">{{ p.uuid }}</td>
|
||||||
|
<td class="px-3 py-2">{{ p.name ?? '—' }}</td>
|
||||||
|
<td class="px-3 py-2 uppercase text-xs text-gray-600">{{ p.type }}</td>
|
||||||
|
<td class="px-3 py-2">
|
||||||
|
<span class="inline-flex items-center px-2 py-0.5 rounded text-xs"
|
||||||
|
:class="{
|
||||||
|
'bg-yellow-50 text-yellow-700': ['queued','running'].includes(p.status),
|
||||||
|
'bg-emerald-50 text-emerald-700': p.status === 'completed',
|
||||||
|
'bg-rose-50 text-rose-700': p.status === 'failed',
|
||||||
|
'bg-gray-100 text-gray-600': p.status === 'draft',
|
||||||
|
}"
|
||||||
|
>{{ p.status }}</span>
|
||||||
|
</td>
|
||||||
|
<td class="px-3 py-2">{{ p.total_items }}</td>
|
||||||
|
<td class="px-3 py-2">{{ p.sent_count }}</td>
|
||||||
|
<td class="px-3 py-2">{{ p.failed_count }}</td>
|
||||||
|
<td class="px-3 py-2 text-xs text-gray-500">{{ p.finished_at ?? '—' }}</td>
|
||||||
|
<td class="px-3 py-2 text-right">
|
||||||
|
<button @click="goShow(p.id)" class="text-indigo-600 hover:underline text-sm">Odpri</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-if="!packages.data?.length">
|
||||||
|
<td colspan="10" class="px-3 py-8 text-center text-sm text-gray-500">Ni paketov za prikaz.</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-4 flex items-center justify-between text-sm">
|
||||||
|
<div class="text-gray-600">
|
||||||
|
Prikazano {{ packages.from || 0 }}–{{ packages.to || 0 }} od {{ packages.total || 0 }}
|
||||||
|
</div>
|
||||||
|
<div class="space-x-2">
|
||||||
|
<Link :href="packages.prev_page_url || '#'" :class="['px-3 py-1.5 rounded border', packages.prev_page_url ? 'text-gray-700 hover:bg-gray-50' : 'text-gray-400 cursor-not-allowed']">Nazaj</Link>
|
||||||
|
<Link :href="packages.next_page_url || '#'" :class="['px-3 py-1.5 rounded border', packages.next_page_url ? 'text-gray-700 hover:bg-gray-50' : 'text-gray-400 cursor-not-allowed']">Naprej</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</AdminLayout>
|
||||||
|
</template>
|
||||||
282
resources/js/Pages/Admin/Packages/Show.vue
Normal file
282
resources/js/Pages/Admin/Packages/Show.vue
Normal file
|
|
@ -0,0 +1,282 @@
|
||||||
|
<script setup>
|
||||||
|
import AdminLayout from "@/Layouts/AdminLayout.vue";
|
||||||
|
import { Link, router } from "@inertiajs/vue3";
|
||||||
|
import { onMounted, onUnmounted, ref, computed } from "vue";
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
package: { type: Object, required: true },
|
||||||
|
items: { type: Object, required: true },
|
||||||
|
preview: { type: [Object, null], default: null },
|
||||||
|
});
|
||||||
|
|
||||||
|
const refreshing = ref(false);
|
||||||
|
let timer = null;
|
||||||
|
|
||||||
|
const isRunning = computed(() => ["queued", "running"].includes(props.package.status));
|
||||||
|
|
||||||
|
// Derive a summary of payload/template/body from the first item on the page.
|
||||||
|
// Assumption: payload is the same across items in a package (both flows use a common payload).
|
||||||
|
const firstItem = computed(() => (props.items?.data && props.items.data.length ? props.items.data[0] : null));
|
||||||
|
const firstPayload = computed(() => (firstItem.value ? firstItem.value.payload_json || {} : {}));
|
||||||
|
const messageBody = computed(() => {
|
||||||
|
const b = firstPayload.value?.body;
|
||||||
|
if (typeof b === 'string') {
|
||||||
|
const t = b.trim();
|
||||||
|
return t.length ? t : null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
const payloadSummary = computed(() => ({
|
||||||
|
profile_id: firstPayload.value?.profile_id ?? null,
|
||||||
|
sender_id: firstPayload.value?.sender_id ?? null,
|
||||||
|
template_id: firstPayload.value?.template_id ?? null,
|
||||||
|
delivery_report: !!firstPayload.value?.delivery_report,
|
||||||
|
}));
|
||||||
|
|
||||||
|
function reload() {
|
||||||
|
refreshing.value = true;
|
||||||
|
router.reload({
|
||||||
|
only: ["package", "items"],
|
||||||
|
onFinish: () => (refreshing.value = false),
|
||||||
|
preserveScroll: true,
|
||||||
|
preserveState: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function dispatchPkg() {
|
||||||
|
router.post(
|
||||||
|
route("admin.packages.dispatch", props.package.id),
|
||||||
|
{},
|
||||||
|
{ onSuccess: reload }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function cancelPkg() {
|
||||||
|
router.post(
|
||||||
|
route("admin.packages.cancel", props.package.id),
|
||||||
|
{},
|
||||||
|
{ onSuccess: reload }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
if (isRunning.value) {
|
||||||
|
timer = setInterval(reload, 3000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
onUnmounted(() => {
|
||||||
|
if (timer) clearInterval(timer);
|
||||||
|
});
|
||||||
|
|
||||||
|
async function copyText(text) {
|
||||||
|
if (!text) return;
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
} catch (e) {
|
||||||
|
// Fallback for older browsers
|
||||||
|
const ta = document.createElement('textarea');
|
||||||
|
ta.value = text;
|
||||||
|
ta.style.position = 'fixed';
|
||||||
|
ta.style.opacity = '0';
|
||||||
|
document.body.appendChild(ta);
|
||||||
|
ta.focus();
|
||||||
|
ta.select();
|
||||||
|
try { document.execCommand('copy'); } catch (_) {}
|
||||||
|
document.body.removeChild(ta);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<AdminLayout :title="`Paket #${package.id}`">
|
||||||
|
<div class="flex items-center justify-between mb-4">
|
||||||
|
<div>
|
||||||
|
<h2 class="text-base font-semibold text-gray-800">Paket #{{ package.id }}</h2>
|
||||||
|
<p class="text-xs text-gray-500">
|
||||||
|
UUID: <span class="font-mono">{{ package.uuid }}</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Link
|
||||||
|
:href="route('admin.packages.index')"
|
||||||
|
class="text-sm text-gray-600 hover:underline"
|
||||||
|
>← Nazaj</Link
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
v-if="['draft', 'failed'].includes(package.status)"
|
||||||
|
@click="dispatchPkg"
|
||||||
|
class="px-3 py-1.5 rounded bg-indigo-600 text-white text-sm"
|
||||||
|
>
|
||||||
|
Zaženi
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
v-if="isRunning"
|
||||||
|
@click="cancelPkg"
|
||||||
|
class="px-3 py-1.5 rounded bg-rose-600 text-white text-sm"
|
||||||
|
>
|
||||||
|
Prekliči
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
v-if="!isRunning"
|
||||||
|
@click="reload"
|
||||||
|
class="px-3 py-1.5 rounded border text-sm"
|
||||||
|
>
|
||||||
|
Osveži
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid sm:grid-cols-4 gap-3 mb-4">
|
||||||
|
<div class="rounded border bg-white p-3">
|
||||||
|
<p class="text-xs text-gray-500">Status</p>
|
||||||
|
<p class="text-sm font-semibold mt-1 uppercase">{{ package.status }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="rounded border bg-white p-3">
|
||||||
|
<p class="text-xs text-gray-500">Skupaj</p>
|
||||||
|
<p class="text-sm font-semibold mt-1">{{ package.total_items }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="rounded border bg-white p-3">
|
||||||
|
<p class="text-xs text-gray-500">Poslano</p>
|
||||||
|
<p class="text-sm font-semibold mt-1 text-emerald-700">
|
||||||
|
{{ package.sent_count }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="rounded border bg-white p-3">
|
||||||
|
<p class="text-xs text-gray-500">Neuspešno</p>
|
||||||
|
<p class="text-sm font-semibold mt-1 text-rose-700">{{ package.failed_count }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Payload / Message preview -->
|
||||||
|
<div class="mb-4 grid gap-3 sm:grid-cols-2">
|
||||||
|
<div class="rounded border bg-white p-3">
|
||||||
|
<p class="text-xs text-gray-500 mb-2">Sporočilo</p>
|
||||||
|
<template v-if="preview && preview.content">
|
||||||
|
<div class="text-sm whitespace-pre-wrap text-gray-800">{{ preview.content }}</div>
|
||||||
|
<div class="mt-2">
|
||||||
|
<button @click="copyText(preview.content)" class="px-2 py-1 rounded border text-xs">Kopiraj</button>
|
||||||
|
</div>
|
||||||
|
<div v-if="preview.source === 'template' && preview.template" class="mt-2 text-xs text-gray-500">
|
||||||
|
Predloga: {{ preview.template.name }} (#{{ preview.template.id }})
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<div v-if="messageBody" class="text-sm whitespace-pre-wrap text-gray-800">
|
||||||
|
{{ messageBody }}
|
||||||
|
</div>
|
||||||
|
<div v-else class="text-sm text-gray-600">
|
||||||
|
<template v-if="payloadSummary.template_id">
|
||||||
|
Uporabljena bo predloga #{{ payloadSummary.template_id }}.
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
Vsebina sporočila ni določena.
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
<div class="rounded border bg-white p-3">
|
||||||
|
<p class="text-xs text-gray-500 mb-2">Meta / Nastavitve pošiljanja</p>
|
||||||
|
<dl class="text-sm text-gray-700 grid grid-cols-3 gap-y-1">
|
||||||
|
<dt class="col-span-1 text-gray-500">Profil</dt>
|
||||||
|
<dd class="col-span-2">{{ payloadSummary.profile_id ?? '—' }}</dd>
|
||||||
|
<dt class="col-span-1 text-gray-500">Pošiljatelj</dt>
|
||||||
|
<dd class="col-span-2">{{ payloadSummary.sender_id ?? '—' }}</dd>
|
||||||
|
<dt class="col-span-1 text-gray-500">Predloga</dt>
|
||||||
|
<dd class="col-span-2">{{ payloadSummary.template_id ?? '—' }}</dd>
|
||||||
|
<dt class="col-span-1 text-gray-500">Delivery report</dt>
|
||||||
|
<dd class="col-span-2">{{ payloadSummary.delivery_report ? 'da' : 'ne' }}</dd>
|
||||||
|
</dl>
|
||||||
|
<div v-if="package.meta && (package.meta.source || package.meta.skipped !== undefined)" class="mt-2 text-xs text-gray-500">
|
||||||
|
<span v-if="package.meta.source" class="mr-3">Vir: {{ package.meta.source }}</span>
|
||||||
|
<span v-if="package.meta.skipped !== undefined">Preskočeno: {{ package.meta.skipped }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="overflow-hidden rounded-md border bg-white">
|
||||||
|
<table class="min-w-full divide-y divide-gray-200">
|
||||||
|
<thead class="bg-gray-50">
|
||||||
|
<tr class="text-xs text-gray-500">
|
||||||
|
<th class="px-3 py-2 text-left font-medium">ID</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Prejemnik</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Sporočilo</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Status</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Napaka</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Provider ID</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Cena</th>
|
||||||
|
<th class="px-3 py-2 text-left font-medium">Valuta</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody class="divide-y divide-gray-200 text-sm">
|
||||||
|
<tr v-for="it in items.data" :key="it.id">
|
||||||
|
<td class="px-3 py-2">{{ it.id }}</td>
|
||||||
|
<td class="px-3 py-2">
|
||||||
|
{{ (it.target_json && it.target_json.number) || "—" }}
|
||||||
|
</td>
|
||||||
|
<td class="px-3 py-2">
|
||||||
|
<div class="flex items-start gap-2">
|
||||||
|
<div class="text-xs text-gray-800 max-w-[420px] line-clamp-2 whitespace-pre-wrap">{{ it.rendered_preview || '—' }}</div>
|
||||||
|
<button v-if="it.rendered_preview" @click="copyText(it.rendered_preview)" class="px-2 py-0.5 rounded border text-xs">Kopiraj</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td class="px-3 py-2">
|
||||||
|
<span
|
||||||
|
class="inline-flex items-center px-2 py-0.5 rounded text-xs"
|
||||||
|
:class="{
|
||||||
|
'bg-yellow-50 text-yellow-700': ['queued', 'processing'].includes(
|
||||||
|
it.status
|
||||||
|
),
|
||||||
|
'bg-emerald-50 text-emerald-700': it.status === 'sent',
|
||||||
|
'bg-rose-50 text-rose-700': it.status === 'failed',
|
||||||
|
'bg-gray-100 text-gray-600':
|
||||||
|
it.status === 'canceled' || it.status === 'skipped',
|
||||||
|
}"
|
||||||
|
>{{ it.status }}</span
|
||||||
|
>
|
||||||
|
</td>
|
||||||
|
<td class="px-3 py-2 text-xs text-rose-700">{{ it.last_error ?? "—" }}</td>
|
||||||
|
<td class="px-3 py-2 text-xs text-gray-500 font-mono">
|
||||||
|
{{ it.provider_message_id ?? "—" }}
|
||||||
|
</td>
|
||||||
|
<td class="px-3 py-2">{{ it.cost ?? "—" }}</td>
|
||||||
|
<td class="px-3 py-2">{{ it.currency ?? "—" }}</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-if="!items.data?.length">
|
||||||
|
<td colspan="8" class="px-3 py-8 text-center text-sm text-gray-500">
|
||||||
|
Ni elementov za prikaz.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-4 flex items-center justify-between text-sm">
|
||||||
|
<div class="text-gray-600">
|
||||||
|
Prikazano {{ items.from || 0 }}–{{ items.to || 0 }} od {{ items.total || 0 }}
|
||||||
|
</div>
|
||||||
|
<div class="space-x-2">
|
||||||
|
<Link
|
||||||
|
:href="items.prev_page_url || '#'"
|
||||||
|
:class="[
|
||||||
|
'px-3 py-1.5 rounded border',
|
||||||
|
items.prev_page_url
|
||||||
|
? 'text-gray-700 hover:bg-gray-50'
|
||||||
|
: 'text-gray-400 cursor-not-allowed',
|
||||||
|
]"
|
||||||
|
>Nazaj</Link
|
||||||
|
>
|
||||||
|
<Link
|
||||||
|
:href="items.next_page_url || '#'"
|
||||||
|
:class="[
|
||||||
|
'px-3 py-1.5 rounded border',
|
||||||
|
items.next_page_url
|
||||||
|
? 'text-gray-700 hover:bg-gray-50'
|
||||||
|
: 'text-gray-400 cursor-not-allowed',
|
||||||
|
]"
|
||||||
|
>Naprej</Link
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="refreshing" class="mt-2 text-xs text-gray-500">Osveževanje ...</div>
|
||||||
|
</AdminLayout>
|
||||||
|
</template>
|
||||||
|
|
@ -153,6 +153,16 @@
|
||||||
// SMS logs
|
// SMS logs
|
||||||
Route::get('sms-logs', [\App\Http\Controllers\Admin\SmsLogController::class, 'index'])->name('sms-logs.index');
|
Route::get('sms-logs', [\App\Http\Controllers\Admin\SmsLogController::class, 'index'])->name('sms-logs.index');
|
||||||
Route::get('sms-logs/{smsLog}', [\App\Http\Controllers\Admin\SmsLogController::class, 'show'])->name('sms-logs.show');
|
Route::get('sms-logs/{smsLog}', [\App\Http\Controllers\Admin\SmsLogController::class, 'show'])->name('sms-logs.show');
|
||||||
|
|
||||||
|
// Packages (batch jobs)
|
||||||
|
Route::get('packages', [\App\Http\Controllers\Admin\PackageController::class, 'index'])->name('packages.index');
|
||||||
|
Route::get('packages/{package}', [\App\Http\Controllers\Admin\PackageController::class, 'show'])->name('packages.show');
|
||||||
|
Route::post('packages', [\App\Http\Controllers\Admin\PackageController::class, 'store'])->name('packages.store');
|
||||||
|
Route::post('packages/{package}/dispatch', [\App\Http\Controllers\Admin\PackageController::class, 'dispatch'])->name('packages.dispatch');
|
||||||
|
Route::post('packages/{package}/cancel', [\App\Http\Controllers\Admin\PackageController::class, 'cancel'])->name('packages.cancel');
|
||||||
|
// Packages - contract-based helpers
|
||||||
|
Route::get('packages-contracts', [\App\Http\Controllers\Admin\PackageController::class, 'contracts'])->name('packages.contracts');
|
||||||
|
Route::post('packages-from-contracts', [\App\Http\Controllers\Admin\PackageController::class, 'storeFromContracts'])->name('packages.store-from-contracts');
|
||||||
});
|
});
|
||||||
|
|
||||||
// Contract document generation (JSON) - protected by auth+verified; permission enforced inside controller service
|
// Contract document generation (JSON) - protected by auth+verified; permission enforced inside controller service
|
||||||
|
|
@ -327,6 +337,10 @@
|
||||||
Route::delete('client-cases/{client_case:uuid}/documents/{document:uuid}', [ClientCaseContoller::class, 'deleteDocument'])->name('clientCase.document.delete');
|
Route::delete('client-cases/{client_case:uuid}/documents/{document:uuid}', [ClientCaseContoller::class, 'deleteDocument'])->name('clientCase.document.delete');
|
||||||
// client-case / person phone - send SMS
|
// client-case / person phone - send SMS
|
||||||
Route::post('client-cases/{client_case:uuid}/phone/{phone_id}/sms', [ClientCaseContoller::class, 'sendSmsToPhone'])->name('clientCase.phone.sms');
|
Route::post('client-cases/{client_case:uuid}/phone/{phone_id}/sms', [ClientCaseContoller::class, 'sendSmsToPhone'])->name('clientCase.phone.sms');
|
||||||
|
// client-case / contracts list for SMS dialog
|
||||||
|
Route::get('client-cases/{client_case:uuid}/contracts/list', [ClientCaseContoller::class, 'listContracts'])->name('clientCase.contracts.list');
|
||||||
|
// client-case / SMS template preview
|
||||||
|
Route::post('client-cases/{client_case:uuid}/sms/preview', [ClientCaseContoller::class, 'previewSms'])->name('clientCase.sms.preview');
|
||||||
// contract / documents (direct access by contract)
|
// contract / documents (direct access by contract)
|
||||||
Route::get('contracts/{contract:uuid}/documents/{document:uuid}/view', [ClientCaseContoller::class, 'viewContractDocument'])->name('contract.document.view');
|
Route::get('contracts/{contract:uuid}/documents/{document:uuid}/view', [ClientCaseContoller::class, 'viewContractDocument'])->name('contract.document.view');
|
||||||
Route::get('contracts/{contract:uuid}/documents/{document:uuid}/download', [ClientCaseContoller::class, 'downloadContractDocument'])->name('contract.document.download');
|
Route::get('contracts/{contract:uuid}/documents/{document:uuid}/download', [ClientCaseContoller::class, 'downloadContractDocument'])->name('contract.document.download');
|
||||||
|
|
|
||||||
55
tests/Unit/PackageItemSmsJobTest.php
Normal file
55
tests/Unit/PackageItemSmsJobTest.php
Normal file
|
|
@ -0,0 +1,55 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Jobs\PackageItemSmsJob;
|
||||||
|
use App\Models\Package;
|
||||||
|
use App\Models\SmsLog;
|
||||||
|
use App\Models\SmsProfile;
|
||||||
|
use App\Services\Sms\SmsService;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
uses(RefreshDatabase::class);
|
||||||
|
|
||||||
|
it('processes a queued package item and updates counters', function () {
|
||||||
|
$package = Package::create([
|
||||||
|
'uuid' => (string) Str::uuid(),
|
||||||
|
'type' => Package::TYPE_SMS,
|
||||||
|
'status' => Package::STATUS_DRAFT,
|
||||||
|
'name' => 'Test SMS Package',
|
||||||
|
'total_items' => 1,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$profile = SmsProfile::factory()->create();
|
||||||
|
|
||||||
|
$item = $package->items()->create([
|
||||||
|
'status' => 'queued',
|
||||||
|
'target_json' => ['number' => '+38640123456'],
|
||||||
|
'payload_json' => ['profile_id' => $profile->id, 'body' => 'Hello world'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Mock SmsService to return a successful log
|
||||||
|
$log = new SmsLog([
|
||||||
|
'status' => 'sent',
|
||||||
|
'provider_message_id' => 'abc123',
|
||||||
|
'cost' => 0.0100,
|
||||||
|
'currency' => 'EUR',
|
||||||
|
'meta' => ['parts' => 1],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->mock(SmsService::class)
|
||||||
|
->shouldReceive('sendFromTemplate')->zeroOrMoreTimes()
|
||||||
|
->andReturn($log);
|
||||||
|
$this->mock(SmsService::class)
|
||||||
|
->shouldReceive('sendRaw')->zeroOrMoreTimes()
|
||||||
|
->andReturn($log);
|
||||||
|
|
||||||
|
$job = new PackageItemSmsJob($item->id);
|
||||||
|
$job->handle(app(SmsService::class));
|
||||||
|
|
||||||
|
$item->refresh();
|
||||||
|
$package->refresh();
|
||||||
|
|
||||||
|
expect($item->status)->toBe('sent');
|
||||||
|
expect($package->sent_count)->toBe(1);
|
||||||
|
expect($package->failed_count)->toBe(0);
|
||||||
|
});
|
||||||
53
tests/Unit/PhoneSelectorTest.php
Normal file
53
tests/Unit/PhoneSelectorTest.php
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\Person\Person;
|
||||||
|
use App\Models\Person\PersonPhone;
|
||||||
|
use App\Services\Contact\PhoneSelector;
|
||||||
|
|
||||||
|
it('selects validated mobile first', function () {
|
||||||
|
$person = Person::factory()->create();
|
||||||
|
// Non-mobile validated
|
||||||
|
PersonPhone::factory()->for($person, 'person')->landline()->validated()->create();
|
||||||
|
// Mobile not validated
|
||||||
|
PersonPhone::factory()->for($person, 'person')->mobile()->notValidated()->create();
|
||||||
|
// Mobile validated (should win)
|
||||||
|
$best = PersonPhone::factory()->for($person, 'person')->mobile()->validated()->create();
|
||||||
|
|
||||||
|
$selector = new PhoneSelector;
|
||||||
|
$result = $selector->selectForPerson($person->fresh('phones'));
|
||||||
|
|
||||||
|
expect($result['phone'])->not->toBeNull();
|
||||||
|
expect($result['phone']->id)->toBe($best->id);
|
||||||
|
expect($result['reason'])->toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to validated any type then mobile', function () {
|
||||||
|
$person = Person::factory()->create();
|
||||||
|
$validatedAny = PersonPhone::factory()->for($person, 'person')->landline()->validated()->create();
|
||||||
|
$mobile = PersonPhone::factory()->for($person, 'person')->mobile()->notValidated()->create();
|
||||||
|
|
||||||
|
$selector = new PhoneSelector;
|
||||||
|
$result = $selector->selectForPerson($person->fresh('phones'));
|
||||||
|
|
||||||
|
expect($result['phone']->id)->toBe($validatedAny->id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns first active when no better option', function () {
|
||||||
|
$person = Person::factory()->create();
|
||||||
|
$first = PersonPhone::factory()->for($person, 'person')->landline()->notValidated()->create();
|
||||||
|
PersonPhone::factory()->for($person, 'person')->landline()->notValidated()->create();
|
||||||
|
|
||||||
|
$selector = new PhoneSelector;
|
||||||
|
$result = $selector->selectForPerson($person->fresh('phones'));
|
||||||
|
|
||||||
|
expect($result['phone']->id)->toBe($first->id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns reason when no phones', function () {
|
||||||
|
$person = Person::factory()->create();
|
||||||
|
$selector = new PhoneSelector;
|
||||||
|
$result = $selector->selectForPerson($person->fresh('phones'));
|
||||||
|
|
||||||
|
expect($result['phone'])->toBeNull();
|
||||||
|
expect($result['reason'])->toBe('no_active_phones');
|
||||||
|
});
|
||||||
38
tests/Unit/SmsServiceFormatEuTest.php
Normal file
38
tests/Unit/SmsServiceFormatEuTest.php
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\SmsProfile;
|
||||||
|
use App\Services\Sms\SmsClient;
|
||||||
|
use App\Services\Sms\SmsMessage;
|
||||||
|
use App\Services\Sms\SmsResult;
|
||||||
|
use App\Services\Sms\SmsService;
|
||||||
|
|
||||||
|
it('formats amounts to EU style', function () {
|
||||||
|
$client = new class implements SmsClient
|
||||||
|
{
|
||||||
|
public function send(SmsProfile $profile, SmsMessage $message): SmsResult
|
||||||
|
{
|
||||||
|
throw new RuntimeException('not used');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getCreditBalance(SmsProfile $profile): int
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getPriceQuotes(SmsProfile $profile): array
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
$sms = new SmsService($client);
|
||||||
|
|
||||||
|
expect($sms->formatAmountEu(0))->toBe('0,00');
|
||||||
|
expect($sms->formatAmountEu('1'))->toBe('1,00');
|
||||||
|
expect($sms->formatAmountEu('12.3'))->toBe('12,30');
|
||||||
|
expect($sms->formatAmountEu('1234.56'))->toBe('1.234,56');
|
||||||
|
expect($sms->formatAmountEu('9876543.21'))->toBe('9.876.543,21');
|
||||||
|
expect($sms->formatAmountEu('-42.5'))->toBe('-42,50');
|
||||||
|
// Accept EU input too
|
||||||
|
expect($sms->formatAmountEu('1.234,56'))->toBe('1.234,56');
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue
Block a user