public function sendInvoice(Invoice $invoice, $reminder = false) { $invoice->load('invitations', 'client.language', 'account'); $entityType = $invoice->getEntityType(); $client = $invoice->client; $account = $invoice->account; if ($invoice->trashed() || $client->trashed()) { return false; } $account->loadLocalizationSettings($client); $view = 'invoice'; $accountName = $invoice->account->getDisplayName(); $emailTemplate = $invoice->account->getEmailTemplate($reminder ?: $entityType); $emailSubject = $invoice->account->getEmailSubject($reminder ?: $entityType); $this->initClosure($invoice); $response = false; $sent = false; foreach ($invoice->invitations as $invitation) { if (Auth::check()) { $user = Auth::user(); } else { $user = $invitation->user; if ($invitation->user->trashed()) { $user = $account->users()->orderBy('id')->first(); } } if (!$user->email || !$user->confirmed) { continue; } if (!$invitation->contact->email || $invitation->contact->trashed()) { continue; } $invitation->sent_date = \Carbon::now()->toDateTimeString(); $invitation->save(); $variables = ['account' => $account, 'client' => $client, 'invitation' => $invitation, 'amount' => $invoice->getRequestedAmount()]; $data['body'] = $this->processVariables($emailTemplate, $variables); $data['link'] = $invitation->getLink(); $data['entityType'] = $entityType; $data['invoice_id'] = $invoice->id; $subject = $this->processVariables($emailSubject, $variables); $fromEmail = $user->email; $response = $this->sendTo($invitation->contact->email, $fromEmail, $accountName, $subject, $view, $data); if ($response === true) { $sent = true; Activity::emailInvoice($invitation); } } if ($sent === true) { if (!$invoice->isSent()) { $invoice->invoice_status_id = INVOICE_STATUS_SENT; $invoice->save(); } $account->loadLocalizationSettings(); Event::fire(new InvoiceSent($invoice)); } return $response ?: trans('texts.email_error'); }
public static function get($x) { $sql = "SELECT * FROM invoices where invoiceID = :x"; $row = DB::SelectOne($sql, ["x" => $x]); $invoice = new Invoice(); $invoice->id = $row->invoiceID; $invoice->date = $row->invoiceDate; $invoice->customer = $row->customer; // I really want an array of items here.... /// How could i possibly fetch the items for just this inovice id???? $invoice->tools = Tool::getByInvoiceId($x); $invoice->calcTotal(); return $invoice; }
public function sendNotification(User $user, Invoice $invoice, $notificationType, Payment $payment = null) { if (!$user->email) { return; } $entityType = $notificationType == 'approved' ? ENTITY_QUOTE : ENTITY_INVOICE; $view = "{$entityType}_{$notificationType}"; $data = ['entityType' => $entityType, 'clientName' => $invoice->client->getDisplayName(), 'accountName' => $invoice->account->getDisplayName(), 'userName' => $user->getDisplayName(), 'invoiceAmount' => Utils::formatMoney($invoice->getRequestedAmount(), $invoice->client->getCurrencyId()), 'invoiceNumber' => $invoice->invoice_number, 'invoiceLink' => SITE_URL . "/{$entityType}s/{$invoice->public_id}"]; if ($payment) { $data['paymentAmount'] = Utils::formatMoney($payment->amount, $invoice->client->getCurrencyId()); } $subject = trans("texts.notification_{$entityType}_{$notificationType}_subject", ['invoice' => $invoice->invoice_number, 'client' => $invoice->client->getDisplayName()]); $this->sendTo($user->email, CONTACT_EMAIL, CONTACT_NAME, $subject, $view, $data); }
public function fire() { $this->info(date('Y-m-d') . ' Running SendRecurringInvoices...'); $today = new DateTime(); $invoices = Invoice::with('account.timezone', 'invoice_items', 'client', 'user')->whereRaw('is_deleted IS FALSE AND deleted_at IS NULL AND is_recurring IS TRUE AND frequency_id > 0 AND start_date <= ? AND (end_date IS NULL OR end_date >= ?)', [$today, $today])->orderBy('id', 'asc')->get(); $this->info(count($invoices) . ' recurring invoice(s) found'); foreach ($invoices as $recurInvoice) { $shouldSendToday = $recurInvoice->shouldSendToday(); $this->info('Processing Invoice ' . $recurInvoice->id . ' - Should send ' . ($shouldSendToday ? 'YES' : 'NO')); if (!$shouldSendToday) { continue; } $recurInvoice->account->loadLocalizationSettings($recurInvoice->client); $invoice = $this->invoiceRepo->createRecurringInvoice($recurInvoice); if ($invoice && !$invoice->isPaid()) { $this->info('Sending Invoice'); $this->mailer->sendInvoice($invoice); } } $delayedAutoBillInvoices = Invoice::with('account.timezone', 'recurring_invoice', 'invoice_items', 'client', 'user')->whereRaw('is_deleted IS FALSE AND deleted_at IS NULL AND is_recurring IS FALSE AND balance > 0 AND due_date = ? AND recurring_invoice_id IS NOT NULL', [$today->format('Y-m-d')])->orderBy('invoices.id', 'asc')->get(); $this->info(count($delayedAutoBillInvoices) . ' due recurring invoice instance(s) found'); /** @var Invoice $invoice */ foreach ($delayedAutoBillInvoices as $invoice) { if ($invoice->isPaid()) { continue; } if ($invoice->getAutoBillEnabled() && $invoice->client->autoBillLater()) { $this->info('Processing Autobill-delayed Invoice ' . $invoice->id); $this->paymentService->autoBillInvoice($invoice); } } $this->info('Done'); }
public function save($publicId = null, $input) { if ($publicId) { $payment = Payment::scope($publicId)->firstOrFail(); } else { $payment = Payment::createNew(); } $paymentTypeId = $input['payment_type_id'] ? $input['payment_type_id'] : null; $payment->payment_type_id = $paymentTypeId; $payment->payment_date = Utils::toSqlDate($input['payment_date']); $payment->transaction_reference = trim($input['transaction_reference']); if (!$publicId) { $clientId = Client::getPrivateId($input['client']); $amount = Utils::parseFloat($input['amount']); if ($paymentTypeId == PAYMENT_TYPE_CREDIT) { $credits = Credit::scope()->where('client_id', '=', $clientId)->where('balance', '>', 0)->orderBy('created_at')->get(); $applied = 0; foreach ($credits as $credit) { $applied += $credit->apply($amount); if ($applied >= $amount) { break; } } } $payment->client_id = $clientId; $payment->invoice_id = isset($input['invoice']) && $input['invoice'] != "-1" ? Invoice::getPrivateId($input['invoice']) : null; $payment->amount = $amount; } $payment->save(); return $payment; }
public function update($id, Request $request) { $invoice = Invoice::find($id); $rules = $invoice->getValidatorRules(); $validator = $this->validate($request, $rules); if ($validator) { return response()->json($validator, '404'); } $input = $request->all(); $invoice->update($input); /** |----------------------------------------------------- | Add customer to invoice |----------------------------------------------------- */ $customer_id = $request->get('customer')['id']; $customer = Customer::find($customer_id); $invoice->updateCustomerWithShippingAddress($customer); /** |----------------------------------------------------- | Add list products to invoice |----------------------------------------------------- */ $invoice->addProductItems($request->get('items')); /** |----------------------------------------------------- | Save to Db |----------------------------------------------------- */ redirect()->route('sale.invoice.show', [$invoice], 302); }
public function sendTo($toEmail, $fromEmail, $fromName, $subject, $view, $data = []) { $views = ['emails.' . $view . '_html', 'emails.' . $view . '_text']; try { Mail::send($views, $data, function ($message) use($toEmail, $fromEmail, $fromName, $subject, $data) { $replyEmail = $fromEmail; $fromEmail = CONTACT_EMAIL; if (isset($data['invoice_id'])) { $invoice = Invoice::with('account')->where('id', '=', $data['invoice_id'])->get()->first(); if ($invoice->account->pdf_email_attachment && file_exists($invoice->getPDFPath())) { $message->attach($invoice->getPDFPath(), array('as' => $invoice->getFileName(), 'mime' => 'application/pdf')); } } $message->to($toEmail)->from($fromEmail, $fromName)->replyTo($replyEmail, $fromName)->subject($subject); }); return true; } catch (Exception $exception) { if (method_exists($exception, 'getResponse')) { $response = $exception->getResponse()->getBody()->getContents(); $response = json_decode($response); return nl2br($response->Message); } else { return $exception->getMessage(); } } }
public function edit($publicId) { $payment = Payment::scope($publicId)->firstOrFail(); $payment->payment_date = Utils::fromSqlDate($payment->payment_date); $data = array('client' => null, 'invoice' => null, 'invoices' => Invoice::scope()->where('is_recurring', '=', false)->where('is_quote', '=', false)->with('client', 'invoice_status')->orderBy('invoice_number')->get(), 'payment' => $payment, 'method' => 'PUT', 'url' => 'payments/' . $publicId, 'title' => trans('texts.edit_payment'), 'paymentTypes' => Cache::get('paymentTypes'), 'clients' => Client::scope()->with('contacts')->orderBy('name')->get()); return View::make('payments.edit', $data); }
public function store() { $data = Input::all(); $error = false; if (isset($data['invoice_id'])) { $invoice = Invoice::scope($data['invoice_id'])->with('client')->first(); if ($invoice) { $data['invoice'] = $invoice->public_id; $data['client'] = $invoice->client->public_id; } else { $error = trans('validation.not_in', ['attribute' => 'invoice_id']); } } else { $error = trans('validation.not_in', ['attribute' => 'invoice_id']); } if (!isset($data['transaction_reference'])) { $data['transaction_reference'] = ''; } if (!$error) { $payment = $this->paymentRepo->save($data); $payment = Payment::scope($payment->public_id)->with('client', 'contact', 'user', 'invoice')->first(); $payment = Utils::remapPublicIds([$payment]); } $response = json_encode($error ?: $payment, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(); return Response::make($response, 200, $headers); }
public function sendTo($toEmail, $fromEmail, $fromName, $subject, $view, $data = []) { // https://github.com/wildbit/laravel-postmark-provider/issues/2 if (isset($data['invoice_id']) && isset($_ENV['POSTMARK_API_TOKEN'])) { $views = 'emails.' . $view . '_html'; } else { $views = ['emails.' . $view . '_html', 'emails.' . $view . '_text']; } try { Mail::send($views, $data, function ($message) use($toEmail, $fromEmail, $fromName, $subject, $data) { $toEmail = strtolower($toEmail); $replyEmail = $fromEmail; $fromEmail = CONTACT_EMAIL; $message->to($toEmail)->from($fromEmail, $fromName)->replyTo($replyEmail, $fromName)->subject($subject); if (isset($data['invoice_id'])) { $invoice = Invoice::with('account')->where('id', '=', $data['invoice_id'])->first(); if ($invoice->account->pdf_email_attachment && file_exists($invoice->getPDFPath())) { $message->attach($invoice->getPDFPath(), array('as' => $invoice->getFileName(), 'mime' => 'application/pdf')); } } }); return true; } catch (Exception $exception) { Utils::logError('Email Error: ' . $exception->getMessage()); if (isset($_ENV['POSTMARK_API_TOKEN'])) { $response = $exception->getResponse()->getBody()->getContents(); $response = json_decode($response); return nl2br($response->Message); } else { return $exception->getMessage(); } } }
public function createNinjaInvoice($client) { $account = $this->getNinjaAccount(); $lastInvoice = Invoice::withTrashed()->whereAccountId($account->id)->orderBy('public_id', 'DESC')->first(); $publicId = $lastInvoice ? $lastInvoice->public_id + 1 : 1; $invoice = new Invoice(); $invoice->account_id = $account->id; $invoice->user_id = $account->users()->first()->id; $invoice->public_id = $publicId; $invoice->client_id = $client->id; $invoice->invoice_number = $account->getNextInvoiceNumber(); $invoice->invoice_date = date_create()->format('Y-m-d'); $invoice->amount = PRO_PLAN_PRICE; $invoice->balance = PRO_PLAN_PRICE; $invoice->save(); $item = new InvoiceItem(); $item->account_id = $account->id; $item->user_id = $account->users()->first()->id; $item->public_id = $publicId; $item->qty = 1; $item->cost = PRO_PLAN_PRICE; $item->notes = trans('texts.pro_plan_description'); $item->product_key = trans('texts.pro_plan_product'); $invoice->invoice_items()->save($item); $invitation = new Invitation(); $invitation->account_id = $account->id; $invitation->user_id = $account->users()->first()->id; $invitation->public_id = $publicId; $invitation->invoice_id = $invoice->id; $invitation->contact_id = $client->contacts()->first()->id; $invitation->invitation_key = str_random(RANDOM_KEY_LENGTH); $invitation->save(); return $invitation; }
public function fire() { $this->info(date('Y-m-d') . ' ChargeRenewalInvoices...'); $ninjaAccount = $this->accountRepo->getNinjaAccount(); $invoices = Invoice::whereAccountId($ninjaAccount->id)->whereDueDate(date('Y-m-d'))->where('balance', '>', 0)->with('client')->orderBy('id')->get(); $this->info(count($invoices) . ' invoices found'); foreach ($invoices as $invoice) { // check if account has switched to free since the invoice was created $account = Account::find($invoice->client->public_id); if (!$account) { continue; } $company = $account->company; if (!$company->plan || $company->plan == PLAN_FREE) { continue; } try { $this->info("Charging invoice {$invoice->invoice_number}"); $this->paymentService->autoBillInvoice($invoice); } catch (Exception $exception) { $this->info('Error: ' . $exception->getMessage()); } } $this->info('Done'); }
/** * @SWG\Post( * path="/payments", * summary="Create a payment", * tags={"payment"}, * @SWG\Parameter( * in="body", * name="body", * @SWG\Schema(ref="#/definitions/Payment") * ), * @SWG\Response( * response=200, * description="New payment", * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Payment")) * ), * @SWG\Response( * response="default", * description="an ""unexpected"" error" * ) * ) */ public function store() { $data = Input::all(); $error = false; if (isset($data['invoice_id'])) { $invoice = Invoice::scope($data['invoice_id'])->with('client')->first(); if ($invoice) { $data['invoice'] = $invoice->public_id; $data['client'] = $invoice->client->public_id; } else { $error = trans('validation.not_in', ['attribute' => 'invoice_id']); } } else { $error = trans('validation.not_in', ['attribute' => 'invoice_id']); } if (!isset($data['transaction_reference'])) { $data['transaction_reference'] = ''; } if ($error) { return $error; } $payment = $this->paymentRepo->save($data); $payment = Payment::scope($payment->public_id)->with('client', 'contact', 'user', 'invoice')->first(); $transformer = new PaymentTransformer(Auth::user()->account, Input::get('serializer')); $data = $this->createItem($payment, $transformer, 'payment'); return $this->response($data); }
public function actionInvoice($id) { if (Yii::$app->user->identity->type == 'normal') { return $this->redirect(['update', 'id' => $id]); } $admin_id = Yii::$app->user->identity->id; $model = $this->findModel($id); $invoice = Invoice::find(); $invoice = $invoice->where('job_id=' . $id); $invoice = $invoice->orderBy('id DESC'); $invoice = $invoice->asArray(); $invoice = $invoice->limit(1); $invoice = $invoice->all(); // $companies = Company::find(); // if(Yii::$app->user->identity->type=='normal'){ // $companies = $companies->innerJoin('wolf_admin_to_company wc','wc.company_id=wolf_company.company_id'); // $companies = $companies->where('admin_id='.$admin_id); // } // $companies = $companies->orderBy('company_name'); // $companies = $companies->asArray(); // $companies = $companies->all(); $jobScheduleSearch = new JobScheduleSearch(['job_id' => $id]); $scheduleData = $jobScheduleSearch->search(Yii::$app->request->getQueryParams()); $scheduleData->pagination->pageSize = -1; //infinite value return $this->render('invoice', ['model' => $this->findModel($id), 'scheduleData' => $scheduleData, 'jobScheduleSearch' => $jobScheduleSearch, 'invoice' => $invoice]); }
public function sendInvoice(Invoice $invoice) { $invoice->load('invitations', 'client.language', 'account'); $entityType = $invoice->getEntityType(); $client = $invoice->client; $account = $invoice->account; $account->loadLocalizationSettings($client); $view = 'invoice'; $subject = trans("texts.{$entityType}_subject", ['invoice' => $invoice->invoice_number, 'account' => $invoice->account->getDisplayName()]); $accountName = $invoice->account->getDisplayName(); $emailTemplate = $invoice->account->getEmailTemplate($entityType); $invoiceAmount = Utils::formatMoney($invoice->getRequestedAmount(), $client->getCurrencyId()); $this->initClosure($invoice); foreach ($invoice->invitations as $invitation) { if (!$invitation->user || !$invitation->user->email || $invitation->user->trashed()) { return false; } if (!$invitation->contact || !$invitation->contact->email || $invitation->contact->trashed()) { return false; } $invitation->sent_date = \Carbon::now()->toDateTimeString(); $invitation->save(); $variables = ['$footer' => $invoice->account->getEmailFooter(), '$link' => $invitation->getLink(), '$client' => $client->getDisplayName(), '$account' => $accountName, '$contact' => $invitation->contact->getDisplayName(), '$amount' => $invoiceAmount, '$advancedRawInvoice->' => '$']; // Add variables for available payment types foreach (Gateway::getPaymentTypeLinks() as $type) { $variables["\${$type}_link"] = URL::to("/payment/{$invitation->invitation_key}/{$type}"); } $data['body'] = str_replace(array_keys($variables), array_values($variables), $emailTemplate); $data['body'] = preg_replace_callback('/\\{\\{\\$?(.*)\\}\\}/', $this->advancedTemplateHandler, $data['body']); $data['link'] = $invitation->getLink(); $data['entityType'] = $entityType; $data['invoice_id'] = $invoice->id; $fromEmail = $invitation->user->email; $response = $this->sendTo($invitation->contact->email, $fromEmail, $accountName, $subject, $view, $data); if ($response !== true) { return $response; } Activity::emailInvoice($invitation); } if (!$invoice->isSent()) { $invoice->invoice_status_id = INVOICE_STATUS_SENT; $invoice->save(); } $account->loadLocalizationSettings(); Event::fire(new InvoiceSent($invoice)); return $response; }
/** * Add or Edit Form */ public function invoiceProfile($invoice_id) { // Validation Rules $validator = Validator::make(['invoice_id' => $invoice_id], ['invoice_id' => 'integer']); // If Validation Fails if ($validator->fails()) { return redirect('/customers')->withErrors($validator->messages()->toArray()); } // Get the invoice model $invoice = new Invoice($invoice_id); // Invoice Items as an array $items = $invoice->getItems(); // All Items Collection $all_items = Item::all(); // Return the Invoice Profile View return view('invoices.profile', ['invoice' => $invoice, 'items' => $items->getArray(), 'all_items' => $all_items->getArray()]); }
public function index() { $invoices = Invoice::scope()->with('client', 'user')->where('invoices.is_quote', '=', true)->orderBy('created_at', 'desc')->get(); $invoices = Utils::remapPublicIds($invoices); $response = json_encode($invoices, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(count($invoices)); return Response::make($response, 200, $headers); }
protected function getDatatableActions($entityType) { return [[trans('texts.edit_invoice'), function ($model) { return URL::to("invoices/{$model->public_id}/edit"); }, function ($model) { return Invoice::canEditItem($model); }]]; }
/** * Get the validation rules that apply to the request. * * @return array */ public function rules() { if ($this->action == ACTION_ARCHIVE) { return []; } $publicId = $this->route('invoices'); $invoiceId = Invoice::getPrivateId($publicId); $rules = ['invoice_items' => 'valid_invoice_items', 'invoice_number' => 'unique:invoices,invoice_number,' . $invoiceId . ',id,account_id,' . Auth::user()->account_id, 'discount' => 'positive']; return $rules; }
/** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $input = $this->input(); $invoice = Invoice::scope($input['invoice'])->invoices()->firstOrFail(); $rules = ['client' => 'required', 'invoice' => 'required', 'amount' => "required|numeric|between:0.01,{$invoice->balance}", 'payment_date' => 'required']; if (!empty($input['payment_type_id']) && $input['payment_type_id'] == PAYMENT_TYPE_CREDIT) { $rules['payment_type_id'] = 'has_credit:' . $input['client'] . ',' . $input['amount']; } return $rules; }
/** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $input = $this->input(); $invoice = Invoice::scope($input['invoice'])->firstOrFail(); $rules = array('client' => 'required', 'invoice' => 'required', 'amount' => "required|less_than:{$invoice->balance}|positive"); if ($input['payment_type_id'] == PAYMENT_TYPE_CREDIT) { $rules['payment_type_id'] = 'has_credit:' . $input['client'] . ',' . $input['amount']; } return $rules; }
/** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $publicId = Request::get('public_id'); $invoiceId = $publicId ? Invoice::getPrivateId($publicId) : ''; $rules = ['client.contacts' => 'valid_contacts', 'invoice_number' => 'required|unique:invoices,invoice_number,' . $invoiceId . ',id,account_id,' . Auth::user()->account_id, 'discount' => 'positive']; /* There's a problem parsing the dates if (Request::get('is_recurring') && Request::get('start_date') && Request::get('end_date')) { $rules['end_date'] = 'after' . Request::get('start_date'); } */ return $rules; }
/** * Execute the console command. * * @return mixed */ public function handle() { $force = $this->option('force'); $account = $this->argument('account'); $accounts = null; if ($account) { $accounts = Account::find($account)->get(); } else { $accounts = Account::all(); } $latestInvoice = $this->invoice->latest()->first(); $invoiceYear = Carbon::parse($latestInvoice->created_at)->year; if (Carbon::now()->year > $invoiceYear || $force) { $accounts->transform(function ($a) { /** @var Account $a */ $a->invoice_number_counter = 1; $a->update(); }); $this->info('The counter has been resetted successfully for ' . $accounts->count() . ' account(s).'); } }
/** * Display the specified resource. * * @param int $id * @return Response */ public function show($publicId) { $client = Client::withTrashed()->scope($publicId)->with('contacts', 'size', 'industry')->firstOrFail(); Utils::trackViewed($client->getDisplayName(), ENTITY_CLIENT); $actionLinks = [['label' => trans('texts.new_task'), 'url' => '/tasks/create/' . $client->public_id]]; if (Utils::isPro()) { array_push($actionLinks, ['label' => trans('texts.new_quote'), 'url' => '/quotes/create/' . $client->public_id]); } array_push($actionLinks, ['label' => trans('texts.enter_payment'), 'url' => '/payments/create/' . $client->public_id], ['label' => trans('texts.enter_credit'), 'url' => '/credits/create/' . $client->public_id]); $data = array('actionLinks' => $actionLinks, 'showBreadcrumbs' => false, 'client' => $client, 'credit' => $client->getTotalCredit(), 'title' => trans('texts.view_client'), 'hasRecurringInvoices' => Invoice::scope()->where('is_recurring', '=', true)->whereClientId($client->id)->count() > 0, 'hasQuotes' => Invoice::scope()->where('is_quote', '=', true)->whereClientId($client->id)->count() > 0, 'hasTasks' => Task::scope()->whereClientId($client->id)->count() > 0, 'gatewayLink' => $client->getGatewayLink()); return View::make('clients.show', $data); }
public function fire() { $this->info(date('Y-m-d') . ' ChargeRenewalInvoices...'); $account = $this->accountRepo->getNinjaAccount(); $invoices = Invoice::whereAccountId($account->id)->whereDueDate(date('Y-m-d'))->with('client')->orderBy('id')->get(); $this->info(count($invoices) . ' invoices found'); foreach ($invoices as $invoice) { $this->info("Charging invoice {$invoice->invoice_number}"); $this->paymentService->autoBillInvoice($invoice); } $this->info('Done'); }
public function sendInvoice(Invoice $invoice, $reminder = false, $pdfString = false) { $invoice->load('invitations', 'client.language', 'account'); $entityType = $invoice->getEntityType(); $client = $invoice->client; $account = $invoice->account; if ($client->trashed()) { return trans('texts.email_errors.inactive_client'); } elseif ($invoice->trashed()) { return trans('texts.email_errors.inactive_invoice'); } $account->loadLocalizationSettings($client); $emailTemplate = $account->getEmailTemplate($reminder ?: $entityType); $emailSubject = $account->getEmailSubject($reminder ?: $entityType); $sent = false; if ($account->attatchPDF() && !$pdfString) { $pdfString = $invoice->getPDFString(); } foreach ($invoice->invitations as $invitation) { $response = $this->sendInvitation($invitation, $invoice, $emailTemplate, $emailSubject, $pdfString); if ($response === true) { $sent = true; } } $account->loadLocalizationSettings(); if ($sent === true) { if ($invoice->is_quote) { event(new QuoteWasEmailed($invoice)); } else { event(new InvoiceWasEmailed($invoice)); } } return $response; }
public function sendInvoice(Invoice $invoice, $reminder = false, $pdfString = false) { $invoice->load('invitations', 'client.language', 'account'); $entityType = $invoice->getEntityType(); $client = $invoice->client; $account = $invoice->account; if ($invoice->trashed() || $client->trashed()) { return false; } $account->loadLocalizationSettings($client); $emailTemplate = $account->getEmailTemplate($reminder ?: $entityType); $emailSubject = $account->getEmailSubject($reminder ?: $entityType); $sent = false; if ($account->attatchPDF() && !$pdfString) { $pdfString = $invoice->getPDFString(); } foreach ($invoice->invitations as $invitation) { if ($this->sendInvitation($invitation, $invoice, $emailTemplate, $emailSubject, $pdfString)) { $sent = true; } } $account->loadLocalizationSettings(); if ($sent === true) { Event::fire(new InvoiceSent($invoice)); } return $sent ?: trans('texts.email_error'); }
public function sendInvoice(Invoice $invoice) { $invoice->load('invitations', 'client', 'account'); $entityType = $invoice->getEntityType(); $view = 'invoice'; $subject = trans("texts.{$entityType}_subject", ['invoice' => $invoice->invoice_number, 'account' => $invoice->account->getDisplayName()]); $accountName = $invoice->account->getDisplayName(); $emailTemplate = $invoice->account->getEmailTemplate($entityType); $invoiceAmount = Utils::formatMoney($invoice->getRequestedAmount(), $invoice->client->currency_id); foreach ($invoice->invitations as $invitation) { if (!$invitation->user || !$invitation->user->email) { return false; } if (!$invitation->contact || !$invitation->contact->email) { return false; } $invitation->sent_date = \Carbon::now()->toDateTimeString(); $invitation->save(); $variables = ['$footer' => $invoice->account->getEmailFooter(), '$link' => $invitation->getLink(), '$client' => $invoice->client->getDisplayName(), '$account' => $accountName, '$contact' => $invitation->contact->getDisplayName(), '$amount' => $invoiceAmount]; $data['body'] = str_replace(array_keys($variables), array_values($variables), $emailTemplate); $data['link'] = $invitation->getLink(); $data['entityType'] = $entityType; $data['invoice_id'] = $invoice->id; $fromEmail = $invitation->user->email; $this->sendTo($invitation->contact->email, $fromEmail, $accountName, $subject, $view, $data); Activity::emailInvoice($invitation); } if (!$invoice->isSent()) { $invoice->invoice_status_id = INVOICE_STATUS_SENT; $invoice->save(); } Event::fire(new InvoiceSent($invoice)); }
/** * Get the validation rules that apply to the request. * * @return array */ public function rules() { if (!$this->invoice_id || !$this->amount) { return ['invoice_id' => 'required', 'amount' => 'required']; } $invoice = Invoice::scope($this->invoice_id)->firstOrFail(); $this->merge(['invoice_id' => $invoice->id, 'client_id' => $invoice->client->id]); $rules = array('amount' => "required|less_than:{$invoice->balance}|positive"); if ($this->payment_type_id == PAYMENT_TYPE_CREDIT) { $rules['payment_type_id'] = 'has_credit:' . $invoice->client->public_id . ',' . $this->amount; } return $rules; }
public function entity() { $invoice = parent::entity(); // support loading an invoice by its invoice number if ($this->invoice_number && !$invoice) { $invoice = Invoice::scope()->whereInvoiceNumber($this->invoice_number)->withTrashed()->firstOrFail(); } // eager load the invoice items if ($invoice && !$invoice->relationLoaded('invoice_items')) { $invoice->load('invoice_items'); } return $invoice; }