feat(sales): fresh sales implementation

This commit is contained in:
Darko Gjorgjijoski
2026-08-21 01:26:48 +02:00
parent e5dc314b68
commit 5269344458
53 changed files with 5736 additions and 0 deletions
@@ -0,0 +1,24 @@
<?php
namespace App\Domains\Sales\Http\Controllers\Company;
use App\Domains\Sales\Models\Estimate;
use App\Platform\Http\Controller;
use App\Platform\Pdf\Rendering\PdfTemplateUtils;
use Illuminate\Http\Request;
class EstimateTemplatesController extends Controller
{
/**
* List the PDF templates an estimate can be rendered with, each already
* paired with its preview image.
*/
public function __invoke(Request $request)
{
$this->authorize('viewAny', Estimate::class);
return response()->json([
'estimateTemplates' => PdfTemplateUtils::getFormattedTemplates('estimate'),
]);
}
}
@@ -0,0 +1,179 @@
<?php
namespace App\Domains\Sales\Http\Controllers\Company;
use App\Domains\Sales\Application\EstimateService;
use App\Domains\Sales\Http\Requests\DeleteEstimatesRequest;
use App\Domains\Sales\Http\Requests\EstimatesRequest;
use App\Domains\Sales\Http\Requests\SendEstimatesRequest;
use App\Domains\Sales\Http\Resources\EstimateResource;
use App\Domains\Sales\Http\Resources\InvoiceResource;
use App\Domains\Sales\Jobs\GenerateEstimatePdfJob;
use App\Domains\Sales\Models\Estimate;
use App\Domains\Sales\Models\Invoice;
use App\Platform\Http\Controller;
use Illuminate\Http\Request;
use Illuminate\Mail\Markdown;
/**
* Company-scoped estimate endpoints: listing, the write surface, bulk removal,
* mailing, and the two document conversions.
*/
class EstimatesController extends Controller
{
public function __construct(private readonly EstimateService $estimateService) {}
/**
* Paginated estimates of the active company, joined to their customer so the
* list can be filtered and sorted by customer name.
*/
public function index(Request $request)
{
$this->authorize('viewAny', Estimate::class);
$filters = $request->all();
$perPage = $request->has('limit') ? $request->input('limit') : 10;
$page = Estimate::query()
->whereCompany()
->join('customers', fn ($join) => $join->on('customers.id', '=', 'estimates.customer_id'))
->applyFilters($filters)
->select(['estimates.*', 'customers.name'])
->orderByDesc('created_at')
->paginateData($perPage);
return EstimateResource::collection($page)->additional([
'meta' => [
'estimate_total_count' => Estimate::query()->whereCompany()->count(),
],
]);
}
/**
* Persist a new estimate, optionally mailing it straight away, and queue the
* PDF render.
*/
public function store(EstimatesRequest $request)
{
$this->authorize('create', Estimate::class);
$estimate = $this->estimateService->create(...$this->writeArguments($request));
if ($request->has('estimateSend')) {
$this->estimateService->send($estimate, $request->only(['title', 'body']));
}
GenerateEstimatePdfJob::dispatch($estimate);
return EstimateResource::make($estimate);
}
public function show(Request $request, Estimate $estimate)
{
$this->authorize('view', $estimate);
return EstimateResource::make($estimate);
}
/**
* Overwrite an estimate — lines and taxes are replaced wholesale — and
* re-render its PDF.
*/
public function update(EstimatesRequest $request, Estimate $estimate)
{
$this->authorize('update', $estimate);
$estimate = $this->estimateService->update($estimate, ...$this->writeArguments($request));
GenerateEstimatePdfJob::dispatch($estimate, true);
return EstimateResource::make($estimate);
}
/**
* Bulk removal. Ids outside the active company are silently skipped.
*/
public function delete(DeleteEstimatesRequest $request)
{
$this->authorize('delete multiple estimates');
$ids = Estimate::query()
->whereCompany()
->whereIn('id', $request->input('ids'))
->pluck('id');
Estimate::destroy($ids);
return response()->json(['success' => true]);
}
public function send(SendEstimatesRequest $request, Estimate $estimate)
{
$this->authorize('send estimate', $estimate);
return response()->json(
$this->estimateService->send($estimate, $request->all())
);
}
/**
* Render the mail body the customer would receive, without sending it.
*/
public function sendPreview(SendEstimatesRequest $request, Estimate $estimate)
{
$this->authorize('send estimate', $estimate);
$data = $this->estimateService->sendEstimateData($estimate, $request->all());
$data['url'] = $estimate->estimatePdfUrl;
$renderer = new Markdown(view(), config('mail.markdown'));
return $renderer->render('emails.send.estimate', ['data' => $data]);
}
public function clone(Request $request, Estimate $estimate)
{
$this->authorize('view', $estimate);
$this->authorize('create', Estimate::class);
return EstimateResource::make($this->estimateService->clone($estimate));
}
/**
* Reading the source estimate is checked on top of the invoice-create
* ability so the conversion cannot reach across companies.
*/
public function convertToInvoice(Request $request, Estimate $estimate)
{
$this->authorize('view', $estimate);
$this->authorize('create', Invoice::class);
return InvoiceResource::make($this->estimateService->convertToInvoice($estimate));
}
public function changeStatus(Request $request, Estimate $estimate)
{
$this->authorize('send estimate', $estimate);
$this->estimateService->changeStatus($estimate, $request->input('status'));
return response()->json(['success' => true]);
}
/**
* The arguments create() and update() share, keyed by parameter name.
*
* @return array<string, mixed>
*/
private function writeArguments(EstimatesRequest $request): array
{
$fields = $request->input('customFields');
return [
'attributes' => $request->getEstimatePayload(),
'items' => $request->input('items'),
'taxes' => $request->has('taxes') ? $request->input('taxes') : null,
'customFields' => is_iterable($fields) ? $fields : null,
];
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Domains\Sales\Http\Controllers\Company;
use App\Domains\Sales\Models\Invoice;
use App\Platform\Http\Controller;
use App\Platform\Pdf\Rendering\PdfTemplateUtils;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class InvoiceTemplatesController extends Controller
{
/**
* List the PDF templates an invoice can be rendered with, each already
* paired with its preview image.
*
* @return JsonResponse
*/
public function __invoke(Request $request)
{
$this->authorize('viewAny', Invoice::class);
return response()->json([
'invoiceTemplates' => PdfTemplateUtils::getFormattedTemplates('invoice'),
]);
}
}
@@ -0,0 +1,132 @@
<?php
namespace App\Domains\Sales\Http\Controllers\Company;
use App\Domains\Sales\Application\RecurringInvoiceService;
use App\Domains\Sales\Http\Requests\RecurringInvoiceRequest;
use App\Domains\Sales\Http\Resources\RecurringInvoiceResource;
use App\Domains\Sales\Models\RecurringInvoice;
use App\Platform\Http\Controller;
use Illuminate\Http\Request;
/**
* The admin surface for standing orders — the schedules that mint invoices on
* a cron expression.
*
* Each row is an invoice held in template form, so the write endpoints hand
* the service the same three parcels a document does: the row's own columns,
* the line items, and the document-level taxes.
*/
class RecurringInvoiceController extends Controller
{
public function __construct(
private readonly RecurringInvoiceService $recurringInvoiceService,
) {}
/**
* Page through the company's schedules.
*
* Alongside the page itself the payload carries how many schedules the
* company holds in total, which the listing screen shows even when a
* filter has narrowed the rows down to a handful.
*/
public function index(Request $request)
{
$this->authorize('viewAny', RecurringInvoice::class);
$perPage = $request->has('limit') ? $request->input('limit') : 10;
$schedules = RecurringInvoice::whereCompany()
->applyFilters($request->all())
->paginateData($perPage);
$companyTotal = RecurringInvoice::whereCompany()->count();
return RecurringInvoiceResource::collection($schedules)
->additional(['meta' => [
'recurring_invoice_total_count' => $companyTotal,
]]);
}
/**
* Set up a new schedule from the submitted template.
*/
public function store(RecurringInvoiceRequest $request)
{
$this->authorize('create', RecurringInvoice::class);
$schedule = $this->recurringInvoiceService->create(
attributes: $request->getRecurringInvoicePayload(),
items: $request->input('items'),
taxes: $request->has('taxes') ? $request->input('taxes') : null,
customFields: $this->customFields($request),
);
return new RecurringInvoiceResource($schedule);
}
/**
* Show one schedule.
*/
public function show(RecurringInvoice $recurringInvoice)
{
$this->authorize('view', $recurringInvoice);
return new RecurringInvoiceResource($recurringInvoice);
}
/**
* Restate a schedule, template and all.
*
* Items and taxes are replaced wholesale rather than reconciled, so the
* submission is the schedule's new contents in full.
*/
public function update(RecurringInvoiceRequest $request, RecurringInvoice $recurringInvoice)
{
$this->authorize('update', $recurringInvoice);
$this->recurringInvoiceService->update(
recurringInvoice: $recurringInvoice,
attributes: $request->getRecurringInvoicePayload(),
items: $request->input('items'),
taxes: $request->has('taxes') ? $request->input('taxes') : null,
customFields: $this->customFields($request),
);
return new RecurringInvoiceResource($recurringInvoice);
}
/**
* Drop several schedules at once.
*
* The submitted ids are narrowed to the acting company before anything is
* removed, so ids belonging elsewhere are quietly passed over. Invoices
* already minted by a dropped schedule survive it — they are merely cut
* loose from the parent.
*/
public function delete(Request $request)
{
$this->authorize('delete multiple recurring invoices');
$ids = RecurringInvoice::whereCompany()
->whereIn('id', $request->input('ids'))
->pluck('id');
$this->recurringInvoiceService->delete($ids);
return response()->json([
'success' => true,
]);
}
/**
* The submitted custom-field values, or nothing when the payload carries
* something the service cannot walk.
*/
private function customFields(RecurringInvoiceRequest $request): ?iterable
{
$values = $request->input('customFields');
return is_iterable($values) ? $values : null;
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Domains\Sales\Http\Controllers\Company;
use App\Domains\Sales\Models\RecurringInvoice;
use App\Platform\Http\Controller;
use Illuminate\Http\Request;
/**
* Previews the moment a schedule would fire for the first time.
*/
class RecurringInvoiceFrequencyController extends Controller
{
/**
* Read a cron expression and a start date, and answer with the first
* firing they produce.
*
* The schedule form asks for this while it is still being filled in, so
* nothing here is gated or written down — the date is worked out, handed
* back and forgotten. A start date the parser cannot read, or an
* expression it cannot parse, comes back as a server error rather than a
* validation message.
*/
public function __invoke(Request $request)
{
$nextRun = RecurringInvoice::getNextInvoiceDate(
$request->input('frequency'),
$request->input('starts_at'),
);
return response()->json([
'success' => true,
'next_invoice_at' => $nextRun,
]);
}
}
@@ -0,0 +1,92 @@
<?php
namespace App\Domains\Sales\Http\Controllers\Company;
use App\Domains\Receivables\Models\Payment;
use App\Domains\Sales\Application\SerialNumberService;
use App\Domains\Sales\Models\Estimate;
use App\Domains\Sales\Models\Invoice;
use App\Platform\Http\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* Serves the number-format previews the settings and document screens use.
*/
class SerialNumberController extends Controller
{
/**
* Render the number the next document of the requested kind would carry.
*
* The `key` query parameter picks the document kind; an unknown one is
* reported as a plain failure rather than an error. `format` overrides the
* company's stored format so the settings screen can preview edits, and
* `model_id` lets an existing document keep the numbers it already has.
*/
public function nextNumber(Request $request, Invoice $invoice, Estimate $estimate, Payment $payment): JsonResponse
{
$serial = (new SerialNumberService)
->setCompany($request->header('company'))
->setCustomer($request->userId);
// Invoices and credit notes live in one table, so each is pinned to its
// own row type: the preview must never count the other kind's rows.
switch ($request->key) {
case 'invoice':
$serial->setModel($invoice)
->setSequenceScope(['type' => Invoice::TYPE_INVOICE]);
break;
case 'credit_note':
$serial->setModel($invoice)
->setSettingKey('credit_note_number_format')
->setSequenceScope(['type' => Invoice::TYPE_CREDIT_NOTE]);
break;
case 'estimate':
$serial->setModel($estimate);
break;
case 'payment':
$serial->setModel($payment);
break;
default:
return response()->json([
'success' => false,
]);
}
try {
$nextNumber = $serial->setModelObject($request->model_id)
->getNextNumber($request->input('format'));
} catch (\Exception $exception) {
return response()->json([
'success' => false,
'message' => $exception->getMessage(),
]);
}
return response()->json([
'success' => true,
'nextNumber' => $nextNumber,
]);
}
/**
* List the tokens a submitted format string is made of.
*/
public function placeholders(Request $request): JsonResponse
{
$format = $request->input('format');
return response()->json([
'success' => true,
'placeholders' => $format ? SerialNumberService::getPlaceholders($format) : [],
]);
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Domains\Sales\Http\Controllers\CustomerPortal;
use App\Domains\Accounts\Models\Company;
use App\Domains\Sales\Http\Resources\CustomerPortal\EstimateResource;
use App\Platform\Http\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
class AcceptEstimateController extends Controller
{
/**
* Record the contact's verdict on one of their own offers.
*
* Known defect, kept as-is: the submitted value is written through
* without a whitelist, so the stored status is whatever string arrives.
*
* @param string $id
* @return Response
*/
public function __invoke(Request $request, Company $company, $id)
{
$contact = Auth::guard('customer')->id();
$estimate = $company->estimates()->whereCustomer($contact)->where('id', $id)->first();
if ($estimate === null) {
return response()->json(['error' => 'estimate_not_found'], Response::HTTP_NOT_FOUND);
}
$verdict = $request->only('status');
$estimate->update($verdict);
return EstimateResource::make($estimate);
}
}
@@ -0,0 +1,92 @@
<?php
namespace App\Domains\Sales\Http\Controllers\CustomerPortal;
use App\Domains\Accounts\Models\CompanySetting;
use App\Domains\Contacts\Models\Customer;
use App\Domains\Sales\Http\Resources\EstimateResource;
use App\Domains\Sales\Mail\EstimateViewedMail;
use App\Domains\Sales\Models\Estimate;
use App\Platform\Http\Controller;
use App\Platform\Mail\Models\EmailLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class EstimatePdfController extends Controller
{
/**
* Stream the offer behind an emailed link. Opening it counts as reading
* the offer, so the document is marked seen on the way through.
*/
public function getPdf(EmailLog $emailLog, Request $request)
{
$estimate = $this->documentBehind($emailLog);
$this->recordReading($estimate);
return $estimate->getGeneratedPDFOrStream('estimate');
}
/**
* Serve the same offer as JSON for the viewer shell.
*
* Note the payload is the back-office representation, not the trimmed
* portal one its invoice counterpart uses. Left as it stands.
*/
public function getEstimate(EmailLog $emailLog)
{
return EstimateResource::make($this->documentBehind($emailLog));
}
/**
* Trade an email-log token for the offer it was issued for.
*
* Holding the token is the whole credential, so the guard is narrow: the
* log must point at an offer, and the link must still be inside the
* company's expiry window.
*/
private function documentBehind(EmailLog $emailLog): Estimate
{
$document = $emailLog->mailable;
if (! $document instanceof Estimate) {
abort(404);
}
if ($emailLog->isExpired()) {
abort(403, 'Link Expired.');
}
return $document;
}
/**
* Promote an offer that is still awaiting a reader, and tell the issuer
* about it when they asked to be told.
*/
private function recordReading(Estimate $estimate): void
{
$unread = [Estimate::STATUS_SENT, Estimate::STATUS_DRAFT];
if (! in_array($estimate->status, $unread)) {
return;
}
$estimate->update(['status' => Estimate::STATUS_VIEWED]);
$wanted = CompanySetting::getSetting('notify_estimate_viewed', $estimate->company_id);
if ($wanted != 'YES') {
return;
}
$payload = [
'estimate' => Estimate::findOrFail($estimate->id)->toArray(),
'user' => Customer::find($estimate->customer_id)->toArray(),
];
$mailbox = CompanySetting::getSetting('notification_email', $estimate->company_id);
Mail::to($mailbox)->send(new EstimateViewedMail($payload));
}
}
@@ -0,0 +1,78 @@
<?php
namespace App\Domains\Sales\Http\Controllers\CustomerPortal;
use App\Domains\Accounts\Models\Company;
use App\Domains\Sales\Http\Resources\CustomerPortal\EstimateResource;
use App\Domains\Sales\Models\Estimate;
use App\Platform\Http\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
class EstimatesController extends Controller
{
/**
* Page through the offers addressed to the signed-in contact.
*
* Unsent work stays private to the issuer, so drafts reach neither the
* page itself nor the counter beside it.
*
* @return Response
*/
public function index(Request $request)
{
$perPage = 10;
if ($request->has('limit')) {
$perPage = $request->limit;
}
$contact = Auth::guard('customer')->id();
$query = Estimate::with(['items', 'customer', 'taxes', 'creator'])
->where('status', '<>', Estimate::STATUS_DRAFT)
->whereCustomer($contact);
$query->applyFilters($request->only([
'status',
'estimate_number',
'from_date',
'to_date',
'orderByField',
'orderBy',
]));
$page = $query->latest()->paginateData($perPage);
$visible = Estimate::query()
->where('status', '<>', Estimate::STATUS_DRAFT)
->whereCustomer($contact)
->count();
return EstimateResource::collection($page)
->additional(['meta' => [
'estimateTotalCount' => $visible,
]]);
}
/**
* Hand back a single offer, looked up inside the portal's company and
* narrowed to the signed-in contact so ids cannot be probed.
*
* @param string $id
* @return Response
*/
public function show(Company $company, $id)
{
$contact = Auth::guard('customer')->id();
$estimate = $company->estimates()->whereCustomer($contact)->where('id', $id)->first();
if ($estimate === null) {
return response()->json(['error' => 'estimate_not_found'], Response::HTTP_NOT_FOUND);
}
return EstimateResource::make($estimate);
}
}
@@ -0,0 +1,104 @@
<?php
namespace App\Domains\Sales\Http\Controllers\CustomerPortal;
use App\Domains\Accounts\Models\CompanySetting;
use App\Domains\Contacts\Models\Customer;
use App\Domains\Sales\Http\Resources\CustomerPortal\InvoiceResource;
use App\Domains\Sales\Mail\InvoiceViewedMail;
use App\Domains\Sales\Models\Invoice;
use App\Platform\Http\Controller;
use App\Platform\Mail\Models\EmailLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class InvoicePdfController extends Controller
{
/**
* Answer an emailed link: the rendered document when the caller asks for
* the file, otherwise the portal shell that frames it. Either way the
* visit counts as the customer having read the bill.
*/
public function getPdf(EmailLog $emailLog, Request $request)
{
$invoice = $this->documentBehind($emailLog);
$this->recordReading($invoice);
if ($request->has('pdf')) {
return $invoice->getGeneratedPDFOrStream('invoice');
}
$issuer = $invoice->company_id;
return view('app')->with([
'customer_logo' => get_company_setting('customer_portal_logo', $issuer),
'current_theme' => get_company_setting('customer_portal_theme', $issuer),
]);
}
/**
* Serve the same document as JSON for the viewer shell, in the trimmed
* portal shape.
*/
public function getInvoice(EmailLog $emailLog)
{
return InvoiceResource::make($this->documentBehind($emailLog));
}
/**
* Trade an email-log token for the document it was issued for.
*
* Holding the token is the whole credential, so the guard is narrow. The
* log must point at a billing document (a token minted for some other
* kind of mail must not disclose one, however the ids line up), and the
* link must still be inside the company's expiry window.
*/
private function documentBehind(EmailLog $emailLog): Invoice
{
$document = $emailLog->mailable;
if (! $document instanceof Invoice) {
abort(404);
}
if ($emailLog->isExpired()) {
abort(403, 'Link Expired.');
}
return $document;
}
/**
* Promote a document that is still awaiting a reader, and tell the issuer
* about it when they asked to be told.
*/
private function recordReading(Invoice $invoice): void
{
$unread = [Invoice::STATUS_SENT, Invoice::STATUS_DRAFT];
if (! in_array($invoice->status, $unread)) {
return;
}
$invoice->update([
'status' => Invoice::STATUS_VIEWED,
'viewed' => true,
]);
$wanted = CompanySetting::getSetting('notify_invoice_viewed', $invoice->company_id);
if ($wanted != 'YES') {
return;
}
$payload = [
'invoice' => Invoice::findOrFail($invoice->id)->toArray(),
'user' => Customer::find($invoice->customer_id)->toArray(),
];
$mailbox = CompanySetting::getSetting('notification_email', $invoice->company_id);
Mail::to($mailbox)->send(new InvoiceViewedMail($payload));
}
}
@@ -0,0 +1,75 @@
<?php
namespace App\Domains\Sales\Http\Controllers\CustomerPortal;
use App\Domains\Accounts\Models\Company;
use App\Domains\Sales\Http\Resources\CustomerPortal\InvoiceResource;
use App\Domains\Sales\Models\Invoice;
use App\Platform\Http\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
class InvoicesController extends Controller
{
/**
* Page through the billing documents the signed-in contact has received.
*
* Drafts are withheld; the whole query string is handed to the filter
* scope, so anything the model knows how to narrow by is accepted here.
*
* @return Response
*/
public function index(Request $request)
{
$perPage = 10;
if ($request->has('limit')) {
$perPage = $request->limit;
}
$contact = Auth::guard('customer')->id();
$filters = $request->all();
$page = Invoice::with(['items', 'customer', 'creator', 'taxes'])
->where('status', '<>', Invoice::STATUS_DRAFT)
->applyFilters($filters)
->whereCustomer($contact)
->latest()
->paginateData($perPage);
// The counter tallies issued documents alone. A credit note reverses
// an invoice rather than adding one, so it is left out of the total
// even though it is listed among the rows above.
$received = Invoice::query()
->where('type', Invoice::TYPE_INVOICE)
->where('status', '<>', Invoice::STATUS_DRAFT)
->whereCustomer($contact)
->count();
return InvoiceResource::collection($page)
->additional(['meta' => [
'invoiceTotalCount' => $received,
]]);
}
/**
* Hand back a single billing document, looked up inside the portal's
* company and narrowed to the signed-in contact.
*
* @param string $id
* @return Response
*/
public function show(Company $company, $id)
{
$contact = Auth::guard('customer')->id();
$invoice = $company->invoices()->whereCustomer($contact)->where('id', $id)->first();
if ($invoice === null) {
return response()->json(['error' => 'invoice_not_found'], Response::HTTP_NOT_FOUND);
}
return InvoiceResource::make($invoice);
}
}