1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-09-20 08:21:34 +02:00
invoiceninja/app/Models/Invoice.php

667 lines
17 KiB
PHP
Raw Normal View History

2015-03-18 00:39:03 +01:00
<?php namespace App\Models;
2015-03-16 22:45:25 +01:00
2015-09-29 12:21:57 +02:00
use Utils;
2015-10-20 10:23:38 +02:00
use DateTime;
2015-03-31 11:38:24 +02:00
use Illuminate\Database\Eloquent\SoftDeletes;
2015-11-08 09:43:49 +01:00
use Laracasts\Presenter\PresentableTrait;
use App\Models\BalanceAffecting;
2015-11-24 20:45:38 +01:00
use App\Models\Client;
2015-10-28 20:22:07 +01:00
use App\Events\QuoteWasCreated;
use App\Events\QuoteWasUpdated;
use App\Events\InvoiceWasCreated;
use App\Events\InvoiceWasUpdated;
2015-10-29 15:42:05 +01:00
use App\Events\InvoiceInvitationWasEmailed;
use App\Events\QuoteInvitationWasEmailed;
2015-10-28 20:22:07 +01:00
class Invoice extends EntityModel implements BalanceAffecting
2015-03-16 22:45:25 +01:00
{
2015-11-08 09:43:49 +01:00
use PresentableTrait;
2015-11-16 20:21:48 +01:00
use OwnedByClientTrait;
2015-10-25 08:13:06 +01:00
use SoftDeletes {
SoftDeletes::trashed as parentTrashed;
}
2015-11-08 09:43:49 +01:00
protected $presenter = 'App\Ninja\Presenters\InvoicePresenter';
2015-03-31 11:38:24 +02:00
protected $dates = ['deleted_at'];
2015-04-21 22:09:45 +02:00
protected $casts = [
'is_recurring' => 'boolean',
2015-06-10 10:34:20 +02:00
'has_tasks' => 'boolean',
'auto_bill' => 'boolean',
2015-04-21 22:09:45 +02:00
];
2015-11-24 20:45:38 +01:00
// used for custom invoice numbers
2015-10-22 20:48:12 +02:00
public static $patternFields = [
'counter',
'custom1',
'custom2',
'userId',
'year',
'date:',
];
2015-10-28 20:22:07 +01:00
2015-11-24 20:45:38 +01:00
public static $fieldInvoiceNumber = 'invoice_number';
public static $fieldInvoiceDate = 'invoice_date';
public static $fieldDueDate = 'due_date';
public static $fieldAmount = 'amount';
public static $fieldPaid = 'paid';
public static $fieldNotes = 'notes';
public static $fieldTerms = 'terms';
public static function getImportColumns()
{
return [
Client::$fieldName,
Invoice::$fieldInvoiceNumber,
Invoice::$fieldInvoiceDate,
Invoice::$fieldDueDate,
Invoice::$fieldAmount,
Invoice::$fieldPaid,
Invoice::$fieldNotes,
Invoice::$fieldTerms,
];
}
public static function getImportMap()
{
return [
2015-11-25 10:35:24 +01:00
'number^po' => 'invoice_number',
'amount' => 'amount',
2015-11-24 20:45:38 +01:00
'organization' => 'name',
2015-11-25 10:35:24 +01:00
'paid^date' => 'paid',
'invoice_date|create_date' => 'invoice_date',
2015-11-24 20:45:38 +01:00
'terms' => 'terms',
'notes' => 'notes',
];
}
2015-10-28 20:22:07 +01:00
public function getRoute()
{
$entityType = $this->getEntityType();
return "/{$entityType}s/{$this->public_id}/edit";
}
public function getDisplayName()
{
return $this->is_recurring ? trans('texts.recurring') : $this->invoice_number;
}
2015-11-02 07:51:57 +01:00
public function affectsBalance()
{
return !$this->is_quote && !$this->is_recurring;
}
2015-10-28 20:22:07 +01:00
public function getAdjustment()
{
2015-11-02 07:51:57 +01:00
if (!$this->affectsBalance()) {
2015-10-28 20:22:07 +01:00
return 0;
}
return $this->getRawAdjustment();
}
private function getRawAdjustment()
{
return floatval($this->amount) - floatval($this->getOriginal('amount'));
}
public function isChanged()
{
if ($this->getRawAdjustment() != 0) {
return true;
}
foreach ([
'invoice_number',
'po_number',
'invoice_date',
'due_date',
'terms',
'public_notes',
'invoice_footer',
'partial'
] as $field) {
if ($this->$field != $this->getOriginal($field)) {
return true;
}
}
return false;
}
public function getAmountPaid()
{
if ($this->is_quote || $this->is_recurring) {
return 0;
}
return ($this->amount - $this->balance);
}
2015-10-25 08:13:06 +01:00
public function trashed()
2015-10-23 13:55:18 +02:00
{
2015-10-25 08:13:06 +01:00
if ($this->client && $this->client->trashed()) {
2015-10-23 13:55:18 +02:00
return true;
}
2015-10-25 08:13:06 +01:00
return self::parentTrashed();
2015-10-23 13:55:18 +02:00
}
2015-03-16 22:45:25 +01:00
public function account()
{
2015-03-31 11:38:24 +02:00
return $this->belongsTo('App\Models\Account');
2015-03-16 22:45:25 +01:00
}
public function user()
{
2015-09-25 11:57:40 +02:00
return $this->belongsTo('App\Models\User')->withTrashed();
2015-03-16 22:45:25 +01:00
}
public function client()
{
2015-03-31 11:38:24 +02:00
return $this->belongsTo('App\Models\Client')->withTrashed();
2015-03-16 22:45:25 +01:00
}
public function invoice_items()
{
2015-03-31 11:38:24 +02:00
return $this->hasMany('App\Models\InvoiceItem')->orderBy('id');
2015-03-16 22:45:25 +01:00
}
public function invoice_status()
{
2015-03-31 11:38:24 +02:00
return $this->belongsTo('App\Models\InvoiceStatus');
2015-03-16 22:45:25 +01:00
}
public function invoice_design()
{
2015-03-31 11:38:24 +02:00
return $this->belongsTo('App\Models\InvoiceDesign');
2015-03-16 22:45:25 +01:00
}
2015-07-07 22:08:16 +02:00
public function recurring_invoice()
{
return $this->belongsTo('App\Models\Invoice');
}
public function recurring_invoices()
{
return $this->hasMany('App\Models\Invoice', 'recurring_invoice_id');
}
2015-03-16 22:45:25 +01:00
public function invitations()
{
2015-03-31 11:38:24 +02:00
return $this->hasMany('App\Models\Invitation')->orderBy('invitations.contact_id');
2015-03-16 22:45:25 +01:00
}
2015-10-29 15:42:05 +01:00
public function markInvitationsSent($notify = false)
{
foreach ($this->invitations as $invitation) {
$this->markInvitationSent($invitation, false, $notify);
}
}
public function markInvitationSent($invitation, $messageId = false, $notify = true)
2015-10-28 20:22:07 +01:00
{
if (!$this->isSent()) {
$this->invoice_status_id = INVOICE_STATUS_SENT;
$this->save();
}
2015-10-29 15:42:05 +01:00
$invitation->markSent($messageId);
// if the user marks it as sent rather than acually sending it
// then we won't track it in the activity log
if (!$notify) {
return;
}
if ($this->is_quote) {
event(new QuoteInvitationWasEmailed($invitation));
} else {
event(new InvoiceInvitationWasEmailed($invitation));
}
2015-10-28 20:22:07 +01:00
}
public function markViewed()
{
if (!$this->isViewed()) {
$this->invoice_status_id = INVOICE_STATUS_VIEWED;
$this->save();
}
}
2015-11-18 15:40:50 +01:00
public function updatePaidStatus($save = true)
2015-10-28 20:22:07 +01:00
{
2015-11-18 23:02:01 +01:00
$statusId = false;
if ($this->amount > 0 && $this->balance == 0) {
$statusId = INVOICE_STATUS_PAID;
} elseif ($this->balance > 0 && $this->balance < $this->amount) {
$statusId = INVOICE_STATUS_PARTIAL;
} elseif ($this->isPartial() && $this->balance > 0) {
$statusId = ($this->balance == $this->amount ? INVOICE_STATUS_SENT : INVOICE_STATUS_PARTIAL);
}
if ($statusId && $statusId != $this->invoice_status_id) {
$this->invoice_status_id = $statusId;
2015-11-18 15:40:50 +01:00
if ($save) {
$this->save();
}
2015-10-28 20:22:07 +01:00
}
}
public function updateBalances($balanceAdjustment, $partial = 0)
{
if ($this->is_deleted) {
return;
}
2015-10-28 20:22:07 +01:00
$this->balance = $this->balance + $balanceAdjustment;
if ($this->partial > 0) {
$this->partial = $partial;
}
$this->save();
}
2015-03-16 22:45:25 +01:00
public function getName()
{
return $this->is_recurring ? trans('texts.recurring') : $this->invoice_number;
2015-03-16 22:45:25 +01:00
}
2015-04-22 23:40:21 +02:00
public function getFileName()
{
$entityType = $this->getEntityType();
return trans("texts.$entityType") . '_' . $this->invoice_number . '.pdf';
}
2015-05-09 20:25:16 +02:00
public function getPDFPath()
{
return storage_path() . '/pdfcache/cache-' . $this->id . '.pdf';
}
2015-07-29 21:55:12 +02:00
public static function calcLink($invoice)
{
return link_to('invoices/' . $invoice->public_id, $invoice->invoice_number);
}
2015-03-16 22:45:25 +01:00
public function getLink()
{
2015-07-29 21:55:12 +02:00
return self::calcLink($this);
2015-03-16 22:45:25 +01:00
}
public function getEntityType()
{
return $this->is_quote ? ENTITY_QUOTE : ENTITY_INVOICE;
}
public function isSent()
{
return $this->invoice_status_id >= INVOICE_STATUS_SENT;
}
public function isViewed()
{
return $this->invoice_status_id >= INVOICE_STATUS_VIEWED;
}
2015-11-18 23:02:01 +01:00
public function isPartial()
{
return $this->invoice_status_id >= INVOICE_STATUS_PARTIAL;
}
2015-03-16 22:45:25 +01:00
public function isPaid()
{
return $this->invoice_status_id >= INVOICE_STATUS_PAID;
}
2015-04-16 21:57:12 +02:00
public function getRequestedAmount()
{
return $this->partial > 0 ? $this->partial : $this->balance;
}
2015-03-16 22:45:25 +01:00
public function hidePrivateFields()
{
$this->setVisible([
'invoice_number',
'discount',
'is_amount_discount',
'po_number',
'invoice_date',
'due_date',
'terms',
'invoice_footer',
'public_notes',
'amount',
'balance',
'invoice_items',
'client',
'tax_name',
'tax_rate',
'account',
'invoice_design',
'invoice_design_id',
'is_pro',
'is_quote',
'custom_value1',
'custom_value2',
'custom_taxes1',
'custom_taxes2',
2015-04-16 19:12:56 +02:00
'partial',
2015-06-10 10:34:20 +02:00
'has_tasks',
2015-10-11 16:41:09 +02:00
'custom_text_value1',
'custom_text_value2',
]);
2015-03-16 22:45:25 +01:00
$this->client->setVisible([
'name',
'id_number',
'vat_number',
'address1',
'address2',
'city',
'state',
'postal_code',
'work_phone',
'payment_terms',
'contacts',
'country',
'currency_id',
'custom_value1',
'custom_value2',
]);
2015-03-16 22:45:25 +01:00
$this->account->setVisible([
'name',
'id_number',
'vat_number',
'address1',
'address2',
'city',
'state',
'postal_code',
'work_phone',
'work_email',
'country',
'currency_id',
'custom_label1',
'custom_value1',
'custom_label2',
'custom_value2',
'custom_client_label1',
'custom_client_label2',
'primary_color',
'secondary_color',
'hide_quantity',
'hide_paid_to_date',
'custom_invoice_label1',
'custom_invoice_label2',
'pdf_email_attachment',
2015-09-07 11:07:55 +02:00
'show_item_taxes',
2015-10-11 16:41:09 +02:00
'custom_invoice_text_label1',
'custom_invoice_text_label2',
]);
2015-03-16 22:45:25 +01:00
foreach ($this->invoice_items as $invoiceItem) {
$invoiceItem->setVisible([
'product_key',
'notes',
'cost',
'qty',
'tax_name',
'tax_rate',
]);
2015-03-16 22:45:25 +01:00
}
foreach ($this->client->contacts as $contact) {
$contact->setVisible([
'first_name',
'last_name',
'email',
'phone',
]);
2015-03-16 22:45:25 +01:00
}
return $this;
}
2015-10-15 16:14:13 +02:00
public function getSchedule()
{
if (!$this->start_date || !$this->is_recurring || !$this->frequency_id) {
return false;
}
2015-10-20 10:23:38 +02:00
$startDate = $this->getOriginal('last_sent_date') ?: $this->getOriginal('start_date');
2015-10-22 20:48:12 +02:00
$startDate .= ' ' . $this->account->recurring_hour . ':00:00';
2015-10-15 21:37:01 +02:00
$startDate = $this->account->getDateTime($startDate);
2015-10-18 12:37:04 +02:00
$endDate = $this->end_date ? $this->account->getDateTime($this->getOriginal('end_date')) : null;
2015-10-15 21:37:01 +02:00
$timezone = $this->account->getTimezone();
2015-10-15 16:14:13 +02:00
$rule = $this->getRecurrenceRule();
$rule = new \Recurr\Rule("{$rule}", $startDate, $endDate, $timezone);
// Fix for months with less than 31 days
$transformerConfig = new \Recurr\Transformer\ArrayTransformerConfig();
$transformerConfig->enableLastDayOfMonthFix();
$transformer = new \Recurr\Transformer\ArrayTransformer();
$transformer->setConfig($transformerConfig);
$dates = $transformer->transform($rule);
if (count($dates) < 2) {
return false;
}
return $dates;
}
public function getNextSendDate()
{
if ($this->start_date && !$this->last_sent_date) {
2015-10-22 20:48:12 +02:00
$startDate = $this->getOriginal('start_date') . ' ' . $this->account->recurring_hour . ':00:00';
2015-10-15 21:37:01 +02:00
return $this->account->getDateTime($startDate);
2015-10-15 16:14:13 +02:00
}
if (!$schedule = $this->getSchedule()) {
return null;
}
if (count($schedule) < 2) {
return null;
}
return $schedule[1]->getStart();
}
public function getPrettySchedule($min = 1, $max = 10)
{
if (!$schedule = $this->getSchedule($max)) {
return null;
}
$dates = [];
for ($i=$min; $i<min($max, count($schedule)); $i++) {
$date = $schedule[$i];
$date = $this->account->formatDate($date->getStart());
$dates[] = $date;
}
return implode('<br/>', $dates);
}
private function getRecurrenceRule()
{
$rule = '';
switch ($this->frequency_id) {
case FREQUENCY_WEEKLY:
$rule = 'FREQ=WEEKLY;';
break;
case FREQUENCY_TWO_WEEKS:
$rule = 'FREQ=WEEKLY;INTERVAL=2;';
break;
case FREQUENCY_FOUR_WEEKS:
$rule = 'FREQ=WEEKLY;INTERVAL=4;';
break;
case FREQUENCY_MONTHLY:
$rule = 'FREQ=MONTHLY;';
break;
case FREQUENCY_THREE_MONTHS:
$rule = 'FREQ=MONTHLY;INTERVAL=3;';
break;
case FREQUENCY_SIX_MONTHS:
$rule = 'FREQ=MONTHLY;INTERVAL=6;';
break;
case FREQUENCY_ANNUALLY:
$rule = 'FREQ=YEARLY;';
break;
}
if ($this->end_date) {
$rule .= 'UNTIL=' . $this->end_date;
}
return $rule;
}
/*
2015-10-20 10:23:38 +02:00
public function shouldSendToday()
{
if (!$nextSendDate = $this->getNextSendDate()) {
return false;
}
return $this->account->getDateTime() >= $nextSendDate;
}
*/
2015-03-16 22:45:25 +01:00
public function shouldSendToday()
{
if (!$this->start_date || strtotime($this->start_date) > strtotime('now')) {
return false;
}
if ($this->end_date && strtotime($this->end_date) < strtotime('now')) {
return false;
}
$dayOfWeekToday = date('w');
$dayOfWeekStart = date('w', strtotime($this->start_date));
$dayOfMonthToday = date('j');
$dayOfMonthStart = date('j', strtotime($this->start_date));
if (!$this->last_sent_date) {
return true;
} else {
$date1 = new DateTime($this->last_sent_date);
$date2 = new DateTime();
$diff = $date2->diff($date1);
$daysSinceLastSent = $diff->format("%a");
$monthsSinceLastSent = ($diff->format('%y') * 12) + $diff->format('%m');
if ($daysSinceLastSent == 0) {
return false;
}
}
switch ($this->frequency_id) {
case FREQUENCY_WEEKLY:
return $daysSinceLastSent >= 7;
case FREQUENCY_TWO_WEEKS:
return $daysSinceLastSent >= 14;
case FREQUENCY_FOUR_WEEKS:
return $daysSinceLastSent >= 28;
case FREQUENCY_MONTHLY:
return $monthsSinceLastSent >= 1;
case FREQUENCY_THREE_MONTHS:
return $monthsSinceLastSent >= 3;
case FREQUENCY_SIX_MONTHS:
return $monthsSinceLastSent >= 6;
case FREQUENCY_ANNUALLY:
return $monthsSinceLastSent >= 12;
default:
return false;
}
return false;
}
2015-09-17 21:01:06 +02:00
2015-10-15 16:14:13 +02:00
public function getReminder()
{
2015-09-17 21:01:06 +02:00
for ($i=1; $i<=3; $i++) {
$field = "enable_reminder{$i}";
if (!$this->account->$field) {
continue;
}
$field = "num_days_reminder{$i}";
$date = date('Y-m-d', strtotime("- {$this->account->$field} days"));
if ($this->due_date == $date) {
return "reminder{$i}";
}
}
return false;
}
2015-10-13 09:11:44 +02:00
public function getPDFString()
2015-09-17 21:01:06 +02:00
{
2015-10-13 09:11:44 +02:00
if (!env('PHANTOMJS_CLOUD_KEY')) {
return false;
2015-09-29 12:21:57 +02:00
}
2015-10-13 09:11:44 +02:00
$invitation = $this->invitations[0];
$link = $invitation->getLink();
$curl = curl_init();
2015-11-28 21:00:24 +01:00
2015-10-13 09:11:44 +02:00
$jsonEncodedData = json_encode([
2015-11-28 21:00:24 +01:00
'url' => "{$link}?phantomjs=true",
'renderType' => 'html',
'outputAsJson' => false,
'renderSettings' => [
'passThroughHeaders' => true,
],
2015-10-13 09:11:44 +02:00
'delayTime' => 1000,
]);
$opts = [
2015-11-28 21:00:24 +01:00
CURLOPT_URL => PHANTOMJS_CLOUD . env('PHANTOMJS_CLOUD_KEY') . '/',
2015-10-13 09:11:44 +02:00
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $jsonEncodedData,
2015-11-28 21:00:24 +01:00
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Content-Length: '.strlen($jsonEncodedData)
],
2015-10-13 09:11:44 +02:00
];
curl_setopt_array($curl, $opts);
$encodedString = strip_tags(curl_exec($curl));
curl_close($curl);
return Utils::decodePDF($encodedString);
2015-09-17 21:01:06 +02:00
}
2015-03-16 22:45:25 +01:00
}
2015-07-12 21:43:45 +02:00
Invoice::creating(function ($invoice) {
if (!$invoice->is_recurring) {
2015-10-22 20:48:12 +02:00
$invoice->account->incrementCounter($invoice);
}
2015-07-12 21:43:45 +02:00
});
Invoice::created(function ($invoice) {
2015-10-28 20:22:07 +01:00
if ($invoice->is_quote) {
event(new QuoteWasCreated($invoice));
} else {
event(new InvoiceWasCreated($invoice));
}
2015-03-16 22:45:25 +01:00
});
Invoice::updating(function ($invoice) {
2015-10-28 20:22:07 +01:00
if ($invoice->is_quote) {
event(new QuoteWasUpdated($invoice));
} else {
event(new InvoiceWasUpdated($invoice));
}
2015-07-12 21:43:45 +02:00
});