1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-10 13:12:50 +01:00

Merge pull request #8692 from turbo124/v5-develop

Fixes for static analysis
This commit is contained in:
David Bomba 2023-08-06 15:27:30 +10:00 committed by GitHub
commit 305352a080
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
115 changed files with 921 additions and 709 deletions

View File

@ -1 +1 @@
5.6.25
5.6.26

View File

@ -120,6 +120,7 @@ class PaymentFilters extends QueryFilters
*/
public function match_transactions($value = 'true'): Builder
{
if ($value == 'true') {
return $this->builder
->where('is_deleted', 0)

View File

@ -56,7 +56,7 @@ class TaskFilters extends QueryFilters
* - all
* - invoiced
*
* @param string client_status The invoice status as seen by the client
* @param string $value The invoice status as seen by the client
* @return Builder
*/
public function client_status(string $value = ''): Builder

View File

@ -230,7 +230,6 @@ class InvoiceItemSumInclusive
$item_tax += $this->formatValue($item_tax_rate1_total, $this->currency->precision);
// if($item_tax_rate1_total != 0)
if (strlen($this->item->tax_name1) > 1) {
$this->groupTax($this->item->tax_name1, $this->item->tax_rate1, $item_tax_rate1_total);
}

View File

@ -111,13 +111,13 @@ class ProRata
case RecurringInvoice::FREQUENCY_MONTHLY:
return now()->diffInDays(now()->addMonthNoOverflow());
case RecurringInvoice::FREQUENCY_TWO_MONTHS:
return now()->diffInDays(now()->addMonthNoOverflow(2));
return now()->diffInDays(now()->addMonthsNoOverflow(2));
case RecurringInvoice::FREQUENCY_THREE_MONTHS:
return now()->diffInDays(now()->addMonthNoOverflow(3));
return now()->diffInDays(now()->addMonthsNoOverflow(3));
case RecurringInvoice::FREQUENCY_FOUR_MONTHS:
return now()->diffInDays(now()->addMonthNoOverflow(4));
return now()->diffInDays(now()->addMonthsNoOverflow(4));
case RecurringInvoice::FREQUENCY_SIX_MONTHS:
return now()->diffInDays(now()->addMonthNoOverflow(6));
return now()->diffInDays(now()->addMonthsNoOverflow(6));
case RecurringInvoice::FREQUENCY_ANNUALLY:
return now()->diffInDays(now()->addYear());
case RecurringInvoice::FREQUENCY_TWO_YEARS:

View File

@ -64,6 +64,7 @@ class SubscriptionCalculator
}
if ($refund_invoice) {
/** @var \App\Models\Subscription $subscription **/
$subscription = Subscription::find($this->invoice->subscription_id);
$pro_rata = new ProRata;

View File

@ -58,7 +58,7 @@ class ActivityController extends BaseController
$system = ctrans('texts.system');
$data = $activities->cursor()->map(function ($activity) use ($system) {
$data = $activities->cursor()->map(function ($activity) {
return $activity->activity_string();
@ -90,7 +90,7 @@ class ActivityController extends BaseController
$system = ctrans('texts.system');
$data = $activities->cursor()->map(function ($activity) use ($system) {
$data = $activities->cursor()->map(function ($activity) {
return $activity->activity_string();

View File

@ -62,11 +62,15 @@ class ContactForgotPasswordController extends Controller
if (Ninja::isHosted() && $request->session()->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
/** @var \App\Models\Company $company **/
$company = Company::where('company_key', $request->session()->get('company_key'))->first();
$account = $company->account;
}
if (! $account) {
/** @var \App\Models\Account $account **/
$account = Account::first();
$company = $account->companies->first();
}
@ -97,7 +101,11 @@ class ContactForgotPasswordController extends Controller
$this->validateEmail($request);
if (Ninja::isHosted() && $company = Company::where('company_key', $request->input('company_key'))->first()) {
/** @var \App\Models\Company $company **/
/** @var \App\Models\ClientContact $contact **/
$contact = ClientContact::where(['email' => $request->input('email'), 'company_id' => $company->id])
->whereHas('client', function ($query) {
$query->where('is_deleted', 0);

View File

@ -52,6 +52,7 @@ class ContactLoginController extends Controller
$company = Company::where('company_key', $company_key)->first();
}
/** @var \App\Models\Company $company **/
if ($company) {
$account = $company->account;
} elseif (! $company && strpos($request->getHost(), 'invoicing.co') !== false) {
@ -63,6 +64,7 @@ class ContactLoginController extends Controller
$company = Company::where('portal_domain', $request->getSchemeAndHttpHost())->first();
} elseif (Ninja::isSelfHost()) {
/** @var \App\Models\Account $account **/
$account = Account::first();
$company = $account->default_company;
} else {
@ -97,6 +99,7 @@ class ContactLoginController extends Controller
}
if (Ninja::isHosted() && $request->has('password') && $company = Company::where('company_key', $request->input('company_key'))->first()) {
/** @var \App\Models\Company $company **/
$contact = ClientContact::where(['email' => $request->input('email'), 'company_id' => $company->id])
->whereHas('client', function ($query) {
$query->where('is_deleted', 0);

View File

@ -39,7 +39,8 @@ class ContactRegisterController extends Controller
} else {
$key = request()->session()->has('company_key') ? request()->session()->get('company_key') : $company_key;
}
/** @var \App\Models\Company $company **/
$company = Company::where('company_key', $key)->firstOrFail();
App::forgetInstance('translator');

View File

@ -71,6 +71,8 @@ class ContactResetPasswordController extends Controller
{
if ($request->session()->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
/** @var \App\Models\Company $company **/
$company = Company::where('company_key', $request->session()->get('company_key'))->first();
$db = $company->db;
$account = $company->account;
@ -79,10 +81,12 @@ class ContactResetPasswordController extends Controller
if ($account_key) {
MultiDB::findAndSetDbByAccountKey($account_key);
/** @var \App\Models\Account $account **/
$account = Account::where('key', $account_key)->first();
$db = $account->companies->first()->db;
$company = $account->companies->first();
} else {
/** @var \App\Models\Account $account **/
$account = Account::first();
$db = $account->companies->first()->db;
$company = $account->companies->first();

View File

@ -82,6 +82,7 @@ class ForgotPasswordController extends Controller
{
if ($request->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->input('company_key'));
/** @var \App\Models\Company $company **/
$company = Company::where('company_key', $request->input('company_key'))->first();
$account = $company->account;
} else {

View File

@ -60,6 +60,7 @@ class ResetPasswordController extends Controller
if (Ninja::isHosted()) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
/** @var \App\Models\Company $company **/
$company = Company::where('company_key', $request->session()->get('company_key'))->first();
}

View File

@ -114,7 +114,10 @@ class BankTransactionController extends BaseController
public function match(MatchBankTransactionRequest $request)
{
$bts = (new MatchBankTransactions(auth()->user()->company()->id, auth()->user()->company()->db, $request->all()))->handle();
/** @var \App\Models\User $user */
$user = auth()->user();
$bts = (new MatchBankTransactions($user->company()->id, $user->company()->db, $request->all()))->handle();
return $this->listResponse($bts);
}

View File

@ -85,7 +85,7 @@ class BankTransactionRuleController extends BaseController
* @OA\JsonContent(ref="#/components/schemas/Error"),
* ),
* )
* @param BankTransactionFilters $filter
* @param BankTransactionRuleFilters $filters
* @return Response|mixed
*/
public function index(BankTransactionRuleFilters $filters)
@ -302,7 +302,9 @@ class BankTransactionRuleController extends BaseController
*/
public function create(CreateBankTransactionRuleRequest $request)
{
$bank_transaction_rule = BankTransactionRuleFactory::create(auth()->user()->company()->id, auth()->user()->id, auth()->user()->account_id);
/** @var \App\Models\User $user **/
$user = auth()->user();
$bank_transaction_rule = BankTransactionRuleFactory::create($user->company()->id, $user->id);
return $this->itemResponse($bank_transaction_rule);
}
@ -347,8 +349,11 @@ class BankTransactionRuleController extends BaseController
*/
public function store(StoreBankTransactionRuleRequest $request)
{
//stub to store the model
$bank_transaction_rule = $this->bank_transaction_repo->save($request->all(), BankTransactionRuleFactory::create(auth()->user()->company()->id, auth()->user()->id, auth()->user()->account_id));
/** @var \App\Models\User $user **/
$user = auth()->user();
$bank_transaction_rule = $this->bank_transaction_repo->save($request->all(), BankTransactionRuleFactory::create($user->company()->id, $user->id));
return $this->itemResponse($bank_transaction_rule);
}

View File

@ -516,19 +516,11 @@ class BaseController extends Controller
$query->where('bank_transactions.user_id', $user->id);
}
},
'company.bank_transaction_rules'=> function ($query) use ($updated_at, $user) {
$query->where('updated_at', '>=', $updated_at);
if (! $user->isAdmin()) {
$query->where('bank_transaction_rules.user_id', $user->id);
}
'company.bank_transaction_rules'=> function ($query) {
$query->whereNotNull('updated_at');
},
'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);
}
'company.task_schedulers'=> function ($query) {
$query->whereNotNull('updated_at');
},
]
);
@ -627,7 +619,7 @@ class BaseController extends Controller
}
},
'company.bank_transaction_rules'=> function ($query) use ($user) {
if (! $user->isAdmin()) {
if (! $user->isAdmin() && !$user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) {
$query->where('bank_transaction_rules.user_id', $user->id);
}
},
@ -656,24 +648,6 @@ class BaseController extends Controller
return $this->response($this->manager->createData($resource)->toArray());
}
/**
* In case a user is not an admin and is
* able to access multiple companies, then we
* need to pass back the mini load only
*
* @deprecated
* @return bool
*/
// private function complexPermissionsUser(): bool
// {
// //if the user is attached to more than one company AND they are not an admin across all companies
// if (auth()->user()->company_users()->count() > 1 && (auth()->user()->company_users()->where('is_admin', 1)->count() != auth()->user()->company_users()->count())) {
// return true;
// }
// return false;
// }
/**
* Passes back the miniloaded data response
*

View File

@ -27,7 +27,12 @@ class ContactHashLoginController extends Controller
public function login(string $contact_key)
{
if (request()->has('subscription') && request()->subscription == 'true') {
$recurring_invoice = RecurringInvoice::where('client_id', auth()->guard('contact')->client->id)
/** @var \App\Models\ClientContact $client_contact **/
$client_contact = auth()->guard('contact');
/** @var \App\Models\RecurringInvoice $recurring_invoice **/
$recurring_invoice = RecurringInvoice::where('client_id', $client_contact->client->id)
->whereNotNull('subscription_id')
->whereNull('deleted_at')
->first();

View File

@ -56,6 +56,7 @@ class DocumentController extends Controller
{
MultiDB::documentFindAndSetDb($document_hash);
/** @var \App\Models\Document $document **/
$document = Document::where('hash', $document_hash)->firstOrFail();
$headers = ['Cache-Control:' => 'no-cache'];
@ -69,6 +70,7 @@ class DocumentController extends Controller
public function downloadMultiple(DownloadMultipleDocumentsRequest $request)
{
/** @var \Illuminate\Database\Eloquent\Collection<Document> $documents **/
$documents = Document::whereIn('id', $this->transformKeys($request->file_hash))
->where('company_id', auth()->guard('contact')->user()->company_id)
->get();

View File

@ -212,7 +212,10 @@ class InvitationController extends Controller
public function paymentRouter(string $contact_key, string $payment_id)
{
/** @var \App\Models\ClientContact $contact **/
$contact = ClientContact::withTrashed()->where('contact_key', $contact_key)->firstOrFail();
/** @var \App\Models\Payment $payment **/
$payment = Payment::find($this->decodePrimaryKey($payment_id));
if ($payment->client_id != $contact->client_id) {

View File

@ -97,13 +97,6 @@ class InvoiceController extends Controller
$file = (new \App\Jobs\Entity\CreateRawPdf($invitation, $invitation->company->db))->handle();
// $headers = ['Content-Type' => 'application/pdf'];
// $entity_string = $data['entity_type'];
// $file_name = $invitation->{$entity_string}->numberFormatter().'.pdf';
// return response()->streamDownload(function () use ($file) {
// echo $file;
// }, $file_name, $headers);
$headers = ['Content-Type' => 'application/pdf'];
return response()->make($file, 200, $headers);

View File

@ -44,6 +44,8 @@ class NinjaPlanController extends Controller
if (! $company) {
MultiDB::findAndSetDbByAccountKey($account_or_company_key);
/** @var \App\Models\Account $account **/
$account = Account::where('key', $account_or_company_key)->first();
} else {
$account = $company->account;
@ -137,6 +139,8 @@ class NinjaPlanController extends Controller
//set free trial
if (auth()->guard('contact')->user()->client->custom_value2) {
MultiDB::findAndSetDbByAccountKey(auth()->guard('contact')->user()->client->custom_value2);
/** @var \App\Models\Account $account **/
$account = Account::where('key', auth()->guard('contact')->user()->client->custom_value2)->first();
// $account->trial_started = now();
// $account->trial_plan = 'pro';

View File

@ -27,6 +27,7 @@ use App\Services\Subscription\SubscriptionService;
use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
use Illuminate\Contracts\View\Factory;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
@ -111,6 +112,7 @@ class PaymentController extends Controller
public function response(PaymentResponseRequest $request)
{
/** @var \App\Models\CompanyGateway $gateway **/
$gateway = CompanyGateway::findOrFail($request->input('company_gateway_id'));
$payment_hash = PaymentHash::where('hash', $request->payment_hash)->firstOrFail();
$invoice = Invoice::with('client')->find($payment_hash->fee_invoice_id);
@ -166,16 +168,19 @@ class PaymentController extends Controller
$payment = $payment->service()->applyCredits($payment_hash)->save();
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Invoice> $invoices */
$invoices = Invoice::whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')));
$invoices->each(function ($i) {
$i->is_proforma = false;
$i->saveQuietly();
$invoices->each(function ($invoice) {
/** @var \App\Models\Invoice $invoice **/
$invoice->is_proforma = false;
$invoice->saveQuietly();
});
event('eloquent.created: App\Models\Payment', $payment);
if ($invoices->sum('balance') > 0) {
/** @var \App\Models\Invoice $invoice **/
$invoice = $invoices->first();
return redirect()->route('client.invoice.show', ['invoice' => $invoice->hashed_id, 'hash' => $request->input('hash')]);

View File

@ -55,9 +55,13 @@ class PaymentMethodController extends Controller
$gateway = $this->getClientGateway();
$data['gateway'] = $gateway;
$data['client'] = auth()->user()->client;
/** @var \App\Models\ClientContact auth()->user() **/
$client_contact = auth()->user();
$data['client'] = $client_contact->client;
return $gateway
->driver(auth()->user()->client)
->driver($client_contact->client)
->setPaymentMethod($request->query('method'))
->checkRequirements()
->authorizeView($data);
@ -73,8 +77,11 @@ class PaymentMethodController extends Controller
{
$gateway = $this->getClientGateway();
/** @var \App\Models\ClientContact auth()->user() **/
$client_contact = auth()->user();
return $gateway
->driver(auth()->user()->client)
->driver($client_contact->client)
->setPaymentMethod($request->query('method'))
->checkRequirements()
->authorizeResponse($request);
@ -95,18 +102,23 @@ class PaymentMethodController extends Controller
public function verify(ClientGatewayToken $payment_method)
{
/** @var \App\Models\ClientContact auth()->user() **/
$client_contact = auth()->user();
return $payment_method->gateway
->driver(auth()->user()->client)
->driver($client_contact->client)
->setPaymentMethod(request()->query('method'))
->verificationView($payment_method);
}
public function processVerification(Request $request, ClientGatewaytoken $payment_method)
{
// $gateway = $this->getClientGateway();
/** @var \App\Models\ClientContact auth()->user() **/
$client_contact = auth()->user();
return $payment_method->gateway
->driver(auth()->user()->client)
->driver($client_contact->client)
->setPaymentMethod(request()->query('method'))
->processVerification($request, $payment_method);
}
@ -119,9 +131,12 @@ class PaymentMethodController extends Controller
*/
public function destroy(ClientGatewayToken $payment_method)
{
/** @var \App\Models\ClientContact auth()->user() **/
$client_contact = auth()->user();
if ($payment_method->gateway()->exists()) {
$payment_method->gateway
->driver(auth()->user()->client)
->driver($client_contact->client)
->setPaymentMethod(request()->query('method'))
->detach($payment_method);
}
@ -143,15 +158,18 @@ class PaymentMethodController extends Controller
private function getClientGateway()
{
/** @var \App\Models\ClientContact auth()->user() **/
$client_contact = auth()->user();
if (request()->query('method') == GatewayType::CREDIT_CARD) {
return auth()->user()->client->getCreditCardGateway();
return $client_contact->client->getCreditCardGateway();
}
if (request()->query('method') == GatewayType::BACS) {
return auth()->user()->client->getBACSGateway();
return $client_contact->client->getBACSGateway();
}
if (in_array(request()->query('method'), [GatewayType::BANK_TRANSFER, GatewayType::DIRECT_DEBIT, GatewayType::SEPA])) {
return auth()->user()->client->getBankTransferGateway();
return $client_contact->client->getBankTransferGateway();
}
abort(404, 'Gateway not found.');

View File

@ -50,8 +50,6 @@ class ProfileController extends Controller
$client_contact->save();
// auth()->user()->fresh();
return back()->withSuccess(
ctrans('texts.profile_updated_successfully')
);
@ -63,7 +61,7 @@ class ProfileController extends Controller
//update avatar if needed
if ($request->file('logo')) {
$path = (new UploadAvatar($request->file('logo'), auth()->user()->client->client_hash))->handle();
$path = (new UploadAvatar($request->file('logo'), $client->client_hash))->handle();
if ($path) {
$client->logo = $path;

View File

@ -83,7 +83,7 @@ class QuoteController extends Controller
return $this->downloadQuotes((array) $transformed_ids);
}
if ($request->action = 'approve') {
if ($request->action == 'approve') {
return $this->approve((array) $transformed_ids, $request->has('process'));
}
@ -92,8 +92,11 @@ class QuoteController extends Controller
public function downloadQuotes($ids)
{
/** @var \App\Models\ClientContact $client_contact **/
$client_contact = auth()->user();
$data['quotes'] = Quote::whereIn('id', $ids)
->whereClientId(auth()->user()->client->id)
->whereClientId($client_contact->client->id)
->withTrashed()
->get();
@ -113,8 +116,12 @@ class QuoteController extends Controller
protected function downloadQuotePdf(array $ids)
{
/** @var \App\Models\ClientContact $client_contact **/
$client_contact = auth()->user();
$quotes = Quote::whereIn('id', $ids)
->whereClientId(auth()->user()->client->id)
->whereClientId($client_contact->client_id)
->withTrashed()
->get();

View File

@ -30,7 +30,11 @@ class UploadController extends Controller
*/
public function __invoke(StoreUploadRequest $request)
{
$this->saveDocuments($request->getFile(), auth()->user()->client, true);
/** @var \App\Models\ClientContact $client_contact **/
$client_contact = auth()->user();
$this->saveDocuments($request->getFile(), $client_contact->client, true);
return response([], 200);
}

View File

@ -547,6 +547,8 @@ class CompanyController extends BaseController
//If we are deleting the default companies, we'll need to make a new company the default.
if ($account->default_company_id == $company_id) {
/** @var \App\Models\Company $new_default_company **/
$new_default_company = Company::whereAccountId($account->id)->first();
$account->default_company_id = $new_default_company->id;
$account->save();
@ -560,7 +562,7 @@ class CompanyController extends BaseController
* Update the specified resource in storage.
*
* @param UploadCompanyRequest $request
* @param Company $client
* @param Company $company
* @return Response
*
*
@ -622,7 +624,7 @@ class CompanyController extends BaseController
/**
* Update the specified resource in storage.
*
* @param UploadCompanyRequest $request
* @param DefaultCompanyRequest $request
* @param Company $company
* @return Response
*

View File

@ -111,6 +111,7 @@ class CompanyUserController extends BaseController
*/
public function update(UpdateCompanyUserRequest $request, User $user)
{
$company = auth()->user()->company();
$company_user = CompanyUser::whereUserId($user->id)->whereCompanyId($company->id)->first();
@ -135,7 +136,7 @@ class CompanyUserController extends BaseController
public function updatePreferences(UpdateCompanyUserPreferencesRequest $request, User $user)
{
/** @var \App\Models\User $logged_in_user */
$company = auth()->user()->company();
$company_user = CompanyUser::whereUserId($user->id)->whereCompanyId($company->id)->first();

View File

@ -148,7 +148,10 @@ class CreditController extends BaseController
*/
public function create(CreateCreditRequest $request)
{
$credit = CreditFactory::create(auth()->user()->company()->id, auth()->user()->id);
/** @var \App\Models\User $user**/
$user = auth()->user();
$credit = CreditFactory::create($user->company()->id, auth()->user()->id);
return $this->itemResponse($credit);
}
@ -193,9 +196,13 @@ class CreditController extends BaseController
*/
public function store(StoreCreditRequest $request)
{
$client = Client::find($request->input('client_id'));
$credit = $this->credit_repository->save($request->all(), CreditFactory::create(auth()->user()->company()->id, auth()->user()->id));
/** @var \App\Models\User $user**/
$user = auth()->user();
// $client = Client::find($request->input('client_id'));
$credit = $this->credit_repository->save($request->all(), CreditFactory::create($user->company()->id, $user->id));
$credit = $credit->service()
->fillDefaults()
@ -207,7 +214,7 @@ class CreditController extends BaseController
$credit->client->service()->updatePaidToDate(-1 * $credit->balance)->save();
}
event(new CreditWasCreated($credit, $credit->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
event(new CreditWasCreated($credit, $credit->company, Ninja::eventVars($user->id)));
return $this->itemResponse($credit);
}
@ -383,7 +390,10 @@ class CreditController extends BaseController
->triggeredActions($request)
->deletePdf();
event(new CreditWasUpdated($credit, $credit->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
/** @var \App\Models\User $user**/
$user = auth()->user();
event(new CreditWasUpdated($credit, $credit->company, Ninja::eventVars($user->id)));
return $this->itemResponse($credit);
}
@ -495,9 +505,13 @@ class CreditController extends BaseController
*/
public function bulk(BulkCreditRequest $request)
{
/** @var \App\Models\User $user**/
$user = auth()->user();
$action = $request->input('action');
if (Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) {
if (Ninja::isHosted() && (stripos($action, 'email') !== false) && !$user->company()->account->account_sms_verified) {
return response(['message' => 'Please verify your account to send emails.'], 400);
}
@ -515,20 +529,20 @@ class CreditController extends BaseController
*/
if ($action == 'bulk_download' && $credits->count() > 1) {
$credits->each(function ($credit) {
if (auth()->user()->cannot('view', $credit)) {
$credits->each(function ($credit) use($user){
if ($user->cannot('view', $credit)) {
nlog('access denied');
return response()->json(['message' => ctrans('text.access_denied')]);
}
});
ZipCredits::dispatch($credits, $credits->first()->company, auth()->user());
ZipCredits::dispatch($credits, $credits->first()->company, $user);
return response()->json(['message' => ctrans('texts.sent_message')], 200);
}
if ($action == 'bulk_print' && auth()->user()->can('view', $credits->first())) {
if ($action == 'bulk_print' && $user->can('view', $credits->first())) {
$paths = $credits->map(function ($credit) {
return $credit->service()->getCreditPdf($credit->invitations->first());
});
@ -540,8 +554,8 @@ class CreditController extends BaseController
}, 'print.pdf', ['Content-Type' => 'application/pdf']);
}
$credits->each(function ($credit, $key) use ($action) {
if (auth()->user()->can('edit', $credit)) {
$credits->each(function ($credit, $key) use ($action, $user) {
if ($user->can('edit', $credit)) {
$this->performAction($credit, $action, true);
}
});

View File

@ -69,7 +69,7 @@ class DocumentController extends BaseController
* @OA\JsonContent(ref="#/components/schemas/Error"),
* ),
* )
* @param DocumentsFilters $filters
* @param DocumentFilters $filters
* @return Response|mixed
*/
public function index(DocumentFilters $filters)
@ -168,6 +168,9 @@ class DocumentController extends BaseController
public function bulk()
{
/** @var \App\Models\User $user */
$user = auth()->user();
$action = request()->input('action');
$ids = request()->input('ids');
@ -179,15 +182,15 @@ class DocumentController extends BaseController
}
if ($action == 'download') {
ZipDocuments::dispatch($documents->pluck('id'), auth()->user()->company(), auth()->user());
ZipDocuments::dispatch($documents->pluck('id'), $user->company(), auth()->user());
return response()->json(['message' => ctrans('texts.sent_message')], 200);
}
/*
* Send the other actions to the switch
*/
$documents->each(function ($document, $key) use ($action) {
if (auth()->user()->can('edit', $document)) {
$documents->each(function ($document, $key) use ($action, $user) {
if ($user->can('edit', $document)) {
$this->document_repo->{$action}($document);
}
});

View File

@ -73,7 +73,7 @@ class EmailController extends BaseController
$mo->cc[] = new Address($request->cc_email);
}
$entity_obj->invitations->each(function ($invitation) use ($data, $entity_obj, $template, $mo) {
$entity_obj->invitations->each(function ($invitation) use ($entity_obj, $mo) {
if (! $invitation->contact->trashed() && $invitation->contact->email) {
$entity_obj->service()->markSent()->save();

View File

@ -138,8 +138,7 @@ class ExpenseCategoryController extends BaseController
/**
* Store a newly created resource in storage.
*
* @param StoreInvoiceRequest $request The request
*
* @param StoreExpenseCategoryRequest $request
* @return Response
*
*
@ -175,7 +174,10 @@ class ExpenseCategoryController extends BaseController
*/
public function store(StoreExpenseCategoryRequest $request)
{
$expense_category = ExpenseCategoryFactory::create(auth()->user()->company()->id, auth()->user()->id);
/** @var \App\Models\User $user **/
$user = auth()->user();
$expense_category = ExpenseCategoryFactory::create($user->company()->id, $user->id);
$expense_category->fill($request->all());
$expense_category->save();
@ -454,14 +456,17 @@ class ExpenseCategoryController extends BaseController
*/
public function bulk()
{
/** @var \App\Models\User $user **/
$user = auth()->user();
$action = request()->input('action');
$ids = request()->input('ids');
$expense_categories = ExpenseCategory::withTrashed()->find($this->transformKeys($ids));
$expense_categories->each(function ($expense_category, $key) use ($action) {
if (auth()->user()->can('edit', $expense_category)) {
$expense_categories->each(function ($expense_category, $key) use ($action, $user) {
if ($user->can('edit', $expense_category)) {
$this->base_repo->{$action}($expense_category);
}
});

View File

@ -43,6 +43,8 @@ class HostedMigrationController extends Controller
$company = $account->companies->first();
/** @var \App\Models\CompanyToken $company_token **/
$company_token = CompanyToken::where('user_id', auth()->user()->id)
->where('company_id', $company->id)
->first();
@ -60,6 +62,7 @@ class HostedMigrationController extends Controller
MultiDB::findAndSetDbByCompanyKey($input['account_key']);
/** @var \App\Models\Company $company **/
$company = Company::with('account')->where('company_key', $input['account_key'])->first();
$forward_url = $company->domain();

View File

@ -255,7 +255,6 @@ class MigrationController extends BaseController
* ),
* )
* @param Request $request
* @param Company $company
* @return \Illuminate\Http\JsonResponse|void
*/
public function startMigration(Request $request)

View File

@ -11,14 +11,15 @@
namespace App\Http\Controllers;
use App\Http\Requests\OneTimeToken\OneTimeRouterRequest;
use App\Http\Requests\OneTimeToken\OneTimeTokenRequest;
use App\Models\Company;
use App\Models\User;
use App\Models\Company;
use App\Libraries\MultiDB;
use Illuminate\Support\Str;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use App\Http\Requests\OneTimeToken\OneTimeTokenRequest;
use App\Http\Requests\OneTimeToken\OneTimeRouterRequest;
class OneTimeTokenController extends BaseController
{
@ -33,7 +34,7 @@ class OneTimeTokenController extends BaseController
/**
* Store a newly created resource in storage.
*
* @param CreateOneTimeTokenRequest $request
* @param OneTimeTokenRequest $request
* @return Response
*
* @OA\Post(
@ -64,11 +65,14 @@ class OneTimeTokenController extends BaseController
*/
public function create(OneTimeTokenRequest $request)
{
/** @var \App\Models\User $user */
$user = auth()->user();
$hash = Str::random(64);
$data = [
'user_id' => auth()->user()->id,
'company_key'=> auth()->user()->company()->company_key,
'user_id' => $user->id,
'company_key'=> $user->company()->company_key,
'context' => $request->input('context'),
];
@ -83,10 +87,6 @@ class OneTimeTokenController extends BaseController
MultiDB::findAndSetDbByCompanyKey($data['company_key']);
// $user = User::findOrFail($data['user_id']);
// Auth::login($user, true);
// Cache::forget($request->input('hash'));
$this->sendTo($data['context']);
}

View File

@ -152,7 +152,10 @@ class PaymentController extends BaseController
*/
public function create(CreatePaymentRequest $request)
{
$payment = PaymentFactory::create(auth()->user()->company()->id, auth()->user()->id);
/** @var \App\Models\User $user */
$user = auth()->user();
$payment = PaymentFactory::create($user->company()->id, $user->id);
return $this->itemResponse($payment);
}
@ -203,7 +206,10 @@ class PaymentController extends BaseController
*/
public function store(StorePaymentRequest $request)
{
$payment = $this->payment_repo->save($request->all(), PaymentFactory::create(auth()->user()->company()->id, auth()->user()->id));
/** @var \App\Models\User $user */
$user = auth()->user();
$payment = $this->payment_repo->save($request->all(), PaymentFactory::create($user->company()->id, $user->id));
event('eloquent.created: App\Models\Payment', $payment);
@ -372,13 +378,16 @@ class PaymentController extends BaseController
*/
public function update(UpdatePaymentRequest $request, Payment $payment)
{
/** @var \App\Models\User $user */
$user = auth()->user();
if ($request->entityIsDeleted($payment)) {
return $request->disallowUpdate();
}
$payment = $this->payment_repo->save($request->all(), $payment);
event(new PaymentWasUpdated($payment, $payment->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
event(new PaymentWasUpdated($payment, $payment->company, Ninja::eventVars($user->id)));
event('eloquent.updated: App\Models\Payment', $payment);
@ -495,14 +504,17 @@ class PaymentController extends BaseController
*/
public function bulk()
{
/** @var \App\Models\User $user */
$user = auth()->user();
$action = request()->input('action');
$ids = request()->input('ids');
$payments = Payment::withTrashed()->find($this->transformKeys($ids));
$payments->each(function ($payment, $key) use ($action) {
if (auth()->user()->can('edit', $payment)) {
$payments->each(function ($payment, $key) use ($action, $user) {
if ($user->can('edit', $payment)) {
$this->performAction($payment, $action, true);
}
});
@ -576,7 +588,6 @@ class PaymentController extends BaseController
* @OA\JsonContent(ref="#/components/schemas/Error"),
* ),
* )
* @param ActionPaymentRequest $request
* @param Payment $payment
* @param $action
*/

View File

@ -23,6 +23,8 @@ class PaymentNotificationWebhookController extends Controller
public function __invoke(PaymentNotificationWebhookRequest $request, string $company_key, string $company_gateway_id, string $client_hash)
{
/** @var \App\Models\CompanyGateway $company_gateway */
$company_gateway = CompanyGateway::find($this->decodePrimaryKey($company_gateway_id));
$client = Client::find($this->decodePrimaryKey($client_hash));

View File

@ -1,20 +1,29 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2023. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Http\Controllers;
use App\Models\PaymentTerm;
use Illuminate\Http\Response;
use App\Utils\Traits\MakesHash;
use App\Factory\PaymentTermFactory;
use App\Filters\PaymentTermFilters;
use App\Http\Requests\PaymentTerm\CreatePaymentTermRequest;
use App\Http\Requests\PaymentTerm\DestroyPaymentTermRequest;
use App\Http\Requests\PaymentTerm\ShowPaymentTermRequest;
use App\Http\Requests\PaymentTerm\StorePaymentTermRequest;
use App\Http\Requests\PaymentTerm\UpdatePaymentTermRequest;
use App\Models\PaymentTerm;
use App\Repositories\PaymentTermRepository;
use App\Transformers\PaymentTermTransformer;
use App\Utils\Traits\MakesHash;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests\PaymentTerm\EditPaymentTermRequest;
use App\Http\Requests\PaymentTerm\ShowPaymentTermRequest;
use App\Http\Requests\PaymentTerm\StorePaymentTermRequest;
use App\Http\Requests\PaymentTerm\CreatePaymentTermRequest;
use App\Http\Requests\PaymentTerm\UpdatePaymentTermRequest;
use App\Http\Requests\PaymentTerm\DestroyPaymentTermRequest;
class PaymentTermController extends BaseController
{
@ -25,7 +34,7 @@ class PaymentTermController extends BaseController
protected $entity_transformer = PaymentTermTransformer::class;
/**
* @var PaymentRepository
* @var PaymentTermRepository
*/
protected $payment_term_repo;
@ -121,7 +130,9 @@ class PaymentTermController extends BaseController
*/
public function create(CreatePaymentTermRequest $request)
{
$payment_term = PaymentTermFactory::create(auth()->user()->company()->id, auth()->user()->id);
/** @var \App\Models\User $user */
$user = auth()->user();
$payment_term = PaymentTermFactory::create($user->company()->id, $user->id);
return $this->itemResponse($payment_term);
}
@ -172,7 +183,10 @@ class PaymentTermController extends BaseController
*/
public function store(StorePaymentTermRequest $request)
{
$payment_term = PaymentTermFactory::create(auth()->user()->company()->id, auth()->user()->id);
/** @var \App\Models\User $user */
$user = auth()->user();
$payment_term = PaymentTermFactory::create($user->company()->id, $user->id);
$payment_term->fill($request->all());
$payment_term->save();
@ -270,13 +284,13 @@ class PaymentTermController extends BaseController
* @OA\JsonContent(ref="#/components/schemas/Error"),
* ),
* )
* @param EditPaymentRequest $request
* @param Payment $payment
* @param EditPaymentTermRequest $request
* @param PaymentTerm $payment_term
* @return Response|mixed
*/
public function edit(EditPaymentRequest $request, Payment $payment)
public function edit(EditPaymentTermRequest $request, PaymentTerm $payment_term)
{
return $this->itemResponse($payment);
return $this->itemResponse($payment_term);
}
/**
@ -447,14 +461,17 @@ class PaymentTermController extends BaseController
*/
public function bulk()
{
/** @var \App\Models\User $user */
$user = auth()->user();
$action = request()->input('action');
$ids = request()->input('ids');
$payment_terms = PaymentTerm::withTrashed()->company()->find($this->transformKeys($ids));
$payment_terms->each(function ($payment_term, $key) use ($action) {
if (auth()->user()->can('edit', $payment_term)) {
$payment_terms->each(function ($payment_term, $key) use ($action, $user) {
if ($user->can('edit', $payment_term)) {
$this->payment_term_repo->{$action}($payment_term);
}
});

View File

@ -209,13 +209,17 @@ class PreviewController extends BaseController
if ($request->has('entity_id')) {
/** @var \App\Models\BaseModel $class */
$entity_obj = $class::on(config('database.default'))
/** @var \App\Models\Quote | \App\Models\Invoice | \App\Models\RecurringInvoice | \App\Models\Credit $class */
$temp_obj = $class::on(config('database.default'))
->with('client.company')
->where('id', $this->decodePrimaryKey($request->input('entity_id')))
->where('company_id', $company->id)
->withTrashed()
->first();
/** Prevents null values from being passed into entity_obj */
if($temp_obj)
$entity_obj = $temp_obj;
}
if ($request->has('footer') && !$request->filled('footer') && $request->input('entity') == 'recurring_invoice') {
@ -239,6 +243,7 @@ class PreviewController extends BaseController
$html = new HtmlEngine($entity_obj->invitations()->first());
/** @var \App\Models\Design $design */
$design = \App\Models\Design::withTrashed()->find($entity_obj->design_id);
/* Catch all in case migration doesn't pass back a valid design */
@ -343,6 +348,7 @@ class PreviewController extends BaseController
$t = app('translator');
$t->replace(Ninja::transformTranslations($company->settings));
/** @var \App\Models\InvoiceInvitation $invitation */
$invitation = InvoiceInvitation::where('company_id', $company->id)->orderBy('id', 'desc')->first();
/* If we don't have a valid invitation in the system - create a mock using transactions */

View File

@ -140,10 +140,13 @@ class PreviewPurchaseOrderController extends BaseController
return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true));
}
/** @var \App\Models\User $user */
$user = auth()->user();
if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true));
$numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
$numbered_pdf = $this->pageNumbering($pdf, $user->company());
if ($numbered_pdf) {
$pdf = $numbered_pdf;
@ -153,7 +156,7 @@ class PreviewPurchaseOrderController extends BaseController
}
//else
$file_path = (new PreviewPdf($maker->getCompiledHTML(true), auth()->user()->company()))->handle();
$file_path = (new PreviewPdf($maker->getCompiledHTML(true), $user->company()))->handle();
return response()->download($file_path, basename($file_path), ['Cache-Control:' => 'no-cache'])->deleteFileAfterSend(true);
}
@ -163,12 +166,15 @@ class PreviewPurchaseOrderController extends BaseController
public function live(PreviewPurchaseOrderRequest $request)
{
$company = auth()->user()->company();
/** @var \App\Models\User $user */
$user = auth()->user();
$company = $user->company();
MultiDB::setDb($company->db);
$repo = new PurchaseOrderRepository();
$entity_obj = PurchaseOrderFactory::create($company->id, auth()->user()->id);
$entity_obj = PurchaseOrderFactory::create($company->id, $user->id);
$class = PurchaseOrder::class;
try {
@ -196,6 +202,7 @@ class PreviewPurchaseOrderController extends BaseController
$html = new VendorHtmlEngine($entity_obj->invitations()->first());
/** @var \App\Models\Design $design */
$design = \App\Models\Design::withTrashed()->find($entity_obj->design_id);
/* Catch all in case migration doesn't pass back a valid design */
@ -243,6 +250,8 @@ class PreviewPurchaseOrderController extends BaseController
return;
}
/** @var \App\Models\User $user */
$user = auth()->user();
//if phantom js...... inject here..
if (config('ninja.phantomjs_pdf_generation') || config('ninja.pdf_generator') == 'phantom') {
@ -252,7 +261,7 @@ class PreviewPurchaseOrderController extends BaseController
if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true));
$numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
$numbered_pdf = $this->pageNumbering($pdf, $user->company());
if ($numbered_pdf) {
$pdf = $numbered_pdf;
@ -279,11 +288,15 @@ class PreviewPurchaseOrderController extends BaseController
private function blankEntity()
{
/** @var \App\Models\User $user */
$user = auth()->user();
App::forgetInstance('translator');
$t = app('translator');
$t->replace(Ninja::transformTranslations(auth()->user()->company()->settings));
$t->replace(Ninja::transformTranslations($user->company()->settings));
$invitation = PurchaseOrderInvitation::where('company_id', auth()->user()->company()->id)->orderBy('id', 'desc')->first();
/** @var \App\Models\PurchaseOrderInvitation $invitation */
$invitation = PurchaseOrderInvitation::where('company_id', $user->company()->id)->orderBy('id', 'desc')->first();
/* If we don't have a valid invitation in the system - create a mock using transactions */
if (!$invitation) {
@ -327,10 +340,13 @@ class PreviewPurchaseOrderController extends BaseController
return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true));
}
/** @var \App\Models\User $user */
$user = auth()->user();
if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true));
$numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
$numbered_pdf = $this->pageNumbering($pdf, $user->company());
if ($numbered_pdf) {
$pdf = $numbered_pdf;
@ -339,7 +355,7 @@ class PreviewPurchaseOrderController extends BaseController
return $pdf;
}
$file_path = (new PreviewPdf($maker->getCompiledHTML(true), auth()->user()->company()))->handle();
$file_path = (new PreviewPdf($maker->getCompiledHTML(true), $user->company()))->handle();
$response = Response::make($file_path, 200);
$response->header('Content-Type', 'application/pdf');
@ -349,40 +365,47 @@ class PreviewPurchaseOrderController extends BaseController
private function mockEntity()
{
DB::connection(auth()->user()->company()->db)->beginTransaction();
/** @var \App\Models\User $user */
$user = auth()->user();
DB::connection($user->company()->db)->beginTransaction();
/** @var \App\Models\Vendor $vendor */
$vendor = Vendor::factory()->create([
'user_id' => auth()->user()->id,
'company_id' => auth()->user()->company()->id,
'user_id' => $user->id,
'company_id' => $user->company()->id,
]);
/** @var \App\Models\VendorContact $contact */
$contact = VendorContact::factory()->create([
'user_id' => auth()->user()->id,
'company_id' => auth()->user()->company()->id,
'user_id' => $user->id,
'company_id' => $user->company()->id,
'vendor_id' => $vendor->id,
'is_primary' => 1,
'send_email' => true,
]);
/** @var \App\Models\PurchaseOrder $purchase_order */
$purchase_order = PurchaseOrder::factory()->create([
'user_id' => auth()->user()->id,
'company_id' => auth()->user()->company()->id,
'user_id' => $user->id,
'company_id' => $user->company()->id,
'vendor_id' => $vendor->id,
'terms' => 'Sample Terms',
'footer' => 'Sample Footer',
'public_notes' => 'Sample Public Notes',
]);
/** @var \App\Models\PurchaseOrderInvitation $invitation */
$invitation = PurchaseOrderInvitation::factory()->create([
'user_id' => auth()->user()->id,
'company_id' => auth()->user()->company()->id,
'user_id' => $user->id,
'company_id' => $user->company()->id,
'purchase_order_id' => $purchase_order->id,
'vendor_contact_id' => $contact->id,
]);
$purchase_order->setRelation('invitations', $invitation);
$purchase_order->setRelation('vendor', $vendor);
$purchase_order->setRelation('company', auth()->user()->company());
$purchase_order->setRelation('company', $user->company());
$purchase_order->load('vendor.company');
$design_object = json_decode(json_encode(request()->input('design')));
@ -413,7 +436,10 @@ class PreviewPurchaseOrderController extends BaseController
->design($design)
->build();
DB::connection(auth()->user()->company()->db)->rollBack();
/** @var \App\Models\User $user */
$user = auth()->user();
DB::connection($user->company()->db)->rollBack();
if (request()->query('html') == 'true') {
return $maker->getCompiledHTML();
@ -426,7 +452,7 @@ class PreviewPurchaseOrderController extends BaseController
if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true));
$numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
$numbered_pdf = $this->pageNumbering($pdf, $user->company());
if ($numbered_pdf) {
$pdf = $numbered_pdf;
@ -435,7 +461,7 @@ class PreviewPurchaseOrderController extends BaseController
return $pdf;
}
$file_path = (new PreviewPdf($maker->getCompiledHTML(true), auth()->user()->company()))->handle();
$file_path = (new PreviewPdf($maker->getCompiledHTML(true), $user->company()))->handle();
$response = Response::make($file_path, 200);
$response->header('Content-Type', 'application/pdf');

View File

@ -312,7 +312,10 @@ class ProjectController extends BaseController
*/
public function create(CreateProjectRequest $request)
{
$project = ProjectFactory::create(auth()->user()->company()->id, auth()->user()->id);
/** @var \App\Models\User $user */
$user = auth()->user();
$project = ProjectFactory::create($user->company()->id, $user->id);
return $this->itemResponse($project);
}
@ -357,7 +360,10 @@ class ProjectController extends BaseController
*/
public function store(StoreProjectRequest $request)
{
$project = ProjectFactory::create(auth()->user()->company()->id, auth()->user()->id);
/** @var \App\Models\User $user */
$user = auth()->user();
$project = ProjectFactory::create($user->company()->id, $user->id);
$project->fill($request->all());
$project->saveQuietly();
@ -486,14 +492,17 @@ class ProjectController extends BaseController
*/
public function bulk()
{
/** @var \App\Models\User $user */
$user = auth()->user();
$action = request()->input('action');
$ids = request()->input('ids');
$projects = Project::withTrashed()->find($this->transformKeys($ids));
$projects->each(function ($project, $key) use ($action) {
if (auth()->user()->can('edit', $project)) {
$projects->each(function ($project, $key) use ($action, $user) {
if ($user->can('edit', $project)) {
$this->project_repo->{$action}($project);
}
});
@ -504,12 +513,10 @@ class ProjectController extends BaseController
/**
* Update the specified resource in storage.
*
* @param UploadProductRequest $request
* @param Product $project
* @param UploadProjectRequest $request
* @param Project $project
* @return Response
*
*
*
* @OA\Put(
* path="/api/v1/projects/{id}/upload",
* operationId="uploadProject",

View File

@ -162,7 +162,10 @@ class QuoteController extends BaseController
*/
public function create(CreateQuoteRequest $request)
{
$quote = QuoteFactory::create(auth()->user()->company()->id, auth()->user()->id);
/** @var \App\Models\User $user */
$user = auth()->user();
$quote = QuoteFactory::create($user->company()->id, $user->id);
return $this->itemResponse($quote);
}
@ -208,16 +211,17 @@ class QuoteController extends BaseController
*/
public function store(StoreQuoteRequest $request)
{
$client = Client::find($request->input('client_id'));
$quote = $this->quote_repo->save($request->all(), QuoteFactory::create(auth()->user()->company()->id, auth()->user()->id));
/** @var \App\Models\User $user */
$user = auth()->user();
$quote = $this->quote_repo->save($request->all(), QuoteFactory::create($user->company()->id, $user->id));
$quote = $quote->service()
->fillDefaults()
->triggeredActions($request)
->save();
event(new QuoteWasCreated($quote, $quote->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
event(new QuoteWasCreated($quote, $quote->company, Ninja::eventVars($user->id)));
return $this->itemResponse($quote);
}
@ -509,11 +513,14 @@ class QuoteController extends BaseController
*/
public function bulk(BulkActionQuoteRequest $request)
{
/** @var \App\Models\User $user */
$user = auth()->user();
$action = request()->input('action');
$ids = request()->input('ids');
if (Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) {
if (Ninja::isHosted() && (stripos($action, 'email') !== false) && !$user->account->account_sms_verified) {
return response(['message' => 'Please verify your account to send emails.'], 400);
}
@ -528,8 +535,8 @@ class QuoteController extends BaseController
*/
if ($action == 'bulk_download' && $quotes->count() >= 1) {
$quotes->each(function ($quote) {
if (auth()->user()->cannot('view', $quote)) {
$quotes->each(function ($quote) use($user){
if ($user->cannot('view', $quote)) {
return response()->json(['message'=> ctrans('texts.access_denied')]);
}
});
@ -543,8 +550,8 @@ class QuoteController extends BaseController
$this->entity_type = Quote::class;
$this->entity_transformer = QuoteTransformer::class;
$quotes->each(function ($quote, $key) use ($action) {
if (auth()->user()->can('edit', $quote) && $quote->service()->isConvertable()) {
$quotes->each(function ($quote, $key) use ($user) {
if ($user->can('edit', $quote) && $quote->service()->isConvertable()) {
$quote->service()->convertToInvoice();
}
});
@ -552,7 +559,7 @@ class QuoteController extends BaseController
return $this->listResponse(Quote::withTrashed()->whereIn('id', $this->transformKeys($ids))->company());
}
if ($action == 'bulk_print' && auth()->user()->can('view', $quotes->first())) {
if ($action == 'bulk_print' && $user->can('view', $quotes->first())) {
$paths = $quotes->map(function ($quote) {
return $quote->service()->getQuotePdf();
});
@ -566,9 +573,9 @@ class QuoteController extends BaseController
if ($action == 'convert_to_project') {
$quotes->each(function ($quote, $key) use ($action) {
if (auth()->user()->can('edit', $quote)) {
$project = CloneQuoteToProjectFactory::create($quote, auth()->user()->id);
$quotes->each(function ($quote, $key) use ($user) {
if ($user->can('edit', $quote)) {
$project = CloneQuoteToProjectFactory::create($quote, $user->id);
if (empty($project->number)) {
$project->number = $this->getNextProjectNumber($project);
@ -585,8 +592,8 @@ class QuoteController extends BaseController
/*
* Send the other actions to the switch
*/
$quotes->each(function ($quote, $key) use ($action) {
if (auth()->user()->can('edit', $quote)) {
$quotes->each(function ($quote, $key) use ($action, $user) {
if ($user->can('edit', $quote)) {
$this->performAction($quote, $action, true);
}
});
@ -607,18 +614,18 @@ class QuoteController extends BaseController
* tags={"quotes"},
* summary="Performs a custom action on an Quote",
* description="Performs a custom action on an Quote.
The current range of actions are as follows
- clone_to_quote
- history
- delivery_note
- mark_paid
- download
- archive
- delete
- convert
- convert_to_invoice
- email",
*
* The current range of actions are as follows
* - clone_to_quote
* - history
* - delivery_note
* - mark_paid
* - download
* - archive
* - delete
* - convert
* - convert_to_invoice
* - email",
* @OA\Parameter(ref="#/components/parameters/X-API-TOKEN"),
* @OA\Parameter(ref="#/components/parameters/X-Requested-With"),
* @OA\Parameter(ref="#/components/parameters/include"),

View File

@ -49,7 +49,7 @@ class RecurringExpenseController extends BaseController
protected $entity_transformer = RecurringExpenseTransformer::class;
/**
* @var RecurringExpenseepository
* @var RecurringExpenseRepository
*/
protected $recurring_expense_repo;
@ -72,7 +72,7 @@ class RecurringExpenseController extends BaseController
* summary="Gets a list of recurring_expenses",
* description="Lists recurring_expenses, search and filters allow fine grained lists to be generated.
Query parameters can be added to performed more fine grained filtering of the recurring_expenses, these are handled by the RecurringExpenseFilters class which defines the methods available",
* Query parameters can be added to performed more fine grained filtering of the recurring_expenses, these are handled by the RecurringExpenseFilters class which defines the methods available",
* @OA\Parameter(ref="#/components/parameters/X-API-TOKEN"),
* @OA\Parameter(ref="#/components/parameters/X-Requested-With"),
* @OA\Parameter(ref="#/components/parameters/include"),
@ -320,7 +320,10 @@ class RecurringExpenseController extends BaseController
*/
public function create(CreateRecurringExpenseRequest $request)
{
$recurring_expense = RecurringExpenseFactory::create(auth()->user()->company()->id, auth()->user()->id);
/** @var \App\Models\User $user */
$user = auth()->user();
$recurring_expense = RecurringExpenseFactory::create($user->company()->id, $user->id);
return $this->itemResponse($recurring_expense);
}
@ -365,10 +368,13 @@ class RecurringExpenseController extends BaseController
*/
public function store(StoreRecurringExpenseRequest $request)
{
$recurring_expense = $this->recurring_expense_repo->save($request->all(), RecurringExpenseFactory::create(auth()->user()->company()->id, auth()->user()->id));
/** @var \App\Models\User $user */
$user = auth()->user();
$recurring_expense = $this->recurring_expense_repo->save($request->all(), RecurringExpenseFactory::create($user->company()->id, $user->id));
$recurring_expense->service()->triggeredActions($request)->save();
event(new RecurringExpenseWasCreated($recurring_expense, $recurring_expense->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
event(new RecurringExpenseWasCreated($recurring_expense, $recurring_expense->company, Ninja::eventVars($user->id)));
return $this->itemResponse($recurring_expense);
}
@ -481,13 +487,16 @@ class RecurringExpenseController extends BaseController
*/
public function bulk()
{
/** @var \App\Models\User $user */
$user = auth()->user();
$action = request()->input('action');
$ids = request()->input('ids');
$recurring_expenses = RecurringExpense::withTrashed()->find($this->transformKeys($ids));
$recurring_expenses->each(function ($recurring_expense, $key) use ($action) {
if (auth()->user()->can('edit', $recurring_expense)) {
$recurring_expenses->each(function ($recurring_expense, $key) use ($action, $user) {
if ($user->can('edit', $recurring_expense)) {
$this->performAction($recurring_expense, $action, true);
}
});

View File

@ -148,7 +148,10 @@ class RecurringQuoteController extends BaseController
*/
public function create(CreateRecurringQuoteRequest $request)
{
$recurring_quote = RecurringQuoteFactory::create(auth()->user()->company()->id, auth()->user()->id);
/** @var \App\Models\User $user */
$user = auth()->user();
$recurring_quote = RecurringQuoteFactory::create($user->company()->id, $user->id);
return $this->itemResponse($recurring_quote);
}
@ -193,7 +196,10 @@ class RecurringQuoteController extends BaseController
*/
public function store(StoreRecurringQuoteRequest $request)
{
$recurring_quote = $this->recurring_quote_repo->save($request, RecurringQuoteFactory::create(auth()->user()->company()->id, auth()->user()->id));
/** @var \App\Models\User $user */
$user = auth()->user();
$recurring_quote = $this->recurring_quote_repo->save($request, RecurringQuoteFactory::create($user->company()->id, $user->id));
return $this->itemResponse($recurring_quote);
}
@ -479,14 +485,17 @@ class RecurringQuoteController extends BaseController
*/
public function bulk()
{
/** @var \App\Models\User $user */
$user = auth()->user();
$action = request()->input('action');
$ids = request()->input('ids');
$recurring_quotes = RecurringQuote::withTrashed()->find($this->transformKeys($ids));
$recurring_quotes->each(function ($recurring_quote, $key) use ($action) {
if (auth()->user()->can('edit', $recurring_quote)) {
$recurring_quotes->each(function ($recurring_quote, $key) use ($action, $user) {
if ($user->can('edit', $recurring_quote)) {
$this->recurring_quote_repo->{$action}($recurring_quote);
}
});
@ -573,11 +582,11 @@ class RecurringQuoteController extends BaseController
// return $this->itemResponse($recurring_invoice);
break;
case 'clone_to_quote':
$quote = CloneRecurringQuoteToQuoteFactory::create($recurring_invoice, auth()->user()->id);
$this->entity_transformer = QuoteTransformer::class;
$this->entity_type = Quote::class;
// $quote = CloneRecurringQuoteToQuoteFactory::create($recurring_invoice, auth()->user()->id);
// $this->entity_transformer = QuoteTransformer::class;
// $this->entity_type = Quote::class;
return $this->itemResponse($quote);
// return $this->itemResponse($quote);
break;
case 'history':
// code...

View File

@ -53,6 +53,7 @@ class ClientController extends BaseController
public function show(Request $request, string $contact_key)
{
/** @var \App\Models\Company $company */
$company = Company::where('company_key', $request->header('X-API-COMPANY-KEY'))->first();
if (! $company->enable_shop_api) {
@ -69,6 +70,7 @@ class ClientController extends BaseController
public function store(StoreShopClientRequest $request)
{
/** @var \App\Models\Company $company */
$company = Company::where('company_key', $request->header('X-API-COMPANY-KEY'))->first();
if (! $company->enable_shop_api) {

View File

@ -53,6 +53,7 @@ class InvoiceController extends BaseController
public function show(Request $request, string $invitation_key)
{
/** @var \App\Models\Company $company */
$company = Company::where('company_key', $request->header('X-API-COMPANY-KEY'))->first();
if (! $company->enable_shop_api) {
@ -69,6 +70,7 @@ class InvoiceController extends BaseController
public function store(StoreShopInvoiceRequest $request)
{
/** @var \App\Models\Company $company */
$company = Company::where('company_key', $request->header('X-API-COMPANY-KEY'))->first();
if (! $company->enable_shop_api) {

View File

@ -36,6 +36,7 @@ class ProductController extends BaseController
*/
public function index(Request $request)
{
/** @var \App\Models\Company $company */
$company = Company::where('company_key', $request->header('X-API-COMPANY-KEY'))->firstOrFail();
if (! $company->enable_shop_api) {
@ -49,6 +50,7 @@ class ProductController extends BaseController
public function show(Request $request, string $product_key)
{
/** @var \App\Models\Company $company */
$company = Company::where('company_key', $request->header('X-API-COMPANY-KEY'))->firstOrFail();
if (! $company->enable_shop_api) {

View File

@ -28,6 +28,7 @@ class ProfileController extends BaseController
public function show(Request $request)
{
/** @var \App\Models\Company $company */
$company = Company::where('company_key', $request->header('X-API-COMPANY-KEY'))->first();
if (! $company->enable_shop_api) {

View File

@ -19,8 +19,6 @@ class StaticController extends BaseController
/**
* Show the list of Invoices.
*
* @param InvoiceFilters $filters The filters
*
* @return Response
*
* @OA\Get(
@ -54,7 +52,11 @@ class StaticController extends BaseController
*/
public function __invoke()
{
$response = Statics::company(auth()->user()->getCompany()->getLocale());
/** @var \App\Models\User $user */
$user = auth()->user();
$response = Statics::company($user->company()->getLocale());
return response()->json($response, 200, ['Content-type'=> 'application/json; charset=utf-8'], JSON_PRETTY_PRINT);
}

View File

@ -81,6 +81,7 @@ class StripeConnectController extends BaseController
MultiDB::findAndSetDbByCompanyKey($request->getTokenContent()['company_key']);
/** @var \App\Models\Company $company */
$company = Company::where('company_key', $request->getTokenContent()['company_key'])->first();
$company_gateway = CompanyGateway::query()

View File

@ -27,8 +27,11 @@ class StripeController extends BaseController
public function update()
{
if (auth()->user()->isAdmin()) {
StripeUpdatePaymentMethods::dispatch(auth()->user()->company());
/** @var \App\Models\User $user */
$user = auth()->user();
if ($user->isAdmin()) {
StripeUpdatePaymentMethods::dispatch($user->company());
return response()->json(['message' => 'Processing'], 200);
}
@ -38,10 +41,11 @@ class StripeController extends BaseController
public function import()
{
// return response()->json(['message' => 'Processing'], 200);
/** @var \App\Models\User $user */
$user = auth()->user();
if (auth()->user()->isAdmin()) {
ImportStripeCustomers::dispatch(auth()->user()->company());
if ($user->isAdmin()) {
ImportStripeCustomers::dispatch($user->company());
return response()->json(['message' => 'Processing'], 200);
}
@ -51,10 +55,14 @@ class StripeController extends BaseController
public function verify()
{
if (auth()->user()->isAdmin()) {
MultiDB::findAndSetDbByCompanyKey(auth()->user()->company()->company_key);
/** @var \App\Models\User $user */
$user = auth()->user();
$company_gateway = CompanyGateway::where('company_id', auth()->user()->company()->id)
if ($user->isAdmin()) {
MultiDB::findAndSetDbByCompanyKey($user->company()->company_key);
/** @var \App\Models\CompanyGateway $company_gateway */
$company_gateway = CompanyGateway::where('company_id', $user->company()->id)
->where('is_deleted', 0)
->whereIn('gateway_key', $this->stripe_keys)
->first();
@ -67,7 +75,11 @@ class StripeController extends BaseController
public function disconnect(string $company_gateway_id)
{
$company_gateway = CompanyGateway::where('company_id', auth()->user()->company()->id)
/** @var \App\Models\User $user */
$user = auth()->user();
/** @var \App\Models\CompanyGateway $company_gateway */
$company_gateway = CompanyGateway::where('company_id', $user->company()->id)
->where('id', $this->decodePrimaryKey($company_gateway_id))
->whereIn('gateway_key', $this->stripe_keys)
->firstOrFail();

View File

@ -48,7 +48,7 @@ class SubscriptionController extends BaseController
/**
* Show the list of Subscriptions.
*
* @return \Illuminate\Http\JsonResponse
* @return \Illuminate\Http\Response
*
* @OA\Get(
* path="/api/v1/subscriptions",
@ -92,7 +92,7 @@ class SubscriptionController extends BaseController
*
* @param CreateSubscriptionRequest $request The request
*
* @return \Illuminate\Http\JsonResponse
* @return \Illuminate\Http\Response
*
*
* @OA\Get(
@ -127,7 +127,10 @@ class SubscriptionController extends BaseController
*/
public function create(CreateSubscriptionRequest $request): \Illuminate\Http\Response
{
$subscription = SubscriptionFactory::create(auth()->user()->company()->id, auth()->user()->id);
/** @var \App\Models\User $user */
$user = auth()->user();
$subscription = SubscriptionFactory::create($user->company()->id, $user->id);
return $this->itemResponse($subscription);
}
@ -137,7 +140,7 @@ class SubscriptionController extends BaseController
*
* @param StoreSubscriptionRequest $request The request
*
* @return \Illuminate\Http\JsonResponse
* @return \Illuminate\Http\Response
*
*
* @OA\Post(
@ -172,9 +175,12 @@ class SubscriptionController extends BaseController
*/
public function store(StoreSubscriptionRequest $request): \Illuminate\Http\Response
{
$subscription = $this->subscription_repo->save($request->all(), SubscriptionFactory::create(auth()->user()->company()->id, auth()->user()->id));
/** @var \App\Models\User $user */
$user = auth()->user();
event(new SubscriptionWasCreated($subscription, $subscription->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
$subscription = $this->subscription_repo->save($request->all(), SubscriptionFactory::create($user->company()->id, $user->id));
event(new SubscriptionWasCreated($subscription, $subscription->company, Ninja::eventVars($user->id)));
return $this->itemResponse($subscription);
}
@ -183,9 +189,9 @@ class SubscriptionController extends BaseController
* Display the specified resource.
*
* @param ShowSubscriptionRequest $request The request
* @param Invoice $subscription The invoice
* @param Subscription $subscription The invoice
*
* @return \Illuminate\Http\JsonResponse
* @return \Illuminate\Http\Response
*
*
* @OA\Get(
@ -238,9 +244,9 @@ class SubscriptionController extends BaseController
* Show the form for editing the specified resource.
*
* @param EditSubscriptionRequest $request The request
* @param Invoice $subscription The invoice
* @param Subscription $subscription The subscription
*
* @return \Illuminate\Http\JsonResponse
* @return \Illuminate\Http\Response
*
* @OA\Get(
* path="/api/v1/subscriptions/{id}/edit",
@ -292,9 +298,9 @@ class SubscriptionController extends BaseController
* Update the specified resource in storage.
*
* @param UpdateSubscriptionRequest $request The request
* @param Subscription $subscription The invoice
* @param Subscription $subscription The subscription
*
* @return \Illuminate\Http\JsonResponse
* @return \Illuminate\Http\Response
*
*
* @OA\Put(
@ -338,7 +344,7 @@ class SubscriptionController extends BaseController
* ),
* )
*/
public function update(UpdateSubscriptionRequest $request, Subscription $subscription)
public function update(UpdateSubscriptionRequest $request, Subscription $subscription): \Illuminate\Http\Response
{
if ($request->entityIsDeleted($subscription)) {
return $request->disallowUpdate();
@ -346,7 +352,10 @@ class SubscriptionController extends BaseController
$subscription = $this->subscription_repo->save($request->all(), $subscription);
event(new SubscriptionWasUpdated($subscription, $subscription->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
/** @var \App\Models\User $user */
$user = auth()->user();
event(new SubscriptionWasUpdated($subscription, $subscription->company, Ninja::eventVars($user->id)));
return $this->itemResponse($subscription);
}
@ -355,9 +364,9 @@ class SubscriptionController extends BaseController
* Remove the specified resource from storage.
*
* @param DestroySubscriptionRequest $request
* @param Subscription $invoice
* @param Subscription $subscription
*
* @return \Illuminate\Http\JsonResponse
* @return \Illuminate\Http\Response
*
* @throws \Exception
* @OA\Delete(
@ -459,13 +468,16 @@ class SubscriptionController extends BaseController
*/
public function bulk()
{
/** @var \App\Models\User $user */
$user = auth()->user();
$action = request()->input('action');
$ids = request()->input('ids');
$subscriptions = Subscription::withTrashed()->find($this->transformKeys($ids));
$subscriptions->each(function ($subscription, $key) use ($action) {
if (auth()->user()->can('edit', $subscription)) {
$subscriptions->each(function ($subscription, $key) use ($action, $user) {
if ($user->can('edit', $subscription)) {
$this->subscription_repo->{$action}($subscription);
}
});

View File

@ -50,7 +50,7 @@ class TaskController extends BaseController
protected $entity_transformer = TaskTransformer::class;
/**
* @var Taskepository
* @var TaskRepository
*/
protected $task_repo;
@ -583,7 +583,7 @@ class TaskController extends BaseController
/**
* Store a newly created resource in storage.
*
* @param StoreTaskRequest $request
* @param SortTaskRequest $request
* @return Response
*
*

View File

@ -11,19 +11,20 @@
namespace App\Http\Controllers;
use App\Models\TaskStatus;
use Illuminate\Http\Response;
use App\Utils\Traits\MakesHash;
use App\Factory\TaskStatusFactory;
use App\Filters\TaskStatusFilters;
use App\Http\Requests\TaskStatus\ActionTaskStatusRequest;
use App\Http\Requests\TaskStatus\CreateTaskStatusRequest;
use App\Http\Requests\TaskStatus\DestroyTaskStatusRequest;
use App\Http\Requests\TaskStatus\ShowTaskStatusRequest;
use App\Http\Requests\TaskStatus\StoreTaskStatusRequest;
use App\Http\Requests\TaskStatus\UpdateTaskStatusRequest;
use App\Models\TaskStatus;
use App\Repositories\TaskStatusRepository;
use App\Transformers\TaskStatusTransformer;
use App\Utils\Traits\MakesHash;
use Illuminate\Http\Response;
use App\Http\Requests\TaskStatus\EditTaskStatusRequest;
use App\Http\Requests\TaskStatus\ShowTaskStatusRequest;
use App\Http\Requests\TaskStatus\StoreTaskStatusRequest;
use App\Http\Requests\TaskStatus\ActionTaskStatusRequest;
use App\Http\Requests\TaskStatus\CreateTaskStatusRequest;
use App\Http\Requests\TaskStatus\UpdateTaskStatusRequest;
use App\Http\Requests\TaskStatus\DestroyTaskStatusRequest;
class TaskStatusController extends BaseController
{

View File

@ -48,7 +48,7 @@ class VendorController extends BaseController
protected $entity_transformer = VendorTransformer::class;
/**
* @var Vendorepository
* @var VendorRepository
*/
protected $vendor_repo;

View File

@ -81,6 +81,7 @@ class DocumentController extends Controller
{
MultiDB::documentFindAndSetDb($document_hash);
/** @var \App\Models\Document $document */
$document = Document::where('hash', $document_hash)->firstOrFail();
$headers = [];
@ -94,6 +95,7 @@ class DocumentController extends Controller
public function downloadMultiple(DownloadMultipleDocumentsRequest $request)
{
/** @var \Illuminate\Database\Eloquent\Collection<Document> $documents */
$documents = Document::whereIn('id', $this->transformKeys($request->file_hash))
->where('company_id', auth()->guard('vendor')->user()->company_id)
->get();

View File

@ -75,10 +75,10 @@ class PurchaseOrderController extends Controller
}
/**
* Show specific invoice.
* Show specific PurchaseOrder.
*
* @param ShowInvoiceRequest $request
* @param Invoice $invoice
* @param ShowPurchaseOrderRequest $request
* @param PurchaseOrder $purchase_order
*
* @return Factory|View
*/

View File

@ -24,26 +24,35 @@ class MatchBankTransactionRequest extends Request
*/
public function authorize() : bool
{
return auth()->user()->isAdmin() || auth()->user()->can('create', BankTransaction::class) || auth()->user()->hasPermission('edit_bank_transaction');
/** @var \App\Models\User $user */
$user = auth()->user();
return $user->isAdmin() || $user->can('create', BankTransaction::class) || $user->hasPermission('edit_bank_transaction');
}
public function rules()
public function rules(): array
{
/** @var \App\Models\User $user */
$user = auth()->user();
$rules = [
'transactions' => 'bail|array',
'transactions.*.invoice_ids' => 'nullable|string|sometimes',
];
$rules['transactions.*.ninja_category_id'] = 'bail|nullable|sometimes|exists:expense_categories,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
$rules['transactions.*.vendor_id'] = 'bail|nullable|sometimes|exists:vendors,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
$rules['transactions.*.id'] = 'bail|required|exists:bank_transactions,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
$rules['transactions.*.payment_id'] = 'bail|sometimes|nullable|exists:payments,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
$rules['transactions.*.ninja_category_id'] = 'bail|nullable|sometimes|exists:expense_categories,id,company_id,'.$user->company()->id.',is_deleted,0';
$rules['transactions.*.vendor_id'] = 'bail|nullable|sometimes|exists:vendors,id,company_id,'.$user->company()->id.',is_deleted,0';
$rules['transactions.*.id'] = 'bail|required|exists:bank_transactions,id,company_id,'.$user->company()->id.',is_deleted,0';
$rules['transactions.*.payment_id'] = 'bail|sometimes|nullable|exists:payments,id,company_id,'.$user->company()->id.',is_deleted,0';
return $rules;
}
public function prepareForValidation()
{
/** @var \App\Models\User $user */
$user = auth()->user();
$inputs = $this->all();
foreach ($inputs['transactions'] as $key => $input) {
@ -61,7 +70,7 @@ class MatchBankTransactionRequest extends Request
if (array_key_exists('payment_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['payment_id']) >= 1) {
$inputs['transactions'][$key]['payment_id'] = $this->decodePrimaryKey($inputs['transactions'][$key]['payment_id']);
$p = Payment::withTrashed()->where('company_id', auth()->user()->company()->id)->where('id', $inputs['transactions'][$key]['payment_id'])->first();
$p = Payment::withTrashed()->where('company_id', $user->company()->id)->where('id', $inputs['transactions'][$key]['payment_id'])->first();
/*Ensure we don't relink an existing payment*/
if (!$p || is_numeric($p->transaction_id)) {

View File

@ -65,7 +65,7 @@ class SendEmailRequest extends Request
$input['entity_id'] = $this->decodePrimaryKey($input['entity_id']);
}
if (array_key_exists('entity', $input)) {
if (isset($input['entity'])) {
$input['entity'] = "App\Models\\".ucfirst(Str::camel($input['entity']));
}
@ -83,15 +83,13 @@ class SendEmailRequest extends Request
{
$input = $this->all();
if (Ninja::isHosted() && !auth()->user()->account->account_sms_verified) {
$this->error_message = ctrans('texts.authorization_sms_failure');
return false;
}
/*Make sure we have all the require ingredients to send a template*/
if (array_key_exists('entity', $input) && array_key_exists('entity_id', $input) && is_string($input['entity']) && $input['entity_id']) {
if (isset($input['entity']) && array_key_exists('entity_id', $input) && is_string($input['entity']) && $input['entity_id']) {
/** @var \App\Models\User $user */
$user = auth()->user();
@ -108,6 +106,9 @@ class SendEmailRequest extends Request
return true;
}
}
else {
$this->error_message = "Invalid entity or entity_id";
}
return false;
}

View File

@ -218,7 +218,7 @@ class MatchBankTransactions implements ShouldQueue
private function matchInvoicePayment($input) :self
{
$this->bt = BankTransaction::find($input['id']);
$this->bt = BankTransaction::withTrashed()->find($input['id']);
if (!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) {
return $this;

View File

@ -51,9 +51,9 @@ class CreateEInvoice implements ShouldQueue
/* Set customized translations _NOW_ */
$t->replace(Ninja::transformTranslations($this->invoice->client->getMergedSettings()));
$e_invoice_type = $this->invoice->client->getSetting('e_invoice_type');
switch ($e_invoice_type) {
case "EN16931":
case "XInvoice_2_2":
@ -63,13 +63,13 @@ class CreateEInvoice implements ShouldQueue
case "XInvoice-Extended":
case "XInvoice-BasicWL":
case "XInvoice-Basic":
return (new ZugferdEInvoice($this->invoice, $this->alterPDF, $this->custom_pdf_path))->run();
return (new ZugferdEInvoice($this->invoice))->run();
case "Facturae_3.2":
case "Facturae_3.2.1":
case "Facturae_3.2.2":
return (new FacturaEInvoice($this->invoice, str_replace("Facturae_", "", $e_invoice_type)))->run();
default:
return (new ZugferdEInvoice($this->invoice, $this->alterPDF, $this->custom_pdf_path))->run();
return (new ZugferdEInvoice($this->invoice))->run();
}

View File

@ -110,31 +110,54 @@ class SendRecurring implements ShouldQueue
if ($invoice->auto_bill_enabled && $invoice->client->getSetting('auto_bill_date') == 'on_send_date' && $invoice->client->getSetting('auto_email_invoice')) {
nlog("attempting to autobill {$invoice->number}");
AutoBill::dispatch($invoice->id, $this->db, true)->delay(rand(1, 2));
//04-08-2023 edge case to support where online payment notifications are not enabled
if(!$invoice->client->getSetting('client_online_payment_notification')){
$this->sendRecurringEmails($invoice);
}
}
elseif ($invoice->auto_bill_enabled && $invoice->client->getSetting('auto_bill_date') == 'on_due_date' && $invoice->client->getSetting('auto_email_invoice') && ($invoice->due_date && Carbon::parse($invoice->due_date)->startOfDay()->lte(now()->startOfDay()))) {
nlog("attempting to autobill {$invoice->number}");
AutoBill::dispatch($invoice->id, $this->db, true)->delay(rand(1, 2));
}
elseif ($invoice->client->getSetting('auto_email_invoice')) {
//Admin notification for recurring invoice sent.
if ($invoice->invitations->count() >= 1) {
$invoice->entityEmailEvent($invoice->invitations->first(), 'invoice', 'email_template_invoice');
//04-08-2023 edge case to support where online payment notifications are not enabled
if(!$invoice->client->getSetting('client_online_payment_notification')) {
$this->sendRecurringEmails($invoice);
}
$invoice->invitations->each(function ($invitation) use ($invoice) {
if ($invitation->contact && ! $invitation->contact->trashed() && strlen($invitation->contact->email) >= 1 && $invoice->client->getSetting('auto_email_invoice')) {
try {
EmailEntity::dispatch($invitation, $invoice->company)->delay(rand(1, 2));
} catch (\Exception $e) {
nlog($e->getMessage());
}
nlog("Firing email for invoice {$invoice->number}");
}
});
}
elseif ($invoice->client->getSetting('auto_email_invoice')) {
$this->sendRecurringEmails($invoice);
}
}
/**
* Sends the recurring invoice emails to
* the designated contacts
*
* @param Invoice $invoice
* @return void
*/
private function sendRecurringEmails(Invoice $invoice): void
{
//Admin notification for recurring invoice sent.
if ($invoice->invitations->count() >= 1) {
$invoice->entityEmailEvent($invoice->invitations->first(), 'invoice', 'email_template_invoice');
}
$invoice->invitations->each(function ($invitation) use ($invoice) {
if ($invitation->contact && ! $invitation->contact->trashed() && strlen($invitation->contact->email) >= 1 && $invoice->client->getSetting('auto_email_invoice')) {
try {
EmailEntity::dispatch($invitation, $invoice->company)->delay(rand(1, 2));
} catch (\Exception $e) {
nlog($e->getMessage());
}
nlog("Firing email for invoice {$invoice->number}");
}
});
}
/**
@ -145,7 +168,8 @@ class SendRecurring implements ShouldQueue
private function createRecurringInvitations($invoice) :Invoice
{
if ($this->recurring_invoice->invitations->count() == 0) {
$this->recurring_invoice = $this->recurring_invoice->service()->createInvitations()->save();
$this->recurring_invoice->service()->createInvitations()->save();
$this->recurring_invoice = $this->recurring_invoice->fresh();
}
$this->recurring_invoice->invitations->each(function ($recurring_invitation) use ($invoice) {
@ -172,18 +196,4 @@ class SendRecurring implements ShouldQueue
nlog(print_r($exception->getMessage(), 1));
}
}
/**
*
* 1/8/2022
*
* Improvements here include moving the emailentity and autobilling into the queue.
*
* Further improvements could using the CompanyRecurringCron.php stub which divides
* the recurring invoices into companies and spins them off into their own queue to
* improve parallel processing.
*
* Need to be careful we do not overload redis and OOM.
*/
}

View File

@ -185,42 +185,42 @@ class Account extends BaseModel
return self::class;
}
public function users()
public function users(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(User::class)->withTrashed();
}
public function default_company()
public function default_company(): \Illuminate\Database\Eloquent\Relations\HasOne
{
return $this->hasOne(Company::class, 'id', 'default_company_id');
}
public function payment()
public function payment(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Payment::class)->withTrashed();
}
public function companies()
public function companies(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Company::class);
}
public function bank_integrations()
public function bank_integrations(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(BankIntegration::class);
}
public function company_users()
public function company_users(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(CompanyUser::class);
}
public function owner()
public function owner(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(CompanyUser::class)->where('is_owner', true)->first() ? $this->hasMany(CompanyUser::class)->where('is_owner', true)->first()->user : false;
}
public function tokens()
public function tokens(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(CompanyToken::class)->withTrashed();
}
@ -293,12 +293,12 @@ class Account extends BaseModel
}
}
public function isPaid()
public function isPaid(): bool
{
return Ninja::isNinja() ? ($this->isPaidHostedClient() && ! $this->isTrial()) : $this->hasFeature(self::FEATURE_WHITE_LABEL);
}
public function isPaidHostedClient()
public function isPaidHostedClient(): bool
{
if (! Ninja::isNinja()) {
return false;
@ -312,7 +312,7 @@ class Account extends BaseModel
return $this->plan == 'pro' || $this->plan == 'enterprise';
}
public function isFreeHostedClient()
public function isFreeHostedClient(): bool
{
if (! Ninja::isNinja()) {
return false;
@ -325,7 +325,7 @@ class Account extends BaseModel
return $this->plan == 'free' || is_null($this->plan) || empty($this->plan);
}
public function isEnterpriseClient()
public function isEnterpriseClient(): bool
{
if (! Ninja::isNinja()) {
return false;
@ -334,7 +334,7 @@ class Account extends BaseModel
return $this->plan == 'enterprise';
}
public function isTrial()
public function isTrial(): bool
{
if (! Ninja::isNinja()) {
return false;
@ -345,7 +345,7 @@ class Account extends BaseModel
return $plan_details && $plan_details['trial'];
}
public function startTrial($plan)
public function startTrial($plan): void
{
if (! Ninja::isNinja()) {
return;

View File

@ -33,6 +33,8 @@ use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundExceptio
* @property string $number
* @property int $company_id
* @property int $id
* @property int $user_id
* @property int $assigned_user_id
* @property \App\Models\Company $company
* @method static \Illuminate\Database\Eloquent\Builder|BaseModel|Illuminate\Database\Eloquent\Relations\BelongsTo|\Awobaz\Compoships\Database\Eloquent\Relations\BelongsTo|\App\Models\Company company()
* @method static \Illuminate\Database\Eloquent\Builder|BaseModel|Illuminate\Database\Eloquent\Relations\HasMany|BaseModel orderBy()

View File

@ -215,7 +215,7 @@ class ClientContact extends Authenticatable implements HasLocalePreference
}
}
public function client()
public function client(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Client::class)->withTrashed();
}
@ -225,32 +225,32 @@ class ClientContact extends Authenticatable implements HasLocalePreference
return $this->where('is_primary', true);
}
public function company()
public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Company::class);
}
public function user()
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(User::class)->withTrashed();
}
public function invoice_invitations()
public function invoice_invitations(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(InvoiceInvitation::class);
}
public function recurring_invoice_invitations()
public function recurring_invoice_invitations(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(RecurringInvoiceInvitation::class);
}
public function quote_invitations()
public function quote_invitations(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(QuoteInvitation::class);
}
public function credit_invitations()
public function credit_invitations(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(CreditInvitation::class);
}

View File

@ -11,22 +11,23 @@
namespace App\Models;
use App\Utils\Ninja;
use Illuminate\Support\Carbon;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\MakesDates;
use App\Helpers\Invoice\InvoiceSum;
use App\Helpers\Invoice\InvoiceSumInclusive;
use App\Jobs\Entity\CreateEntityPdf;
use App\Models\Presenters\CreditPresenter;
use App\Utils\Traits\MakesReminders;
use App\Services\Credit\CreditService;
use App\Services\Ledger\LedgerService;
use App\Utils\Ninja;
use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\MakesInvoiceValues;
use App\Utils\Traits\MakesReminders;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use App\Utils\Traits\MakesInvoiceValues;
use Laracasts\Presenter\PresentableTrait;
use App\Models\Presenters\CreditPresenter;
use App\Helpers\Invoice\InvoiceSumInclusive;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;
/**
* App\Models\Credit
@ -215,32 +216,32 @@ class Credit extends BaseModel
return $this->dateMutator($value);
}
public function assigned_user()
public function assigned_user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(User::class, 'assigned_user_id', 'id')->withTrashed();
}
public function vendor()
public function vendor(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Vendor::class);
}
public function history()
public function history(): \Illuminate\Database\Eloquent\Relations\HasManyThrough
{
return $this->hasManyThrough(Backup::class, Activity::class);
}
public function activities()
public function activities(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Activity::class)->orderBy('id', 'DESC')->take(50);
}
public function company()
public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Company::class);
}
public function user()
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(User::class)->withTrashed();
}
@ -250,17 +251,12 @@ class Credit extends BaseModel
return $this->belongsTo(Client::class)->withTrashed();
}
// public function contacts()
// {
// return $this->hasManyThrough(ClientContact::class, Client::class);
// }
public function invitations()
public function invitations(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(CreditInvitation::class);
}
public function project()
public function project(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Project::class)->withTrashed();
}
@ -268,17 +264,17 @@ class Credit extends BaseModel
/**
* The invoice which the credit has been created from.
*/
public function invoice()
public function invoice(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Invoice::class);
}
public function company_ledger()
public function company_ledger(): \Illuminate\Database\Eloquent\Relations\MorphMany
{
return $this->morphMany(CompanyLedger::class, 'company_ledgerable');
}
public function ledger()
public function ledger(): \App\Services\Ledger\LedgerService
{
return new LedgerService($this);
}
@ -287,17 +283,17 @@ class Credit extends BaseModel
* The invoice/s which the credit has
* been applied to.
*/
public function invoices()
public function invoices(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(Invoice::class)->using(Paymentable::class);
}
public function payments()
public function payments(): \Illuminate\Database\Eloquent\Relations\MorphToMany
{
return $this->morphToMany(Payment::class, 'paymentable');
}
public function documents()
public function documents(): \Illuminate\Database\Eloquent\Relations\MorphMany
{
return $this->morphMany(Document::class, 'documentable');
}
@ -320,7 +316,7 @@ class Credit extends BaseModel
return $credit_calc->build();
}
public function service()
public function service(): \App\Services\Credit\CreditService
{
return new CreditService($this);
}
@ -423,12 +419,12 @@ class Credit extends BaseModel
];
}
public function translate_entity()
public function translate_entity(): string
{
return ctrans('texts.credit');
}
public static function stringStatus(int $status)
public static function stringStatus(int $status): string
{
switch ($status) {
case self::STATUS_DRAFT:

View File

@ -56,32 +56,6 @@ use Illuminate\Support\Facades\Storage;
* @method static \Illuminate\Database\Eloquent\Builder|Document onlyTrashed()
* @method static \Illuminate\Database\Eloquent\Builder|Document query()
* @method static \Illuminate\Database\Eloquent\Builder|BaseModel scope()
* @method static \Illuminate\Database\Eloquent\Builder|Document whereAssignedUserId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereCompanyId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereCustomValue1($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereCustomValue2($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereCustomValue3($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereCustomValue4($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereDeletedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereDisk($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereDocumentableId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereDocumentableType($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereHash($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereHeight($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereIsDefault($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereIsPublic($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereName($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document wherePreview($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereProjectId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereSize($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereType($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereUrl($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereUserId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereVendorId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document whereWidth($value)
* @method static \Illuminate\Database\Eloquent\Builder|Document withTrashed()
* @method static \Illuminate\Database\Eloquent\Builder|Document withoutTrashed()
* @mixin \Eloquent

View File

@ -107,42 +107,27 @@ class InvoiceInvitation extends BaseModel
return Invoice::class;
}
/**
* @return mixed
*/
public function invoice()
public function invoice(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Invoice::class)->withTrashed();
}
/**
* @return mixed
*/
public function getEntity()
public function getEntity(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Invoice::class)->withTrashed();
}
/**
* @return mixed
*/
public function contact()
public function contact(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(ClientContact::class, 'client_contact_id', 'id')->withTrashed();
}
/**
* @return mixed
*/
public function user()
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(User::class)->withTrashed();
}
/**
* @return BelongsTo
*/
public function company()
public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Company::class);
}
@ -156,24 +141,24 @@ class InvoiceInvitation extends BaseModel
return sprintf('<img src="data:image/svg+xml;base64,%s"></img><p/>%s: %s', $this->signature_base64, ctrans('texts.signed'), $this->createClientDate($this->signature_date, $this->contact->client->timezone()->name));
}
public function getName()
public function getName(): string
{
return $this->key;
}
public function markViewed()
public function markViewed(): void
{
$this->viewed_date = Carbon::now();
$this->save();
}
public function markOpened()
public function markOpened(): void
{
$this->opened_date = Carbon::now();
$this->save();
}
public function pdf_file_path()
public function pdf_file_path(): string
{
$storage_path = Storage::url($this->invoice->client->invoice_filepath($this).$this->invoice->numberFormatter().'.pdf');

View File

@ -20,7 +20,7 @@ use Illuminate\Database\Eloquent\Model;
* @property string $hash
* @property string $fee_total
* @property int|null $fee_invoice_id
* @property object|array $data
* @property mixed $data
* @property int|null $payment_id
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at

View File

@ -17,9 +17,11 @@ namespace App\Models\Presenters;
class UserPresenter extends EntityPresenter
{
/**
* Returns the first and last names concatenated.
*
* @return string
*/
public function name()
public function name(): string
{
if (! $this->entity) {
return 'No User Object Available';
@ -30,8 +32,13 @@ class UserPresenter extends EntityPresenter
return $first_name.' '.$last_name;
}
public function getDisplayName()
/**
* Returns a full name (with fallback) of the user
*
* @return string
*/
public function getDisplayName(): string
{
if ($this->getFullName()) {
return $this->getFullName();
@ -43,6 +50,7 @@ class UserPresenter extends EntityPresenter
}
/**
* Returns the full name of the user
* @return string
*/
public function getFullName()
@ -53,4 +61,35 @@ class UserPresenter extends EntityPresenter
return '';
}
}
/**
* Returns the first name of the user
*
* @return string
*/
public function firstName(): string
{
if (! $this->entity) {
return 'No First Name Available';
}
return $this->entity->first_name ?? 'First Name';
}
/**
* Returns the last name of the user
*
* @return string
*/
public function lastName(): string
{
if (! $this->entity) {
return 'No Last Name Available';
}
return $this->entity->last_name ?? 'Last Name';
}
}

View File

@ -106,7 +106,7 @@ use Illuminate\Support\Facades\Storage;
* @property-read int|null $payments_count
* @property-read \App\Models\Project|null $project
* @property-read \App\Models\User $user
* @property-read \App\Models\Vendor|null $vendor
* @property \App\Models\Vendor|null $vendor
* @method static \Illuminate\Database\Eloquent\Builder|BaseModel company()
* @method static \Illuminate\Database\Eloquent\Builder|BaseModel exclude($columns)
* @method static \Database\Factories\PurchaseOrderFactory factory($count = null, $state = [])

View File

@ -15,6 +15,7 @@ use App\Utils\Ninja;
use App\Utils\Traits\Inviteable;
use App\Utils\Traits\MakesDates;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
@ -102,49 +103,37 @@ class PurchaseOrderInvitation extends BaseModel
return PurchaseOrder::class;
}
/**
* @return mixed
*/
public function purchase_order()
public function purchase_order(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(PurchaseOrder::class)->withTrashed();
}
/**
* @return mixed
*/
public function entity()
public function entity(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(PurchaseOrder::class)->withTrashed();
}
/**
* @return mixed
*/
public function contact()
public function contact(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(VendorContact::class, 'vendor_contact_id', 'id')->withTrashed();
}
/**
* @return mixed
*/
public function user()
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(User::class)->withTrashed();
}
public function company()
public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Company::class);
}
public function getName()
public function getName(): string
{
return $this->key;
}
public function markViewed()
public function markViewed(): void
{
$this->viewed_date = Carbon::now();
$this->save();

View File

@ -22,9 +22,9 @@ use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundExceptio
* @property-read mixed $id
* @method static \Illuminate\Database\Eloquent\Builder|StaticModel company()
* @method static \Illuminate\Database\Eloquent\Builder|StaticModel exclude($columns)
* @method static \Illuminate\Database\Eloquent\Builder|StaticModel newModelQuery($value)
* @method static \Illuminate\Database\Eloquent\Builder|StaticModel newQuery($value)
* @method static \Illuminate\Database\Eloquent\Builder|StaticModel query(?$value)
* @method static \Illuminate\Database\Eloquent\Builder|StaticModel newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|StaticModel newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|StaticModel query()
* @method static \Illuminate\Database\Eloquent\Builder|StaticModel find($value)
* @method static \Illuminate\Database\Eloquent\Builder|StaticModel with($value)
* @method static \Illuminate\Database\Eloquent\Builder|StaticModel withTrashed($value)

View File

@ -66,41 +66,6 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @method static \Illuminate\Database\Eloquent\Builder|Subscription onlyTrashed()
* @method static \Illuminate\Database\Eloquent\Builder|Subscription query()
* @method static \Illuminate\Database\Eloquent\Builder|BaseModel scope()
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereAllowCancellation($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereAllowPlanChanges($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereAllowQueryOverrides($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereAssignedUserId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereAutoBill($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereCompanyId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereCurrencyId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereDeletedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereFrequencyId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereGroupId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereIsAmountDiscount($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereIsDeleted($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereMaxSeatsLimit($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereMinSeatsLimit($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereName($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereOptionalProductIds($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereOptionalRecurringProductIds($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription wherePerSeatEnabled($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription wherePlanMap($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription wherePrice($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereProductIds($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription wherePromoCode($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription wherePromoDiscount($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription wherePromoPrice($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereRecurringProductIds($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereRefundPeriod($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereRegistrationRequired($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereTrialDuration($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereTrialEnabled($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereUseInventoryManagement($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereUserId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription whereWebhookConfiguration($value)
* @method static \Illuminate\Database\Eloquent\Builder|Subscription withTrashed()
* @method static \Illuminate\Database\Eloquent\Builder|Subscription withoutTrashed()
* @mixin \Eloquent

View File

@ -82,6 +82,8 @@ use Illuminate\Foundation\Auth\User as Authenticatable;
* @property-read int|null $notifications_count
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\CompanyToken> $tokens
* @property-read int|null $tokens_count
* @property \App\Models\CompanyToken $token
* @property int $company_id
* @method static \Database\Factories\UserFactory factory($count = null, $state = [])
* @method static \Illuminate\Database\Eloquent\Builder|User filter(\App\Filters\QueryFilters $filters)
* @method static \Illuminate\Database\Eloquent\Builder|User newModelQuery()
@ -231,7 +233,7 @@ class User extends Authenticatable implements MustVerifyEmail
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function companies()
public function companies(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(Company::class)->using(CompanyUser::class)->withPivot('permissions', 'settings', 'is_admin', 'is_owner', 'is_locked')->withTimestamps();
}
@ -283,7 +285,7 @@ class User extends Authenticatable implements MustVerifyEmail
return $this->getCompany();
}
public function company_users()
public function company_users(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(CompanyUser::class)->withTrashed();
}
@ -313,8 +315,6 @@ class User extends Authenticatable implements MustVerifyEmail
return $this->token()->cu;
// return $this->hasOneThrough(CompanyUser::class, CompanyToken::class, 'user_id', 'user_id', 'id', 'user_id')
// ->withTrashed();
}
/**
@ -327,7 +327,7 @@ class User extends Authenticatable implements MustVerifyEmail
return $this->company()->id;
}
public function clients()
public function clients(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Client::class);
}
@ -352,7 +352,6 @@ class User extends Authenticatable implements MustVerifyEmail
{
return json_decode($this->token()->cu->settings);
//return json_decode($this->company_user->settings);
}
/**
@ -364,14 +363,12 @@ class User extends Authenticatable implements MustVerifyEmail
{
return $this->token()->cu->is_admin;
// return $this->company_user->is_admin;
}
public function isOwner() : bool
{
return $this->token()->cu->is_owner;
// return $this->company_user->is_owner;
}
/**
@ -389,7 +386,7 @@ class User extends Authenticatable implements MustVerifyEmail
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function contacts()
public function contacts(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(ClientContact::class);
}
@ -581,12 +578,12 @@ class User extends Authenticatable implements MustVerifyEmail
return false;
}
public function documents()
public function documents(): \Illuminate\Database\Eloquent\Relations\MorphMany
{
return $this->morphMany(Document::class, 'documentable');
}
public function isVerified()
public function isVerified(): bool
{
return is_null($this->email_verified_at) ? false : true;
}

View File

@ -63,9 +63,7 @@ use Laracasts\Presenter\PresentableTrait;
* @property-read \App\Models\Company $company
* @property-read mixed $contact_id
* @property-read mixed $hashed_id
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
* @property-read int|null $notifications_count
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PurchaseOrderInvitation> $purchase_order_invitations
* @property-read int|null $purchase_order_invitations_count
* @property-read \App\Models\User $user
* @property-read \App\Models\Vendor $vendor
@ -74,66 +72,10 @@ use Laracasts\Presenter\PresentableTrait;
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact onlyTrashed()
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact query()
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereAcceptedTermsVersion($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereAvatar($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereAvatarSize($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereAvatarType($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereCompanyId($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereConfirmationCode($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereConfirmed($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereContactKey($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereCustomValue1($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereCustomValue2($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereCustomValue3($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereCustomValue4($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereDeletedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereEmail($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereEmailVerifiedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereFailedLogins($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereFirstName($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereGoogle2faSecret($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereIsLocked($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereIsPrimary($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereLastLogin($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereLastName($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereOauthProviderId($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereOauthUserId($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact wherePassword($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact wherePhone($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereRememberToken($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereSendEmail($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereToken($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereUserId($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact whereVendorId($value)
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact withTrashed()
* @method static \Illuminate\Database\Eloquent\Builder|VendorContact withoutTrashed()
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PurchaseOrderInvitation> $purchase_order_invitations
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PurchaseOrderInvitation> $purchase_order_invitations
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PurchaseOrderInvitation> $purchase_order_invitations
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PurchaseOrderInvitation> $purchase_order_invitations
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PurchaseOrderInvitation> $purchase_order_invitations
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PurchaseOrderInvitation> $purchase_order_invitations
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PurchaseOrderInvitation> $purchase_order_invitations
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PurchaseOrderInvitation> $purchase_order_invitations
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PurchaseOrderInvitation> $purchase_order_invitations
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PurchaseOrderInvitation> $purchase_order_invitations
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PurchaseOrderInvitation> $purchase_order_invitations
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection<int, \Illuminate\Notifications\DatabaseNotification> $notifications
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PurchaseOrderInvitation> $purchase_order_invitations
* @mixin \Eloquent
*/
class VendorContact extends Authenticatable implements HasLocalePreference
@ -213,7 +155,7 @@ class VendorContact extends Authenticatable implements HasLocalePreference
return $this->encodePrimaryKey($this->id);
}
public function vendor()
public function vendor(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Vendor::class)->withTrashed();
}
@ -223,12 +165,12 @@ class VendorContact extends Authenticatable implements HasLocalePreference
return $this->where('is_primary', true);
}
public function company()
public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Company::class);
}
public function user()
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(User::class)->withTrashed();
}

View File

@ -74,9 +74,6 @@ class CheckoutComPaymentDriver extends BaseDriver
*/
public $gateway;
/**
* @var
*/
public $payment_method; //the gateway type id
public static $methods = [
@ -178,7 +175,7 @@ class CheckoutComPaymentDriver extends BaseDriver
/**
* Process the payment response
*
* @param Request $request The payment request
* @param \Illuminate\Http\Request $request The payment request
* @return \Illuminate\View\View
*/
public function processPaymentResponse($request)

View File

@ -69,7 +69,9 @@ class CreditCard
// $error .= " - {$response->approval_message}";
// $error_code = property_exists($response, 'approval_message') ? $response->approval_message : 'Undefined code';
$error = '';
$error_code = '';
$data = [
'response' => $response,
'error' => $error,

View File

@ -100,6 +100,7 @@ class CreditCard implements MethodInterface
);
if ($request->shouldUseToken()) {
/** @var \App\Models\ClientGatewayToken $cgt **/
$cgt = ClientGatewayToken::where('token', $request->token)->first();
$token = $cgt->token;
}

View File

@ -61,11 +61,13 @@ class PaymentIntentProcessingWebhook implements ShouldQueue
foreach ($this->stripe_request as $transaction) {
if (array_key_exists('payment_intent', $transaction)) {
/** @var \App\Models\Payment $payment **/
$payment = Payment::query()
->where('company_id', $company->id)
->where('transaction_reference', $transaction['payment_intent'])
->first();
} else {
/** @var \App\Models\Payment $payment **/
$payment = Payment::query()
->where('company_id', $company->id)
->where('transaction_reference', $transaction['id'])
@ -80,6 +82,7 @@ class PaymentIntentProcessingWebhook implements ShouldQueue
}
if (isset($transaction['payment_method'])) {
/** @var \App\Models\ClientGatewayToken $cgt **/
$cgt = ClientGatewayToken::where('token', $transaction['payment_method'])->first();
if ($cgt && $cgt->meta?->state == 'unauthorized') {
@ -94,7 +97,7 @@ class PaymentIntentProcessingWebhook implements ShouldQueue
if ($this->payment_completed) {
return;
}
/** @var \App\Models\CompanyGateway $company_gateway **/
$company_gateway = CompanyGateway::find($this->company_gateway_id);
$stripe_driver = $company_gateway->driver()->init();
@ -123,8 +126,10 @@ class PaymentIntentProcessingWebhook implements ShouldQueue
return;
}
/** @var \App\Models\Company $company **/
$company = Company::where('company_key', $this->company_key)->first();
/** @var \App\Models\Payment $payment **/
$payment = Payment::query()
->where('company_id', $company->id)
->where('transaction_reference', $charge['id'])

View File

@ -113,8 +113,10 @@ class PaymentIntentWebhook implements ShouldQueue
return;
}
/** @var \App\Models\Company $company **/
$company = Company::where('company_key', $this->company_key)->first();
/** @var \App\Models\Payment $payment **/
$payment = Payment::query()
->where('company_id', $company->id)
->where('transaction_reference', $charge['id'])

View File

@ -58,6 +58,7 @@ class StripeWebhook implements ShouldQueue
$company = Company::where('company_key', $this->company_key)->first();
/** @var \App\Models\CompanyGateway $company_gateway **/
$company_gateway = CompanyGateway::find($this->company_gateway_id);
$stripe = $company_gateway->driver()->init();

View File

@ -49,6 +49,7 @@ class UpdateCustomer implements ShouldQueue
$company = Company::where('company_key', $this->company_key)->first();
/** @var \App\Models\CompanyGateway $company_gateway **/
$company_gateway = CompanyGateway::find($this->company_gateway_id);
$client = Client::withTrashed()->find($this->client_id);

View File

@ -174,7 +174,9 @@ class WePayPaymentDriver extends BaseDriver
$config = $this->company_gateway->getConfig();
$accountId = $this->company_gateway->getConfigField('accountId');
$objectId = false;
$objectType = '';
foreach (array_keys($input) as $key) {
if ('_id' == substr($key, -3)) {
$objectType = substr($key, 0, -3);
@ -183,7 +185,7 @@ class WePayPaymentDriver extends BaseDriver
}
}
if (! isset($objectType)) {
if (! $objectId) {
throw new \Exception('Could not find object id parameter');
}
@ -226,12 +228,13 @@ class WePayPaymentDriver extends BaseDriver
return ['message' => 'Processed successfully'];
} elseif ($objectType == 'checkout') {
/** @var \App\Models\Payment $payment */
$payment = Payment::where('company_id', $this->company_gateway->company_id)
->where('transaction_reference', '=', $objectId)
->first();
if (! $payment) {
throw new Exception('Unknown payment');
throw new \Exception('Unknown payment');
}
if ($payment->is_deleted) {

View File

@ -38,9 +38,9 @@ class ActivityRepository extends BaseRepository
/**
* Save the Activity.
*
* @param stdClass $fields The fields
* @param Collection $entity The entity that you wish to have backed up (typically Invoice, Quote etc etc rather than Payment)
* @param $event_vars
* @param \stdClass $fields The fields
* @param \App\Models\Invoice | \App\Models\Quote | \App\Models\Credit | \App\Models\PurchaseOrder $entity
* @param array $event_vars
*/
public function save($fields, $entity, $event_vars)
{
@ -69,8 +69,8 @@ class ActivityRepository extends BaseRepository
/**
* Creates a backup.
*
* @param Collection $entity The entity
* @param Collection $activity The activity
* @param \App\Models\Invoice | \App\Models\Quote | \App\Models\Credit | \App\Models\PurchaseOrder $entity
* @param \App\Models\Activity $activity The activity
*/
public function createBackup($entity, $activity)
{
@ -98,6 +98,7 @@ class ActivityRepository extends BaseRepository
public function getTokenId(array $event_vars)
{
if ($event_vars['token']) {
/** @var \App\Models\CompanyToken $company_token **/
$company_token = CompanyToken::where('token', $event_vars['token'])->first();
if ($company_token) {

View File

@ -56,9 +56,6 @@ class UserRepository extends BaseRepository
$company = auth()->user()->company();
$account = $company->account;
// if(array_key_exists('oauth_provider_id', $details))
// unset($details['oauth_provider_id']);
if (request()->has('validated_phone')) {
$details['phone'] = request()->input('validated_phone');
$user->verified_phone_number = false;
@ -103,8 +100,8 @@ class UserRepository extends BaseRepository
(new CreateCompanyToken($cu->company, $cu->user, 'restored_user'))->handle();
}
} else {
$cu->notifications = $data['company_user']['notifications'];
$cu->settings = $data['company_user']['settings'];
$cu->notifications = $data['company_user']['notifications'] ?? '';
$cu->settings = $data['company_user']['settings'] ?? '';
$cu->save();
}
}

View File

@ -48,12 +48,14 @@ class ProcessBankRules extends AbstractService
private function matchCredit()
{
/** @var \Illuminate\Database\Eloquent\Collection<Invoice> $this->invoices */
$this->invoices = Invoice::where('company_id', $this->bank_transaction->company_id)
->whereIn('status_id', [1,2,3])
->where('is_deleted', 0)
->get();
$invoice = $this->invoices->first(function ($value, $key) {
/** @var \App\Models\Invoice $value */
return str_contains($this->bank_transaction->description, $value->number);
});

View File

@ -310,25 +310,6 @@ class AutoBillInvoice extends AbstractService
return $this;
}
// private function applyPaymentToCredit($credit, $amount) :Credit
// {
// $credit_item = new InvoiceItem;
// $credit_item->type_id = '1';
// $credit_item->product_key = ctrans('texts.credit');
// $credit_item->notes = ctrans('texts.credit_payment', ['invoice_number' => $this->invoice->number]);
// $credit_item->quantity = 1;
// $credit_item->cost = $amount * -1;
// $credit_items = $credit->line_items;
// $credit_items[] = $credit_item;
// $credit->line_items = $credit_items;
// $credit = $credit->calc()->getCredit();
// $credit->save();
// return $credit;
// }
/**
* Harvests a client gateway token which passes the
@ -371,37 +352,4 @@ class AutoBillInvoice extends AbstractService
return false;
}
/**
* Adds a gateway fee to the invoice.
*
* @param float $fee The fee amount.
* @return AutoBillInvoice
* @deprecated / unused
*/
// private function addFeeToInvoice(float $fee)
// {
// //todo if we increase the invoice balance here, we will also need to adjust UP the client balance and ledger?
// $starting_amount = $this->invoice->amount;
// $item = new InvoiceItem;
// $item->quantity = 1;
// $item->cost = $fee;
// $item->notes = ctrans('texts.online_payment_surcharge');
// $item->type_id = 3;
// $items = (array) $this->invoice->line_items;
// $items[] = $item;
// $this->invoice->line_items = $items;
// $this->invoice->saveQuietly();
// $this->invoice = $this->invoice->calc()->getInvoice()->saveQuietly();
// if ($starting_amount != $this->invoice->amount && $this->invoice->status_id != Invoice::STATUS_DRAFT) {
// $this->invoice->client->service()->updateBalance($this->invoice->amount - $starting_amount)->save();
// $this->invoice->ledger()->updateInvoiceBalance($this->invoice->amount - $starting_amount, "Invoice {$this->invoice->number} balance updated after stale gateway fee removed")->save();
// }
// return $this;
// }
}

View File

@ -482,6 +482,8 @@ class FacturaEInvoice extends AbstractService
"fax" => "",
"website" => substr($company->settings->website, 0, 50),
"contactPeople" => substr($company->owner()->present()->name(), 0, 40),
"firstName" => $company->owner()->present()->firstName(),
"lastName" => $company->owner()->present()->lastName(),
// 'centres' => $this->setFace(),
// "cnoCnae" => "04647", // Clasif. Nacional de Act. Económicas
// "ineTownCode" => "280796" // Cód. de municipio del INE

View File

@ -23,7 +23,7 @@ use horstoeko\zugferd\codelists\ZugferdDutyTaxFeeCategories;
class ZugferdEInvoice extends AbstractService
{
public function __construct(public Invoice $invoice, private bool $alterPDF, private string $custom_pdf_path = "", private array $tax_map = [])
public function __construct(public Invoice $invoice, private array $tax_map = [])
{
}
@ -91,6 +91,7 @@ class ZugferdEInvoice extends AbstractService
//Create line items and calculate taxes
foreach ($this->invoice->line_items as $index => $item) {
/** @var \App\DataMapper\InvoiceItem $item **/
$xrechnung->addNewPosition($index)
->setDocumentPositionGrossPrice($item->gross_line_total)
->setDocumentPositionNetPrice($item->line_total);
@ -175,22 +176,6 @@ class ZugferdEInvoice extends AbstractService
$xrechnung->writeFile(Storage::disk($disk)->path($client->e_invoice_filepath($this->invoice->invitations->first()) . $this->invoice->getFileName("xml")));
// The validity can be checked using https://portal3.gefeg.com/invoice/validation or https://e-rechnung.bayern.de/app/#/upload
if ($this->alterPDF) {
if ($this->custom_pdf_path != "") {
$pdfBuilder = new ZugferdDocumentPdfBuilder($xrechnung, $this->custom_pdf_path);
$pdfBuilder->generateDocument();
$pdfBuilder->saveDocument($this->custom_pdf_path);
} else {
$filepath_pdf = $client->invoice_filepath($this->invoice->invitations->first()) . $this->invoice->getFileName();
$file = Storage::disk($disk)->exists($filepath_pdf);
if ($file) {
$pdfBuilder = new ZugferdDocumentPdfBuilder($xrechnung, Storage::disk($disk)->path($filepath_pdf));
$pdfBuilder->generateDocument();
$pdfBuilder->saveDocument(Storage::disk($disk)->path($filepath_pdf));
}
}
}
return $client->e_invoice_filepath($this->invoice->invitations->first()) . $this->invoice->getFileName("xml");
}

View File

@ -17,7 +17,7 @@ use App\Models\Invoice;
use App\Services\AbstractService;
use Illuminate\Support\Facades\Storage;
class GetInvoiceXInvoice extends AbstractService
class GetInvoiceEInvoice extends AbstractService
{
public function __construct(public Invoice $invoice, public ?ClientContact $contact = null)
{

View File

@ -48,7 +48,7 @@ class InvoiceService
return $this;
}
/**
* applyPaymentAmount
*
@ -194,9 +194,13 @@ class InvoiceService
public function getEInvoice($contact = null)
{
return (new GetInvoiceXInvoice($this->invoice, $contact))->run();
return (new GetInvoiceEInvoice($this->invoice, $contact))->run();
}
public function mergeEInvoice($contact = null): void
{
(new MergeEInvoice($this->invoice, $contact))->run();
}
public function sendEmail($contact = null)
{
$send_email = new SendEmail($this->invoice, null, $contact);

View File

@ -0,0 +1,61 @@
<?php
namespace App\Services\Invoice;
use App\Models\ClientContact;
use App\Models\Invoice;
use App\Services\AbstractService;
use horstoeko\zugferd\ZugferdDocumentPdfBuilder;
use Illuminate\Support\Facades\Storage;
use horstoeko\zugferd\ZugferdDocumentReader;
class MergeEInvoice extends AbstractService
{
public function __construct(public Invoice $invoice, public ?ClientContact $contact = null)
{
}
/**
* @throws \Exception
*/
public function run(): void
{
$e_invoice_type = $this->invoice->client->getSetting('e_invoice_type');
switch ($e_invoice_type) {
case "EN16931":
case "XInvoice_2_2":
case "XInvoice_2_1":
case "XInvoice_2_0":
case "XInvoice_1_0":
case "XInvoice-Extended":
case "XInvoice-BasicWL":
case "XInvoice-Basic":
$this->embedEInvoiceZuGFerD();
//case "Facturae_3.2":
//case "Facturae_3.2.1":
//case "Facturae_3.2.2":
//
default:
$this->embedEInvoiceZuGFerD();
break;
}
}
/**
* @throws \Exception
*/
private function embedEInvoiceZuGFerD(): void
{
$filepath_pdf = $this->invoice->client->invoice_filepath($this->invoice->invitations->first()) . $this->invoice->getFileName();
$e_invoice_path = $this->invoice->client->e_invoice_filepath($this->invoice->invitations->first()) . $this->invoice->getFileName("xml");
$document = ZugferdDocumentReader::readAndGuessFromFile($e_invoice_path);
$disk = config('filesystems.default');
if (!Storage::disk($disk)->exists($this->invoice->client->e_invoice_filepath($this->invoice->invitations->first()))) {
Storage::makeDirectory($this->invoice->client->e_invoice_filepath($this->invoice->invitations->first()));
}
$pdfBuilder = new ZugferdDocumentPdfBuilder($document, Storage::disk($disk)->path($filepath_pdf));
$pdfBuilder->generateDocument();
$pdfBuilder->saveDocument(Storage::disk($disk)->path($filepath_pdf));
}
}

View File

@ -39,7 +39,6 @@ class PdfBuilder
/**
* The DOM Document;
*
* @var $document
*/
public DomDocument $document;
@ -617,9 +616,8 @@ class PdfBuilder
/**
* Formats the line items for display.
*
* @param mixed $items
* @param array<\App\DataMapper\InvoiceItem> $items
* @param string $table_type
* @param mixed|null $custom_fields
*
* @return array
*/
@ -956,7 +954,7 @@ class PdfBuilder
* Performs a variable check to ensure
* the variable exists
*
* @param string $variables
* @param string $variable
* @return bool
*
*/
@ -1313,7 +1311,7 @@ class PdfBuilder
* Generates the custom values for the
* entity.
*
* @param array
* @param array $variables
* @return array
*/
public function genericDetailsBuilder(array $variables): array
@ -1470,7 +1468,7 @@ class PdfBuilder
* Passes an array of items by reference
* and performs a nl2br
*
* @param array
* @param array $items
* @return void
*
*/

View File

@ -103,26 +103,31 @@ class PdfMock
switch ($this->request['entity_type']) {
case 'invoice':
/** @var \App\Models\Invoice | \App\Models\Credit | \App\Models\Quote $entity */
$entity = Invoice::factory()->make();
$entity->client = Client::factory()->make(['settings' => $settings]);
$entity->invitation = InvoiceInvitation::factory()->make();
break;
case 'quote':
/** @var \App\Models\Invoice | \App\Models\Credit | \App\Models\Quote $entity */
$entity = Quote::factory()->make();
$entity->client = Client::factory()->make(['settings' => $settings]);
$entity->invitation = QuoteInvitation::factory()->make();
break;
case 'credit':
/** @var \App\Models\Invoice | \App\Models\Credit | \App\Models\Quote $entity */
$entity = Credit::factory()->make();
$entity->client = Client::factory()->make(['settings' => $settings]);
$entity->invitation = CreditInvitation::factory()->make();
break;
case 'purchase_order':
/** @var \App\Models\Invoice | \App\Models\Credit | \App\Models\Quote $entity */
$entity = PurchaseOrder::factory()->make();
$entity->client = Client::factory()->make(['settings' => $settings]);
$entity->invitation = PurchaseOrderInvitation::factory()->make();
break;
case PurchaseOrder::class:
/** @var \App\Models\PurchaseOrder $entity */
$entity = PurchaseOrder::factory()->make();
$entity->invitation = PurchaseOrderInvitation::factory()->make();
$entity->vendor = Vendor::factory()->make();
@ -183,7 +188,6 @@ class PdfMock
/**
* getStubVariables
*
* @return void
*/
public function getStubVariables()
{

View File

@ -42,7 +42,7 @@ class StubBuilder
public $entity_type;
public mixed $recipient;
public \App\Models\Client | \App\Models\Vendor $recipient;
public mixed $contact;

View File

@ -90,15 +90,10 @@ class RecurringService
public function deletePdf()
{
$this->recurring_entity->invitations->each(function ($invitation) {
// (new UnlinkFile(config('filesystems.default'), $this->recurring_entity->client->recurring_invoice_filepath($invitation) . $this->recurring_entity->numberFormatter().'.pdf'))->handle();
//30-06-2023
try {
Storage::disk(config('filesystems.default'))->delete($this->recurring_entity->client->recurring_invoice_filepath($invitation) . $this->recurring_entity->numberFormatter().'.pdf');
// if (Storage::disk(config('filesystems.default'))->exists($this->invoice->client->invoice_filepath($invitation).$this->invoice->numberFormatter().'.pdf')) {
// }
// if (Ninja::isHosted() && Storage::disk('public')->exists($this->invoice->client->invoice_filepath($invitation).$this->invoice->numberFormatter().'.pdf')) {
Storage::disk('public')->delete($this->recurring_entity->client->recurring_invoice_filepath($invitation) . $this->recurring_entity->numberFormatter().'.pdf');
if (Ninja::isHosted()) {
}

View File

@ -27,6 +27,7 @@ class UpdatePrice extends AbstractService
foreach ($line_items as $key => $line_item) {
/** @var \App\Models\Product $product **/
$product = Product::where('company_id', $this->recurring_invoice->company_id)
->where('product_key', $line_item->product_key)
->where('is_deleted', 0)

View File

@ -11,15 +11,16 @@
namespace App\Transformers;
use App\Models\Client;
use App\Models\Vendor;
use App\Models\Expense;
use App\Models\Invoice;
use App\Models\ExpenseCategory;
use App\Transformers\ExpenseCategoryTransformer;
use App\Models\Document;
use App\Models\ExpenseCategory;
use App\Utils\Traits\MakesHash;
use League\Fractal\Resource\Item;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Transformers\ExpenseCategoryTransformer;
/**
* class ExpenseTransformer.

View File

@ -11,10 +11,12 @@
namespace App\Transformers;
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderInvitation;
use App\Models\Vendor;
use App\Models\Expense;
use App\Models\Document;
use App\Models\PurchaseOrder;
use App\Utils\Traits\MakesHash;
use App\Models\PurchaseOrderInvitation;
class PurchaseOrderTransformer extends EntityTransformer
{

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