Merge branch 'v5-develop' into v5-stable

This commit is contained in:
David Bomba 2023-01-17 18:26:29 +11:00
commit 94d3f2023b
125 changed files with 148865 additions and 147913 deletions

View file

@ -7,35 +7,35 @@ assignees: ''
---
**What version of Invoice Ninja are you running? ie v4.5.25 / v5.0.30**
<!-- Before posting please check our "Troubleshooting" category in the docs:
https://invoiceninja.github.io/docs/self-host-troubleshooting/ -->
**What environment are you running?**
Docker
Shared Hosting
ZIP
Other
## Setup
- Version: <!-- i.e. v4.5.25 / v5.0.30 -->
- Environment: <!-- Docker/Shared Hosting/ZIP/Other -->
**Have you checked log files (storage/logs/) Please provide redacted output**
## Checklist
- Can you replicate the issue on our v5 demo site https://demo.invoiceninja.com pr https://react.invoicing.co/demo?
- Have you searched existing issues?
- Have you reported this to Slack/forum before posting?
**Have you searched existing issues?**
## Describe the bug
<!-- A clear and concise description of the bug. -->
**Have you reported this to Slack/forum before posting?**
### Steps To Reproduce
<!-- Please list the steps to reproduce the issue. -->
**Describe the bug**
A clear and concise description of what the bug is.
### Expected Behavior
<!-- A clear and concise description of what you expected to happen. -->
**Steps To Reproduce**
Please list the steps to reproduce the issue
## Additional context
<!-- Add any other context about the problem here. -->
**Expected behavior**
A clear and concise description of what you expected to happen.
### Screenshots
<!-- If applicable, add screenshots to help explain your problem. -->
**Screenshots**
If applicable, add screenshots to help explain your problem.
### Logs
<!-- Please check the log files (storage/logs/) and provide redacted output -->
```
**Additional context**
Add any other context about the problem here.
<!-- Note: Before posting don't forget to check our "Troubleshooting" category in the [docs](https://invoiceninja.github.io/docs/self-host-troubleshooting/) (https://invoiceninja.github.io/docs/self-host-troubleshooting/) -->
**(v5) Can you replicate the issue on our demo site? https://demo.invoiceninja.com**
```

119
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,119 @@
# Contributing to CONTRIBUTING.md
First off, thanks for taking the time to contribute!
All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions.
> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
> - Star the project
> - Tweet about it
> - Refer this project in your project's readme
> - Mention the project at local meetups and tell your friends/colleagues
## Table of Contents
- [Code of Conduct](#code-of-conduct)
- [I Have a Question](#i-have-a-question)
- [I Want To Contribute](#i-want-to-contribute)
- [Reporting Bugs](#reporting-bugs)
- [Suggesting Enhancements](#suggesting-enhancements)
- [Your First Code Contribution](#your-first-code-contribution)
- [Improving The Documentation](#improving-the-documentation)
- [Styleguides](#styleguides)
- [Commit Messages](#commit-messages)
- [Join The Project Team](#join-the-project-team)
## Code of Conduct
This project and everyone participating in it is governed by the
[CONTRIBUTING.md Code of Conduct](blob/v5-stable/CODE_OF_CONDUCT.md).
By participating, you are expected to uphold this code. Please report unacceptable behavior
to <>.
## I Have a Question
> If you want to ask a question, we assume that you have read the available [Documentation](https://invoiceninja.github.io), Searched the [Forum](https://forum.invoiceninja.com), or tried chatting with us on [Slack](https://invoiceninja.slack.com) [generate a slack invite here](http://slack.invoiceninja.com)
Please reserve issues for bugs, general questions posted in the issues section will be closed and redirected to other support venues.
## I Want To Contribute
> ### Legal Notice
> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. Please note that you'll need to sign the CLA for any PRs to be accepted
### Reporting Bugs
#### Before Submitting a Bug Report
A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible.
- Make sure that you are using the latest version.
- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](https://invoiceninja.github.io). If you are looking for support, you might want to check [this section](#i-have-a-question)).
- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](issues?q=label%3Abug).
- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue.
- Collect information about the bug:
- Stack trace (Traceback)
- OS, Platform and Version (Windows, Linux, macOS, x86, ARM)
- Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant.
- Possibly your input and the output
- Can you reliably reproduce the issue? And can you also reproduce it with older versions?
#### How Do I Submit a Good Bug Report?
> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to <>.
We use GitHub issues to track bugs and errors. If you run into an issue with the project:
- Open an [Issue](/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.)
- Explain the behavior you would expect and the actual behavior.
- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case.
- Provide the information you collected in the previous section.
Once it's filed:
- The project team will label the issue accordingly.
- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced.
- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution).
### Suggesting Enhancements
This section guides you through submitting an enhancement suggestion for CONTRIBUTING.md, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions.
#### Before Submitting an Enhancement
- Make sure that you are using the latest version.
- Read the [documentation]() carefully and find out if the functionality is already covered, maybe by an individual configuration.
- Perform a [search](/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library.
#### How Do I Submit a Good Enhancement Suggestion?
Enhancement suggestions are tracked as [GitHub issues](/issues).
- Use a **clear and descriptive title** for the issue to identify the suggestion.
- Provide a **step-by-step description of the suggested enhancement** in as many details as possible.
- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you.
- You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux.
- **Explain why this enhancement would be useful** to most CONTRIBUTING.md users. You may also want to point out the other projects that solved it better and which could serve as inspiration.
### Your First Code Contribution
All PRs should be created against the v5-develop branch.
## Attribution
This guide is based on the **contributing.md**. [Make your own](https://contributing.md/)!

200
README.md
View file

@ -1,97 +1,103 @@
<p align="center">
<img src="https://raw.githubusercontent.com/hillelcoren/invoice-ninja/master/public/images/round_logo.png" alt="Sublime's custom image"/>
</p>
![v5-develop phpunit](https://github.com/invoiceninja/invoiceninja/workflows/phpunit/badge.svg?branch=v5-develop)
[![Codacy Badge](https://app.codacy.com/project/badge/Grade/d16c78aad8574466bf83232b513ef4fb)](https://www.codacy.com/gh/turbo124/invoiceninja/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=turbo124/invoiceninja&amp;utm_campaign=Badge_Grade)
<a href="https://cla-assistant.io/invoiceninja/invoiceninja"><img src="https://cla-assistant.io/readme/badge/invoiceninja/invoiceninja" alt="CLA assistant" /></a>
# Invoice Ninja 5
## [Hosted](https://www.invoiceninja.com) | [Self-Hosted](https://www.invoiceninja.org)
### We're on Slack, join us at [slack.invoiceninja.com](http://slack.invoiceninja.com), [forum.invoiceninja.com](https://forum.invoiceninja.com) or if you like [StackOverflow](https://stackoverflow.com/tags/invoice-ninja/)
Just make sure to add the `invoice-ninja` tag to your question.
## Introduction
Version 5 of Invoice Ninja is here! We've taken the best parts of version 4 and bolted on all of the most requested features to produce a invoicing application like no other.
All Pro and Enterprise features from the hosted app are included in the open-code. We offer a $30 per year white-label license to remove the Invoice Ninja branding from client facing parts of the app.
* [Videos](https://www.youtube.com/@appinvoiceninja)
* [API Documentation](https://app.swaggerhub.com/apis/invoiceninja/invoiceninja)
* [APP Documentation](https://invoiceninja.github.io/)
* [Support Forum](https://forum.invoiceninja.com)
* [StackOverflow](https://stackoverflow.com/tags/invoice-ninja/)
## Mobile Apps
* [iPhone](https://apps.apple.com/app/id1503970375?platform=iphone)
* [Android](https://play.google.com/store/apps/details?id=com.invoiceninja.app)
## Desktop Apps
* [macOS](https://apps.apple.com/app/id1503970375?platform=mac)
* [Windows](https://microsoft.com/en-us/p/invoice-ninja/9n3f2bbcfdr6)
* [Linux](https://snapcraft.io/invoiceninja)
## Installation Options
* [Docker File](https://hub.docker.com/r/invoiceninja/invoiceninja/)
* [Cloudron](https://cloudron.io/store/com.invoiceninja.cloudronapp.html)
* [Softaculous](https://www.softaculous.com/apps/ecommerce/Invoice_Ninja)
## Recommended Providers
* [Stripe](https://stripe.com/)
* [Postmark](https://postmarkapp.com/)
## Quick Start
```bash
git clone https://github.com/invoiceninja/invoiceninja.git
git checkout v5-stable
cp .env.example .env
composer update
php artisan key:generate
```
Please Note: Your APP_KEY in the .env file is used to encrypt data, if you lose this you will not be able to run the application.
Run if you want to load sample data, remember to configure .env
```
php artisan migrate:fresh --seed && php artisan db:seed && php artisan ninja:create-test-data
```
To run the web server
```
php artisan serve
```
Navigate to (replace ninja.test as required)
```
http://ninja.test:8000/setup - To setup your configuration if you didn't load sample data.
http://ninja.test:8000/ - For Administrator Logon
user: small@example.com
pass: password
http://ninja.test:8000/client/login - For Client Portal
user: user@example.com
pass: password
```
## Credits
* [Hillel Coren](https://hillelcoren.com/)
* [David Bomba](https://github.com/turbo124)
* [Benjamin Beganović](https://github.com/beganovich)
* [All contributors](https://github.com/invoiceninja/invoiceninja/graphs/contributors)
## Security
If you find a security issue with this application please send an email to contact@invoiceninja.com Please follow responsible disclosure procedures if you detect an issue. For further information on responsible disclosure please read [here](https://cheatsheetseries.owasp.org/cheatsheets/Vulnerability_Disclosure_Cheat_Sheet.html)
## License
Invoice Ninja is released under the Elastic License.
See [LICENSE](LICENSE) for details.
<p align="center">
<img src="https://raw.githubusercontent.com/hillelcoren/invoice-ninja/master/public/images/round_logo.png" alt="Sublime's custom image"/>
</p>
![v5-develop phpunit](https://github.com/invoiceninja/invoiceninja/workflows/phpunit/badge.svg?branch=v5-develop)
[![Codacy Badge](https://app.codacy.com/project/badge/Grade/d16c78aad8574466bf83232b513ef4fb)](https://www.codacy.com/gh/turbo124/invoiceninja/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=turbo124/invoiceninja&amp;utm_campaign=Badge_Grade)
<a href="https://cla-assistant.io/invoiceninja/invoiceninja"><img src="https://cla-assistant.io/readme/badge/invoiceninja/invoiceninja" alt="CLA assistant" /></a>
# Invoice Ninja 5
## [Hosted](https://www.invoiceninja.com) | [Self-Hosted](https://www.invoiceninja.org)
Join us on [Slack](http://slack.invoiceninja.com), [Discourse](https://forum.invoiceninja.com) -
or [StackOverflow](https://stackoverflow.com/tags/invoice-ninja/) if you like,
just make sure to add the `invoice-ninja` tag to your question.
## Introduction
Version 5 of Invoice Ninja is here!
We took the best parts of version 4 and add the most requested features
to produce a invoicing application like no other.
All Pro and Enterprise features from the hosted app are included in the open code.
We offer a $30 per year white-label license to remove the Invoice Ninja branding from client facing parts of the app.
* [Videos](https://www.youtube.com/@appinvoiceninja)
* [API Documentation](https://app.swaggerhub.com/apis/invoiceninja/invoiceninja)
* [APP Documentation](https://invoiceninja.github.io/)
* [Support Forum](https://forum.invoiceninja.com)
* [StackOverflow](https://stackoverflow.com/tags/invoice-ninja/)
## Setup
### Mobile Apps
* [iPhone](https://apps.apple.com/app/id1503970375?platform=iphone)
* [Android](https://play.google.com/store/apps/details?id=com.invoiceninja.app)
### Desktop Apps
* [macOS](https://apps.apple.com/app/id1503970375?platform=mac)
* [Windows](https://microsoft.com/en-us/p/invoice-ninja/9n3f2bbcfdr6)
* [Linux](https://snapcraft.io/invoiceninja)
### Installation Options
* [Docker File](https://hub.docker.com/r/invoiceninja/invoiceninja/)
* [Cloudron](https://cloudron.io/store/com.invoiceninja.cloudronapp.html)
* [Softaculous](https://www.softaculous.com/apps/ecommerce/Invoice_Ninja)
### Recommended Providers
* [Stripe](https://stripe.com/)
* [Postmark](https://postmarkapp.com/)
## Quick Hosting Setup
```sh
git clone https://github.com/invoiceninja/invoiceninja.git
git checkout v5-stable
cp .env.example .env
composer update
php artisan key:generate
```
Please Note:
Your APP_KEY in the .env file is used to encrypt data, if you lose this you will not be able to run the application.
Run if you want to load sample data, remember to configure .env
```sh
php artisan migrate:fresh --seed && php artisan db:seed && php artisan ninja:create-test-data
```
To run the web server
```sh
php artisan serve
```
Navigate to (replace localhost with the appropriate domain)
```
http://localhost:8000/setup - To setup your configuration if you did not load sample data.
http://localhost:8000/ - For Administrator Logon
user: small@example.com
pass: password
http://localhost:8000/client/login - For Client Portal
user: user@example.com
pass: password
```
## Credits
* [Hillel Coren](https://hillelcoren.com/)
* [David Bomba](https://github.com/turbo124)
* [Benjamin Beganović](https://github.com/beganovich)
* [All Contributors](https://github.com/invoiceninja/invoiceninja/graphs/contributors)
## Security
If you find a security issue with this application, please send an email to contact@invoiceninja.com.
Please follow responsible disclosure procedures if you detect an issue.
For further information on responsible disclosure please read [here](https://cheatsheetseries.owasp.org/cheatsheets/Vulnerability_Disclosure_Cheat_Sheet.html).
## License
Invoice Ninja is released under the Elastic License.
See [LICENSE](LICENSE) for details.

View file

@ -1 +1 @@
5.5.55
5.5.56

View file

@ -134,6 +134,9 @@ class CreateAccount extends Command
(new CreateCompanyPaymentTerms($company, $user))->handle();
(new CreateCompanyTaskStatuses($company, $user))->handle();
(new VersionCheck())->handle();
$this->warmCache();
}
private function warmCache()
@ -142,25 +145,20 @@ class CreateAccount extends Command
$cached_tables = config('ninja.cached_tables');
foreach ($cached_tables as $name => $class) {
if (! Cache::has($name)) {
// check that the table exists in case the migration is pending
if (! Schema::hasTable((new $class())->getTable())) {
continue;
}
if ($name == 'payment_terms') {
$orderBy = 'num_days';
} elseif ($name == 'fonts') {
$orderBy = 'sort_order';
} elseif (in_array($name, ['currencies', 'industries', 'languages', 'countries', 'banks'])) {
$orderBy = 'name';
} else {
$orderBy = 'id';
}
$tableData = $class::orderBy($orderBy)->get();
if ($tableData->count()) {
Cache::forever($name, $tableData);
}
if ($name == 'payment_terms') {
$orderBy = 'num_days';
} elseif ($name == 'fonts') {
$orderBy = 'sort_order';
} elseif (in_array($name, ['currencies', 'industries', 'languages', 'countries', 'banks'])) {
$orderBy = 'name';
} else {
$orderBy = 'id';
}
$tableData = $class::orderBy($orderBy)->get();
if ($tableData->count()) {
Cache::forever($name, $tableData);
}
}
}
}

View file

@ -437,7 +437,7 @@ class CreateTestData extends Command
'company_id' => $client->company->id,
]);
Document::factory()->count(5)->create([
Document::factory()->count(1)->create([
'user_id' => $client->user->id,
'company_id' => $client->company_id,
'documentable_type' => Vendor::class,

View file

@ -56,7 +56,7 @@ class ReactBuilder extends Command
$directoryIterator = new \RecursiveDirectoryIterator(public_path('react'), \RecursiveDirectoryIterator::SKIP_DOTS);
foreach (new \RecursiveIteratorIterator($directoryIterator) as $file) {
if (str_contains($file->getFileName(), '.js')) {
if (str_contains($file->getFileName(), '.js') && !strpos($file->getFileName(), '.json')) {
if (str_contains($file->getFileName(), 'index.')) {
$includes .= '<script type="module" crossorigin src="/react/'.$file->getFileName().'"></script>'."\n";
} else {

View file

@ -71,7 +71,7 @@ class Kernel extends ConsoleKernel
$schedule->job(new RecurringInvoicesCron)->hourly()->withoutOverlapping()->name('recurring-invoice-job')->onOneServer();
/* Stale Invoice Cleanup*/
$schedule->job(new CleanStaleInvoiceOrder)->hourly()->withoutOverlapping()->name('stale-invoice-job')->onOneServer();
$schedule->job(new CleanStaleInvoiceOrder)->hourlyAt(30)->withoutOverlapping()->name('stale-invoice-job')->onOneServer();
/* Sends recurring invoices*/
$schedule->job(new RecurringExpensesCron)->dailyAt('00:10')->withoutOverlapping()->name('recurring-expense-job')->onOneServer();
@ -89,7 +89,7 @@ class Kernel extends ConsoleKernel
$schedule->job(new SchedulerCheck)->dailyAt('01:10')->withoutOverlapping();
/* Checks for scheduled tasks */
$schedule->job(new TaskScheduler())->dailyAt('06:50')->withoutOverlapping()->name('task-scheduler-job')->onOneServer();
$schedule->job(new TaskScheduler())->hourlyAt(10)->withoutOverlapping()->name('task-scheduler-job')->onOneServer();
/* Performs system maintenance such as pruning the backup table */
$schedule->job(new SystemMaintenance)->sundays()->at('02:30')->withoutOverlapping()->name('system-maintenance-job')->onOneServer();

View file

@ -12,15 +12,16 @@
namespace App\DataMapper;
/**
* ClientSettings.
* BaseSettings.
*/
class BaseSettings
{
//@deprecated
public function __construct($obj)
{
foreach ($obj as $key => $value) {
$obj->{$key} = $value;
}
// foreach ($obj as $key => $value) {
// $obj->{$key} = $value;
// }
}
public static function setCasts($obj, $casts)
@ -57,7 +58,4 @@ class BaseSettings
}
}
public static function castSingleAttribute($key, $data)
{
}
}

View file

@ -447,7 +447,17 @@ class CompanySettings extends BaseSettings
public $mailgun_domain = '';
public $auto_bill_standard_invoices = false;
public $email_alignment = 'center'; // center , left, right
public $show_email_footer = true;
public static $casts = [
'show_email_footer' => 'bool',
'email_alignment' => 'string',
'auto_bill_standard_invoices' => 'bool',
'postmark_secret' => 'string',
'mailgun_secret' => 'string',
'mailgun_domain' => 'string',
@ -724,8 +734,9 @@ class CompanySettings extends BaseSettings
* and always ensure an up to date class is returned.
*
* @param $obj
* @deprecated
*/
public function __construct($obj)
public function __construct()
{
// parent::__construct($obj);
}

View file

@ -235,12 +235,17 @@ class EmailTemplateDefaults
public static function emailStatementSubject()
{
return '';
return ctrans('texts.your_statement');
}
public static function emailStatementTemplate()
{
return '';
$statement_message = '<p>$client<br><br>'.self::transformText('client_statement_body').'<br></p>';
return $statement_message;
// return ctrans('texts.client_statement_body', ['start_date' => '$start_date', 'end_date' => '$end_date']);
}
private static function transformText($string)

View file

@ -0,0 +1,96 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\DataMapper;
use App\Models\Client;
use stdClass;
class ClientStatement
{
/**
* Defines the template name
*
* @var string
*/
public string $template = 'client_statement';
/**
* An array of clients hashed_ids
*
* Leave blank if this action should apply to all clients
*
* @var array
*/
public array $clients = [];
/**
* The consts to be used to define the date_range variable of the statement
*/
public const THIS_MONTH = 'this_month';
public const THIS_QUARTER = 'this_quarter';
public const THIS_YEAR = 'this_year';
public const PREVIOUS_MONTH = 'previous_month';
public const PREVIOUS_QUARTER = 'previous_quarter';
public const PREVIOUS_YEAR = 'previous_year';
public const CUSTOM_RANGE = "custom_range";
/**
* The date range the statement should include
*
* @var string
*/
public string $date_range = 'this_month';
/**
* If a custom range is select for the date range then
* the start_date should be supplied in Y-m-d format
*
* @var string
*/
public string $start_date = '';
/**
* If a custom range is select for the date range then
* the end_date should be supplied in Y-m-d format
*
* @var string
*/
public string $end_date = '';
/**
* Flag which allows the payment table
* to be shown
*
* @var boolean
*/
public bool $show_payments_table = true;
/**
* Flag which allows the aging table
* to be shown
*
* @var boolean
*/
public bool $show_aging_table = true;
/**
* String const which defines whether
* the invoices to be shown are either
* paid or unpaid
*
* @var string
*/
public string $status = 'paid'; // paid | unpaid
}

View file

@ -16,12 +16,10 @@ use App\Exceptions\InternalPDFFailure;
use App\Exceptions\PhantomPDFFailure;
use App\Exceptions\StripeConnectFailure;
use App\Utils\Ninja;
use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;
use Illuminate\Database\Eloquent\RelationNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Illuminate\Http\Request;
@ -34,11 +32,11 @@ use Illuminate\Validation\ValidationException;
use PDOException;
use Sentry\Laravel\Integration;
use Sentry\State\Scope;
use Swift_TransportException;
use Symfony\Component\Console\Exception\CommandNotFoundException;
use Symfony\Component\Debug\Exception\FatalThrowableError;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use League\Flysystem\UnableToCreateDirectory;
use Throwable;
class Handler extends ExceptionHandler
@ -50,7 +48,30 @@ class Handler extends ExceptionHandler
*/
protected $dontReport = [
PDOException::class,
//Swift_TransportException::class,
MaxAttemptsExceededException::class,
CommandNotFoundException::class,
ValidationException::class,
ModelNotFoundException::class,
NotFoundHttpException::class,
];
protected $selfHostDontReport = [
FilePermissionsFailure::class,
PDOException::class,
MaxAttemptsExceededException::class,
CommandNotFoundException::class,
ValidationException::class,
ModelNotFoundException::class,
NotFoundHttpException::class,
UnableToCreateDirectory::class,
GuzzleHttp\Exception\ConnectException::class,
Symfony\Component\Process\Exception\RuntimeException::class,
InvalidArgumentException::class,
RuntimeException::class,
];
protected $hostedDontReport = [
PDOException::class,
MaxAttemptsExceededException::class,
CommandNotFoundException::class,
ValidationException::class,
@ -80,11 +101,10 @@ class Handler extends ExceptionHandler
{
if (! Schema::hasTable('accounts')) {
info('account table not found');
return;
}
if (Ninja::isHosted() && ! ($exception instanceof ValidationException)) {
if (Ninja::isHosted()) {
Integration::configureScope(function (Scope $scope): void {
$name = 'hosted@invoiceninja.com';
@ -105,8 +125,11 @@ class Handler extends ExceptionHandler
]);
});
Integration::captureUnhandledException($exception);
} elseif (app()->bound('sentry') && $this->shouldReport($exception)) {
if ($this->validException($exception) && $this->sentryShouldReport($exception)) {
Integration::captureUnhandledException($exception);
}
} elseif (app()->bound('sentry')) {
Integration::configureScope(function (Scope $scope): void {
if (auth()->guard('contact') && auth()->guard('contact')->user() && auth()->guard('contact')->user()->company->account->report_errors) {
$scope->setUser([
@ -123,7 +146,7 @@ class Handler extends ExceptionHandler
}
});
if ($this->validException($exception)) {
if ($this->validException($exception) && $this->sentryShouldReport($exception)) {
Integration::captureUnhandledException($exception);
}
}
@ -160,6 +183,23 @@ class Handler extends ExceptionHandler
return true;
}
/**
* Determine if the exception is in the "do not report" list.
*
* @param \Throwable $e
* @return bool
*/
protected function sentryShouldReport(Throwable $e)
{
if(Ninja::isHosted())
$dontReport = array_merge($this->hostedDontReport, $this->internalDontReport);
else
$dontReport = array_merge($this->selfHostDontReport, $this->internalDontReport);
return is_null(Arr::first($dontReport, fn ($type) => $e instanceof $type));
}
/**
* Render an exception into an HTTP response.
*
@ -180,8 +220,8 @@ class Handler extends ExceptionHandler
return response()->json(['message' => $exception->getMessage()], 500);
} elseif ($exception instanceof ThrottleRequestsException && $request->expectsJson()) {
return response()->json(['message'=>'Too many requests'], 429);
} elseif ($exception instanceof FatalThrowableError && $request->expectsJson()) {
return response()->json(['message'=>'Fatal error'], 500);
// } elseif ($exception instanceof FatalThrowableError && $request->expectsJson()) {
// return response()->json(['message'=>'Fatal error'], 500); //@deprecated
} elseif ($exception instanceof AuthorizationException) {
return response()->json(['message'=> $exception->getMessage()], 401);
} elseif ($exception instanceof TokenMismatchException) {
@ -196,7 +236,6 @@ class Handler extends ExceptionHandler
} elseif ($exception instanceof MethodNotAllowedHttpException && $request->expectsJson()) {
return response()->json(['message'=>'Method not supported for this route'], 404);
} elseif ($exception instanceof ValidationException && $request->expectsJson()) {
// nlog($exception->validator->getMessageBag());
return response()->json(['message' => 'The given data was invalid.', 'errors' => $exception->validator->getMessageBag()], 422);
} elseif ($exception instanceof RelationNotFoundException && $request->expectsJson()) {
return response()->json(['message' => "Relation `{$exception->relation}` is not a valid include."], 400);
@ -208,13 +247,6 @@ class Handler extends ExceptionHandler
return response()->json(['message' => $exception->getMessage()], 400);
}
// elseif ($exception instanceof QueryException) {
// return response()->json(['message' => 'We had a problem executing this query. Please retry.'], 500);
// }
return parent::render($request, $exception);
}

View file

@ -0,0 +1,32 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Factory;
use App\Models\Scheduler;
class SchedulerFactory
{
public static function create($company_id, $user_id) :Scheduler
{
$scheduler = new Scheduler;
$scheduler->name = '';
$scheduler->company_id = $company_id;
$scheduler->user_id = $user_id;
$scheduler->parameters = [];
$scheduler->is_paused = false;
$scheduler->is_deleted = false;
$scheduler->template = '';
return $scheduler;
}
}

View file

@ -68,28 +68,22 @@ class BankIntegrationFilters extends QueryFilters
return $this->builder;
}
$table = 'bank_integrations';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
return $this->builder->where(function ($query) use ($filters) {
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
$query->orWhereNull('deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
$query->orWhere(function ($query) {
$query->whereNotNull('deleted_at');
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
$query->orWhere('is_deleted', 1);
}
});
}
@ -107,19 +101,6 @@ class BankIntegrationFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
}
/**
* Filters the query by the users company ID.
*

View file

@ -134,14 +134,12 @@ class BankTransactionFilters extends QueryFilters
return $this->builder;
}
$table = 'bank_transactions';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
return $this->builder->where(function ($query) use ($filters) {
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
$query->orWhereNull('deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {

View file

@ -55,45 +55,6 @@ class BankTransactionRuleFilters extends QueryFilters
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'bank_transaction_rules';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*

View file

@ -122,45 +122,6 @@ class ClientFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'clients';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -176,59 +137,7 @@ class ClientFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
$query = DB::table('clients')
->join('companies', 'companies.id', '=', 'clients.company_id')
->join('client_contacts', 'client_contacts.client_id', '=', 'clients.id')
->where('clients.company_id', '=', $company_id)
->where('client_contacts.is_primary', '=', true)
->where('client_contacts.deleted_at', '=', null)
->select(
DB::raw('COALESCE(clients.country_id, companies.country_id) country_id'),
DB::raw("CONCAT(COALESCE(client_contacts.first_name, ''), ' ', COALESCE(client_contacts.last_name, '')) contact"),
'clients.id',
'clients.name',
'clients.private_notes',
'client_contacts.first_name',
'client_contacts.last_name',
'clients.custom_value1',
'clients.custom_value2',
'clients.custom_value3',
'clients.custom_value4',
'clients.balance',
'clients.last_login',
'clients.created_at',
'clients.created_at as client_created_at',
'client_contacts.phone',
'client_contacts.email',
'clients.deleted_at',
'clients.is_deleted',
'clients.user_id',
'clients.id_number',
'clients.settings'
);
/*
* If the user does not have permissions to view all invoices
* limit the user to only the invoices they have created
*/
if (Gate::denies('view-list', Client::class)) {
$query->where('clients.user_id', '=', $user->id);
}
return $query;
}
/**
* Filters the query by the users company ID.
*

View file

@ -37,45 +37,6 @@ class CompanyGatewayFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'company_gateways';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -89,19 +50,6 @@ class CompanyGatewayFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
return $this->builder;
}
/**
* Filters the query by the users company ID.
*

View file

@ -88,45 +88,6 @@ class CreditFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted - legacy from V1.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'credits';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -140,19 +101,6 @@ class CreditFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
// ..
}
/**
* Filters the query by the users company ID.
*

View file

@ -40,45 +40,6 @@ class DesignFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'designs';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*

View file

@ -64,19 +64,6 @@ class DocumentFilters extends QueryFilters
return $this->builder;
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
return $this->builder;
}
/**
* Filters the query by the users company ID.
*

View file

@ -35,49 +35,10 @@ class ExpenseCategoryFilters extends QueryFilters
return $this->builder;
}
return $this->builder->where('expense_categories.name', 'like', '%'.$filter.'%');
return $this->builder->where('name', 'like', '%'.$filter.'%');
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'expense_categories';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -95,21 +56,6 @@ class ExpenseCategoryFilters extends QueryFilters
return $this->builder;
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
return $this->builder;
}
/**
* Filters the query by the users company ID.
*

View file

@ -69,14 +69,15 @@ class ExpenseFilters extends QueryFilters
return $this->builder;
}
$this->builder->whereNested(function ($query) use($status_parameters){
$this->builder->where(function ($query) use($status_parameters){
if (in_array('logged', $status_parameters)) {
$query->orWhere(function ($query){
$query->where('amount', '>', 0)
->whereNull('invoice_id')
->whereNull('payment_date');
->whereNull('payment_date')
->where('should_be_invoiced',false);
});
}
@ -135,46 +136,6 @@ class ExpenseFilters extends QueryFilters
return $this->builder;
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'expenses';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -192,46 +153,6 @@ class ExpenseFilters extends QueryFilters
return $this->builder;
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
$query = DB::table('expenses')
->join('companies', 'companies.id', '=', 'expenses.company_id')
->where('expenses.company_id', '=', $company_id)
->select(
DB::raw('COALESCE(expenses.country_id, companies.country_id) country_id'),
DB::raw("CONCAT(COALESCE(expense_contacts.first_name, ''), ' ', COALESCE(expense_contacts.last_name, '')) contact"),
'expenses.id',
'expenses.private_notes',
'expenses.custom_value1',
'expenses.custom_value2',
'expenses.custom_value3',
'expenses.custom_value4',
'expenses.created_at',
'expenses.created_at as expense_created_at',
'expenses.deleted_at',
'expenses.is_deleted',
'expenses.user_id',
);
/*
* If the user does not have permissions to view all invoices
* limit the user to only the invoices they have created
*/
if (Gate::denies('view-list', Expense::class)) {
$query->where('expenses.user_id', '=', $user->id);
}
return $query;
}
/**
* Filters the query by the users company ID.
*

View file

@ -47,30 +47,33 @@ class InvoiceFilters extends QueryFilters
$status_parameters = explode(',', $value);
$invoice_filters = [];
if (in_array('all', $status_parameters)) {
return $this->builder;
}
if (in_array('paid', $status_parameters)) {
$invoice_filters[] = Invoice::STATUS_PAID;
}
$this->builder->where(function ($query) use($status_parameters){
if (in_array('unpaid', $status_parameters)) {
$invoice_filters[] = Invoice::STATUS_SENT;
$invoice_filters[] = Invoice::STATUS_PARTIAL;
}
$invoice_filters = [];
if(count($invoice_filters) >0){
$this->builder->whereIn('status_id', $invoice_filters);
}
if (in_array('overdue', $status_parameters)) {
$this->builder->orWhereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->where('due_date', '<', Carbon::now())
->orWhere('partial_due_date', '<', Carbon::now());
}
if (in_array('paid', $status_parameters)) {
$invoice_filters[] = Invoice::STATUS_PAID;
}
if (in_array('unpaid', $status_parameters)) {
$invoice_filters[] = Invoice::STATUS_SENT;
$invoice_filters[] = Invoice::STATUS_PARTIAL;
}
if(count($invoice_filters) >0){
$query->whereIn('status_id', $invoice_filters);
}
if (in_array('overdue', $status_parameters)) {
$query->orWhereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->where('due_date', '<', Carbon::now())
->orWhere('partial_due_date', '<', Carbon::now());
}
});
return $this->builder;
}
@ -106,45 +109,6 @@ class InvoiceFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted - legacy from V1.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'invoices';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* @return Builder
* @throws RuntimeException
@ -221,18 +185,6 @@ class InvoiceFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
}
/**
* Filters the query by the users company ID.
*

View file

@ -42,45 +42,6 @@ class PaymentFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'payments';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Returns a list of payments that can be matched to bank transactions
*/
@ -92,7 +53,8 @@ class PaymentFilters extends QueryFilters
->where('is_deleted',0)
->where(function ($query){
$query->whereNull('transaction_id')
->orWhere("transaction_id","");
->orWhere("transaction_id","")
->company();
});
}
@ -118,18 +80,6 @@ class PaymentFilters extends QueryFilters
return $this->builder->where('number', $number);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
}
/**
* Filters the query by the users company ID.
*

View file

@ -40,45 +40,6 @@ class PaymentTermFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'payment_terms';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -92,19 +53,6 @@ class PaymentTermFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
return $this->builder;
}
/**
* Filters the query by the users company ID.
*

View file

@ -53,45 +53,6 @@ class ProductFilters extends QueryFilters
return $this->builder->where('product_key', $filter);
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'products';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -108,18 +69,6 @@ class ProductFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
}
/**
* Filters the query by the users company ID.
*

View file

@ -42,45 +42,6 @@ class ProjectFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'projects';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -94,43 +55,6 @@ class ProjectFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
$query = DB::table('projects')
->join('companies', 'companies.id', '=', 'projects.company_id')
->where('projects.company_id', '=', $company_id)
->select(
'projects.id',
'projects.name',
'projects.public_notes',
'projects.private_notes',
'projects.created_at',
'projects.created_at as project_created_at',
'projects.deleted_at',
'projects.is_deleted',
'projects.user_id',
'projects.assigned_user_id',
);
/*
* If the user does not have permissions to view all invoices
* limit the user to only the invoices they have created
*/
if (Gate::denies('view-list', Project::class)) {
$query->where('projects.user_id', '=', $user->id);
}
return $query;
}
/**
* Filters the query by the users company ID.
*
@ -138,8 +62,6 @@ class ProjectFilters extends QueryFilters
*/
public function entityFilter()
{
//return $this->builder->whereCompanyId(auth()->user()->company()->id);
// return $this->builder->whereCompanyId(auth()->user()->company()->id)->orWhere('company_id', null);
return $this->builder->company();
}
}

View file

@ -42,27 +42,35 @@ class PurchaseOrderFilters extends QueryFilters
return $this->builder;
}
$po_status = [];
$this->builder->where(function ($query) use ($status_parameters){
if (in_array('draft', $status_parameters)) {
$po_status[] = PurchaseOrder::STATUS_DRAFT;
}
$po_status = [];
if (in_array('sent', $status_parameters)) {
$po_status[] = PurchaseOrder::STATUS_SENT;
}
if (in_array('draft', $status_parameters)) {
$po_status[] = PurchaseOrder::STATUS_DRAFT;
}
if (in_array('accepted', $status_parameters)) {
$po_status[] = PurchaseOrder::STATUS_ACCEPTED;
}
if (in_array('sent', $status_parameters)) {
$query->orWhere(function ($q){
$q->where('status_id', PurchaseOrder::STATUS_SENT)
->whereNull('due_date')
->orWhere('due_date', '>=', now()->toDateString());
});
}
if (in_array('cancelled', $status_parameters)) {
$po_status[] = PurchaseOrder::STATUS_CANCELLED;
}
if (in_array('accepted', $status_parameters)) {
$po_status[] = PurchaseOrder::STATUS_ACCEPTED;
}
if(count($status_parameters) >=1) {
$this->builder->whereIn('status_id', $status_parameters);
}
if (in_array('cancelled', $status_parameters)) {
$po_status[] = PurchaseOrder::STATUS_CANCELLED;
}
if(count($status_parameters) >=1) {
$query->whereIn('status_id', $status_parameters);
}
})
return $this->builder;
}
@ -93,45 +101,6 @@ class PurchaseOrderFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted - legacy from V1.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'purchase_orders';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -145,19 +114,6 @@ class PurchaseOrderFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
// ..
}
/**
* Filters the query by the users company ID.
*

View file

@ -129,6 +129,38 @@ abstract class QueryFilters
return $parts;
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters) {
if (in_array(self::STATUS_ACTIVE, $filters)) {
$query->orWhereNull('deleted_at');
}
if (in_array(self::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) {
$query->whereNotNull('deleted_at')->where('is_deleted',0);
});
}
if (in_array(self::STATUS_DELETED, $filters)) {
$query->orWhere('is_deleted', 1);
}
});
}
/**
* String to operator convertor.
*

View file

@ -66,83 +66,52 @@ class QuoteFilters extends QueryFilters
return $this->builder;
}
$quote_filters = [];
$this->builder->where(function ($query) use ($status_parameters){
if (in_array('draft', $status_parameters)) {
$quote_filters[] = Quote::STATUS_DRAFT;
}
if (in_array('sent', $status_parameters)) {
$query->orWhere(function ($q){
$q->where('status_id', Quote::STATUS_SENT)
->whereNull('due_date')
->orWhere('due_date', '>=', now()->toDateString());
});
}
$quote_filters = [];
if (in_array('sent', $status_parameters)) {
$quote_filters[] = Quote::STATUS_SENT;
}
if (in_array('draft', $status_parameters)) {
$quote_filters[] = Quote::STATUS_DRAFT;
}
if (in_array('approved', $status_parameters)) {
$quote_filters[] = Quote::STATUS_APPROVED;
}
if (in_array('approved', $status_parameters)) {
$quote_filters[] = Quote::STATUS_APPROVED;
}
if(count($quote_filters) >=1){
$this->builder->whereIn('status_id', $quote_filters);
}
if(count($quote_filters) >0){
$query->orWhereIn('status_id', $quote_filters);
}
if (in_array('expired', $status_parameters)) {
$this->builder->orWhere(function ($query){
$query->where('status_id', Quote::STATUS_SENT)
->whereNotNull('due_date')
->where('due_date', '<=', now()->toDateString());
});
}
if (in_array('expired', $status_parameters)) {
$query->orWhere(function ($q){
$q->where('status_id', Quote::STATUS_SENT)
->whereNotNull('due_date')
->where('due_date', '<=', now()->toDateString());
});
}
if (in_array('upcoming', $status_parameters)) {
$this->builder->orWhere(function ($query){
$query->where('status_id', Quote::STATUS_SENT)
->where('due_date', '>=', now()->toDateString())
->orderBy('due_date', 'DESC');
});
}
if (in_array('upcoming', $status_parameters)) {
$query->orWhere(function ($q){
$q->where('status_id', Quote::STATUS_SENT)
->where('due_date', '>=', now()->toDateString())
->orderBy('due_date', 'DESC');
});
}
});
return $this->builder;
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'quotes';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
public function number($number = '')
{
return $this->builder->where('number', 'like', '%'.$number.'%');
@ -164,18 +133,6 @@ class QuoteFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
}
/**
* Filters the query by the users company ID.
*

View file

@ -45,45 +45,6 @@ class RecurringExpenseFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'recurring_expenses';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -97,45 +58,6 @@ class RecurringExpenseFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
$query = DB::table('recurring_expenses')
->join('companies', 'companies.id', '=', 'recurring_expenses.company_id')
->where('recurring_expenses.company_id', '=', $company_id)
->select(
DB::raw('COALESCE(recurring_expenses.country_id, companies.country_id) country_id'),
'recurring_expenses.id',
'recurring_expenses.private_notes',
'recurring_expenses.custom_value1',
'recurring_expenses.custom_value2',
'recurring_expenses.custom_value3',
'recurring_expenses.custom_value4',
'recurring_expenses.created_at',
'recurring_expenses.created_at as expense_created_at',
'recurring_expenses.deleted_at',
'recurring_expenses.is_deleted',
'recurring_expenses.user_id',
);
/*
* If the user does not have permissions to view all invoices
* limit the user to only the invoices they have created
*/
if (Gate::denies('view-list', RecurringExpense::class)) {
$query->where('recurring_expenses.user_id', '=', $user->id);
}
return $query;
}
/**
* Filters the query by the users company ID.
*

View file

@ -65,59 +65,20 @@ class RecurringInvoiceFilters extends QueryFilters
return $this->builder;
}
if (in_array('active', $status_parameters)) {
$this->builder->where('status_id', RecurringInvoice::STATUS_ACTIVE);
}
$recurring_filters = [];
if (in_array('paused', $status_parameters)) {
$this->builder->where('status_id', RecurringInvoice::STATUS_PAUSED);
}
if (in_array('completed', $status_parameters)) {
$this->builder->where('status_id', RecurringInvoice::STATUS_COMPLETED);
}
return $this->builder;
}
if (in_array('active', $status_parameters))
$recurring_filters[] = RecurringInvoice::STATUS_ACTIVE;
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
if (in_array('paused', $status_parameters))
$recurring_filters[] = RecurringInvoice::STATUS_PAUSED;
$table = 'recurring_invoices';
$filters = explode(',', $filter);
if (in_array('completed', $status_parameters))
$recurring_filters[] = RecurringInvoice::STATUS_COMPLETED;
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
return $this->builder->whereIn('status_id', $recurring_filters);
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
@ -133,18 +94,6 @@ class RecurringInvoiceFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
}
/**
* Filters the query by the users company ID.
*

View file

@ -40,45 +40,6 @@ class RecurringQuoteFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'recurring_';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -92,18 +53,6 @@ class RecurringQuoteFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
}
/**
* Filters the query by the users company ID.
*

View file

@ -40,45 +40,6 @@ class SubscriptionFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'subscriptions';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -92,31 +53,6 @@ class SubscriptionFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
$query = DB::table('subscriptions')
->join('companies', 'companies.id', '=', 'subscriptions.company_id')
->where('subscriptions.company_id', '=', $company_id);
/*
* If the user does not have permissions to view all invoices
* limit the user to only the invoices they have created
*/
if (Gate::denies('view-list', Webhook::class)) {
$query->where('subscriptions.user_id', '=', $user->id);
}
return $query;
}
/**
* Filters the query by the users company ID.
*

View file

@ -63,18 +63,6 @@ class SystemLogFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
}
/**
* Filters the query by the users company ID.
*

View file

@ -74,46 +74,6 @@ class TaskFilters extends QueryFilters
return $this->builder;
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'tasks';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
public function project_tasks($project)
{
@ -137,18 +97,6 @@ class TaskFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
}
/**
* Filters the query by the users company ID.
*

View file

@ -37,45 +37,6 @@ class TaskStatusFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'task_statuses';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -89,19 +50,6 @@ class TaskStatusFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
return $this->builder;
}
/**
* Filters the query by the users company ID.
*

View file

@ -37,45 +37,6 @@ class TaxRateFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'tax_rates';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -89,19 +50,6 @@ class TaxRateFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
return $this->builder;
}
/**
* Filters the query by the users company ID.
*

View file

@ -39,45 +39,6 @@ class TokenFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'company_tokens';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -90,42 +51,7 @@ class TokenFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
$query = DB::table('company_tokens')
->join('companies', 'companies.id', '=', 'company_tokens.company_id')
->where('company_tokens.company_id', '=', $company_id)
->select(
'company_tokens.id',
'company_tokens.name',
'company_tokens.token',
'company_tokens.created_at',
'company_tokens.created_at as token_created_at',
'company_tokens.deleted_at',
'company_tokens.is_deleted',
'company_tokens.user_id',
);
/*
* If the user does not have permissions to view all invoices
* limit the user to only the invoices they have created
*/
if (Gate::denies('view-list', CompanyToken::class)) {
$query->where('company_tokens.user_id', '=', $user->id);
}
return $query;
}
/**
* Filters the query by the users company ID.
*

View file

@ -40,44 +40,6 @@ class UserFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'users';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
@ -92,18 +54,6 @@ class UserFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
}
/**
* Filters the query by the users company ID.
*

View file

@ -50,45 +50,6 @@ class VendorFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'vendors';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -102,59 +63,6 @@ class VendorFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
$query = DB::table('vendors')
->join('companies', 'companies.id', '=', 'vendors.company_id')
->join('vendor_contacts', 'vendor_contacts.vendor_id', '=', 'vendors.id')
->where('vendors.company_id', '=', $company_id)
->where('vendor_contacts.is_primary', '=', true)
->where('vendor_contacts.deleted_at', '=', null)
->select(
// DB::raw('COALESCE(vendors.currency_id, companies.currency_id) currency_id'),
DB::raw('COALESCE(vendors.country_id, companies.country_id) country_id'),
DB::raw("CONCAT(COALESCE(vendor_contacts.first_name, ''), ' ', COALESCE(vendor_contacts.last_name, '')) contact"),
'vendors.id',
'vendors.name',
'vendors.private_notes',
'vendor_contacts.first_name',
'vendor_contacts.last_name',
'vendors.custom_value1',
'vendors.custom_value2',
'vendors.custom_value3',
'vendors.custom_value4',
'vendors.balance',
'vendors.last_login',
'vendors.created_at',
'vendors.created_at as vendor_created_at',
'vendor_contacts.phone',
'vendor_contacts.email',
'vendors.deleted_at',
'vendors.is_deleted',
'vendors.user_id',
'vendors.id_number',
'vendors.settings'
);
/*
* If the user does not have permissions to view all invoices
* limit the user to only the invoices they have created
*/
if (Gate::denies('view-list', Vendor::class)) {
$query->where('vendors.user_id', '=', $user->id);
}
return $query;
}
/**
* Filters the query by the users company ID.
*

View file

@ -40,45 +40,6 @@ class WebhookFilters extends QueryFilters
});
}
/**
* Filters the list based on the status
* archived, active, deleted.
*
* @param string filter
* @return Builder
*/
public function status(string $filter = '') : Builder
{
if (strlen($filter) == 0) {
return $this->builder;
}
$table = 'webhooks';
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters, $table) {
$query->whereNull($table.'.id');
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull($table.'.deleted_at');
}
if (in_array(parent::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) use ($table) {
$query->whereNotNull($table.'.deleted_at');
if (! in_array($table, ['users'])) {
$query->where($table.'.is_deleted', '=', 0);
}
});
}
if (in_array(parent::STATUS_DELETED, $filters)) {
$query->orWhere($table.'.is_deleted', '=', 1);
}
});
}
/**
* Sorts the list based on $sort.
*
@ -92,41 +53,6 @@ class WebhookFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
/**
* Returns the base query.
*
* @param int company_id
* @param User $user
* @return Builder
* @deprecated
*/
public function baseQuery(int $company_id, User $user) : Builder
{
$query = DB::table('webhooks')
->join('companies', 'companies.id', '=', 'webhooks.company_id')
->where('webhooks.company_id', '=', $company_id)
->select(
'webhooks.id',
'webhooks.target_url',
'webhooks.event_id',
'webhooks.created_at',
'webhooks.created_at as token_created_at',
'webhooks.deleted_at',
'webhooks.format',
'webhooks.user_id',
);
/*
* If the user does not have permissions to view all invoices
* limit the user to only the invoices they have created
*/
if (Gate::denies('view-list', Webhook::class)) {
$query->where('webhooks.user_id', '=', $user->id);
}
return $query;
}
/**
* Filters the query by the users company ID.
*

View file

@ -65,8 +65,20 @@ class GmailTransport extends AbstractTransport
$body->setRaw($this->base64_encode($bcc_list.$message->toString()));
$service->users_messages->send('me', $body, []);
try{
$service->users_messages->send('me', $body, []);
}
catch(Google\Service\Exception $e) {
/* Need to slow down */
if($e->getCode() == '429') {
sleep(5);
$service->users_messages->send('me', $body, []);
}
}
}
private function base64_encode($data)

View file

@ -87,10 +87,10 @@ class SwissQrGenerator
$qrBill->setUltimateDebtor(
QrBill\DataGroup\Element\StructuredAddress::createWithStreet(
substr($this->client->present()->name(), 0 , 70),
$this->client->address1 ? substr($this->client->address1, 0 , 70) : '_',
$this->client->address2 ? substr($this->client->address2, 0 , 16) : '_',
$this->client->postal_code ? substr($this->client->postal_code, 0, 16) : '_',
$this->client->city ? substr($this->client->city, 0, 35) : '_',
$this->client->address1 ? substr($this->client->address1, 0 , 70) : ' ',
$this->client->address2 ? substr($this->client->address2, 0 , 16) : ' ',
$this->client->postal_code ? substr($this->client->postal_code, 0, 16) : ' ',
$this->client->city ? substr($this->client->city, 0, 35) : ' ',
'CH'
));

View file

@ -109,6 +109,7 @@ class BaseController extends Controller
'company.bank_integrations',
'company.bank_transactions',
'company.bank_transaction_rules',
'company.task_schedulers',
];
private $mini_load = [
@ -128,6 +129,7 @@ class BaseController extends Controller
'company.subscriptions',
'company.bank_integrations',
'company.bank_transaction_rules',
'company.task_schedulers',
];
public function __construct()
@ -465,6 +467,13 @@ class BaseController extends Controller
$query->where('bank_transaction_rules.user_id', $user->id);
}
},
'company.task_schedulers'=> function ($query) use ($updated_at, $user) {
$query->where('updated_at', '>=', $updated_at);
if (! $user->isAdmin()) {
$query->where('schedulers.user_id', $user->id);
}
},
]
);
@ -545,6 +554,12 @@ class BaseController extends Controller
$query->where('bank_transaction_rules.user_id', $user->id);
}
},
'company.task_schedulers'=> function ($query) use ($user) {
if (! $user->isAdmin()) {
$query->where('schedulers.user_id', $user->id);
}
},
]
);
@ -803,6 +818,13 @@ class BaseController extends Controller
$query->where('bank_transactions.user_id', $user->id);
}
},
'company.task_schedulers'=> function ($query) use ($created_at, $user) {
$query->where('created_at', '>=', $created_at);
if (! $user->isAdmin()) {
$query->where('schedulers.user_id', $user->id);
}
},
]
);
@ -984,6 +1006,9 @@ class BaseController extends Controller
//pass report errors bool to front end
$data['report_errors'] = Ninja::isSelfHost() ? $account->report_errors : true;
//pass whitelabel bool to front end
$data['white_label'] = Ninja::isSelfHost() ? $account->isPaid() : false;
//pass referral code to front end
$data['rc'] = request()->has('rc') ? request()->input('rc') : '';
$data['build'] = request()->has('build') ? request()->input('build') : '';

View file

@ -148,6 +148,7 @@ class NinjaPlanController extends Controller
$account->plan_term = 'month';
$account->plan_started = now();
$account->plan_expires = now()->addDays(14);
$account->is_trial=true;
$account->save();
}
@ -216,7 +217,7 @@ class NinjaPlanController extends Controller
if ($account) {
//offer the option to have a free trial
if (! $account->trial_started && ! $account->plan) {
if (!$account->is_trial) {
return $this->trial();
}

View file

@ -109,16 +109,24 @@ class ClientStatementController extends BaseController
*/
public function statement(CreateStatementRequest $request)
{
$send_email = false;
if($request->has('send_email') && $request->send_email == 'true')
$send_email = true;
$pdf = $request->client()->service()->statement(
$request->only(['start_date', 'end_date', 'show_payments_table', 'show_aging_table', 'status'])
$request->only(['start_date', 'end_date', 'show_payments_table', 'show_aging_table', 'status']), $send_email
);
if($send_email)
return response()->json(['message' => ctrans('texts.email_queued')], 200);
if ($pdf) {
return response()->streamDownload(function () use ($pdf) {
echo $pdf;
}, ctrans('texts.statement').'.pdf', ['Content-Type' => 'application/pdf']);
}
return response()->json(['message' => 'Something went wrong. Please check logs.']);
return response()->json(['message' => ctrans('texts.error_title')], 500);
}
}

View file

@ -16,7 +16,6 @@ use App\Factory\CreditFactory;
use App\Factory\InvoiceFactory;
use App\Factory\QuoteFactory;
use App\Factory\RecurringInvoiceFactory;
use App\Http\Requests\Invoice\StoreInvoiceRequest;
use App\Http\Requests\Preview\PreviewInvoiceRequest;
use App\Jobs\Util\PreviewPdf;
use App\Libraries\MultiDB;
@ -44,7 +43,6 @@ use App\Utils\Traits\MakesInvoiceHtml;
use App\Utils\Traits\Pdf\PageNumbering;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Response;
use Turbo124\Beacon\Facades\LightLogs;
@ -109,8 +107,6 @@ class PreviewController extends BaseController
$class = "App\Models\\$entity";
$pdf_class = "App\Jobs\\$entity\\Create{$entity}Pdf";
$entity_obj = $class::whereId($this->decodePrimaryKey(request()->input('entity_id')))->company()->first();
if (! $entity_obj) {
@ -214,6 +210,12 @@ class PreviewController extends BaseController
->first();
}
if($request->has('footer') && !$request->filled('footer') && $request->input('entity') == 'recurring_invoice')
$request->merge(['footer' => $company->settings->invoice_footer]);
if($request->has('terms') && !$request->filled('terms') && $request->input('entity') == 'recurring_invoice')
$request->merge(['terms' => $company->settings->invoice_terms]);
$entity_obj = $repo->save($request->all(), $entity_obj);
if (! $request->has('entity_id')) {
@ -404,8 +406,8 @@ class PreviewController extends BaseController
'user_id' => auth()->user()->id,
'company_id' => auth()->user()->company()->id,
'client_id' => $client->id,
'terms' => 'Sample Terms',
'footer' => 'Sample Footer',
'terms' => auth()->user()->company()->settings->invoice_terms,
'footer' => auth()->user()->company()->settings->invoice_footer,
'public_notes' => 'Sample Public Notes',
]);

View file

@ -502,7 +502,6 @@ class PurchaseOrderController extends BaseController
/*
* Download Purchase Order/s
*/
if ($action == 'bulk_download' && $purchase_orders->count() >= 1) {
$purchase_orders->each(function ($purchase_order) {
if (auth()->user()->cannot('view', $purchase_order)) {

View file

@ -1,4 +1,13 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Http\Controllers;

View file

@ -16,7 +16,6 @@ use App\Models\Client;
use App\Utils\Ninja;
use App\Utils\Traits\AppSetup;
use App\Utils\Traits\ClientGroupSettingsSaver;
use Beganovich\Snappdf\Snappdf;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;
@ -108,6 +107,8 @@ class SelfUpdateController extends BaseController
$zipFile->openFile($file);
$zipFile->deleteFromName(".htaccess");
$zipFile->extractTo(base_path());
$zipFile->close();

View file

@ -11,37 +11,40 @@
namespace App\Http\Controllers;
use App\Http\Requests\TaskScheduler\CreateScheduledTaskRequest;
use App\Http\Requests\TaskScheduler\UpdateScheduleRequest;
use App\Factory\SchedulerFactory;
use App\Http\Requests\TaskScheduler\CreateSchedulerRequest;
use App\Http\Requests\TaskScheduler\ShowSchedulerRequest;
use App\Http\Requests\TaskScheduler\StoreSchedulerRequest;
use App\Http\Requests\TaskScheduler\UpdateSchedulerRequest;
use App\Http\Requests\Task\DestroySchedulerRequest;
use App\Jobs\Ninja\TaskScheduler;
use App\Jobs\Report\ProfitAndLoss;
use App\Models\Scheduler;
use App\Repositories\TaskSchedulerRepository;
use App\Transformers\TaskSchedulerTransformer;
use App\Repositories\SchedulerRepository;
use App\Transformers\SchedulerTransformer;
use App\Utils\Traits\MakesHash;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Symfony\Component\HttpFoundation\Request;
class TaskSchedulerController extends BaseController
{
use MakesHash;
protected $entity_type = Scheduler::class;
protected $entity_transformer = TaskSchedulerTransformer::class;
protected $entity_transformer = SchedulerTransformer::class;
protected TaskSchedulerRepository $scheduler_repository;
public function __construct(TaskSchedulerRepository $scheduler_repository)
public function __construct(protected SchedulerRepository $scheduler_repository)
{
parent::__construct();
$this->scheduler_repository = $scheduler_repository;
}
/**
* @OA\GET(
* path="/api/v1/task_scheduler/",
* path="/api/v1/task_schedulers/",
* operationId="getTaskSchedulers",
* tags={"task_scheduler"},
* tags={"task_schedulers"},
* summary="Task Scheduler Index",
* description="Get all schedulers with associated jobs",
* @OA\Parameter(ref="#/components/parameters/X-Api-Secret"),
@ -67,11 +70,57 @@ class TaskSchedulerController extends BaseController
return $this->listResponse($schedulers);
}
/**
* Show the form for creating a new resource.
*
* @param CreateSchedulerRequest $request The request
*
* @return Response
*
*
* @OA\Get(
* path="/api/v1/invoices/task_schedulers",
* operationId="getTaskScheduler",
* tags={"task_schedulers"},
* summary="Gets a new blank scheduler object",
* description="Returns a blank object with default values",
* @OA\Parameter(ref="#/components/parameters/X-Api-Secret"),
* @OA\Parameter(ref="#/components/parameters/X-Api-Token"),
* @OA\Parameter(ref="#/components/parameters/X-Requested-With"),
* @OA\Parameter(ref="#/components/parameters/include"),
* @OA\Response(
* response=200,
* description="A blank scheduler object",
* @OA\Header(header="X-MINIMUM-CLIENT-VERSION", ref="#/components/headers/X-MINIMUM-CLIENT-VERSION"),
* @OA\Header(header="X-RateLimit-Remaining", ref="#/components/headers/X-RateLimit-Remaining"),
* @OA\Header(header="X-RateLimit-Limit", ref="#/components/headers/X-RateLimit-Limit"),
* @OA\JsonContent(ref="#/components/schemas/TaskSchedulerSchema"),
* ),
* @OA\Response(
* response=422,
* description="Validation error",
* @OA\JsonContent(ref="#/components/schemas/ValidationError"),
*
* ),
* @OA\Response(
* response="default",
* description="Unexpected Error",
* @OA\JsonContent(ref="#/components/schemas/Error"),
* ),
* )
*/
public function create(CreateSchedulerRequest $request)
{
$scheduler = SchedulerFactory::create(auth()->user()->company()->id, auth()->user()->id);
return $this->itemResponse($scheduler);
}
/**
* @OA\Post(
* path="/api/v1/task_scheduler/",
* path="/api/v1/task_schedulers/",
* operationId="createTaskScheduler",
* tags={"task_scheduler"},
* tags={"task_schedulers"},
* summary="Create task scheduler with job ",
* description="Create task scheduler with a job (action(job) request should be sent via request also. Example: We want client report to be job which will be run
* multiple times, we should send the same parameters in the request as we would send if we wanted to get report, see example",
@ -100,19 +149,18 @@ class TaskSchedulerController extends BaseController
* ),
* )
*/
public function store(CreateScheduledTaskRequest $request)
public function store(StoreSchedulerRequest $request)
{
$scheduler = new Scheduler();
$scheduler->service()->store($scheduler, $request);
$scheduler = $this->scheduler_repository->save($request->all(), SchedulerFactory::create(auth()->user()->company()->id, auth()->user()->id));
return $this->itemResponse($scheduler);
}
/**
* @OA\GET(
* path="/api/v1/task_scheduler/{id}",
* path="/api/v1/task_schedulers/{id}",
* operationId="showTaskScheduler",
* tags={"task_scheduler"},
* tags={"task_schedulers"},
* summary="Show given scheduler",
* description="Get scheduler with associated job",
* @OA\Parameter(ref="#/components/parameters/X-Api-Secret"),
@ -142,16 +190,16 @@ class TaskSchedulerController extends BaseController
* ),
* )
*/
public function show(Scheduler $scheduler)
public function show(ShowSchedulerRequest $request, Scheduler $scheduler)
{
return $this->itemResponse($scheduler);
}
/**
* @OA\PUT(
* path="/api/v1/task_scheduler/{id}",
* path="/api/v1/task_schedulers/{id}",
* operationId="updateTaskScheduler",
* tags={"task_scheduler"},
* tags={"task_schedulers"},
* summary="Update task scheduler ",
* description="Update task scheduler",
* @OA\Parameter(ref="#/components/parameters/X-Api-Secret"),
@ -168,7 +216,7 @@ class TaskSchedulerController extends BaseController
* ),
* ), * @OA\RequestBody(
* required=true,
* @OA\JsonContent(ref="#/components/schemas/UpdateTaskSchedulerSchema")
* @OA\JsonContent(ref="#/components/schemas/TaskSchedulerSchema")
* ),
* @OA\Response(
* response=200,
@ -189,18 +237,18 @@ class TaskSchedulerController extends BaseController
* ),
* )
*/
public function update(Scheduler $scheduler, UpdateScheduleRequest $request)
public function update(UpdateSchedulerRequest $request, Scheduler $scheduler)
{
$scheduler->service()->update($scheduler, $request);
$this->scheduler_repository->save($request->all(), $scheduler);
return $this->itemResponse($scheduler);
}
/**
* @OA\DELETE(
* path="/api/v1/task_scheduler/{id}",
* path="/api/v1/task_schedulers/{id}",
* operationId="destroyTaskScheduler",
* tags={"task_scheduler"},
* tags={"task_schedulers"},
* summary="Destroy Task Scheduler",
* description="Destroy task scheduler and its associated job",
* @OA\Parameter(ref="#/components/parameters/X-Api-Secret"),
@ -230,10 +278,83 @@ class TaskSchedulerController extends BaseController
* ),
* )
*/
public function destroy(Scheduler $scheduler)
public function destroy(DestroySchedulerRequest $request, Scheduler $scheduler)
{
$this->scheduler_repository->delete($scheduler);
return $this->itemResponse($scheduler->fresh());
}
/**
* Perform bulk actions on the list view.
*
* @return Response
*
*
* @OA\Post(
* path="/api/v1/task_schedulers/bulk",
* operationId="bulkTaskSchedulerActions",
* tags={"task_schedulers"},
* summary="Performs bulk actions on an array of task_schedulers",
* description="",
* @OA\Parameter(ref="#/components/parameters/X-Api-Secret"),
* @OA\Parameter(ref="#/components/parameters/X-Api-Token"),
* @OA\Parameter(ref="#/components/parameters/X-Requested-With"),
* @OA\Parameter(ref="#/components/parameters/index"),
* @OA\RequestBody(
* description="array of ids",
* required=true,
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(
* type="array",
* @OA\Items(
* type="integer",
* description="Array of hashed IDs to be bulk 'actioned",
* example="[0,1,2,3]",
* ),
* )
* )
* ),
* @OA\Response(
* response=200,
* description="The TaskSchedule response",
* @OA\Header(header="X-MINIMUM-CLIENT-VERSION", ref="#/components/headers/X-MINIMUM-CLIENT-VERSION"),
* @OA\Header(header="X-RateLimit-Remaining", ref="#/components/headers/X-RateLimit-Remaining"),
* @OA\Header(header="X-RateLimit-Limit", ref="#/components/headers/X-RateLimit-Limit"),
* @OA\JsonContent(ref="#/components/schemas/TaskScheduleSchema"),
* ),
* @OA\Response(
* response=422,
* description="Validation error",
* @OA\JsonContent(ref="#/components/schemas/ValidationError"),
* ),
* @OA\Response(
* response="default",
* description="Unexpected Error",
* @OA\JsonContent(ref="#/components/schemas/Error"),
* ),
* )
*/
public function bulk()
{
$action = request()->input('action');
if(!in_array($action, ['archive', 'restore', 'delete']))
return response()->json(['message' => 'Bulk action does not exist'], 400);
$ids = request()->input('ids');
$task_schedulers = Scheduler::withTrashed()->find($this->transformKeys($ids));
$task_schedulers->each(function ($task_scheduler, $key) use ($action) {
if (auth()->user()->can('edit', $task_scheduler)) {
$this->scheduler_repository->{$action}($task_scheduler);
}
});
return $this->listResponse(Scheduler::withTrashed()->whereIn('id', $this->transformKeys($ids)));
}
}

View file

@ -202,6 +202,12 @@ class BillingPortalPurchase extends Component
elseif(strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0){
$this->price = $this->subscription->promo_price;
}
/* Leave this here, otherwise a logged in user will need to reauth... painfully */
if(Auth::guard('contact')->check()){
return $this->getPaymentMethods(auth()->guard('contact')->user());
}
}
/**

View file

@ -32,8 +32,6 @@ class CheckMailRequest extends Request
*/
public function rules()
{
nlog($this->driver);
return [
'mail_driver' => 'required',
'encryption' => 'required_unless:mail_driver,log',

View file

@ -1,39 +0,0 @@
<?php
namespace App\Http\Requests\TaskScheduler;
use App\Http\Requests\Request;
class CreateScheduledTaskRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize(): bool
{
return auth()->user()->isAdmin();
}
public function rules()
{
return [
'paused' => 'sometimes|bool',
'repeat_every' => 'required|string|in:DAY,WEEK,MONTH,3MONTHS,YEAR',
'start_from' => 'sometimes|string',
'job' => 'required',
];
}
public function prepareForValidation()
{
$input = $this->all();
if (! array_key_exists('start_from', $input)) {
$input['start_from'] = now();
}
$this->replace($input);
}
}

View file

@ -0,0 +1,28 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Http\Requests\TaskScheduler;
use App\Http\Requests\Request;
class CreateSchedulerRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize(): bool
{
return auth()->user()->isAdmin();
}
}

View file

@ -0,0 +1,27 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Http\Requests\Task;
use App\Http\Requests\Request;
class DestroySchedulerRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize() : bool
{
return auth()->user()->isAdmin();
}
}

View file

@ -0,0 +1,27 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Http\Requests\TaskScheduler;
use App\Http\Requests\Request;
class ShowSchedulerRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize() : bool
{
return auth()->user()->can('view', $this->scheduler);
}
}

View file

@ -0,0 +1,44 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Http\Requests\TaskScheduler;
use App\Http\Requests\Request;
use Illuminate\Validation\Rule;
class StoreSchedulerRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize(): bool
{
return auth()->user()->isAdmin();
}
public function rules()
{
$rules = [
'name' => ['bail', 'required', Rule::unique('schedulers')->where('company_id', auth()->user()->company()->id)],
'is_paused' => 'bail|sometimes|boolean',
'frequency_id' => 'bail|required|integer|digits_between:1,12',
'next_run' => 'bail|required|date:Y-m-d',
'template' => 'bail|required|string',
'parameters' => 'bail|array',
];
return $rules;
}
}

View file

@ -1,25 +0,0 @@
<?php
namespace App\Http\Requests\TaskScheduler;
use App\Http\Requests\Request;
class UpdateScheduledJobRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize(): bool
{
return auth()->user()->isAdmin();
}
public function rules(): array
{
return [
'action_name' => 'sometimes|string',
];
}
}

View file

@ -8,14 +8,12 @@
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Http\Requests\TaskScheduler;
use App\Http\Requests\Request;
use Carbon\Carbon;
use Illuminate\Validation\Rule;
class UpdateScheduleRequest extends Request
class UpdateSchedulerRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
@ -29,23 +27,17 @@ class UpdateScheduleRequest extends Request
public function rules(): array
{
return [
'paused' => 'sometimes|bool',
'repeat_every' => 'sometimes|string|in:DAY,WEEK,BIWEEKLY,MONTH,3MONTHS,YEAR',
'start_from' => 'sometimes',
'scheduled_run'=>'sometimes',
$rules = [
'name' => ['bail', 'sometimes', Rule::unique('schedulers')->where('company_id', auth()->user()->company()->id)->ignore($this->task_scheduler->id)],
'is_paused' => 'bail|sometimes|boolean',
'frequency_id' => 'bail|required|integer|digits_between:1,12',
'next_run' => 'bail|required|date:Y-m-d',
'template' => 'bail|required|string',
'parameters' => 'bail|array',
];
}
public function prepareForValidation()
{
$input = $this->all();
if (isset($input['start_from'])) {
$input['scheduled_run'] = Carbon::parse((int) $input['start_from']);
$input['start_from'] = Carbon::parse((int) $input['start_from']);
}
$this->replace($input);
return $rules;
}
}

View file

@ -52,29 +52,30 @@ class ClientLedgerBalanceUpdate implements ShouldQueue
MultiDB::setDb($this->company->db);
CompanyLedger::where('balance', 0)->where('client_id', $this->client->id)->orderBy('updated_at', 'ASC')->cursor()->each(function ($company_ledger) {
if ($company_ledger->balance > 0) {
return;
}
if ($company_ledger->balance == 0)
{
$last_record = CompanyLedger::where('client_id', $company_ledger->client_id)
->where('company_id', $company_ledger->company_id)
->where('balance', '!=', 0)
->orderBy('id', 'DESC')
->first();
if (! $last_record) {
$last_record = CompanyLedger::where('client_id', $company_ledger->client_id)
->where('company_id', $company_ledger->company_id)
->orderBy('id', 'DESC')
->first();
->where('company_id', $company_ledger->company_id)
->where('balance', '!=', 0)
->orderBy('id', 'DESC')
->first();
if (! $last_record) {
$last_record = CompanyLedger::where('client_id', $company_ledger->client_id)
->where('company_id', $company_ledger->company_id)
->orderBy('id', 'DESC')
->first();
}
}
// nlog("Updating Balance NOW");
$company_ledger->balance = $last_record->balance + $company_ledger->adjustment;
$company_ledger->save();
$company_ledger->balance = $last_record->balance + $company_ledger->adjustment;
$company_ledger->save();
});
// nlog("Updating company ledger for client ". $this->client->id);
}
}

View file

@ -90,7 +90,7 @@ class NinjaMailerJob implements ShouldQueue
$this->company = Company::where('company_key', $this->nmo->company->company_key)->first();
/* If any pre conditions fail, we return early here */
if($this->preFlightChecksFail())
if(!$this->company || $this->preFlightChecksFail())
return;
/* Set the email driver */
@ -350,7 +350,10 @@ class NinjaMailerJob implements ShouldQueue
{
$sending_user = $this->nmo->settings->gmail_sending_user_id;
$user = User::find($this->decodePrimaryKey($sending_user));
if($sending_user == "0")
$user = $this->company->owner();
else
$user = User::find($this->decodePrimaryKey($sending_user));
return $user;
}
@ -406,14 +409,6 @@ class NinjaMailerJob implements ShouldQueue
private function setOfficeMailer()
{
$user = $this->resolveSendingUser();
/* Always ensure the user is set on the correct account */
// if($user->account_id != $this->company->account_id){
// $this->nmo->settings->email_sending_method = 'default';
// return $this->setMailDriver();
// }
$this->checkValidSendingUser($user);
@ -455,16 +450,6 @@ class NinjaMailerJob implements ShouldQueue
$this->checkValidSendingUser($user);
/* Always ensure the user is set on the correct account */
// if($user->account_id != $this->company->account_id){
// $this->nmo->settings->email_sending_method = 'default';
// return $this->setMailDriver();
// }
$this->checkValidSendingUser($user);
nlog("Sending via {$user->name()}");
$google = (new Google())->init();

View file

@ -21,6 +21,7 @@ use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
//@rebuild it
class TaskScheduler implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
@ -45,9 +46,10 @@ class TaskScheduler implements ShouldQueue
MultiDB::setDB($db);
Scheduler::with('company')
->where('paused', false)
->where('is_paused', false)
->where('is_deleted', false)
->where('scheduled_run', '<', now())
->whereNotNull('next_run')
->where('next_run', '<=', now())
->cursor()
->each(function ($scheduler) {
$this->doJob($scheduler);
@ -57,59 +59,16 @@ class TaskScheduler implements ShouldQueue
private function doJob(Scheduler $scheduler)
{
nlog("Doing job {$scheduler->action_name}");
$company = $scheduler->company;
$parameters = $scheduler->parameters;
switch ($scheduler->action_name) {
case Scheduler::CREATE_CLIENT_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'contacts.csv');
break;
case Scheduler::CREATE_CLIENT_CONTACT_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'clients.csv');
break;
case Scheduler::CREATE_CREDIT_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'credits.csv');
break;
case Scheduler::CREATE_DOCUMENT_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'documents.csv');
break;
case Scheduler::CREATE_EXPENSE_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'expense.csv');
break;
case Scheduler::CREATE_INVOICE_ITEM_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'invoice_items.csv');
break;
case Scheduler::CREATE_INVOICE_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'invoices.csv');
break;
case Scheduler::CREATE_PAYMENT_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'payments.csv');
break;
case Scheduler::CREATE_PRODUCT_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'products.csv');
break;
case Scheduler::CREATE_PROFIT_AND_LOSS_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'profit_and_loss.csv');
break;
case Scheduler::CREATE_QUOTE_ITEM_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'quote_items.csv');
break;
case Scheduler::CREATE_QUOTE_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'quotes.csv');
break;
case Scheduler::CREATE_RECURRING_INVOICE_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'recurring_invoices.csv');
break;
case Scheduler::CREATE_TASK_REPORT:
SendToAdmin::dispatch($company, $parameters, $scheduler->action_class, 'tasks.csv');
break;
nlog("Doing job {$scheduler->name}");
try {
$scheduler->service()->runTask();
}
catch(\Exception $e){
nlog($e->getMessage());
}
$scheduler->scheduled_run = $scheduler->nextScheduledDate();
$scheduler->save();
}
}

View file

@ -66,13 +66,6 @@ class SendRecurring implements ShouldQueue
// Generate Standard Invoice
$invoice = RecurringInvoiceToInvoiceFactory::create($this->recurring_invoice, $this->recurring_invoice->client);
if ($this->recurring_invoice->auto_bill === 'always') {
$invoice->auto_bill_enabled = true;
} elseif ($this->recurring_invoice->auto_bill === 'optout' || $this->recurring_invoice->auto_bill === 'optin') {
} elseif ($this->recurring_invoice->auto_bill === 'off') {
$invoice->auto_bill_enabled = false;
}
$invoice->date = date('Y-m-d');
nlog("Recurring Invoice Date Set on Invoice = {$invoice->date} - ". now()->format('Y-m-d'));
@ -94,6 +87,14 @@ class SendRecurring implements ShouldQueue
->save();
}
//12-01-2023 i moved this block after fillDefaults to handle if standard invoice auto bill config has been enabled, recurring invoice should override.
if ($this->recurring_invoice->auto_bill === 'always') {
$invoice->auto_bill_enabled = true;
} elseif ($this->recurring_invoice->auto_bill === 'optout' || $this->recurring_invoice->auto_bill === 'optin') {
} elseif ($this->recurring_invoice->auto_bill === 'off') {
$invoice->auto_bill_enabled = false;
}
$invoice = $this->createRecurringInvitations($invoice);
/* 09-01-2022 ensure we create the PDFs at this point in time! */

View file

@ -0,0 +1,94 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Mail\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Attachment;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class ClientStatement extends Mailable
{
/**
* Create a new message instance.
*
* @return void
*/
public function __construct(public array $data){}
/**
* Get the message envelope.
*
* @return \Illuminate\Mail\Mailables\Envelope
*/
public function envelope()
{
return new Envelope(
subject: $this->data['subject'],
tags: [$this->data['company_key']],
replyTo: $this->data['reply_to'],
from: $this->data['from'],
to: $this->data['to'],
bcc: $this->data['bcc']
);
}
/**
* Get the message content definition.
*
* @return \Illuminate\Mail\Mailables\Content
*/
public function content()
{
return new Content(
view: 'email.template.client',
text: 'email.template.text',
with: [
'text_body' => $this->data['body'],
'body' => $this->data['body'],
'whitelabel' => $this->data['whitelabel'],
'settings' => $this->data['settings'],
'whitelabel' => $this->data['whitelabel'],
'logo' => $this->data['logo'],
'signature' => $this->data['signature'],
'company' => $this->data['company'],
'greeting' => $this->data['greeting'],
]
);
}
/**
* Get the attachments for the message.
*
* @return array
*/
public function attachments()
{
$array_of_attachments = [];
foreach($this->data['attachments'] as $attachment)
{
$array_of_attachments[] =
Attachment::fromData(fn () => base64_decode($attachment['file']), $attachment['name'])
->withMime('application/pdf');
}
return $array_of_attachments;
}
}

View file

@ -156,7 +156,11 @@ class PaymentEmailEngine extends BaseEmailEngine
$data['$payment2'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'payment2', $this->payment->custom_value2, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'payment2')];
$data['$payment3'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'payment3', $this->payment->custom_value3, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'payment3')];
$data['$payment4'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'payment4', $this->payment->custom_value4, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'payment4')];
// $data['$type'] = ['value' => $this->payment->type->name ?: '', 'label' => ctrans('texts.payment_type')];
$data['$custom1'] = &$data['$payment1'];
$data['$custom2'] = &$data['$payment2'];
$data['$custom3'] = &$data['$payment3'];
$data['$custom4'] = &$data['$payment4'];
$data['$client1'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'client1', $this->client->custom_value1, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'client1')];
$data['$client2'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'client2', $this->client->custom_value2, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'client2')];

View file

@ -12,15 +12,12 @@
namespace App\Models;
use App\DataMapper\ClientSettings;
use App\DataMapper\CompanySettings;
use App\Jobs\Entity\CreateEntityPdf;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\UserSessionAttributes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
@ -115,17 +112,17 @@ class BaseModel extends Model
* reference to the parent class.
*
* @param $key The key of property
* @return
* @deprecated
*/
public function getSettingsByKey($key)
{
/* Does Setting Exist @ client level */
if (isset($this->getSettings()->{$key})) {
return $this->getSettings()->{$key};
} else {
return (new CompanySettings($this->company->settings))->{$key};
}
}
// public function getSettingsByKey($key)
// {
// /* Does Setting Exist @ client level */
// if (isset($this->getSettings()->{$key})) {
// return $this->getSettings()->{$key};
// } else {
// return (new CompanySettings($this->company->settings))->{$key};
// }
// }
public function setSettingsByEntity($entity, $settings)
{
@ -170,6 +167,7 @@ class BaseModel extends Model
*/
public function resolveRouteBinding($value, $field = null)
{
if (is_numeric($value)) {
throw new ModelNotFoundException("Record with value {$value} not found");
}

View file

@ -181,6 +181,11 @@ class ClientContact extends Authenticatable implements HasLocalePreference
return $this->hasMany(InvoiceInvitation::class);
}
public function recurring_invoice_invitations()
{
return $this->hasMany(RecurringInvoiceInvitation::class);
}
public function quote_invitations()
{
return $this->hasMany(QuoteInvitation::class);

View file

@ -66,6 +66,7 @@ class Company extends BaseModel
protected $presenter = CompanyPresenter::class;
protected $fillable = [
'invoice_task_hours',
'markdown_enabled',
'calculate_expense_tax_by_amount',
'invoice_expense_documents',
@ -171,6 +172,16 @@ class Company extends BaseModel
return $this->morphMany(Document::class, 'documentable');
}
public function schedulers()
{
return $this->hasMany(Scheduler::class);
}
public function task_schedulers() //alias for schedulers
{
return $this->hasMany(Scheduler::class);
}
public function all_documents()
{
return $this->hasMany(Document::class);

View file

@ -11,8 +11,7 @@
namespace App\Models;
use App\Services\TaskScheduler\TaskSchedulerService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Services\Scheduler\SchedulerService;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
@ -20,8 +19,8 @@ use Illuminate\Support\Carbon;
* @property bool paused
* @property bool is_deleted
* @property \Carbon\Carbon|mixed start_from
* @property string repeat_every
* @property \Carbon\Carbon|mixed scheduled_run
* @property int frequency_id
* @property \Carbon\Carbon|mixed next_run
* @property int company_id
* @property int updated_at
* @property int created_at
@ -33,76 +32,38 @@ use Illuminate\Support\Carbon;
*/
class Scheduler extends BaseModel
{
use HasFactory, SoftDeletes;
use SoftDeletes;
protected $fillable = [
'start_from',
'paused',
'repeat_every',
'name',
'frequency_id',
'next_run',
'scheduled_run',
'action_class',
'action_name',
'template',
'is_paused',
'parameters',
'company_id',
];
protected $casts = [
'start_from' => 'timestamp',
'scheduled_run' => 'timestamp',
'next_run' => 'datetime',
'created_at' => 'timestamp',
'updated_at' => 'timestamp',
'deleted_at' => 'timestamp',
'paused' => 'boolean',
'is_paused' => 'boolean',
'is_deleted' => 'boolean',
'parameters' => 'array',
];
const DAILY = 'DAY';
const WEEKLY = 'WEEK';
const BIWEEKLY = 'BIWEEKLY';
const MONTHLY = 'MONTH';
const QUARTERLY = '3MONTHS';
const ANNUALLY = 'YEAR';
const CREATE_CLIENT_REPORT = 'create_client_report';
const CREATE_CLIENT_CONTACT_REPORT = 'create_client_contact_report';
const CREATE_CREDIT_REPORT = 'create_credit_report';
const CREATE_DOCUMENT_REPORT = 'create_document_report';
const CREATE_EXPENSE_REPORT = 'create_expense_report';
const CREATE_INVOICE_ITEM_REPORT = 'create_invoice_item_report';
const CREATE_INVOICE_REPORT = 'create_invoice_report';
const CREATE_PAYMENT_REPORT = 'create_payment_report';
const CREATE_PRODUCT_REPORT = 'create_product_report';
const CREATE_PROFIT_AND_LOSS_REPORT = 'create_profit_and_loss_report';
const CREATE_QUOTE_ITEM_REPORT = 'create_quote_item_report';
const CREATE_QUOTE_REPORT = 'create_quote_report';
const CREATE_RECURRING_INVOICE_REPORT = 'create_recurring_invoice_report';
const CREATE_TASK_REPORT = 'create_task_report';
protected $appends = [
'hashed_id',
];
/**
* Service entry points.
*/
public function service(): TaskSchedulerService
public function service(): SchedulerService
{
return new TaskSchedulerService($this);
return new SchedulerService($this);
}
public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo
@ -110,43 +71,43 @@ class Scheduler extends BaseModel
return $this->belongsTo(Company::class);
}
public function nextScheduledDate(): ?Carbon
{
$offset = 0;
// public function nextScheduledDate(): ?Carbon
// {
// $offset = 0;
$entity_send_time = $this->company->settings->entity_send_time;
// $entity_send_time = $this->company->settings->entity_send_time;
if ($entity_send_time != 0) {
$timezone = $this->company->timezone();
// if ($entity_send_time != 0) {
// $timezone = $this->company->timezone();
$offset -= $timezone->utc_offset;
$offset += ($entity_send_time * 3600);
}
// $offset -= $timezone->utc_offset;
// $offset += ($entity_send_time * 3600);
// }
/*
As we are firing at UTC+0 if our offset is negative it is technically firing the day before so we always need
to add ON a day - a day = 86400 seconds
*/
// /*
// As we are firing at UTC+0 if our offset is negative it is technically firing the day before so we always need
// to add ON a day - a day = 86400 seconds
// */
if ($offset < 0) {
$offset += 86400;
}
// if ($offset < 0) {
// $offset += 86400;
// }
switch ($this->repeat_every) {
case self::DAILY:
return Carbon::parse($this->scheduled_run)->startOfDay()->addDay()->addSeconds($offset);
case self::WEEKLY:
return Carbon::parse($this->scheduled_run)->startOfDay()->addWeek()->addSeconds($offset);
case self::BIWEEKLY:
return Carbon::parse($this->scheduled_run)->startOfDay()->addWeeks(2)->addSeconds($offset);
case self::MONTHLY:
return Carbon::parse($this->scheduled_run)->startOfDay()->addMonthNoOverflow()->addSeconds($offset);
case self::QUARTERLY:
return Carbon::parse($this->scheduled_run)->startOfDay()->addMonthsNoOverflow(3)->addSeconds($offset);
case self::ANNUALLY:
return Carbon::parse($this->scheduled_run)->startOfDay()->addYearNoOverflow()->addSeconds($offset);
default:
return null;
}
}
// switch ($this->repeat_every) {
// case self::DAILY:
// return Carbon::parse($this->scheduled_run)->startOfDay()->addDay()->addSeconds($offset);
// case self::WEEKLY:
// return Carbon::parse($this->scheduled_run)->startOfDay()->addWeek()->addSeconds($offset);
// case self::BIWEEKLY:
// return Carbon::parse($this->scheduled_run)->startOfDay()->addWeeks(2)->addSeconds($offset);
// case self::MONTHLY:
// return Carbon::parse($this->scheduled_run)->startOfDay()->addMonthNoOverflow()->addSeconds($offset);
// case self::QUARTERLY:
// return Carbon::parse($this->scheduled_run)->startOfDay()->addMonthsNoOverflow(3)->addSeconds($offset);
// case self::ANNUALLY:
// return Carbon::parse($this->scheduled_run)->startOfDay()->addYearNoOverflow()->addSeconds($offset);
// default:
// return null;
// }
// }
}

View file

@ -48,6 +48,7 @@ class ClientContactObserver
$clientContact->invoice_invitations()->delete();
$clientContact->quote_invitations()->delete();
$clientContact->credit_invitations()->delete();
$clientContact->recurring_invoice_invitations()->delete();
}
/**
@ -58,9 +59,9 @@ class ClientContactObserver
*/
public function restored(ClientContact $clientContact)
{
$clientContact->invoice_invitations()->restore();
$clientContact->quote_invitations()->restore();
$clientContact->credit_invitations()->restore();
// $clientContact->invoice_invitations()->restore();
// $clientContact->quote_invitations()->restore();
// $clientContact->credit_invitations()->restore();
}
/**

View file

@ -90,9 +90,7 @@ trait Utilities
nlog("checkout failure");
nlog($_payment);
if (is_array($_payment) && array_key_exists('actions', $_payment) && array_key_exists('response_summary', end($_payment['actions']))) {
$error_message = end($_payment['actions'])['response_summary'];
} elseif (is_array($_payment) && array_key_exists('status', $_payment)) {
if (is_array($_payment) && array_key_exists('status', $_payment)) {
$error_message = $_payment['status'];
}
else {

View file

@ -0,0 +1,31 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Policies;
use App\Models\User;
/**
* Class SchedulerPolicy.
*/
class SchedulerPolicy extends EntityPolicy
{
/**
* Checks if the user has create permissions.
*
* @param User $user
* @return bool
*/
public function create(User $user) : bool
{
return $user->isAdmin();
}
}

View file

@ -36,6 +36,7 @@ use App\Models\Quote;
use App\Models\RecurringExpense;
use App\Models\RecurringInvoice;
use App\Models\RecurringQuote;
use App\Models\Scheduler;
use App\Models\Subscription;
use App\Models\Task;
use App\Models\TaskStatus;
@ -67,6 +68,7 @@ use App\Policies\QuotePolicy;
use App\Policies\RecurringExpensePolicy;
use App\Policies\RecurringInvoicePolicy;
use App\Policies\RecurringQuotePolicy;
use App\Policies\SchedulerPolicy;
use App\Policies\SubscriptionPolicy;
use App\Policies\TaskPolicy;
use App\Policies\TaskStatusPolicy;
@ -109,6 +111,7 @@ class AuthServiceProvider extends ServiceProvider
RecurringExpense::class => RecurringExpensePolicy::class,
RecurringInvoice::class => RecurringInvoicePolicy::class,
RecurringQuote::class => RecurringQuotePolicy::class,
Scheduler::class => SchedulerPolicy::class,
Subscription::class => SubscriptionPolicy::class,
Task::class => TaskPolicy::class,
TaskStatus::class => TaskStatusPolicy::class,

View file

@ -225,6 +225,7 @@ use App\Listeners\User\UpdateUserLastLogin;
use App\Listeners\User\UpdatedUserActivity;
use App\Models\Account;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Company;
use App\Models\CompanyGateway;
use App\Models\CompanyToken;
@ -241,6 +242,7 @@ use App\Models\Subscription;
use App\Models\Task;
use App\Models\User;
use App\Observers\AccountObserver;
use App\Observers\ClientContactObserver;
use App\Observers\ClientObserver;
use App\Observers\CompanyGatewayObserver;
use App\Observers\CompanyObserver;
@ -633,6 +635,7 @@ class EventServiceProvider extends ServiceProvider
Account::observe(AccountObserver::class);
Subscription::observe(SubscriptionObserver::class);
Client::observe(ClientObserver::class);
ClientContact::observe(ClientContactObserver::class);
Company::observe(CompanyObserver::class);
CompanyGateway::observe(CompanyGatewayObserver::class);
CompanyToken::observe(CompanyTokenObserver::class);

View file

@ -11,7 +11,9 @@
namespace App\Providers;
use App\Models\Scheduler;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
@ -27,6 +29,21 @@ class RouteServiceProvider extends ServiceProvider
public function boot()
{
parent::boot();
Route::bind('task_scheduler', function ($value) {
if (is_numeric($value)) {
throw new ModelNotFoundException("Record with value {$value} not found");
}
return Scheduler::query()
->withTrashed()
->where('id', $this->decodePrimaryKey($value))->firstOrFail();
});
}
/**

View file

@ -257,7 +257,8 @@ class PaymentRepository extends BaseRepository {
$payment = $payment->service()->deletePayment();
event(new PaymentWasDeleted($payment, $payment->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
if($payment)
event(new PaymentWasDeleted($payment, $payment->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
return $payment;

View file

@ -0,0 +1,38 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Repositories;
use App\Models\Scheduler;
class SchedulerRepository extends BaseRepository
{
/**
* Saves the scheduler.
*
* @param array $data The data
* @param \App\Models\Scheduler $scheduler The scheduler
*
* @return \App\Models\Scheduler
*/
public function save(array $data, Scheduler $scheduler): Scheduler
{
$scheduler->fill($data);
$scheduler->save();
return $scheduler;
}
}

View file

@ -1,16 +0,0 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Repositories;
class TaskSchedulerRepository extends BaseRepository
{
}

View file

@ -30,19 +30,11 @@ use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
class BankMatchingService implements ShouldQueue, ShouldBeUnique
class BankMatchingService implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $company_id;
protected $db;
public function __construct($company_id, $db)
{
$this->company_id = $company_id;
$this->db = $db;
}
public function __construct(public $company_id, public $db){}
public function handle() :void
{

View file

@ -15,29 +15,34 @@ use App\Models\Client;
use App\Models\Credit;
use App\Services\Client\Merge;
use App\Services\Client\PaymentMethod;
use App\Services\Email\EmailObject;
use App\Services\Email\EmailService;
use App\Utils\Number;
use Illuminate\Database\Eloquent\Collection;
use App\Utils\Traits\MakesDates;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Support\Facades\DB;
class ClientService
{
private $client;
use MakesDates;
public function __construct(Client $client)
{
$this->client = $client;
}
private string $client_start_date;
private string $client_end_date;
public function __construct(private Client $client){}
public function updateBalance(float $amount)
{
try {
\DB::connection(config('database.default'))->transaction(function () use($amount) {
DB::connection(config('database.default'))->transaction(function () use($amount) {
$this->client = Client::withTrashed()->where('id', $this->client->id)->lockForUpdate()->first();
$this->client->balance += $amount;
$this->client->save();
}, 2);
}, 1);
}
catch (\Throwable $throwable) {
nlog("DB ERROR " . $throwable->getMessage());
@ -51,48 +56,50 @@ class ClientService
{
try {
\DB::connection(config('database.default'))->transaction(function () use($balance, $paid_to_date) {
DB::connection(config('database.default'))->transaction(function () use($balance, $paid_to_date) {
$this->client = Client::withTrashed()->where('id', $this->client->id)->lockForUpdate()->first();
$this->client->balance += $balance;
$this->client->paid_to_date += $paid_to_date;
$this->client->save();
}, 2);
}, 1);
}
catch (\Throwable $throwable) {
nlog("DB ERROR " . $throwable->getMessage());
}
return $this;
}
public function updatePaidToDate(float $amount)
{
// $this->client->paid_to_date += $amount;
\DB::connection(config('database.default'))->transaction(function () use($amount) {
DB::connection(config('database.default'))->transaction(function () use($amount) {
$this->client = Client::withTrashed()->where('id', $this->client->id)->lockForUpdate()->first();
$this->client->paid_to_date += $amount;
$this->client->save();
}, 2);
}, 1);
return $this;
}
public function adjustCreditBalance(float $amount)
{
$this->client->credit_balance += $amount;
return $this;
}
public function getCreditBalance() :float
{
$credits = Credit::withTrashed()->where('client_id', $this->client->id)
->where('is_deleted', false)
->where(function ($query) {
@ -102,6 +109,7 @@ class ClientService
->orderBy('created_at', 'ASC');
return Number::roundValue($credits->sum('balance'), $this->client->currency()->precision);
}
public function getCredits()
@ -132,12 +140,71 @@ class ClientService
* Generate the client statement.
*
* @param array $options
* @param bool $send_email determines if we should send this statement direct to the client
*/
public function statement(array $options = [])
public function statement(array $options = [], bool $send_email = false)
{
return (new Statement($this->client, $options))->run();
$statement = (new Statement($this->client, $options));
$pdf = $statement->run();
if($send_email)
return $this->emailStatement($pdf, $statement->options);
return $pdf;
}
/**
* Emails the statement to the client
*
* @param mixed $pdf The pdf blob
* @param array $options The statement options array
* @return void
*/
private function emailStatement($pdf, array $options): void
{
$this->client_start_date = $this->translateDate($options['start_date'], $this->client->date_format(), $this->client->locale());
$this->client_end_date = $this->translateDate($options['end_date'], $this->client->date_format(), $this->client->locale());
$email_service = new EmailService($this->buildStatementMailableData($pdf), $this->client->company);
$email_service->send();
}
/**
* Builds and returns an EmailObject for Client Statements
*
* @param mixed $pdf The PDF to send
* @return EmailObject The EmailObject to send
*/
public function buildStatementMailableData($pdf) :EmailObject
{
$email_object = new EmailObject;
$email_object->to = [new Address($this->client->present()->email(), $this->client->present()->name())];
$email_object->attachments = [['file' => base64_encode($pdf), 'name' => ctrans('texts.statement') . ".pdf"]];
$email_object->settings = $this->client->getMergedSettings();
$email_object->company = $this->client->company;
$email_object->client = $this->client;
$email_object->email_template_subject = 'email_subject_statement';
$email_object->email_template_body = 'email_template_statement';
$email_object->variables = [
'$client' => $this->client->present()->name(),
'$start_date' => $this->client_start_date,
'$end_date' => $this->client_end_date,
];
return $email_object;
}
/**
* Saves the client instance
*
* @return Client The Client Model
*/
public function save() :Client
{
$this->client->save();

View file

@ -32,25 +32,16 @@ class Statement
{
use PdfMakerTrait;
protected Client $client;
/**
* @var Invoice|Payment|null
*/
protected $entity;
protected array $options;
protected bool $rollback = false;
public function __construct(Client $client, array $options)
{
$this->client = $client;
public function __construct(protected Client $client, public array $options){}
$this->options = $options;
}
public function run(): ?string
public function run() :?string
{
$this
->setupOptions()
@ -110,7 +101,7 @@ class Statement
$maker = null;
$state = null;
return $pdf;
}

View file

@ -167,7 +167,7 @@ class CreditService
}
public function adjustBalance($adjustment)
{nlog("adjusting by {$adjustment}");
{
$this->credit->balance += $adjustment;
return $this;

View file

@ -0,0 +1,313 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Services\Email;
use App\DataMapper\EmailTemplateDefaults;
use App\Models\Account;
use App\Models\Company;
use App\Services\Email\EmailObject;
use App\Utils\Ninja;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Mail;
use League\CommonMark\CommonMarkConverter;
use Illuminate\Mail\Attachment;
class EmailDefaults
{
/**
* The settings object for this email
* @var CompanySettings $settings
*/
protected $settings;
/**
* The HTML / Template to use for this email
* @var string $template
*/
private string $template;
/**
* The locale to use for
* translations for this email
*/
private string $locale;
/**
* @param EmailService $email_service The email service class
* @param EmailObject $email_object the email object class
*/
public function __construct(protected EmailService $email_service, public EmailObject $email_object){}
/**
* Entry point for generating
* the defaults for the email object
*
* @return EmailObject $email_object The email object
*/
public function run()
{
$this->settings = $this->email_object->settings;
$this->setLocale()
->setFrom()
->setTemplate()
->setBody()
->setSubject()
->setReplyTo()
->setBcc()
->setAttachments()
->setMetaData()
->setVariables();
return $this->email_object;
}
/**
* Sets the meta data for the Email object
*/
private function setMetaData(): self
{
$this->email_object->company_key = $this->email_service->company->company_key;
$this->email_object->logo = $this->email_service->company->present()->logo();
$this->email_object->signature = $this->email_object->signature ?: $this->settings->email_signature;
$this->email_object->whitelabel = $this->email_object->company->account->isPaid() ? true : false;
return $this;
}
/**
* Sets the locale
*/
private function setLocale(): self
{
if($this->email_object->client)
$this->locale = $this->email_object->client->locale();
elseif($this->email_object->vendor)
$this->locale = $this->email_object->vendor->locale();
else
$this->locale = $this->email_service->company->locale();
App::setLocale($this->locale);
App::forgetInstance('translator');
$t = app('translator');
$t->replace(Ninja::transformTranslations($this->settings));
return $this;
}
/**
* Sets the template
*/
private function setTemplate(): self
{
$this->template = $this->email_object->settings->email_style;
match($this->email_object->settings->email_style){
'light' => $this->template = 'email.template.client',
'dark' => $this->template = 'email.template.client',
'custom' => $this->template = 'email.template.custom',
default => $this->template = 'email.template.client',
};
$this->email_object->html_template = $this->template;
return $this;
}
/**
* Sets the FROM address
*/
private function setFrom(): self
{
if($this->email_object->from)
return $this;
$this->email_object->from = new Address($this->email_service->company->owner()->email, $this->email_service->company->owner()->name());
return $this;
}
/**
* Sets the body of the email
*/
private function setBody(): self
{
if($this->email_object->body){
$this->email_object->body = $this->email_object->body;
}
elseif(strlen($this->email_object->settings->{$this->email_object->email_template_body}) > 3){
$this->email_object->body = $this->email_object->settings->{$this->email_object->email_template_body};
}
else{
$this->email_object->body = EmailTemplateDefaults::getDefaultTemplate($this->email_object->email_template_body, $this->locale);
}
if($this->template == 'email.template.custom'){
$this->email_object->body = (str_replace('$body', $this->email_object->body, $this->email_object->settings->email_style_custom));
}
return $this;
}
/**
* Sets the subject of the email
*/
private function setSubject(): self
{
if ($this->email_object->subject) //where the user updates the subject from the UI
return $this;
elseif(strlen($this->email_object->settings->{$this->email_object->email_template_subject}) > 3)
$this->email_object->subject = $this->email_object->settings->{$this->email_object->email_template_subject};
else
$this->email_object->subject = EmailTemplateDefaults::getDefaultTemplate($this->email_object->email_template_subject, $this->locale);
return $this;
}
/**
* Sets the reply to of the email
*/
private function setReplyTo(): self
{
$reply_to_email = str_contains($this->email_object->settings->reply_to_email, "@") ? $this->email_object->settings->reply_to_email : $this->email_service->company->owner()->email;
$reply_to_name = strlen($this->email_object->settings->reply_to_name) > 3 ? $this->email_object->settings->reply_to_name : $this->email_service->company->owner()->present()->name();
$this->email_object->reply_to = array_merge($this->email_object->reply_to, [new Address($reply_to_email, $reply_to_name)]);
return $this;
}
/**
* Replaces the template placeholders
* with variable values.
*/
public function setVariables(): self
{
$this->email_object->body = strtr($this->email_object->body, $this->email_object->variables);
$this->email_object->subject = strtr($this->email_object->subject, $this->email_object->variables);
if($this->template != 'custom')
$this->email_object->body = $this->parseMarkdownToHtml($this->email_object->body);
return $this;
}
/**
* Sets the BCC of the email
*/
private function setBcc(): self
{
$bccs = [];
$bcc_array = [];
if (strlen($this->email_object->settings->bcc_email) > 1) {
if (Ninja::isHosted() && $this->email_service->company->account->isPaid()) {
$bccs = array_slice(explode(',', str_replace(' ', '', $this->email_object->settings->bcc_email)), 0, 2);
} else {
$bccs(explode(',', str_replace(' ', '', $this->email_object->settings->bcc_email)));
}
}
foreach($bccs as $bcc)
{
$bcc_array[] = new Address($bcc);
}
$this->email_object->bcc = array_merge($this->email_object->bcc, $bcc_array);
return $this;
}
/**
* Sets the CC of the email
* @todo at some point....
*/
private function buildCc()
{
return [
];
}
/**
* Sets the attachments for the email
*
* Note that we base64 encode these, as they
* sometimes may not survive serialization.
*
* We decode these in the Mailable later
*/
private function setAttachments(): self
{
$attachments = [];
if ($this->email_object->settings->document_email_attachment && $this->email_service->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) {
foreach ($this->email_service->company->documents as $document) {
$attachments[] = ['file' => base64_encode($document->getFile()), 'name' => $document->name];
}
}
$this->email_object->attachments = array_merge($this->email_object->attachments, $attachments);
return $this;
}
/**
* Sets the headers for the email
*/
private function setHeaders(): self
{
if($this->email_object->invitation_key)
$this->email_object->headers = array_merge($this->email_object->headers, ['x-invitation-key' => $this->email_object->invitation_key]);
return $this;
}
/**
* Converts any markdown to HTML in the email
*
* @param string $markdown The body to convert
* @return string The parsed markdown response
*/
private function parseMarkdownToHtml(string $markdown): ?string
{
$converter = new CommonMarkConverter([
'allow_unsafe_links' => false,
]);
return $converter->convert($markdown);
}
}

View file

@ -0,0 +1,109 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Services\Email;
use App\Services\Email\EmailObject;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Attachment;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Illuminate\Mail\Mailables\Headers;
class EmailMailable extends Mailable
{
/**
* Create a new message instance.
*
* @return void
*/
public function __construct(public EmailObject $email_object){}
/**
* Get the message envelope.
*
* @return \Illuminate\Mail\Mailables\Envelope
*/
public function envelope()
{
return new Envelope(
subject: $this->email_object->subject,
tags: [$this->email_object->company_key],
replyTo: $this->email_object->reply_to,
from: $this->email_object->from,
to: $this->email_object->to,
bcc: $this->email_object->bcc
);
}
/**
* Get the message content definition.
*
* @return \Illuminate\Mail\Mailables\Content
*/
public function content()
{
return new Content(
view: $this->email_object->html_template,
text: $this->email_object->text_template,
with: [
'text_body' => strip_tags($this->email_object->body), //@todo this is a bit hacky here.
'body' => $this->email_object->body,
'settings' => $this->email_object->settings,
'whitelabel' => $this->email_object->whitelabel,
'logo' => $this->email_object->logo,
'signature' => $this->email_object->signature,
'company' => $this->email_object->company,
'greeting' => ''
]
);
}
/**
* Get the attachments for the message.
*
* @return array
*/
public function attachments()
{
$attachments = [];
foreach($this->email_object->attachments as $file)
{
$attachments[] = Attachment::fromData(fn () => base64_decode($file['file']), $file['name']);
}
return $attachments;
}
/**
* Get the message headers.
*
* @return \Illuminate\Mail\Mailables\Headers
*/
public function headers()
{
return new Headers(
messageId: null,
references: [],
text: $this->email_object->headers,
);
}
}

View file

@ -0,0 +1,515 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Services\Email;
use App\DataMapper\Analytics\EmailFailure;
use App\DataMapper\Analytics\EmailSuccess;
use App\DataMapper\EmailTemplateDefaults;
use App\Events\Invoice\InvoiceWasEmailedAndFailed;
use App\Events\Payment\PaymentWasEmailedAndFailed;
use App\Jobs\Util\SystemLogger;
use App\Libraries\Google\Google;
use App\Libraries\MultiDB;
use App\Models\Account;
use App\Models\ClientContact;
use App\Models\Company;
use App\Models\InvoiceInvitation;
use App\Models\Payment;
use App\Models\SystemLog;
use App\Models\User;
use App\Services\Email\EmailObject;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Mail\Attachment;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailer;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;
use League\CommonMark\CommonMarkConverter;
use Turbo124\Beacon\Facades\LightLogs;
class EmailMailer implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, MakesHash;
public $tries = 3; //number of retries
public $backoff = 30; //seconds to wait until retry
public $deleteWhenMissingModels = true;
public $override;
private $mailer;
protected $client_postmark_secret = false;
protected $client_mailgun_secret = false;
protected $client_mailgun_domain = false;
public function __construct(public EmailService $email_service, public Mailable $email_mailable){}
public function handle(): void
{
MultiDB::setDb($this->email_service->company->db);
/* Perform final checks */
if($this->email_service->preFlightChecksFail())
return;
/* Boot the required driver*/
$this->setMailDriver();
/* Init the mailer*/
$mailer = Mail::mailer($this->mailer);
/* Additional configuration if using a client third party mailer */
if($this->client_postmark_secret)
$mailer->postmark_config($this->client_postmark_secret);
if($this->client_mailgun_secret)
$mailer->mailgun_config($this->client_mailgun_secret, $this->client_mailgun_domain);
/* Attempt the send! */
try {
nlog("Using mailer => ". $this->mailer. " ". now()->toDateTimeString());
$mailer->send($this->email_mailable);
Cache::increment($this->email_service->company->account->key);
LightLogs::create(new EmailSuccess($this->email_service->company->company_key))
->send();
} catch (\Exception | \RuntimeException | \Google\Service\Exception $e) {
nlog("error failed with {$e->getMessage()}");
$this->cleanUpMailers();
$message = $e->getMessage();
/**
* Post mark buries the proper message in a a guzzle response
* this merges a text string with a json object
* need to harvest the ->Message property using the following
*/
if($e instanceof ClientException) { //postmark specific failure
$response = $e->getResponse();
$message_body = json_decode($response->getBody()->getContents());
if($message_body && property_exists($message_body, 'Message')){
$message = $message_body->Message;
nlog($message);
}
}
/* If the is an entity attached to the message send a failure mailer */
$this->entityEmailFailed($message);
/* Don't send postmark failures to Sentry */
if(Ninja::isHosted() && (!$e instanceof ClientException))
app('sentry')->captureException($e);
$message = null;
}
}
/**
* Entity notification when an email fails to send
*
* @todo - rewrite this
* @param string $message
* @return void
*/
private function entityEmailFailed($message)
{
if(!$this->email_service->email_object->entity_id)
return;
switch ($this->email_service->email_object->entity_class) {
case Invoice::class:
$invitation = InvoiceInvitation::withTrashed()->find($this->email_service->email_object->entity_id);
if($invitation)
event(new InvoiceWasEmailedAndFailed($invitation, $this->email_service->company, $message, $this->email_service->email_object->reminder_template, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
break;
case Payment::class:
$payment = Payment::withTrashed()->find($this->email_service->email_object->entity_id);
if($payment)
event(new PaymentWasEmailedAndFailed($payment, $this->email_service->company, $message, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
break;
default:
# code...
break;
}
if ($this->email_service->email_object->client_contact instanceof ClientContact)
$this->logMailError($message, $this->email_service->email_object->client_contact);
}
/**
* Sets the mail driver to use and applies any specific configuration
* the the mailable
*/
private function setMailDriver(): self
{
switch ($this->email_service->email_object->settings->email_sending_method) {
case 'default':
$this->mailer = config('mail.default');
break;
case 'gmail':
$this->mailer = 'gmail';
$this->setGmailMailer();
return $this;
case 'office365':
$this->mailer = 'office365';
$this->setOfficeMailer();
return $this;
case 'client_postmark':
$this->mailer = 'postmark';
$this->setPostmarkMailer();
return $this;
case 'client_mailgun':
$this->mailer = 'mailgun';
$this->setMailgunMailer();
return $this;
default:
break;
}
if(Ninja::isSelfHost())
$this->setSelfHostMultiMailer();
return $this;
}
/**
* Allows configuration of multiple mailers
* per company for use by self hosted users
*/
private function setSelfHostMultiMailer(): void
{
if (env($this->email_service->company->id . '_MAIL_HOST'))
{
config([
'mail.mailers.smtp' => [
'transport' => 'smtp',
'host' => env($this->email_service->company->id . '_MAIL_HOST'),
'port' => env($this->email_service->company->id . '_MAIL_PORT'),
'username' => env($this->email_service->company->id . '_MAIL_USERNAME'),
'password' => env($this->email_service->company->id . '_MAIL_PASSWORD'),
],
]);
if(env($this->email_service->company->id . '_MAIL_FROM_ADDRESS'))
{
$this->email_mailable
->from(env($this->email_service->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->email_service->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME')));
}
}
}
/**
* Ensure we discard any data that is not required
*
* @return void
*/
private function cleanUpMailers(): void
{
$this->client_postmark_secret = false;
$this->client_mailgun_secret = false;
$this->client_mailgun_domain = false;
//always dump the drivers to prevent reuse
app('mail.manager')->forgetMailers();
}
/**
* Check to ensure no cross account
* emails can be sent.
*
* @param User $user
*/
private function checkValidSendingUser($user)
{
/* Always ensure the user is set on the correct account */
if($user->account_id != $this->email_service->company->account_id)
{
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
}
/**
* Resolves the sending user
* when configuring the Mailer
* on behalf of the client
*
* @return User $user
*/
private function resolveSendingUser(): ?User
{
$sending_user = $this->email_service->email_object->settings->gmail_sending_user_id;
if($sending_user == "0")
$user = $this->email_service->company->owner();
else
$user = User::find($this->decodePrimaryKey($sending_user));
return $user;
}
/**
* Configures Mailgun using client supplied secret
* as the Mailer
*/
private function setMailgunMailer()
{
if(strlen($this->email_service->email_object->settings->mailgun_secret) > 2 && strlen($this->email_service->email_object->settings->mailgun_domain) > 2){
$this->client_mailgun_secret = $this->email_service->email_object->settings->mailgun_secret;
$this->client_mailgun_domain = $this->email_service->email_object->settings->mailgun_domain;
}
else{
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
$user = $this->resolveSendingUser();
$this->mailable
->from($user->email, $user->name());
}
/**
* Configures Postmark using client supplied secret
* as the Mailer
*/
private function setPostmarkMailer()
{
if(strlen($this->email_service->email_object->settings->postmark_secret) > 2){
$this->client_postmark_secret = $this->email_service->email_object->settings->postmark_secret;
}
else{
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
$user = $this->resolveSendingUser();
$this->mailable
->from($user->email, $user->name());
}
/**
* Configures Microsoft via Oauth
* as the Mailer
*/
private function setOfficeMailer()
{
$user = $this->resolveSendingUser();
$this->checkValidSendingUser($user);
nlog("Sending via {$user->name()}");
$token = $this->refreshOfficeToken($user);
if($token)
{
$user->oauth_user_token = $token;
$user->save();
}
else {
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
$this->mailable
->from($user->email, $user->name())
->withSymfonyMessage(function ($message) use($token) {
$message->getHeaders()->addTextHeader('gmailtoken', $token);
});
sleep(rand(1,3));
}
/**
* Configures GMail via Oauth
* as the Mailer
*/
private function setGmailMailer()
{
$user = $this->resolveSendingUser();
$this->checkValidSendingUser($user);
nlog("Sending via {$user->name()}");
$google = (new Google())->init();
try{
if ($google->getClient()->isAccessTokenExpired()) {
$google->refreshToken($user);
$user = $user->fresh();
}
$google->getClient()->setAccessToken(json_encode($user->oauth_user_token));
sleep(rand(2,4));
}
catch(\Exception $e) {
$this->logMailError('Gmail Token Invalid', $this->email_service->company->clients()->first());
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
/**
* If the user doesn't have a valid token, notify them
*/
if(!$user->oauth_user_token) {
$this->email_service->company->account->gmailCredentialNotification();
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
/*
* Now that our token is refreshed and valid we can boot the
* mail driver at runtime and also set the token which will persist
* just for this request.
*/
$token = $user->oauth_user_token->access_token;
if(!$token) {
$this->email_service->company->account->gmailCredentialNotification();
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
$this->mailable
->from($user->email, $user->name())
->withSymfonyMessage(function ($message) use($token) {
$message->getHeaders()->addTextHeader('gmailtoken', $token);
});
}
/**
* Logs any errors to the SystemLog
*
* @param string $errors
* @param App\Models\User | App\Models\Client $recipient_object
* @return void
*/
private function logMailError($errors, $recipient_object) :void
{
(new SystemLogger(
$errors,
SystemLog::CATEGORY_MAIL,
SystemLog::EVENT_MAIL_SEND,
SystemLog::TYPE_FAILURE,
$recipient_object,
$this->email_service->company
))->handle();
$job_failure = new EmailFailure($this->email_service->company->company_key);
$job_failure->string_metric5 = 'failed_email';
$job_failure->string_metric6 = substr($errors, 0, 150);
LightLogs::create($job_failure)
->send();
$job_failure = null;
}
/**
* Attempts to refresh the Microsoft refreshToken
*
* @param App\Models\User
* @return mixed
*/
private function refreshOfficeToken(User $user): mixed
{
$expiry = $user->oauth_user_token_expiry ?: now()->subDay();
if($expiry->lt(now()))
{
$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => config('ninja.o365.client_id') ,
'client_secret' => config('ninja.o365.client_secret') ,
'scope' => 'email Mail.Send offline_access profile User.Read openid',
'grant_type' => 'refresh_token',
'refresh_token' => $user->oauth_user_refresh_token
],
])->getBody()->getContents());
if($token){
$user->oauth_user_refresh_token = property_exists($token, 'refresh_token') ? $token->refresh_token : $user->oauth_user_refresh_token;
$user->oauth_user_token = $token->access_token;
$user->oauth_user_token_expiry = now()->addSeconds($token->expires_in);
$user->save();
return $token->access_token;
}
return false;
}
return $user->oauth_user_token;
}
public function failed($exception = null)
{
}
}

View file

@ -0,0 +1,84 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Services\Email;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Company;
use App\Models\User;
use App\Models\Vendor;
use App\Models\VendorContact;
use Illuminate\Mail\Mailables\Address;
/**
* EmailObject.
*/
class EmailObject
{
public array $to = [];
public ?Address $from = null;
public array $reply_to = [];
public array $cc = [];
public array $bcc = [];
public ?string $subject = null;
public ?string $body = null;
public array $attachments = [];
public string $company_key;
public ?object $settings = null;
public bool $whitelabel = false;
public ?string $logo = null;
public ?string $signature = null;
public ?string $greeting = null;
public ?Client $client = null;
public ?Vendor $vendor = null;
public ?User $user = null;
public ?ClientContact $client_contact = null;
public ?VendorContact $vendor_contact = null;
public ?string $email_template_body = null;
public ?string $email_template_subject = null;
public ?string $html_template = null;
public ?string $text_template = 'email.template.text';
public array $headers = [];
public ?string $invitation_key = null;
public ?int $entity_id = null;
public ?string $entity_class = null;
public array $variables = [];
}

View file

@ -0,0 +1,160 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Services\Email;
use App\Models\Company;
use App\Services\Email\EmailObject;
use App\Utils\Ninja;
use Illuminate\Mail\Mailable;
class EmailService
{
/**
* Used to flag whether we force send the email regardless
*
* @var bool $override;
*/
protected bool $override;
public Mailable $mailable;
public function __construct(public EmailObject $email_object, public Company $company){}
/**
* Sends the email via a dispatched job
* @param boolean $override Whether the email should send regardless
* @return void
*/
public function send($override = false) :void
{
$this->override = $override;
$this->setDefaults()
->updateMailable()
->email();
}
public function sendNow($force = false) :void
{
$this->setDefaults()
->updateMailable()
->email($force);
}
private function email($force = false): void
{
if($force)
(new EmailMailer($this, $this->mailable))->handle();
else
EmailMailer::dispatch($this, $this->mailable)->delay(2);
}
private function setDefaults(): self
{
$defaults = new EmailDefaults($this, $this->email_object);
$defaults->run();
return $this;
}
private function updateMailable()
{
$this->mailable = new EmailMailable($this->email_object);
return $this;
}
/**
* On the hosted platform we scan all outbound email for
* spam. This sequence processes the filters we use on all
* emails.
*
* @return bool
*/
public function preFlightChecksFail(): bool
{
/* If we are migrating data we don't want to fire any emails */
if($this->company->is_disabled && !$this->override)
return true;
if(Ninja::isSelfHost())
return false;
/* To handle spam users we drop all emails from flagged accounts */
if($this->company->account && $this->company->account->is_flagged)
return true;
/* On the hosted platform we set default contacts a @example.com email address - we shouldn't send emails to these types of addresses */
if($this->hasInValidEmails())
return true;
/* GMail users are uncapped */
if(in_array($this->email_object->settings->email_sending_method, ['gmail', 'office365', 'client_postmark', 'client_mailgun']))
return false;
/* On the hosted platform, if the user is over the email quotas, we do not send the email. */
if($this->company->account && $this->company->account->emailQuotaExceeded())
return true;
/* If the account is verified, we allow emails to flow */
if($this->company->account && $this->company->account->is_verified_account) {
//11-01-2022
/* Continue to analyse verified accounts in case they later start sending poor quality emails*/
// if(class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class))
// (new \Modules\Admin\Jobs\Account\EmailQuality($this->nmo, $this->company))->run();
return false;
}
/* On the hosted platform if the user has not verified their account we fail here - but still check what they are trying to send! */
if($this->company->account && !$this->company->account->account_sms_verified){
if(class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class))
return (new \Modules\Admin\Jobs\Account\EmailFilter($this->email_object, $this->company))->run();
return true;
}
/* On the hosted platform we actively scan all outbound emails to ensure outbound email quality remains high */
if(class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class))
return (new \Modules\Admin\Jobs\Account\EmailFilter($this->email_object, $this->company))->run();
return false;
}
private function hasInValidEmails(): bool
{
foreach($this->email_object->to as $address_object)
{
if(strpos($address_object->address, '@example.com') !== false)
return true;
if(!str_contains($address_object->address, "@"))
return true;
if($address_object->address == " ")
return true;
}
return false;
}
}

View file

@ -35,12 +35,7 @@ class InvoiceService
{
use MakesHash;
public $invoice;
public function __construct($invoice)
{
$this->invoice = $invoice;
}
public function __construct(public Invoice $invoice){}
/**
* Marks as invoice as paid
@ -531,6 +526,10 @@ class InvoiceService
$this->invoice->exchange_rate = $this->invoice->client->currency()->exchange_rate;
}
if ($settings->auto_bill_standard_invoices) {
$this->invoice->auto_bill_enabled = true;
}
if ($settings->counter_number_applied == 'when_saved') {
$this->invoice->service()->applyNumber()->save();
}

View file

@ -14,16 +14,10 @@ namespace App\Services\Invoice;
use App\Events\Invoice\InvoiceWasPaid;
use App\Events\Payment\PaymentWasCreated;
use App\Factory\PaymentFactory;
use App\Jobs\Invoice\InvoiceWorkflowSettings;
use App\Jobs\Ninja\TransactionLog;
use App\Jobs\Payment\EmailPayment;
use App\Libraries\Currency\Conversion\CurrencyApi;
use App\Models\Client;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent;
use App\Services\AbstractService;
use App\Services\Client\ClientService;
use App\Utils\Ninja;
use App\Utils\Traits\GeneratesCounter;
use Illuminate\Support\Carbon;
@ -57,15 +51,18 @@ class MarkPaid extends AbstractService
$this->invoice = Invoice::withTrashed()->where('id', $this->invoice->id)->lockForUpdate()->first();
$this->payable_balance = $this->invoice->balance;
if($this->invoice)
{
$this->payable_balance = $this->invoice->balance;
$this->invoice
->service()
->setExchangeRate()
->updateBalance($this->payable_balance * -1)
->updatePaidToDate($this->payable_balance)
->setStatus(Invoice::STATUS_PAID)
->save();
$this->invoice
->service()
->setExchangeRate()
->updateBalance($this->payable_balance * -1)
->updatePaidToDate($this->payable_balance)
->setStatus(Invoice::STATUS_PAID)
->save();
}
}, 1);
@ -133,16 +130,6 @@ class MarkPaid extends AbstractService
event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
event(new InvoiceWasPaid($this->invoice, $payment, $payment->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
$transaction = [
'invoice' => $this->invoice->transaction_event(),
'payment' => $payment->transaction_event(),
'client' => $this->invoice->client->transaction_event(),
'credit' => [],
'metadata' => [],
];
// TransactionLog::dispatch(TransactionEvent::INVOICE_MARK_PAID, $transaction, $this->invoice->company->db);
event('eloquent.updated: App\Models\Invoice', $this->invoice);
return $this->invoice;

View file

@ -38,22 +38,20 @@ class DeletePayment
\DB::connection(config('database.default'))->transaction(function () {
if ($this->payment->is_deleted) {
return $this->payment;
}
$this->payment = Payment::withTrashed()->where('id', $this->payment->id)->lockForUpdate()->first();
$this->setStatus(Payment::STATUS_CANCELLED) //sets status of payment
->updateCreditables() //return the credits first
->adjustInvoices()
->deletePaymentables()
->cleanupPayment()
->save();
if ($this->payment && !$this->payment->is_deleted) {
$this->setStatus(Payment::STATUS_CANCELLED) //sets status of payment
->updateCreditables() //return the credits first
->adjustInvoices()
->deletePaymentables()
->cleanupPayment()
->save();
}
}, 2);
}, 1);
return $this->payment;

View file

@ -1,57 +0,0 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Services\Schedule;
class ScheduleService
{
public function __construct(public Scheduler $scheduler) {}
public function scheduleStatement()
{
//Is it for one client
//Is it for all clients
//Is it for all clients excluding these clients
//Frequency
//show aging
//show payments
//paid/unpaid
//When to send? 1st of month
//End of month
//This date
}
public function scheduleReport()
{
//Report type
//same schema as ScheduleStatement
}
public function scheduleEntitySend()
{
//Entity
//Entity Id
//When
}
public function projectStatus()
{
//Project ID
//Tasks - task statuses
}
}

View file

@ -0,0 +1,96 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Services\Scheduler;
use App\Models\Client;
use App\Models\Scheduler;
use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
class SchedulerService
{
use MakesHash;
use MakesDates;
private string $method;
private Client $client;
public function __construct(public Scheduler $scheduler) {}
/**
* Called from the TaskScheduler Cron
*
* @return void
*/
public function runTask(): void
{
$this->{$this->scheduler->template}();
}
private function client_statement()
{
$query = Client::query()
->where('company_id', $this->scheduler->company_id)
->where('is_deleted',0);
//Email only the selected clients
if(count($this->scheduler->parameters['clients']) >= 1)
$query->where('id', $this->transformKeys($this->scheduler->parameters['clients']));
$query->cursor()
->each(function ($_client){
$this->client = $_client;
$statement_properties = $this->calculateStatementProperties();
//work out the date range
$pdf = $_client->service()->statement($statement_properties,true);
//calculate next run dates;
});
}
private function calculateStatementProperties()
{
$start_end = $this->calculateStartAndEndDates();
return [
'start_date' =>$start_end[0],
'end_date' =>$start_end[1],
'show_payments_table' => $this->scheduler->parameters['show_payments_table'],
'show_aging_table' => $this->scheduler->parameters['show_aging_table'],
'status' => $this->scheduler->parameters['status']
];
}
private function calculateStartAndEndDates()
{
return match ($this->scheduler->parameters['date_range']) {
'this_month' => [now()->firstOfMonth()->format('Y-m-d'), now()->lastOfMonth()->format('Y-m-d')],
'this_quarter' => [now()->firstOfQuarter()->format('Y-m-d'), now()->lastOfQuarter()->format('Y-m-d')],
'this_year' => [now()->firstOfYear()->format('Y-m-d'), now()->lastOfYear()->format('Y-m-d')],
'previous_month' => [now()->subMonth()->firstOfMonth()->format('Y-m-d'), now()->subMonth()->lastOfMonth()->format('Y-m-d')],
'previous_quarter' => [now()->subQuarter()->firstOfQuarter()->format('Y-m-d'), now()->subQuarter()->lastOfQuarter()->format('Y-m-d')],
'previous_year' => [now()->subYear()->firstOfYear()->format('Y-m-d'), now()->subYear()->lastOfYear()->format('Y-m-d')],
'custom_range' => [$this->scheduler->parameters['start_date'], $this->scheduler->parameters['end_date']],
default => [now()->firstOfMonth()->format('Y-m-d'), now()->lastOfMonth()->format('Y-m-d')],
};
}
}

View file

@ -38,6 +38,8 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Request;
//@deprecated - never used....
class TaskSchedulerService
{

View file

@ -35,6 +35,7 @@ use App\Models\PurchaseOrder;
use App\Models\Quote;
use App\Models\RecurringExpense;
use App\Models\RecurringInvoice;
use App\Models\Scheduler;
use App\Models\Subscription;
use App\Models\SystemLog;
use App\Models\Task;
@ -106,6 +107,8 @@ class CompanyTransformer extends EntityTransformer
'bank_integrations',
'bank_transactions',
'bank_transaction_rules',
'task_schedulers',
'schedulers',
];
/**
@ -194,6 +197,7 @@ class CompanyTransformer extends EntityTransformer
'convert_payment_currency' => (bool) $company->convert_payment_currency,
'convert_expense_currency' => (bool) $company->convert_expense_currency,
'notify_vendor_when_paid' => (bool) $company->notify_vendor_when_paid,
'invoice_task_hours' => (bool) $company->invoice_task_hours,
];
}
@ -232,6 +236,7 @@ class CompanyTransformer extends EntityTransformer
return $this->includeCollection($company->tokens, $transformer, CompanyToken::class);
}
public function includeBankTransactions(Company $company)
{
$transformer = new BankTransactionTransformer($this->serializer);
@ -240,6 +245,20 @@ class CompanyTransformer extends EntityTransformer
}
public function includeTaskSchedulers(Company $company)
{
$transformer = new SchedulerTransformer($this->serializer);
return $this->includeCollection($company->schedulers, $transformer, Scheduler::class);
}
public function includeSchedulers(Company $company)
{
$transformer = new SchedulerTransformer($this->serializer);
return $this->includeCollection($company->schedulers, $transformer, Scheduler::class);
}
public function includeBankTransactionRules(Company $company)
{
$transformer = new BankTransactionRuleTransformer($this->serializer);

View file

@ -14,7 +14,7 @@ namespace App\Transformers;
use App\Models\Scheduler;
use App\Utils\Traits\MakesHash;
class TaskSchedulerTransformer extends EntityTransformer
class SchedulerTransformer extends EntityTransformer
{
use MakesHash;
@ -22,17 +22,17 @@ class TaskSchedulerTransformer extends EntityTransformer
{
return [
'id' => $this->encodePrimaryKey($scheduler->id),
'name' => (string) $scheduler->name,
'frequency_id' => (string) $scheduler->frequency_id,
'next_run' => $scheduler->next_run,
'template' => (string) $scheduler->template,
'is_paused' => (bool) $scheduler->is_paused,
'is_deleted' => (bool) $scheduler->is_deleted,
'parameters'=> (array) $scheduler->parameters,
'is_deleted' => (bool) $scheduler->is_deleted,
'paused' => (bool) $scheduler->paused,
'repeat_every' => (string) $scheduler->repeat_every,
'start_from' => (int) $scheduler->start_from,
'scheduled_run' => (int) $scheduler->scheduled_run,
'updated_at' => (int) $scheduler->updated_at,
'created_at' => (int) $scheduler->created_at,
'archived_at' => (int) $scheduler->deleted_at,
'action_name' => (string) $scheduler->action_name,
'action_class' => (string) $scheduler->action_class,
'parameters'=> (array) $scheduler->parameters,
];
}
}

View file

@ -20,12 +20,10 @@ use App\Models\GatewayType;
use App\Models\InvoiceInvitation;
use App\Models\QuoteInvitation;
use App\Models\RecurringInvoiceInvitation;
use App\Services\PdfMaker\Designs\Utilities\DesignHelpers;
use App\Utils\Ninja;
use App\Utils\Number;
use App\Utils\Traits\AppSetup;
use App\Utils\Traits\MakesDates;
use App\Utils\transformTranslations;
use Exception;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
@ -165,6 +163,16 @@ class HtmlEngine
$data['$view_url'] = ['value' => $this->invitation->getLink(), 'label' => ctrans('texts.view_invoice')];
$data['$date'] = ['value' => $this->translateDate($this->entity->date, $this->client->date_format(), $this->client->locale()) ?: '&nbsp;', 'label' => ctrans('texts.invoice_date')];
$data['$invoice.custom1'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice1', $this->entity->custom_value1, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice1')];
$data['$invoice.custom2'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice2', $this->entity->custom_value2, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice2')];
$data['$invoice.custom3'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice3', $this->entity->custom_value3, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice3')];
$data['$invoice.custom4'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice4', $this->entity->custom_value4, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice4')];
$data['$custom1'] = &$data['$invoice.custom1'];
$data['$custom2'] = &$data['$invoice.custom2'];
$data['$custom3'] = &$data['$invoice.custom3'];
$data['$custom4'] = &$data['$invoice.custom4'];
if($this->entity->project) {
$data['$project.name'] = ['value' => $this->entity->project->name, 'label' => ctrans('texts.project')];
$data['$invoice.project'] = &$data['$project.name'];
@ -204,6 +212,16 @@ class HtmlEngine
$data['$view_url'] = ['value' => $this->invitation->getLink(), 'label' => ctrans('texts.view_quote')];
$data['$date'] = ['value' => $this->translateDate($this->entity->date, $this->client->date_format(), $this->client->locale()) ?: '&nbsp;', 'label' => ctrans('texts.quote_date')];
$data['$quote.custom1'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice1', $this->entity->custom_value1, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice1')];
$data['$quote.custom2'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice2', $this->entity->custom_value2, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice2')];
$data['$quote.custom3'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice3', $this->entity->custom_value3, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice3')];
$data['$quote.custom4'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice4', $this->entity->custom_value4, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice4')];
$data['$custom1'] = &$data['$quote.custom1'];
$data['$custom2'] = &$data['$quote.custom2'];
$data['$custom3'] = &$data['$quote.custom3'];
$data['$custom4'] = &$data['$quote.custom4'];
if($this->entity->project) {
$data['$project.name'] = ['value' => $this->entity->project->name, 'label' => ctrans('texts.project_name')];
$data['$invoice.project'] = &$data['$project.name'];
@ -234,6 +252,11 @@ class HtmlEngine
$data['$credit.custom3'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'credit3', $this->entity->custom_value3, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice3')];
$data['$credit.custom4'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'credit4', $this->entity->custom_value4, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice4')];
$data['$custom1'] = &$data['$credit.custom1'];
$data['$custom2'] = &$data['$credit.custom2'];
$data['$custom3'] = &$data['$credit.custom3'];
$data['$custom4'] = &$data['$credit.custom4'];
}
$data['$portal_url'] = ['value' => $this->invitation->getPortalLink(), 'label' =>''];
@ -251,6 +274,7 @@ class HtmlEngine
$data['$invoice.subtotal'] = &$data['$subtotal'];
/* Do not change the order of these */
if ($this->entity->partial > 0) {
$data['$balance_due'] = ['value' => Number::formatMoney($this->entity->partial, $this->client) ?: '&nbsp;', 'label' => ctrans('texts.partial_due')];
$data['$balance_due_raw'] = ['value' => $this->entity->partial, 'label' => ctrans('texts.partial_due')];
@ -287,10 +311,8 @@ class HtmlEngine
$data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')];
}
// $data['$amount_in_words'] = ['value' => (new \NumberFormatter($this->client->locale(), \NumberFormatter::SPELLOUT))->format($this->entity->amount), 'label' => ''];
// $data['$balance_in_words'] = ['value' => (new \NumberFormatter($this->client->locale(), \NumberFormatter::SPELLOUT))->format($this->entity->balance), 'label' => ''];
/* Do not change the order of these */
// $data['$balance_due'] = $data['$balance_due'];
$data['$outstanding'] = &$data['$balance_due'];
$data['$partial_due'] = ['value' => Number::formatMoney($this->entity->partial, $this->client) ?: '&nbsp;', 'label' => ctrans('texts.partial_due')];
$data['$partial'] = &$data['$partial_due'];
@ -323,10 +345,7 @@ class HtmlEngine
$data['$user_iban'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'company1', $this->settings->custom_value1, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'company1')];
$data['$invoice.custom1'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice1', $this->entity->custom_value1, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice1')];
$data['$invoice.custom2'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice2', $this->entity->custom_value2, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice2')];
$data['$invoice.custom3'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice3', $this->entity->custom_value3, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice3')];
$data['$invoice.custom4'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice4', $this->entity->custom_value4, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice4')];
$data['$invoice.public_notes'] = ['value' => Helpers::processReservedKeywords(\nl2br($this->entity->public_notes ?: ''), $this->client) ?: '', 'label' => ctrans('texts.public_notes')];
$data['$entity.public_notes'] = &$data['$invoice.public_notes'];
$data['$public_notes'] = &$data['$invoice.public_notes'];
@ -345,10 +364,7 @@ class HtmlEngine
$data['$valid_until'] = &$data['$quote.valid_until'];
$data['$credit_amount'] = ['value' => Number::formatMoney($this->entity_calc->getTotal(), $this->client) ?: '&nbsp;', 'label' => ctrans('texts.credit_amount')];
$data['$credit_balance'] = ['value' => Number::formatMoney($this->entity->balance, $this->client) ?: '&nbsp;', 'label' => ctrans('texts.credit_balance')];
$data['$quote.custom1'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice1', $this->entity->custom_value1, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice1')];
$data['$quote.custom2'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice2', $this->entity->custom_value2, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice2')];
$data['$quote.custom3'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice3', $this->entity->custom_value3, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice3')];
$data['$quote.custom4'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'invoice4', $this->entity->custom_value4, $this->client) ?: '&nbsp;', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'invoice4')];
$data['$credit_number'] = &$data['$number'];
$data['$credit_no'] = &$data['$number'];

Some files were not shown because too many files have changed in this diff Show more