From 552d596eae6671484e595d8adad2e6c66a85eee9 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 20 Nov 2024 11:15:49 +1100 Subject: [PATCH] Style fixes --- app/Casts/AsTaxEntityCollection.php | 5 +- app/Casts/ClientSyncCast.php | 2 +- app/Casts/InvoiceSyncCast.php | 5 +- app/Casts/ProductSyncCast.php | 2 +- app/Casts/QuickbooksSettingsCast.php | 3 +- app/Console/Commands/BackupUpdate.php | 4 +- app/Console/Commands/CheckData.php | 26 +- app/Console/Commands/CreateSingleAccount.php | 8 +- app/Console/Commands/EncryptNinja.php | 4 +- app/Console/Commands/MobileLocalization.php | 2 +- app/Console/Commands/ReactBuilder.php | 2 +- app/Console/Commands/SendTestEmails.php | 2 +- app/Console/Commands/TranslationsExport.php | 2 +- app/Console/Commands/TypeCheck.php | 2 +- app/DataMapper/BaseSettings.php | 1 - app/DataMapper/EInvoice/TaxEntity.php | 9 +- app/DataMapper/InvoiceSync.php | 6 +- app/DataMapper/QuickbooksSettings.php | 4 +- app/DataMapper/QuickbooksSync.php | 14 +- .../Sources/PayPalBalanceAffecting.php | 12 +- app/DataMapper/Tax/BaseRule.php | 61 +- app/DataMapper/Tax/DE/Rule.php | 2 +- app/DataMapper/Tax/GB/Rule.php | 27 +- app/DataMapper/Tax/TaxData.php | 2 +- app/DataMapper/Tax/TaxModel.php | 36 +- app/DataMapper/Tax/US/Rule.php | 6 +- app/DataMapper/Tax/ZipTax/Response.php | 4 +- app/DataProviders/SMSNumbers.php | 14 +- app/DataProviders/USStates.php | 10 +- app/Events/Credit/CreditWasUpdated.php | 2 +- app/Events/Invoice/InvoiceWasPaid.php | 4 +- app/Events/Payment/PaymentWasUpdated.php | 4 +- app/Exceptions/PeppolValidationException.php | 1 - app/Export/CSV/ActivityExport.php | 4 +- app/Export/CSV/BaseExport.php | 195 +- app/Export/CSV/ClientExport.php | 6 +- app/Export/CSV/CreditExport.php | 10 +- app/Export/CSV/DocumentExport.php | 2 +- app/Export/CSV/ExpenseExport.php | 20 +- app/Export/CSV/InvoiceExport.php | 10 +- app/Export/CSV/InvoiceItemExport.php | 20 +- app/Export/CSV/PaymentExport.php | 4 +- app/Export/CSV/ProductExport.php | 4 +- app/Export/CSV/ProductSalesExport.php | 16 +- app/Export/CSV/PurchaseOrderExport.php | 10 +- app/Export/CSV/PurchaseOrderItemExport.php | 20 +- app/Export/CSV/QuoteExport.php | 10 +- app/Export/CSV/QuoteItemExport.php | 18 +- app/Export/CSV/RecurringInvoiceExport.php | 9 +- app/Export/CSV/TaskExport.php | 10 +- app/Export/CSV/VendorExport.php | 4 +- app/Export/Decorators/ClientDecorator.php | 8 +- app/Export/Decorators/ContactDecorator.php | 12 +- app/Export/Decorators/CreditDecorator.php | 8 +- app/Export/Decorators/ExpenseDecorator.php | 8 +- app/Export/Decorators/InvoiceDecorator.php | 10 +- app/Export/Decorators/PaymentDecorator.php | 16 +- app/Export/Decorators/ProductDecorator.php | 8 +- .../Decorators/PurchaseOrderDecorator.php | 8 +- app/Export/Decorators/QuoteDecorator.php | 8 +- .../Decorators/RecurringInvoiceDecorator.php | 8 +- app/Export/Decorators/TaskDecorator.php | 12 +- .../Decorators/VendorContactDecorator.php | 8 +- app/Export/Decorators/VendorDecorator.php | 8 +- app/Factory/InvoiceItemFactory.php | 32 +- app/Filters/BankTransactionFilters.php | 4 +- app/Filters/ClientFilters.php | 6 +- app/Filters/CreditFilters.php | 2 +- app/Filters/DesignFilters.php | 2 +- app/Filters/ExpenseFilters.php | 6 +- app/Filters/InvoiceFilters.php | 4 +- app/Filters/PaymentFilters.php | 8 +- app/Filters/ProjectFilters.php | 2 +- app/Filters/PurchaseOrderFilters.php | 2 +- app/Filters/QueryFilters.php | 8 +- app/Filters/QuoteFilters.php | 6 +- app/Filters/RecurringExpenseFilters.php | 2 +- app/Filters/RecurringInvoiceFilters.php | 6 +- app/Filters/TaskFilters.php | 4 +- app/Filters/VendorFilters.php | 2 +- app/Helpers/Bank/Nordigen/Nordigen.php | 12 +- .../Yodlee/Transformer/AccountTransformer.php | 12 +- .../Yodlee/Transformer/IncomeTransformer.php | 2 +- app/Helpers/Chorus/Piste.php | 2 +- app/Helpers/Epc/EpcQrGenerator.php | 2 +- app/Helpers/Invoice/InvoiceItemSum.php | 52 +- .../Invoice/InvoiceItemSumInclusive.php | 2 +- app/Helpers/Invoice/InvoiceSum.php | 16 +- app/Helpers/Invoice/InvoiceSumInclusive.php | 20 +- app/Helpers/Sanitizer.php | 3 +- app/Helpers/SwissQr/SwissQrGenerator.php | 2 +- app/Http/Controllers/AccountController.php | 10 +- app/Http/Controllers/ActivityController.php | 2 +- .../Auth/ContactLoginController.php | 4 +- app/Http/Controllers/Auth/LoginController.php | 6 +- .../Auth/ResetPasswordController.php | 4 +- .../Controllers/Bank/NordigenController.php | 3 +- .../Controllers/BankTransactionController.php | 2 +- app/Http/Controllers/BaseController.php | 10 +- app/Http/Controllers/BrevoController.php | 3 +- app/Http/Controllers/ClientController.php | 24 +- .../ClientPortal/DocumentController.php | 2 +- .../ClientPortal/InvitationController.php | 2 +- .../ClientPortal/InvoiceController.php | 20 +- .../ClientPortal/PaymentMethodController.php | 7 +- .../ClientPortal/PrePaymentController.php | 7 +- .../ClientPortal/QuoteController.php | 2 +- app/Http/Controllers/CompanyController.php | 12 +- .../Controllers/CompanyGatewayController.php | 18 +- .../Controllers/CompanyUserController.php | 2 +- app/Http/Controllers/CreditController.php | 2 +- app/Http/Controllers/DesignController.php | 73 +- app/Http/Controllers/DocumentController.php | 2 +- app/Http/Controllers/EInvoiceController.php | 38 +- .../Controllers/EInvoicePeppolController.php | 25 +- .../Controllers/EInvoiceTokenController.php | 2 +- app/Http/Controllers/EmailController.php | 4 +- .../Gateways/BlockonomicsController.php | 2 +- .../Gateways/GoCardlessOAuthController.php | 3 +- .../Controllers/GroupSettingController.php | 2 +- .../Controllers/HostedMigrationController.php | 2 +- app/Http/Controllers/ImportController.php | 30 +- .../ImportQuickbooksController.php | 2 +- app/Http/Controllers/InvoiceController.php | 18 +- app/Http/Controllers/LicenseController.php | 6 +- app/Http/Controllers/MailgunController.php | 9 +- app/Http/Controllers/MigrationController.php | 8 +- .../Controllers/OneTimeTokenController.php | 2 +- app/Http/Controllers/PaymentController.php | 2 +- app/Http/Controllers/PostMarkController.php | 6 +- app/Http/Controllers/PreviewController.php | 27 +- .../PreviewPurchaseOrderController.php | 2 +- app/Http/Controllers/ProductController.php | 2 +- app/Http/Controllers/ProjectController.php | 3 +- .../Controllers/PurchaseOrderController.php | 2 +- app/Http/Controllers/QuoteController.php | 2 +- .../RecurringInvoiceController.php | 6 +- .../Reports/InvoiceReportController.php | 2 +- .../Reports/ReportExportController.php | 2 +- .../Reports/ReportPreviewController.php | 2 +- app/Http/Controllers/SearchController.php | 37 +- app/Http/Controllers/SelfUpdateController.php | 12 +- app/Http/Controllers/StaticController.php | 2 +- .../Controllers/StripeConnectController.php | 10 +- app/Http/Controllers/SubdomainController.php | 2 +- .../Controllers/SubscriptionController.php | 2 +- app/Http/Controllers/TaskController.php | 4 +- app/Http/Controllers/TaxRateController.php | 6 +- .../Controllers/TemplatePreviewController.php | 2 +- app/Http/Controllers/TwilioController.php | 16 +- app/Http/Controllers/TwoFactorController.php | 2 +- app/Http/Controllers/VendorController.php | 20 +- .../VendorPortal/VendorContactController.php | 3 +- app/Http/Middleware/PasswordProtection.php | 4 +- app/Http/Middleware/QueryLogging.php | 2 +- .../Middleware/ThrottleRequestsWithPredis.php | 4 +- .../Requests/Activity/ShowActivityRequest.php | 2 +- .../Requests/Activity/StoreNoteRequest.php | 5 +- .../UploadBankIntegrationRequest.php | 2 +- .../UploadBankTransactionRequest.php | 2 +- .../Chart/ShowCalculatedFieldRequest.php | 4 +- app/Http/Requests/Chart/ShowChartRequest.php | 2 +- .../Requests/Client/UploadClientRequest.php | 2 +- .../StoreClientGatewayTokenRequest.php | 2 +- .../UpdateClientGatewayTokenRequest.php | 5 +- .../Invoices/ProcessInvoicesInBulkRequest.php | 2 +- .../Payments/PaymentResponseRequest.php | 2 +- .../Requests/Company/UpdateCompanyRequest.php | 8 +- .../CompanyUser/UpdateCompanyUserRequest.php | 2 +- .../Requests/Credit/StoreCreditRequest.php | 4 +- .../Requests/Credit/UpdateCreditRequest.php | 2 +- .../Requests/Credit/UploadCreditRequest.php | 2 +- .../Requests/Design/StoreDesignRequest.php | 2 +- .../Requests/Design/UpdateDesignRequest.php | 2 +- .../Document/StoreDocumentRequest.php | 2 +- .../Document/UpdateDocumentRequest.php | 2 +- .../Peppol/AddTaxIdentifierRequest.php | 6 +- .../EInvoice/Peppol/DisconnectRequest.php | 2 +- .../EInvoice/Peppol/StoreEntityRequest.php | 5 +- .../EInvoice/Peppol/UpdateEntityRequest.php | 1 - .../EInvoice/UpdateEInvoiceConfiguration.php | 4 +- .../EInvoice/ValidateEInvoiceRequest.php | 32 +- app/Http/Requests/Email/SendEmailRequest.php | 7 +- .../Requests/Expense/BulkExpenseRequest.php | 2 +- .../Requests/Expense/UpdateExpenseRequest.php | 5 +- .../Requests/Expense/UploadExpenseRequest.php | 2 +- app/Http/Requests/Import/ImportRequest.php | 2 +- .../Requests/Invoice/BulkInvoiceRequest.php | 4 +- .../Invoice/DestroyInvoiceRequest.php | 3 +- .../Requests/Invoice/StoreInvoiceRequest.php | 15 +- .../Requests/Invoice/UpdateInvoiceRequest.php | 6 +- .../Requests/Invoice/UploadInvoiceRequest.php | 2 +- .../ConnectNordigenBankIntegrationRequest.php | 2 +- .../Requests/Payment/StorePaymentRequest.php | 2 +- .../Requests/Payment/UpdatePaymentRequest.php | 2 +- .../Requests/Payment/UploadPaymentRequest.php | 2 +- .../Preview/PreviewInvoiceRequest.php | 8 +- .../Preview/PreviewPurchaseOrderRequest.php | 8 +- .../Requests/Product/UploadProductRequest.php | 2 +- .../Project/InvoiceProjectRequest.php | 8 +- .../Requests/Project/StoreProjectRequest.php | 2 +- .../Requests/Project/UpdateProjectRequest.php | 2 +- .../Requests/Project/UploadProjectRequest.php | 2 +- .../StorePurchaseOrderRequest.php | 4 +- .../UpdatePurchaseOrderRequest.php | 4 +- .../UploadPurchaseOrderRequest.php | 2 +- app/Http/Requests/Quote/StoreQuoteRequest.php | 6 +- .../Requests/Quote/UpdateQuoteRequest.php | 4 +- .../Requests/Quote/UploadQuoteRequest.php | 2 +- .../StoreRecurringInvoiceRequest.php | 2 +- .../UpdateRecurringInvoiceRequest.php | 2 +- .../UploadRecurringInvoiceRequest.php | 2 +- .../Requests/Report/GenericReportRequest.php | 2 +- .../Report/ProductSalesReportRequest.php | 2 +- .../Requests/Report/ProfitLossRequest.php | 2 +- .../Requests/Report/ReportPreviewRequest.php | 2 +- app/Http/Requests/Request.php | 12 +- app/Http/Requests/Smtp/CheckSmtpRequest.php | 8 +- .../Subscription/BulkSubscriptionRequest.php | 4 +- app/Http/Requests/Task/StoreTaskRequest.php | 6 +- app/Http/Requests/Task/UpdateTaskRequest.php | 10 +- app/Http/Requests/Task/UploadTaskRequest.php | 2 +- .../TaskScheduler/StoreSchedulerRequest.php | 8 +- .../TaskScheduler/UpdateSchedulerRequest.php | 8 +- app/Http/Requests/User/BulkUserRequest.php | 2 +- app/Http/Requests/User/UpdateUserRequest.php | 6 +- .../Requests/Vendor/UpdateVendorRequest.php | 5 +- .../Requests/Vendor/UploadVendorRequest.php | 2 +- .../Company/ValidCompanyQuantity.php | 5 +- .../Company/ValidExpenseMailbox.php | 3 +- .../Company/ValidSubdomain.php | 5 +- .../Credit/ValidCreditsRules.php | 4 +- .../EInvoice/ValidClientScheme.php | 2 +- .../EInvoice/ValidCompanyScheme.php | 2 +- .../Invoice/LockedInvoiceRule.php | 2 +- .../Payment/ValidInvoicesRules.php | 2 +- .../Payment/ValidRefundableRequest.php | 2 +- .../PaymentAppliedValidAmount.php | 4 +- .../Project/ValidProjectForClient.php | 2 +- .../User/HasValidPhoneNumber.php | 2 +- .../Components/Rotessa/AddressComponent.php | 2 +- app/Import/Providers/BaseImport.php | 30 +- app/Import/Providers/Wave.php | 8 +- app/Import/Transformer/BaseTransformer.php | 31 +- .../Transformer/Csv/ClientTransformer.php | 2 +- .../Transformer/Csv/TaskTransformer.php | 18 +- .../Invoice2Go/InvoiceTransformer.php | 30 +- .../Transformer/Wave/ExpenseTransformer.php | 2 +- .../Transformer/Zoho/ClientTransformer.php | 2 +- .../Transformer/Zoho/InvoiceTransformer.php | 2 +- app/Jobs/Bank/MatchBankTransactions.php | 8 +- .../Bank/ProcessBankTransactionsNordigen.php | 22 +- app/Jobs/Brevo/ProcessBrevoInboundWebhook.php | 22 +- app/Jobs/Brevo/ProcessBrevoWebhook.php | 2 +- app/Jobs/Client/UpdateTaxData.php | 4 +- app/Jobs/Company/CompanyExport.php | 8 +- app/Jobs/Company/CompanyImport.php | 69 +- app/Jobs/Company/CompanyTaxRate.php | 10 +- app/Jobs/Company/CreateCompany.php | 18 +- app/Jobs/Credit/ZipCredits.php | 5 +- app/Jobs/Cron/AutoBill.php | 2 +- app/Jobs/Cron/RecurringExpensesCron.php | 2 +- app/Jobs/Cron/SubscriptionCron.php | 2 +- app/Jobs/EDocument/CreateEDocument.php | 2 +- app/Jobs/EDocument/ImportEDocument.php | 2 +- app/Jobs/Entity/CreateRawPdf.php | 4 +- app/Jobs/Entity/EmailEntity.php | 4 +- app/Jobs/Expense/VendorExpenseNotify.php | 2 +- app/Jobs/Invoice/BulkInvoiceJob.php | 71 +- app/Jobs/Invoice/InjectSignature.php | 6 +- app/Jobs/Invoice/ZipInvoices.php | 7 +- app/Jobs/Ledger/UpdateLedger.php | 2 +- app/Jobs/Mail/NinjaMailerJob.php | 24 +- app/Jobs/Mail/PaymentFailedMailer.php | 2 +- app/Jobs/Mail/PaymentFailureMailer.php | 2 +- .../Mailgun/ProcessMailgunInboundWebhook.php | 14 +- app/Jobs/Mailgun/ProcessMailgunWebhook.php | 14 +- app/Jobs/Ninja/AdjustEmailQuota.php | 2 +- app/Jobs/Ninja/BankTransactionSync.php | 2 +- app/Jobs/Ninja/CheckACHStatus.php | 14 +- app/Jobs/Ninja/CompanySizeCheck.php | 4 +- app/Jobs/Ninja/TaskScheduler.php | 4 +- app/Jobs/Payment/EmailPayment.php | 6 +- app/Jobs/Payment/EmailRefundPayment.php | 4 +- app/Jobs/PostMark/ProcessPostmarkWebhook.php | 4 +- app/Jobs/Quote/ZipQuotes.php | 2 +- app/Jobs/RecurringInvoice/SendRecurring.php | 4 +- app/Jobs/Report/PreviewReport.php | 2 +- app/Jobs/Report/SendToAdmin.php | 4 +- .../Subscription/CleanStaleInvoiceOrder.php | 20 +- app/Jobs/Task/TaskAssigned.php | 3 +- app/Jobs/User/VerifyPhone.php | 2 +- app/Jobs/Util/Import.php | 20 +- app/Jobs/Util/ReminderJob.php | 12 +- app/Jobs/Util/StartMigration.php | 2 +- app/Jobs/Util/VersionCheck.php | 2 +- app/Jobs/Util/WebhookSingle.php | 2 +- .../Activity/PaymentCreatedActivity.php | 2 +- .../Contact/UpdateContactLastLogin.php | 2 +- .../Invoice/InvoiceAutoBillFailedActivity.php | 2 +- .../InvoiceFailedEmailNotification.php | 2 +- app/Listeners/Payment/PaymentNotification.php | 2 +- .../Quote/QuoteCreatedNotification.php | 2 +- app/Listeners/User/UpdatedUserActivity.php | 2 +- .../BillingPortal/Authentication/Login.php | 2 +- .../BillingPortal/Authentication/Register.php | 6 +- .../Authentication/RegisterOrLogin.php | 6 +- app/Livewire/BillingPortal/Cart/Coupon.php | 13 +- .../BillingPortal/Cart/OneTimeProducts.php | 2 +- .../Cart/OptionalOneTimeProducts.php | 1 - .../Cart/OptionalRecurringProducts.php | 1 - .../BillingPortal/Cart/RecurringProducts.php | 2 +- .../BillingPortal/Payments/Methods.php | 2 +- app/Livewire/BillingPortal/Summary.php | 20 +- app/Livewire/BillingPortalPurchase.php | 8 +- app/Livewire/BillingPortalPurchasev2.php | 24 +- app/Livewire/CreditsTable.php | 2 +- app/Livewire/Flow2/InvoicePay.php | 14 +- app/Livewire/Flow2/InvoiceSummary.php | 12 +- app/Livewire/Flow2/PaymentMethod.php | 2 +- app/Livewire/Flow2/ProcessPayment.php | 26 +- app/Livewire/Flow2/RequiredFields.php | 13 +- app/Livewire/Flow2/UnderOverPayment.php | 14 +- .../PaymentMethods/UpdateDefaultMethod.php | 4 +- app/Livewire/PdfSlot.php | 34 +- app/Livewire/Profile/Settings/General.php | 2 +- .../Profile/Settings/PersonalAddress.php | 1 - .../Profile/Settings/ShippingAddress.php | 1 - app/Livewire/PurchaseOrdersTable.php | 2 +- app/Livewire/RecurringInvoiceCancellation.php | 3 +- app/Livewire/RequiredClientInfo.php | 8 +- app/Livewire/SubscriptionPlanSwitch.php | 3 +- app/Livewire/SubscriptionsTable.php | 2 +- app/Mail/Admin/ClientPaymentFailureObject.php | 13 +- app/Mail/Admin/VerifyUserObject.php | 2 +- app/Mail/DownloadReport.php | 11 +- app/Mail/Engine/CreditEmailEngine.php | 2 +- app/Mail/Engine/InvoiceEmailEngine.php | 2 +- app/Mail/Engine/PaymentEmailEngine.php | 8 +- app/Mail/Engine/PurchaseOrderEmailEngine.php | 2 +- app/Mail/Engine/QuoteEmailEngine.php | 2 +- app/Mail/Ninja/StripeConnectFailed.php | 4 +- app/Mail/TemplateEmail.php | 6 +- app/Mail/VendorTemplateEmail.php | 4 +- app/Models/Account.php | 2 +- app/Models/Activity.php | 24 +- app/Models/BaseModel.php | 10 +- app/Models/Client.php | 45 +- app/Models/ClientContact.php | 2 +- app/Models/Company.php | 6 +- app/Models/CompanyGateway.php | 4 +- app/Models/Document.php | 8 +- app/Models/EInvoicingToken.php | 3 +- app/Models/Expense.php | 10 +- app/Models/Gateway.php | 6 +- app/Models/Invoice.php | 18 +- app/Models/License.php | 18 +- app/Models/Payment.php | 2 +- app/Models/Presenters/CompanyPresenter.php | 2 +- app/Models/PurchaseOrder.php | 2 +- app/Models/RecurringInvoice.php | 6 +- app/Models/Subscription.php | 2 +- app/Models/SystemLog.php | 4 +- app/Models/Task.php | 54 +- app/Models/User.php | 2 +- .../Ninja/GenericNinjaAdminNotification.php | 2 +- app/Observers/ClientObserver.php | 6 +- .../Authorize/AuthorizeCreditCard.php | 4 +- .../Authorize/AuthorizeCustomer.php | 2 +- .../Authorize/AuthorizePaymentMethod.php | 2 +- .../Authorize/AuthorizeTransaction.php | 6 +- .../Authorize/ChargePaymentProfile.php | 2 +- .../Authorize/RefundTransaction.php | 2 +- app/PaymentDrivers/BTCPay/BTCPay.php | 8 +- app/PaymentDrivers/BTCPayPaymentDriver.php | 27 +- app/PaymentDrivers/BaseDriver.php | 46 +- .../Blockonomics/Blockonomics.php | 13 +- .../BlockonomicsPaymentDriver.php | 10 +- app/PaymentDrivers/Braintree/ACH.php | 10 +- app/PaymentDrivers/Braintree/CreditCard.php | 8 +- app/PaymentDrivers/Braintree/PayPal.php | 6 +- app/PaymentDrivers/BraintreePaymentDriver.php | 20 +- .../CBAPowerBoard/CreditCard.php | 90 +- app/PaymentDrivers/CBAPowerBoard/Customer.php | 32 +- .../CBAPowerBoard/Models/Charge.php | 2 +- .../CBAPowerBoard/Models/Customer.php | 137 +- .../CBAPowerBoard/Models/Gateway.php | 1 - .../CBAPowerBoard/Models/Parse.php | 6 +- .../CBAPowerBoard/Models/Transaction.php | 118 +- app/PaymentDrivers/CBAPowerBoard/Settings.php | 39 +- .../CBAPowerBoardPaymentDriver.php | 22 +- .../CheckoutCom/CheckoutSetupWebhook.php | 2 +- .../CheckoutCom/CheckoutWebhook.php | 8 +- app/PaymentDrivers/CheckoutCom/CreditCard.php | 6 +- app/PaymentDrivers/CheckoutCom/Utilities.php | 2 +- .../CheckoutComPaymentDriver.php | 20 +- app/PaymentDrivers/CustomPaymentDriver.php | 2 +- app/PaymentDrivers/Eway/CreditCard.php | 4 +- .../Factory/ForteCustomerFactory.php | 19 +- .../Factory/SquareCustomerFactory.php | 2 +- app/PaymentDrivers/Forte/ACH.php | 8 +- app/PaymentDrivers/Forte/CreditCard.php | 22 +- app/PaymentDrivers/FortePaymentDriver.php | 40 +- app/PaymentDrivers/GoCardless/ACH.php | 6 +- app/PaymentDrivers/GoCardless/DirectDebit.php | 19 +- .../GoCardless/InstantBankPay.php | 8 +- app/PaymentDrivers/GoCardless/SEPA.php | 14 +- .../GoCardlessPaymentDriver.php | 13 +- app/PaymentDrivers/Mollie/Bancontact.php | 6 +- app/PaymentDrivers/Mollie/BankTransfer.php | 8 +- app/PaymentDrivers/Mollie/CreditCard.php | 6 +- app/PaymentDrivers/Mollie/IDEAL.php | 12 +- app/PaymentDrivers/Mollie/KBC.php | 8 +- app/PaymentDrivers/MolliePaymentDriver.php | 6 +- app/PaymentDrivers/PayFast/CreditCard.php | 10 +- .../PayPal/PayPalBasePaymentDriver.php | 52 +- app/PaymentDrivers/PayPal/PayPalWebhook.php | 22 +- .../PayPalPPCPPaymentDriver.php | 55 +- .../PayPalRestPaymentDriver.php | 48 +- app/PaymentDrivers/PayTrace/CreditCard.php | 6 +- app/PaymentDrivers/PaytracePaymentDriver.php | 12 +- app/PaymentDrivers/Razorpay/Hosted.php | 6 +- .../Rotessa/Jobs/TransactionReport.php | 68 +- app/PaymentDrivers/Rotessa/PaymentMethod.php | 83 +- app/PaymentDrivers/RotessaPaymentDriver.php | 139 +- app/PaymentDrivers/Square/CreditCard.php | 10 +- app/PaymentDrivers/Square/SquareWebhook.php | 10 +- app/PaymentDrivers/SquarePaymentDriver.php | 24 +- app/PaymentDrivers/Stripe/ACH.php | 12 +- app/PaymentDrivers/Stripe/ACSS.php | 12 +- app/PaymentDrivers/Stripe/Alipay.php | 15 +- app/PaymentDrivers/Stripe/Bancontact.php | 2 +- app/PaymentDrivers/Stripe/BankTransfer.php | 2 +- app/PaymentDrivers/Stripe/EPS.php | 2 +- app/PaymentDrivers/Stripe/FPX.php | 2 +- app/PaymentDrivers/Stripe/ImportCustomers.php | 4 +- .../Stripe/Jobs/ChargeRefunded.php | 108 +- .../Jobs/PaymentIntentFailureWebhook.php | 6 +- .../Jobs/PaymentIntentProcessingWebhook.php | 2 +- .../Stripe/Jobs/PaymentIntentWebhook.php | 10 +- app/PaymentDrivers/Stripe/Klarna.php | 2 +- app/PaymentDrivers/Stripe/SEPA.php | 2 +- .../Stripe/UpdatePaymentMethods.php | 7 +- app/PaymentDrivers/Stripe/iDeal.php | 2 +- app/PaymentDrivers/StripePaymentDriver.php | 25 +- app/Providers/StaticServiceProvider.php | 22 +- app/Repositories/ActivityRepository.php | 4 +- .../BankIntegrationRepository.php | 4 +- .../BankTransactionRepository.php | 2 +- app/Repositories/BaseRepository.php | 32 +- .../ClientGatewayTokenRepository.php | 7 +- app/Repositories/ClientRepository.php | 2 +- app/Repositories/CompanyRepository.php | 8 +- app/Repositories/DocumentRepository.php | 3 +- app/Repositories/ExpenseRepository.php | 12 +- app/Repositories/GroupSettingRepository.php | 4 +- .../Quickbooks/Transformers/Transformer.php | 2 +- app/Repositories/InvoiceRepository.php | 2 +- app/Repositories/PaymentRepository.php | 2 +- app/Repositories/ProjectRepository.php | 44 +- app/Repositories/SubscriptionRepository.php | 10 +- app/Repositories/TaskRepository.php | 34 +- app/Repositories/TaskStatusRepository.php | 4 +- app/Repositories/UserRepository.php | 4 +- app/Repositories/VendorRepository.php | 7 +- app/Services/Bank/ProcessBankRules.php | 20 +- app/Services/Chart/ChartCalculations.php | 22 +- app/Services/Chart/ChartQueries.php | 34 +- app/Services/Chart/ChartService.php | 2 +- app/Services/Client/ClientService.php | 60 +- app/Services/Client/RFFService.php | 2 +- app/Services/Client/Statement.php | 15 +- app/Services/Company/CompanyService.php | 8 +- app/Services/Credit/MarkSent.php | 2 +- .../EDocument/Adapters/CII/PaymentMeans.php | 203 +- .../EDocument/Adapters/UBL/PaymentMeans.php | 2 +- .../EDocument/Gateway/MutatorInterface.php | 1 - .../EDocument/Gateway/MutatorUtil.php | 20 +- .../EDocument/Gateway/Qvalia/Invoice.php | 9 +- .../EDocument/Gateway/Qvalia/Mutator.php | 9 +- .../EDocument/Gateway/Qvalia/Partner.php | 11 +- .../EDocument/Gateway/Qvalia/Qvalia.php | 40 +- .../Models/AccountingCustomerParty.php | 86 +- .../Models/AccountingSupplierParty.php | 85 +- .../Models/AdditionalItemProperties.php | 50 +- .../Gateway/Storecove/Models/Address.php | 141 +- .../Storecove/Models/AllowanceCharges.php | 210 +-- .../Gateway/Storecove/Models/Attachments.php | 150 +- .../Storecove/Models/BuyerCustomerParty.php | 28 +- .../Gateway/Storecove/Models/Contact.php | 133 +- .../Gateway/Storecove/Models/Delivery.php | 198 +- .../Storecove/Models/DeliveryLocation.php | 126 +- .../Storecove/Models/DeliveryParty.php | 70 +- .../Storecove/Models/DeliveryTerms.php | 78 +- .../Gateway/Storecove/Models/Document.php | 102 +- .../Gateway/Storecove/Models/Invoice.php | 1654 ++++++++--------- .../Gateway/Storecove/Models/InvoiceLines.php | 578 +++--- .../Gateway/Storecove/Models/Order.php | 554 +++--- .../Gateway/Storecove/Models/OrderLines.php | 498 ++--- .../Storecove/Models/OriginAddress.php | 150 +- .../Gateway/Storecove/Models/Party.php | 138 +- .../Storecove/Models/PaymentMeansArray.php | 184 +- .../Gateway/Storecove/Models/PaymentTerms.php | 30 +- .../Storecove/Models/PublicIdentifiers.php | 50 +- .../Gateway/Storecove/Models/References.php | 318 ++-- .../Gateway/Storecove/Models/RootObject.php | 126 +- .../Storecove/Models/SellerSupplierParty.php | 70 +- .../Gateway/Storecove/Models/Shipment.php | 98 +- .../Gateway/Storecove/Models/Tax.php | 126 +- .../Gateway/Storecove/Models/TaxSubtotals.php | 149 +- .../Storecove/Models/TaxesDutiesFees.php | 134 +- .../EDocument/Gateway/Storecove/Mutator.php | 85 +- .../EDocument/Gateway/Storecove/Storecove.php | 86 +- .../Gateway/Storecove/StorecoveAdapter.php | 125 +- .../Gateway/Storecove/StorecoveProxy.php | 12 +- .../Gateway/Storecove/StorecoveRouter.php | 91 +- .../Gateway/Transformers/StorecoveExpense.php | 52 +- .../EDocument/Imports/MindeeEDocument.php | 24 +- .../EDocument/Imports/ParseEDocument.php | 11 +- app/Services/EDocument/Imports/Ubl2Pdf.php | 75 +- .../EDocument/Imports/UblEDocument.php | 110 +- .../EDocument/Imports/ZugferdEDocument.php | 24 +- app/Services/EDocument/Jobs/SendEDocument.php | 50 +- .../EDocument/Standards/FacturaEInvoice.php | 24 +- .../EDocument/Standards/FatturaPA.php | 2 +- .../EDocument/Standards/FatturaPANew.php | 2 +- app/Services/EDocument/Standards/Peppol.php | 309 +-- .../Standards/Peppol/BaseCountry.php | 2 +- .../EDocument/Standards/Peppol/RO.php | 4 +- .../Validation/Peppol/EntityLevel.php | 75 +- .../Validation/XsltDocumentValidator.php | 29 +- .../EDocument/Standards/ZugferdEDokument.php | 52 +- app/Services/Email/Email.php | 18 +- app/Services/Email/EmailDefaults.php | 19 +- app/Services/InboundMail/InboundMail.php | 2 +- .../InboundMail/InboundMailEngine.php | 70 +- app/Services/Invoice/ApplyNumber.php | 2 +- app/Services/Invoice/ApplyPaymentAmount.php | 2 +- app/Services/Invoice/AutoBillInvoice.php | 13 +- app/Services/Invoice/GenerateDeliveryNote.php | 2 +- app/Services/Invoice/InvoiceService.php | 10 +- app/Services/Invoice/MarkInvoiceDeleted.php | 6 +- app/Services/Invoice/TriggeredActions.php | 2 +- app/Services/Ledger/LedgerService.php | 2 +- app/Services/Payment/DeletePayment.php | 17 +- app/Services/Payment/RefundPayment.php | 6 +- app/Services/Payment/SendEmail.php | 4 +- app/Services/Payment/UpdateInvoicePayment.php | 6 +- app/Services/Pdf/PdfBuilder.php | 20 +- app/Services/Pdf/PdfConfiguration.php | 2 +- app/Services/Pdf/PdfMock.php | 4 +- app/Services/Pdf/PdfService.php | 4 +- app/Services/PdfMaker/Design.php | 32 +- .../Designs/Utilities/DesignHelpers.php | 2 +- app/Services/PdfMaker/PdfMaker.php | 12 +- .../PurchaseOrder/CreateInvitations.php | 2 +- .../PurchaseOrder/PurchaseOrderExpense.php | 4 +- .../Quickbooks/Jobs/QuickbooksImport.php | 44 +- app/Services/Quickbooks/Models/QbClient.php | 12 +- app/Services/Quickbooks/Models/QbInvoice.php | 37 +- app/Services/Quickbooks/Models/QbProduct.php | 25 +- app/Services/Quickbooks/QuickbooksService.php | 25 +- app/Services/Quickbooks/SdkWrapper.php | 20 +- .../Transformers/BaseTransformer.php | 17 +- .../Transformers/ClientTransformer.php | 13 +- .../Transformers/ExpenseTransformer.php | 15 +- .../Transformers/InvoiceTransformer.php | 45 +- .../Transformers/PaymentTransformer.php | 37 +- .../Transformers/ProductTransformer.php | 5 +- .../Transformers/VendorTransformer.php | 8 +- app/Services/Quote/ConvertQuote.php | 2 +- app/Services/Quote/MarkSent.php | 2 +- app/Services/Quote/SendEmail.php | 3 +- app/Services/Quote/TriggeredActions.php | 4 +- app/Services/Recurring/RecurringService.php | 2 +- app/Services/Report/ARDetailReport.php | 4 +- app/Services/Report/ARSummaryReport.php | 2 +- app/Services/Report/ClientBalanceReport.php | 2 +- app/Services/Report/ProfitLoss.php | 6 +- app/Services/Report/TaxSummaryReport.php | 34 +- app/Services/Scheduler/EmailRecord.php | 2 +- app/Services/Scheduler/EmailReport.php | 4 +- .../Subscription/ChangePlanInvoice.php | 4 +- .../Subscription/PaymentLinkService.php | 2 +- .../Subscription/SubscriptionCalculator.php | 10 +- .../Subscription/SubscriptionService.php | 4 +- .../Subscription/SubscriptionStatus.php | 10 +- app/Services/Subscription/UpgradePrice.php | 4 +- app/Services/Subscription/ZeroCostProduct.php | 2 +- app/Services/Tax/Providers/TaxProvider.php | 10 +- app/Services/Tax/Providers/ZipTax.php | 10 +- app/Services/Tax/TaxService.php | 8 +- app/Services/Template/TemplateAction.php | 16 +- app/Services/Template/TemplateService.php | 84 +- app/Services/Vendor/Merge.php | 4 +- app/Services/Vendor/VendorService.php | 2 +- app/Transformers/CompanyTransformer.php | 2 +- app/Transformers/UserTransformer.php | 2 +- app/Utils/Helpers.php | 8 +- app/Utils/HostedPDF/NinjaPdf.php | 4 +- app/Utils/HtmlEngine.php | 27 +- app/Utils/Number.php | 28 +- app/Utils/SystemHealth.php | 2 +- app/Utils/TemplateEngine.php | 6 +- app/Utils/Traits/CleanLineItems.php | 18 +- app/Utils/Traits/ClientGroupSettingsSaver.php | 5 +- app/Utils/Traits/CompanySettingsSaver.php | 13 +- app/Utils/Traits/MakesDates.php | 12 +- app/Utils/Traits/MakesHash.php | 4 +- app/Utils/Traits/MakesReminders.php | 2 +- app/Utils/Traits/Pdf/PDF.php | 2 +- app/Utils/Traits/SettingsSaver.php | 5 +- app/Utils/Traits/SubscriptionHooker.php | 2 +- 613 files changed, 6887 insertions(+), 6906 deletions(-) diff --git a/app/Casts/AsTaxEntityCollection.php b/app/Casts/AsTaxEntityCollection.php index 8b08359cf9..f2929191f1 100644 --- a/app/Casts/AsTaxEntityCollection.php +++ b/app/Casts/AsTaxEntityCollection.php @@ -9,7 +9,6 @@ * @license https://www.elastic.co/licensing/elastic-license */ - namespace App\Casts; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; @@ -19,7 +18,7 @@ class AsTaxEntityCollection implements CastsAttributes { public function get($model, string $key, $value, array $attributes) { - if (!$value || (is_string($value) && $value =="null")) { + if (!$value || (is_string($value) && $value == "null")) { return []; } @@ -33,7 +32,7 @@ class AsTaxEntityCollection implements CastsAttributes if (!$value) { return '[]'; } - + if ($value instanceof TaxEntity) { $value = [$value]; } diff --git a/app/Casts/ClientSyncCast.php b/app/Casts/ClientSyncCast.php index 065da343b6..4e7a68b2e7 100644 --- a/app/Casts/ClientSyncCast.php +++ b/app/Casts/ClientSyncCast.php @@ -18,7 +18,7 @@ class ClientSyncCast implements CastsAttributes { public function get($model, string $key, $value, array $attributes) { - + if (is_null($value)) { return null; // Return null if the value is null } diff --git a/app/Casts/InvoiceSyncCast.php b/app/Casts/InvoiceSyncCast.php index 223accaa9f..c943c5ba1a 100644 --- a/app/Casts/InvoiceSyncCast.php +++ b/app/Casts/InvoiceSyncCast.php @@ -18,7 +18,7 @@ class InvoiceSyncCast implements CastsAttributes { public function get($model, string $key, $value, array $attributes) { - + if (is_null($value)) { return null; // Return null if the value is null } @@ -38,8 +38,9 @@ class InvoiceSyncCast implements CastsAttributes { $data = []; - if(isset($value->qb_id) && strlen($value->qb_id) >= 1) + if (isset($value->qb_id) && strlen($value->qb_id) >= 1) { $data['qb_id'] = $value->qb_id; + } return [ $key => json_encode($data) diff --git a/app/Casts/ProductSyncCast.php b/app/Casts/ProductSyncCast.php index 64fc8fbdae..1ae946a421 100644 --- a/app/Casts/ProductSyncCast.php +++ b/app/Casts/ProductSyncCast.php @@ -18,7 +18,7 @@ class ProductSyncCast implements CastsAttributes { public function get($model, string $key, $value, array $attributes) { - + if (is_null($value)) { return null; // Return null if the value is null } diff --git a/app/Casts/QuickbooksSettingsCast.php b/app/Casts/QuickbooksSettingsCast.php index 4de9333564..32da92be01 100644 --- a/app/Casts/QuickbooksSettingsCast.php +++ b/app/Casts/QuickbooksSettingsCast.php @@ -18,8 +18,9 @@ class QuickbooksSettingsCast implements CastsAttributes { public function get($model, string $key, $value, array $attributes) { - if (is_null($value)) + if (is_null($value)) { return new QuickbooksSettings(); + } $data = json_decode($value, true); return QuickbooksSettings::fromArray($data); diff --git a/app/Console/Commands/BackupUpdate.php b/app/Console/Commands/BackupUpdate.php index b2a16bff25..1952760d94 100644 --- a/app/Console/Commands/BackupUpdate.php +++ b/app/Console/Commands/BackupUpdate.php @@ -56,7 +56,7 @@ class BackupUpdate extends Command { //always return state to first DB - if(Ninja::isSelfHost()) { + if (Ninja::isSelfHost()) { return; } @@ -175,7 +175,7 @@ class BackupUpdate extends Command try { $doc_bin = $document->getFile(); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: BackupUpdate::" . $e->getMessage()); } diff --git a/app/Console/Commands/CheckData.php b/app/Console/Commands/CheckData.php index 4234c2d562..e69cdfceec 100644 --- a/app/Console/Commands/CheckData.php +++ b/app/Console/Commands/CheckData.php @@ -145,15 +145,15 @@ class CheckData extends Command $this->checkOAuth(); } - if($this->option('bank_transaction')) { + if ($this->option('bank_transaction')) { $this->fixBankTransactions(); } - if($this->option('line_items')) { + if ($this->option('line_items')) { $this->cleanInvoiceLineItems(); } - if($this->option('payment_balance')){ + if ($this->option('payment_balance')) { $this->updateClientPaymentBalances(); } $this->logMessage('Done: '.strtoupper($this->isValid ? Account::RESULT_SUCCESS : Account::RESULT_FAILURE)); @@ -492,7 +492,7 @@ class CheckData extends Command try { $entity->service()->createInvitations()->save(); - } catch(\Exception $e) { + } catch (\Exception $e) { } @@ -502,7 +502,7 @@ class CheckData extends Command if ($invitation) { $invitation->save(); } - } catch(\Exception $e) { + } catch (\Exception $e) { $this->logMessage($e->getMessage()); $invitation = null; } @@ -527,7 +527,7 @@ class CheckData extends Command try { $invitation->save(); - } catch(\Exception $e) { + } catch (\Exception $e) { $invitation = null; } } @@ -562,7 +562,7 @@ class CheckData extends Command ->where('is_deleted', 0) ->cursor() ->each(function ($client) { - + $client->service()->updatePaymentBalance(); $this->logMessage("{$client->present()->name()} payment balance = {$client->payment_balance}"); }); @@ -1109,7 +1109,7 @@ class CheckData extends Command BankTransaction::with('payment')->withTrashed()->where('invoice_ids', ',,,,,,,,')->cursor()->each(function ($bt) { - if($bt->payment->exists()) { + if ($bt->payment->exists()) { $this->isValid = false; $bt->invoice_ids = collect($bt->payment->invoices)->pluck('hashed_id')->implode(','); @@ -1144,7 +1144,7 @@ class CheckData extends Command public function checkSubdomainsSet() { - if(Ninja::isSelfHost()) { + if (Ninja::isSelfHost()) { return; } @@ -1169,7 +1169,7 @@ class CheckData extends Command $this->logMessage($p->count() . " Payments with No currency set"); - if($p->count() != 0) { + if ($p->count() != 0) { $this->isValid = false; } @@ -1213,8 +1213,8 @@ class CheckData extends Command $invoice->saveQuietly(); }); - + } - - + + } diff --git a/app/Console/Commands/CreateSingleAccount.php b/app/Console/Commands/CreateSingleAccount.php index ec85679482..3e95cce7f3 100644 --- a/app/Console/Commands/CreateSingleAccount.php +++ b/app/Console/Commands/CreateSingleAccount.php @@ -103,7 +103,7 @@ class CreateSingleAccount extends Command try { $pdo = \DB::connection('ronin')->getPdo(); - if(class_exists(\Modules\Ronin\app\Models\Admin::class)) { + if (class_exists(\Modules\Ronin\app\Models\Admin::class)) { $this->info('Creating Ronin Account'); $this->createRoninAccount(); } @@ -378,7 +378,7 @@ class CreateSingleAccount extends Command Project::query()->with('client')->whereNotNull('client_id')->cursor()->each(function ($p) { - if($p && $p->client && !isset($p->number)) { + if ($p && $p->client && !isset($p->number)) { $p->number = $this->getNextProjectNumber($p); $p->save(); } @@ -584,7 +584,7 @@ class CreateSingleAccount extends Command 'task_rate' => rand(1, 200), ]); - for($x = 0; $x < rand(2, 5); $x++) { + for ($x = 0; $x < rand(2, 5); $x++) { $task = $this->createTask($client); $task->project_id = $project->id; $task->save(); @@ -883,7 +883,7 @@ class CreateSingleAccount extends Command $cg->fees_and_limits = $fees_and_limits; $cg->save(); } - + if (config('ninja.testvars.braintree') && ($this->gateway == 'all' || $this->gateway == 'braintree')) { $cg = new CompanyGateway(); $cg->company_id = $company->id; diff --git a/app/Console/Commands/EncryptNinja.php b/app/Console/Commands/EncryptNinja.php index 242d388a71..89ae74db61 100644 --- a/app/Console/Commands/EncryptNinja.php +++ b/app/Console/Commands/EncryptNinja.php @@ -52,11 +52,11 @@ class EncryptNinja extends Command */ public function handle() { - if($this->option('encrypt')) { + if ($this->option('encrypt')) { return $this->encryptFiles(); } - if($this->option('decrypt')) { + if ($this->option('decrypt')) { return $this->decryptFiles(); } diff --git a/app/Console/Commands/MobileLocalization.php b/app/Console/Commands/MobileLocalization.php index 0ac482dd2b..92398660d6 100644 --- a/app/Console/Commands/MobileLocalization.php +++ b/app/Console/Commands/MobileLocalization.php @@ -63,7 +63,7 @@ class MobileLocalization extends Command { $resources = (array)$this->getResources(); - if(is_iterable($resources)) { + if (is_iterable($resources)) { foreach ($resources as $key => $val) { $transKey = "texts.{$key}"; if (trans($transKey) == $transKey) { diff --git a/app/Console/Commands/ReactBuilder.php b/app/Console/Commands/ReactBuilder.php index d4c5b7533c..c317ec0278 100644 --- a/app/Console/Commands/ReactBuilder.php +++ b/app/Console/Commands/ReactBuilder.php @@ -46,7 +46,7 @@ class ReactBuilder extends Command */ public function handle() { - if($this->option('type') == 'local') { + if ($this->option('type') == 'local') { diff --git a/app/Console/Commands/SendTestEmails.php b/app/Console/Commands/SendTestEmails.php index b778cd2db1..ec01e99080 100644 --- a/app/Console/Commands/SendTestEmails.php +++ b/app/Console/Commands/SendTestEmails.php @@ -68,7 +68,7 @@ class SendTestEmails extends Command }); - } catch(\Exception $e) { + } catch (\Exception $e) { $this->info("Error sending email: " . $e->getMessage()); } } diff --git a/app/Console/Commands/TranslationsExport.php b/app/Console/Commands/TranslationsExport.php index 9bda725a9b..f5ffec685c 100644 --- a/app/Console/Commands/TranslationsExport.php +++ b/app/Console/Commands/TranslationsExport.php @@ -139,7 +139,7 @@ class TranslationsExport extends Command Storage::disk('local')->makeDirectory("lang/{$lang}"); $translations = Lang::getLoader()->load($lang, 'texts'); - foreach($translations as $key => $value) { + foreach ($translations as $key => $value) { $translations[$key] = html_entity_decode($value); } diff --git a/app/Console/Commands/TypeCheck.php b/app/Console/Commands/TypeCheck.php index fdb7bb7971..6d1e443fc2 100644 --- a/app/Console/Commands/TypeCheck.php +++ b/app/Console/Commands/TypeCheck.php @@ -130,7 +130,7 @@ class TypeCheck extends Command $company->saveSettings($company->settings, $company); }); - Invoice::query()->cursor()->each(function ($invoice){ + Invoice::query()->cursor()->each(function ($invoice) { $this->logMessage("Checking invoice {$invoice->id}"); $invoice->line_items = $this->cleanItems($invoice->line_items); $invoice->saveQuietly(); diff --git a/app/DataMapper/BaseSettings.php b/app/DataMapper/BaseSettings.php index 882f1ed0ba..d89da44b12 100644 --- a/app/DataMapper/BaseSettings.php +++ b/app/DataMapper/BaseSettings.php @@ -16,7 +16,6 @@ namespace App\DataMapper; */ class BaseSettings { - public static function setCasts($obj, $casts) { foreach ($casts as $key => $value) { diff --git a/app/DataMapper/EInvoice/TaxEntity.php b/app/DataMapper/EInvoice/TaxEntity.php index 5840fac5bc..885cd3bed7 100644 --- a/app/DataMapper/EInvoice/TaxEntity.php +++ b/app/DataMapper/EInvoice/TaxEntity.php @@ -11,24 +11,23 @@ namespace App\DataMapper\EInvoice; - class TaxEntity { /** @var string $version */ public string $version = 'alpha'; - + /** @var ?int $legal_entity_id */ public ?int $legal_entity_id = null; - + /** @var string $company_key */ public string $company_key = ''; /** @var array */ public array $received_documents = []; - + /** @var bool $acts_as_sender */ public bool $acts_as_sender = true; - + /** @var bool $acts_as_receiver */ public bool $acts_as_receiver = true; /** diff --git a/app/DataMapper/InvoiceSync.php b/app/DataMapper/InvoiceSync.php index 05eb798f2a..534cf35f16 100644 --- a/app/DataMapper/InvoiceSync.php +++ b/app/DataMapper/InvoiceSync.php @@ -20,12 +20,12 @@ use Illuminate\Contracts\Database\Eloquent\Castable; class InvoiceSync implements Castable { public string $qb_id; - + public function __construct(array $attributes = []) { - + $this->qb_id = $attributes['qb_id'] ?? ''; - + } /** diff --git a/app/DataMapper/QuickbooksSettings.php b/app/DataMapper/QuickbooksSettings.php index 87e0805f8b..01809edf75 100644 --- a/app/DataMapper/QuickbooksSettings.php +++ b/app/DataMapper/QuickbooksSettings.php @@ -28,9 +28,9 @@ class QuickbooksSettings implements Castable public int $accessTokenExpiresAt; public int $refreshTokenExpiresAt; - + public string $baseURL; - + public QuickbooksSync $settings; public function __construct(array $attributes = []) diff --git a/app/DataMapper/QuickbooksSync.php b/app/DataMapper/QuickbooksSync.php index c27fc86ab3..23155b4159 100644 --- a/app/DataMapper/QuickbooksSync.php +++ b/app/DataMapper/QuickbooksSync.php @@ -19,19 +19,19 @@ class QuickbooksSync public QuickbooksSyncMap $client; public QuickbooksSyncMap $vendor; - + public QuickbooksSyncMap $invoice; - + public QuickbooksSyncMap $sales; - + public QuickbooksSyncMap $quote; - + public QuickbooksSyncMap $purchase_order; public QuickbooksSyncMap $product; - + public QuickbooksSyncMap $payment; - + public QuickbooksSyncMap $expense; public string $default_income_account = ''; @@ -52,4 +52,4 @@ class QuickbooksSync $this->default_income_account = $attributes['default_income_account'] ?? ''; $this->default_expense_account = $attributes['default_expense_account'] ?? ''; } -} \ No newline at end of file +} diff --git a/app/DataMapper/Sources/PayPalBalanceAffecting.php b/app/DataMapper/Sources/PayPalBalanceAffecting.php index 5494230510..0cda1d9b7d 100644 --- a/app/DataMapper/Sources/PayPalBalanceAffecting.php +++ b/app/DataMapper/Sources/PayPalBalanceAffecting.php @@ -113,11 +113,11 @@ class PayPalBalanceAffecting { $this->cleanUp(); - foreach($this->import_row as $key => $value) { + foreach ($this->import_row as $key => $value) { $prop = $this->key_map[$key] ?? false; - if($prop) { + if ($prop) { echo "Setting {$prop} to {$value}".PHP_EOL; $this->{$prop} = $value; @@ -131,7 +131,7 @@ class PayPalBalanceAffecting private function cleanUp(): self { - foreach($this->key_map as $value) { + foreach ($this->key_map as $value) { echo "Setting {$value} to null".PHP_EOL; $this->{$value} = null; } @@ -175,7 +175,7 @@ class PayPalBalanceAffecting { $name_parts = explode(" ", $this->name ?? ''); - if(count($name_parts) == 2) { + if (count($name_parts) == 2) { $contact['first_name'] = $name_parts[0]; $contact['last_name'] = $name_parts[1]; } else { @@ -202,13 +202,13 @@ class PayPalBalanceAffecting private function returnShippingAddress(): array { - if(strlen($this->shippingAddress ?? '') < 3) { + if (strlen($this->shippingAddress ?? '') < 3) { return []; } $ship_parts = explode(",", $this->shippingAddress); - if(count($ship_parts) != 7) { + if (count($ship_parts) != 7) { return []; } diff --git a/app/DataMapper/Tax/BaseRule.php b/app/DataMapper/Tax/BaseRule.php index a160787876..671df1444a 100644 --- a/app/DataMapper/Tax/BaseRule.php +++ b/app/DataMapper/Tax/BaseRule.php @@ -157,8 +157,8 @@ class BaseRule implements RuleInterface $this->resolveRegions(); - - if(!$this->isTaxableRegion()) { + + if (!$this->isTaxableRegion()) { $this->tax_data = null; $this->tax_rate1 = 0; $this->tax_name1 = ''; @@ -173,8 +173,9 @@ class BaseRule implements RuleInterface $this->tax_data = new Response($this->invoice->tax_data); - if($this->invoice instanceof \App\Models\RecurringInvoice) + if ($this->invoice instanceof \App\Models\RecurringInvoice) { $this->tax_data = new Response($this->client->tax_data); + } return $this; } @@ -187,14 +188,14 @@ class BaseRule implements RuleInterface private function configTaxData(): self { /* We should only apply taxes for configured states */ - if(!array_key_exists($this->client->country->iso_3166_2, $this->region_codes)) { + if (!array_key_exists($this->client->country->iso_3166_2, $this->region_codes)) { nlog('Automatic tax calculations not supported for this country - defaulting to company country'); } /** Harvest the client_region */ /** If the tax data is already set and the invoice is marked as sent, do not adjust the rates */ - if($this->invoice->tax_data && $this->invoice->status_id > 1) { + if ($this->invoice->tax_data && $this->invoice->status_id > 1) { return $this; } @@ -206,23 +207,23 @@ class BaseRule implements RuleInterface $tax_data = false; - if($this->seller_region == 'US' && $this->client_region == 'US') { + if ($this->seller_region == 'US' && $this->client_region == 'US') { $company = $this->invoice->company; /** If no company tax data has been configured, lets do that now. */ /** We should never encounter this scenario */ - if(!$company->origin_tax_data) { + if (!$company->origin_tax_data) { $this->should_calc_tax = false; return $this; } /** If we are in a Origin based state, force the company tax here */ - if($company->origin_tax_data->originDestination == 'O' && ($company->tax_data?->seller_subregion == $this->client_subregion)) { + if ($company->origin_tax_data->originDestination == 'O' && ($company->tax_data?->seller_subregion == $this->client_subregion)) { $tax_data = $company->origin_tax_data; - } elseif($this->client->tax_data) { + } elseif ($this->client->tax_data) { $tax_data = $this->client->tax_data; @@ -231,15 +232,15 @@ class BaseRule implements RuleInterface } /** Applies the tax data to the invoice */ - if(($this->invoice instanceof Invoice || $this->invoice instanceof Quote) && $tax_data) { + if (($this->invoice instanceof Invoice || $this->invoice instanceof Quote) && $tax_data) { $this->invoice->tax_data = $tax_data; - if(\DB::transactionLevel() == 0 && isset($this->invoice->id)) { + if (\DB::transactionLevel() == 0 && isset($this->invoice->id)) { try { $this->invoice->saveQuietly(); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: BaseRule::" . $e->getMessage()); } @@ -279,7 +280,7 @@ class BaseRule implements RuleInterface $states = USStates::$states; - if(isset($states[$this->client->state])) { + if (isset($states[$this->client->state])) { return $this->client->state; } @@ -292,18 +293,18 @@ class BaseRule implements RuleInterface public function isTaxableRegion(): bool { - return + return isset($this->client->company->tax_data->regions->{$this->client_region}->tax_all_subregions) && $this->client->company->tax_data->regions->{$this->client_region}->tax_all_subregions || (isset($this->client->company->tax_data->regions->{$this->client_region}->subregions->{$this->client_subregion}) && ($this->client->company->tax_data->regions->{$this->client_region}->subregions->{$this->client_subregion}->apply_tax ?? false)); } public function defaultForeign(): self { - if($this->invoice->client->is_tax_exempt){ - + if ($this->invoice->client->is_tax_exempt) { + $this->tax_rate1 = 0; $this->tax_name1 = ''; - + $this->tax_rate2 = 0; $this->tax_name2 = ''; @@ -312,16 +313,14 @@ class BaseRule implements RuleInterface return $this; - } - elseif($this->client_region == 'US' && isset($this->tax_data?->taxSales)) { + } elseif ($this->client_region == 'US' && isset($this->tax_data?->taxSales)) { $this->tax_rate1 = $this->tax_data->taxSales * 100; $this->tax_name1 = "{$this->tax_data->geoState} Sales Tax"; return $this; - } - elseif($this->client_region == 'AU') { //these are defaults and are only stubbed out for now, for AU we can actually remove these + } elseif ($this->client_region == 'AU') { //these are defaults and are only stubbed out for now, for AU we can actually remove these $this->tax_rate1 = $this->client->company->tax_data->regions->AU->subregions->AU->tax_rate; $this->tax_name1 = $this->client->company->tax_data->regions->AU->subregions->AU->tax_name; @@ -329,7 +328,7 @@ class BaseRule implements RuleInterface return $this; } - if(isset($this->client->company->tax_data->regions->{$this->client_region}->subregions->{$this->client_subregion})) { + if (isset($this->client->company->tax_data->regions->{$this->client_region}->subregions->{$this->client_subregion})) { if ($this->client_region === 'EU') { $company_country_code = $this->client->company->country()->iso_3166_2; $client_country_code = $this->client->country->iso_3166_2; @@ -350,13 +349,11 @@ class BaseRule implements RuleInterface elseif (in_array($company_country_code, $this->eu_country_codes)) { $this->tax_rate1 = $this->client->company->tax_data->regions->{$this->client_region}->subregions->{$company_country_code}->tax_rate; $this->tax_name1 = $this->client->company->tax_data->regions->{$this->client_region}->subregions->{$company_country_code}->tax_name; - } - elseif($is_over_threshold){ + } elseif ($is_over_threshold) { $this->tax_rate1 = $this->client->company->tax_data->regions->{$this->client_region}->subregions->{$this->client_subregion}->tax_rate; $this->tax_name1 = $this->client->company->tax_data->regions->{$this->client_region}->subregions->{$this->client_subregion}->tax_name; } - } - else { + } else { $this->tax_rate1 = $this->client->company->tax_data->regions->{$this->client_region}->subregions->{$this->client_subregion}->tax_rate; $this->tax_name1 = $this->client->company->tax_data->regions->{$this->client_region}->subregions->{$this->client_subregion}->tax_name; } @@ -368,17 +365,17 @@ class BaseRule implements RuleInterface public function tax($item = null): self { - if ($this->client->is_tax_exempt || !property_exists($item, 'tax_id') ) { + if ($this->client->is_tax_exempt || !property_exists($item, 'tax_id')) { return $this->taxExempt($item); - } elseif($this->client_region == $this->seller_region && $this->isTaxableRegion()) { + } elseif ($this->client_region == $this->seller_region && $this->isTaxableRegion()) { $this->taxByType($item); return $this; - } elseif($this->isTaxableRegion()) { //other regions outside of US + } elseif ($this->isTaxableRegion()) { //other regions outside of US match(intval($item->tax_id)) { Product::PRODUCT_TYPE_EXEMPT => $this->taxExempt($item), @@ -420,7 +417,7 @@ class BaseRule implements RuleInterface public function taxExempt($item): self { - + $this->tax_rate1 = 0; $this->tax_name1 = ''; @@ -485,7 +482,7 @@ class BaseRule implements RuleInterface { $lock_invoices = $this->client->getSetting('lock_invoices'); - if($this->invoice instanceof RecurringInvoice) { + if ($this->invoice instanceof RecurringInvoice) { return true; } @@ -508,7 +505,7 @@ class BaseRule implements RuleInterface //if now is greater than the end of month the invoice was dated - do not modify case 'end_of_month': - if(\Carbon\Carbon::parse($this->invoice->date)->setTimezone($this->invoice->company->timezone()->name)->endOfMonth()->lte(now())) { + if (\Carbon\Carbon::parse($this->invoice->date)->setTimezone($this->invoice->company->timezone()->name)->endOfMonth()->lte(now())) { return false; } return true; diff --git a/app/DataMapper/Tax/DE/Rule.php b/app/DataMapper/Tax/DE/Rule.php index bfc0159d24..cd12da06ef 100644 --- a/app/DataMapper/Tax/DE/Rule.php +++ b/app/DataMapper/Tax/DE/Rule.php @@ -237,7 +237,7 @@ class Rule extends BaseRule implements RuleInterface */ public function calculateRates(): self { - + // Tax exempt clients always get zero tax if ($this->client->is_tax_exempt) { $this->tax_rate = 0; diff --git a/app/DataMapper/Tax/GB/Rule.php b/app/DataMapper/Tax/GB/Rule.php index bb7a93b612..44bad05af6 100644 --- a/app/DataMapper/Tax/GB/Rule.php +++ b/app/DataMapper/Tax/GB/Rule.php @@ -50,7 +50,7 @@ class Rule extends BaseRule implements RuleInterface */ public function init(): self { - + $this->calculateRates(); return $this; @@ -65,11 +65,11 @@ class Rule extends BaseRule implements RuleInterface public function taxByType($item): self { - + if ($this->client->is_tax_exempt || !property_exists($item, 'tax_id') || (isset($item->type_id) && $item->type_id == '5')) { return $this->taxExempt($item); } - + match(intval($item->tax_id)) { Product::PRODUCT_TYPE_EXEMPT => $this->taxExempt($item), Product::PRODUCT_TYPE_DIGITAL => $this->taxDigital($item), @@ -216,7 +216,7 @@ class Rule extends BaseRule implements RuleInterface */ public function override($item): self { - + $this->tax_rate1 = $item->tax_rate1; $this->tax_name1 = $item->tax_name1; $this->tax_rate2 = $item->tax_rate2; @@ -270,14 +270,14 @@ class Rule extends BaseRule implements RuleInterface } // GB => GB sales - if($this->client_subregion == 'GB') { + if ($this->client_subregion == 'GB') { $this->tax_name = $this->client->company->tax_data->regions->UK->subregions->GB->tax_name; $this->tax_rate = $this->client->company->tax_data->regions->UK->subregions->GB->tax_rate ?? 0; return $this; } - + $is_over_threshold = $this->client->company->tax_data->regions->EU->has_sales_above_threshold ?? false; //GB => EU sales - Reverse Charge @@ -287,20 +287,19 @@ class Rule extends BaseRule implements RuleInterface $this->tax_rate = 0; return $this; - } - elseif(in_array($this->client_subregion, $this->eu_country_codes) && $is_over_threshold) { - + } elseif (in_array($this->client_subregion, $this->eu_country_codes) && $is_over_threshold) { + $this->tax_name = $this->client->company->tax_data->regions->EU->subregions->{$this->client->country->iso_3166_2}->tax_name; $this->tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->country->iso_3166_2}->tax_rate ?? 0; - + return $this; } - + // must be tax exempt at this point - $this->tax_name = 'VAT'; - $this->tax_rate = 0; - + $this->tax_name = 'VAT'; + $this->tax_rate = 0; + return $this; } diff --git a/app/DataMapper/Tax/TaxData.php b/app/DataMapper/Tax/TaxData.php index cf9e47b271..9dc5637afa 100644 --- a/app/DataMapper/Tax/TaxData.php +++ b/app/DataMapper/Tax/TaxData.php @@ -25,7 +25,7 @@ class TaxData public function __construct(public Response $origin) { // @phpstan-ignore-next-line - foreach($origin as $key => $value) { + foreach ($origin as $key => $value) { $this->{$key} = $value; } } diff --git a/app/DataMapper/Tax/TaxModel.php b/app/DataMapper/Tax/TaxModel.php index f828cc1691..ae285580a7 100644 --- a/app/DataMapper/Tax/TaxModel.php +++ b/app/DataMapper/Tax/TaxModel.php @@ -21,13 +21,13 @@ class TaxModel /** @var object $regions */ public object $regions; - + /** @var bool $acts_as_sender */ public bool $acts_as_sender = false; - + /** @var bool $acts_as_receiver */ public bool $acts_as_receiver = false; - + /** * __construct * @@ -37,14 +37,14 @@ class TaxModel public function __construct(public mixed $model = null) { - if(!$model) { + if (!$model) { $this->regions = $this->init(); } else { - + $this->seller_subregion = $model->seller_subregion ?? ''; $this->acts_as_sender = $model->acts_as_sender ?? false; $this->acts_as_receiver = $model->acts_as_receiver ?? false; - + $modelArray = get_object_vars($model); foreach ($modelArray as $key => $value) { $this->{$key} = $value; @@ -58,7 +58,7 @@ class TaxModel public function migrate(): self { - if($this->version == 'alpha') { + if ($this->version == 'alpha') { $this->regions->EU->subregions->PL = new \stdClass(); $this->regions->EU->subregions->PL->tax_rate = 23; $this->regions->EU->subregions->PL->tax_name = 'VAT'; @@ -68,7 +68,7 @@ class TaxModel $this->version = 'beta'; } - if($this->version == 'beta') { + if ($this->version == 'beta') { //CEUTA $this->regions->EU->subregions->{'ES-CE'} = new \stdClass(); @@ -138,7 +138,7 @@ class TaxModel $this->usRegion() ->euRegion() ->auRegion(); - // ->ukRegion(); + // ->ukRegion(); return $this->regions; @@ -149,9 +149,9 @@ class TaxModel // Add new UK region $this->regions->UK = new \stdClass(); - $this->regions->UK->has_sales_above_threshold = false; - $this->regions->UK->tax_threshold = 85000; - $this->regions->UK->tax_all_subregions = false; + $this->regions->UK->has_sales_above_threshold = false; + $this->regions->UK->tax_threshold = 85000; + $this->regions->UK->tax_all_subregions = false; $this->regions->UK->subregions = new \stdClass(); // Great Britain (England, Scotland, Wales) @@ -178,7 +178,7 @@ class TaxModel return $this; } - + /** * Builds the model for Australian Taxes * @@ -577,7 +577,7 @@ class TaxModel $this->regions->EU->subregions->IE->tax_name = 'VAT'; $this->regions->EU->subregions->IE->reduced_tax_rate = 0; $this->regions->EU->subregions->IE->apply_tax = false; - + $this->regions->EU->subregions->IS = new \stdClass(); $this->regions->EU->subregions->IS->tax_rate = 24; $this->regions->EU->subregions->IS->tax_name = 'VSK'; @@ -589,7 +589,7 @@ class TaxModel $this->regions->EU->subregions->IT->tax_name = 'IVA'; $this->regions->EU->subregions->IT->reduced_tax_rate = 10; $this->regions->EU->subregions->IT->apply_tax = false; - + $this->regions->EU->subregions->LI = new \stdClass(); $this->regions->EU->subregions->LI->tax_rate = 7.7; $this->regions->EU->subregions->LI->tax_name = 'MWST'; @@ -619,7 +619,7 @@ class TaxModel $this->regions->EU->subregions->MT->tax_name = 'VAT'; $this->regions->EU->subregions->MT->reduced_tax_rate = 5; $this->regions->EU->subregions->MT->apply_tax = false; - + $this->regions->EU->subregions->NO = new \stdClass(); $this->regions->EU->subregions->NO->tax_rate = 25; $this->regions->EU->subregions->NO->tax_name = 'MVA'; @@ -682,7 +682,7 @@ class TaxModel } $subregions[$region_code] = []; - + foreach ($region->subregions as $subregion_code => $subregion) { $subregions[$region_code][] = $subregion_code; } @@ -697,7 +697,7 @@ class TaxModel if (!isset($region->subregions)) { continue; } - + if (isset($region->subregions->{$subregion_code})) { return $region_code; } diff --git a/app/DataMapper/Tax/US/Rule.php b/app/DataMapper/Tax/US/Rule.php index 96542160d7..a966547422 100644 --- a/app/DataMapper/Tax/US/Rule.php +++ b/app/DataMapper/Tax/US/Rule.php @@ -116,7 +116,7 @@ class Rule extends BaseRule implements RuleInterface */ public function taxService($item): self { - if(in_array($this->tax_data?->txbService, ['Y','L'])) { + if (in_array($this->tax_data?->txbService, ['Y','L'])) { $this->default($item); } else { $this->taxExempt($item); @@ -133,7 +133,7 @@ class Rule extends BaseRule implements RuleInterface */ public function taxShipping($item): self { - if($this->tax_data?->txbFreight == 'Y') { + if ($this->tax_data?->txbFreight == 'Y') { return $this->default($item); } @@ -164,7 +164,7 @@ class Rule extends BaseRule implements RuleInterface public function default($item): self { - if($this->tax_data?->stateSalesTax == 0) { + if ($this->tax_data?->stateSalesTax == 0) { $this->tax_rate1 = 0; $this->tax_name1 = ''; diff --git a/app/DataMapper/Tax/ZipTax/Response.php b/app/DataMapper/Tax/ZipTax/Response.php index 59e3653a3f..99d7cfda8c 100644 --- a/app/DataMapper/Tax/ZipTax/Response.php +++ b/app/DataMapper/Tax/ZipTax/Response.php @@ -103,9 +103,9 @@ class Response public function __construct($data = null) { - if($data) { + if ($data) { - foreach($data as $key => $value) { + foreach ($data as $key => $value) { $this->{$key} = $value; } diff --git a/app/DataProviders/SMSNumbers.php b/app/DataProviders/SMSNumbers.php index 0d50bd9a36..c535677275 100644 --- a/app/DataProviders/SMSNumbers.php +++ b/app/DataProviders/SMSNumbers.php @@ -93934,34 +93934,34 @@ class SMSNumbers { // Remove duplicates and reindex array $unique_numbers = array_values(array_unique(self::$temp_numbers)); - + // Sort the array sort($unique_numbers); - + return $unique_numbers; } - + /** * deDupe * * Cleans up the phone numbers are removed duplicates - * + * * @return void */ public static function deDupe() { $unique_numbers = self::uniqueNumbers(); - + $output = "private static array \$temp_numbers = [\n"; foreach ($unique_numbers as $number) { $output .= " '" . $number . "',\n"; } - + $output .= "];"; - + echo $output; } diff --git a/app/DataProviders/USStates.php b/app/DataProviders/USStates.php index a638bca2f9..f02671d0da 100644 --- a/app/DataProviders/USStates.php +++ b/app/DataProviders/USStates.php @@ -33868,19 +33868,19 @@ class USStates public static function getState(?string $zip = '90210'): string { - if(isset(self::$zip_code_map[$zip])) { + if (isset(self::$zip_code_map[$zip])) { return self::$zip_code_map[$zip]; } $prefix_state = self::getStateFromThreeDigitPrefix($zip); - if($prefix_state) { + if ($prefix_state) { return $prefix_state; } $zippo_response = self::getStateFromZippo($zip); - if($zippo_response) { + if ($zippo_response) { return $zippo_response; } @@ -33908,13 +33908,13 @@ class USStates $response = Http::get("https://api.zippopotam.us/us/{$zip}"); - if($response->failed()) { + if ($response->failed()) { return false; } $data = $response->object(); - if(isset($data->places[0])) { + if (isset($data->places[0])) { return $data->places[0]->{'state abbreviation'}; } diff --git a/app/Events/Credit/CreditWasUpdated.php b/app/Events/Credit/CreditWasUpdated.php index 0753a6379f..0cc33adf7f 100644 --- a/app/Events/Credit/CreditWasUpdated.php +++ b/app/Events/Credit/CreditWasUpdated.php @@ -48,7 +48,7 @@ class CreditWasUpdated implements ShouldBroadcast $this->dontBroadcastToCurrentUser(); } - + public function broadcastModel(): BaseModel { return $this->credit; diff --git a/app/Events/Invoice/InvoiceWasPaid.php b/app/Events/Invoice/InvoiceWasPaid.php index 1897ca5f7c..0e147290fd 100644 --- a/app/Events/Invoice/InvoiceWasPaid.php +++ b/app/Events/Invoice/InvoiceWasPaid.php @@ -26,7 +26,9 @@ use Illuminate\Queue\SerializesModels; */ class InvoiceWasPaid implements ShouldBroadcast { - use SerializesModels, DefaultResourceBroadcast, InteractsWithSockets; + use SerializesModels; + use DefaultResourceBroadcast; + use InteractsWithSockets; /** * Create a new event instance. diff --git a/app/Events/Payment/PaymentWasUpdated.php b/app/Events/Payment/PaymentWasUpdated.php index 66dc574059..fa7899fc6f 100644 --- a/app/Events/Payment/PaymentWasUpdated.php +++ b/app/Events/Payment/PaymentWasUpdated.php @@ -24,7 +24,9 @@ use Illuminate\Queue\SerializesModels; */ class PaymentWasUpdated implements ShouldBroadcast { - use SerializesModels, InteractsWithSockets, DefaultResourceBroadcast; + use SerializesModels; + use InteractsWithSockets; + use DefaultResourceBroadcast; /** * @var Payment diff --git a/app/Exceptions/PeppolValidationException.php b/app/Exceptions/PeppolValidationException.php index 5d85eec04c..07b96471be 100644 --- a/app/Exceptions/PeppolValidationException.php +++ b/app/Exceptions/PeppolValidationException.php @@ -15,7 +15,6 @@ use Exception; class PeppolValidationException extends Exception { - protected string $field = ''; public function __construct($message, $field, $code = 0, Exception $previous = null) diff --git a/app/Export/CSV/ActivityExport.php b/app/Export/CSV/ActivityExport.php index f9f60bbcdc..a99f602046 100644 --- a/app/Export/CSV/ActivityExport.php +++ b/app/Export/CSV/ActivityExport.php @@ -104,8 +104,8 @@ class ActivityExport extends BaseExport /** @var \App\Models\DateFormat $df */ $df = DateFormat::query()->find($this->company->settings->date_format_id); - $this->date_format = $df->format; - + $this->date_format = $df->format; + if (count($this->input['report_keys']) == 0) { $this->input['report_keys'] = array_values($this->entity_keys); } diff --git a/app/Export/CSV/BaseExport.php b/app/Export/CSV/BaseExport.php index ac67f08683..21b795ebdc 100644 --- a/app/Export/CSV/BaseExport.php +++ b/app/Export/CSV/BaseExport.php @@ -473,20 +473,20 @@ class BaseExport { if (isset($this->input['client_id']) && $this->input['client_id'] != 'all') { - if(!is_int($this->input['client_id'])) { + if (!is_int($this->input['client_id'])) { $this->input['client_id'] = $this->decodePrimaryKey($this->input['client_id']); } $client = Client::withTrashed()->find($this->input['client_id']); - if(!$client) { + if (!$client) { return $query; } $this->client_description = $client->present()->name; return $query->where('client_id', $this->input['client_id']); - } elseif(isset($this->input['clients']) && count($this->input['clients']) > 0) { + } elseif (isset($this->input['clients']) && count($this->input['clients']) > 0) { $this->client_description = 'Multiple Clients'; return $query->whereIn('client_id', $this->input['clients']); @@ -498,7 +498,7 @@ class BaseExport { $parts = explode(".", $key); - if(!is_array($parts) || count($parts) < 2) { + if (!is_array($parts) || count($parts) < 2) { return ''; } @@ -525,7 +525,7 @@ class BaseExport private function resolveClientContactKey($column, $entity, $transformer) { - if(!$entity->client) { + if (!$entity->client) { return ""; } @@ -537,7 +537,7 @@ class BaseExport private function resolveVendorContactKey($column, $entity, $transformer) { - if(!$entity->vendor) { + if (!$entity->vendor) { return ""; } @@ -551,19 +551,19 @@ class BaseExport private function resolveExpenseKey($column, $entity, $transformer) { - if($column == 'user' && $entity?->expense?->user) { + if ($column == 'user' && $entity?->expense?->user) { return $entity->expense->user->present()->name() ?? ' '; } - if($column == 'assigned_user' && $entity?->expense?->assigned_user) { + if ($column == 'assigned_user' && $entity?->expense?->assigned_user) { return $entity->expense->assigned_user->present()->name() ?? ' '; } - if($column == 'category' && $entity->expense) { + if ($column == 'category' && $entity->expense) { return $entity->expense->category?->name ?? ' '; } - if($entity instanceof Expense) { + if ($entity instanceof Expense) { return ''; } @@ -573,11 +573,11 @@ class BaseExport $manager->setSerializer(new ArraySerializer()); $transformed_entity = $manager->createData($transformed_entity)->toArray(); - if(array_key_exists($column, $transformed_entity)) { + if (array_key_exists($column, $transformed_entity)) { return $transformed_entity[$column]; } - if(property_exists($entity, $column)) { + if (property_exists($entity, $column)) { return $entity?->{$column} ?? ''; } @@ -593,7 +593,7 @@ class BaseExport $transformed_entity = $transformer->transform($entity); - if(array_key_exists($column, $transformed_entity)) { + if (array_key_exists($column, $transformed_entity)) { return $transformed_entity[$column]; } @@ -606,7 +606,7 @@ class BaseExport private function resolveVendorKey($column, $entity, $transformer) { - if(!$entity->vendor) { + if (!$entity->vendor) { return ''; } @@ -616,15 +616,15 @@ class BaseExport $manager->setSerializer(new ArraySerializer()); $transformed_entity = $manager->createData($transformed_entity)->toArray(); - if($column == 'name') { + if ($column == 'name') { return $entity->vendor->present()->name() ?: ''; } - if($column == 'user_id') { + if ($column == 'user_id') { return $entity->vendor->user->present()->name() ?: ''; } - if($column == 'country_id') { + if ($column == 'country_id') { return $entity->vendor->country ? ctrans("texts.country_{$entity->vendor->country->name}") : ''; } @@ -632,11 +632,11 @@ class BaseExport return $entity->vendor->currency() ? $entity->vendor->currency()->code : $entity->company->currency()->code; } - if($column == 'status') { + if ($column == 'status') { return $entity->stringStatus($entity->status_id) ?: ''; } - if(array_key_exists($column, $transformed_entity)) { + if (array_key_exists($column, $transformed_entity)) { return $transformed_entity[$column]; } @@ -650,7 +650,7 @@ class BaseExport private function resolveClientKey($column, $entity, $transformer) { - if(!$entity->client) { + if (!$entity->client) { return ''; } @@ -660,31 +660,31 @@ class BaseExport $manager->setSerializer(new ArraySerializer()); $transformed_client = $manager->createData($transformed_client)->toArray(); - if(in_array($column, ['client.name', 'name'])) { + if (in_array($column, ['client.name', 'name'])) { return $transformed_client['display_name']; } - if(in_array($column, ['client.user_id', 'user_id'])) { + if (in_array($column, ['client.user_id', 'user_id'])) { return $entity->client->user ? $entity->client->user->present()->name() : ''; } - if(in_array($column, ['client.assigned_user_id', 'assigned_user_id'])) { + if (in_array($column, ['client.assigned_user_id', 'assigned_user_id'])) { return $entity->client->assigned_user ? $entity->client->assigned_user->present()->name() : ''; } - if(in_array($column, ['client.country_id', 'country_id'])) { + if (in_array($column, ['client.country_id', 'country_id'])) { return $entity->client->country ? ctrans("texts.country_{$entity->client->country->name}") : ''; } - if(in_array($column, ['client.shipping_country_id', 'shipping_country_id'])) { + if (in_array($column, ['client.shipping_country_id', 'shipping_country_id'])) { return $entity->client->shipping_country ? ctrans("texts.country_{$entity->client->shipping_country->name}") : ''; } - if(in_array($column, ['client.size_id', 'size_id'])) { + if (in_array($column, ['client.size_id', 'size_id'])) { return $entity->client->size?->name ?? ''; } - if(in_array($column, ['client.industry_id', 'industry_id'])) { + if (in_array($column, ['client.industry_id', 'industry_id'])) { return $entity->client->industry?->name ?? ''; } @@ -692,12 +692,12 @@ class BaseExport return $entity->client->currency() ? $entity->client->currency()->code : $entity->company->currency()->code; } - if(in_array($column, ['payment_terms', 'client.payment_terms'])) { + if (in_array($column, ['payment_terms', 'client.payment_terms'])) { return $entity->client->getSetting('payment_terms'); } - if(array_key_exists($column, $transformed_client)) { + if (array_key_exists($column, $transformed_client)) { return $transformed_client[$column]; } @@ -713,7 +713,7 @@ class BaseExport $transformed_entity = $transformer->transform($entity); - if($column == 'status') { + if ($column == 'status') { return $entity->stringStatus($entity->status_id); } @@ -726,7 +726,7 @@ class BaseExport $transformed_entity = $transformer->transform($entity); - if(array_key_exists($column, $transformed_entity)) { + if (array_key_exists($column, $transformed_entity)) { return $transformed_entity[$column]; } @@ -739,24 +739,24 @@ class BaseExport // nlog("searching for {$column}"); $transformed_invoice = false; - if($transformer instanceof PaymentTransformer && ($entity->invoices ?? false)) { + if ($transformer instanceof PaymentTransformer && ($entity->invoices ?? false)) { $transformed_invoices = $transformer->includeInvoices($entity); $manager = new Manager(); $manager->setSerializer(new ArraySerializer()); $transformed_invoices = $manager->createData($transformed_invoices)->toArray(); - if(!isset($transformed_invoices['App\\Models\\Invoice'])) { + if (!isset($transformed_invoices['App\\Models\\Invoice'])) { return ''; } $transformed_invoices = $transformed_invoices['App\\Models\\Invoice']; - if(count($transformed_invoices) == 1 && array_key_exists($column, $transformed_invoices[0])) { + if (count($transformed_invoices) == 1 && array_key_exists($column, $transformed_invoices[0])) { return $transformed_invoices[0][$column]; } - if(count($transformed_invoices) > 1 && array_key_exists($column, $transformed_invoices[0])) { + if (count($transformed_invoices) > 1 && array_key_exists($column, $transformed_invoices[0])) { return implode(', ', array_column($transformed_invoices, $column)); } @@ -764,10 +764,10 @@ class BaseExport } - if($transformer instanceof TaskTransformer && ($entity->invoice ?? false)) { + if ($transformer instanceof TaskTransformer && ($entity->invoice ?? false)) { $transformed_invoice = $transformer->includeInvoice($entity); - if(!$transformed_invoice) { + if (!$transformed_invoice) { return ''; } @@ -777,7 +777,7 @@ class BaseExport } - if($transformed_invoice && array_key_exists($column, $transformed_invoice)) { + if ($transformed_invoice && array_key_exists($column, $transformed_invoice)) { return $transformed_invoice[$column]; } elseif ($transformed_invoice && array_key_exists(str_replace("invoice.", "", $column), $transformed_invoice)) { return $transformed_invoice[$column]; @@ -789,11 +789,11 @@ class BaseExport private function resolvePaymentKey($column, $entity, $transformer) { - if($entity instanceof Payment) { + if ($entity instanceof Payment) { $transformed_payment = $transformer->transform($entity); - if(array_key_exists($column, $transformed_payment)) { + if (array_key_exists($column, $transformed_payment)) { return $transformed_payment[$column]; } elseif (array_key_exists(str_replace("payment.", "", $column), $transformed_payment)) { return $transformed_payment[$column]; @@ -805,15 +805,15 @@ class BaseExport } - if($column == 'amount') { + if ($column == 'amount') { return $entity->payments()->exists() ? $entity->payments()->withoutTrashed()->sum('paymentables.amount') : ctrans('texts.unpaid'); } - if($column == 'refunded') { + if ($column == 'refunded') { return $entity->payments()->exists() ? $entity->payments()->withoutTrashed()->sum('paymentables.refunded') : ''; } - if($column == 'applied') { + if ($column == 'applied') { $refunded = $entity->payments()->withoutTrashed()->sum('paymentables.refunded'); $amount = $entity->payments()->withoutTrashed()->sum('paymentables.amount'); @@ -822,26 +822,26 @@ class BaseExport $payment = $entity->payments()->withoutTrashed()->first(); - if(!$payment) { + if (!$payment) { return ''; } - if($column == 'method') { + if ($column == 'method') { return $payment->translatedType(); } - if($column == 'currency') { + if ($column == 'currency') { return $payment?->currency?->code ?? ''; } $payment_transformer = new PaymentTransformer(); $transformed_payment = $payment_transformer->transform($payment); - if($column == 'status') { + if ($column == 'status') { return $payment->stringStatus($transformed_payment['status_id']); } - if(array_key_exists($column, $transformed_payment)) { + if (array_key_exists($column, $transformed_payment)) { return $transformed_payment[$column]; } @@ -859,12 +859,12 @@ class BaseExport public function applyProductFilters(Builder $query): Builder { - if(isset($this->input['product_key'])) { + if (isset($this->input['product_key'])) { $products = explode(",", $this->input['product_key']); $query->where(function ($q) use ($products) { - foreach($products as $product) { + foreach ($products as $product) { $q->orWhereJsonContains('line_items', ['product_key' => $product]); } }); @@ -884,13 +884,13 @@ class BaseExport */ protected function addClientFilter(Builder $query, $clients): Builder { - if(is_string($clients)) { + if (is_string($clients)) { $clients = explode(',', $clients); } $transformed_clients = $this->transformKeys($clients); - if(count($transformed_clients) > 0) { + if (count($transformed_clients) > 0) { $query->whereIn('client_id', $transformed_clients); } @@ -908,13 +908,13 @@ class BaseExport protected function addVendorFilter(Builder$query, string $vendors): Builder { - if(is_string($vendors)) { + if (is_string($vendors)) { $vendors = explode(',', $vendors); } $transformed_vendors = $this->transformKeys($vendors); - if(count($transformed_vendors) > 0) { + if (count($transformed_vendors) > 0) { $query->whereIn('vendor_id', $transformed_vendors); } @@ -932,13 +932,13 @@ class BaseExport protected function addProjectFilter(Builder $query, string $projects): Builder { - if(is_string($projects)) { + if (is_string($projects)) { $projects = explode(',', $projects); } $transformed_projects = $this->transformKeys($projects); - if(count($transformed_projects) > 0) { + if (count($transformed_projects) > 0) { $query->whereIn('project_id', $transformed_projects); } @@ -956,14 +956,14 @@ class BaseExport protected function addCategoryFilter(Builder $query, string $expense_categories): Builder { - if(is_string($expense_categories)) { + if (is_string($expense_categories)) { $expense_categories = explode(',', $expense_categories); } $transformed_expense_categories = $this->transformKeys($expense_categories); - if(count($transformed_expense_categories) > 0) { + if (count($transformed_expense_categories) > 0) { $query->whereIn('category_id', $transformed_expense_categories); } @@ -984,7 +984,7 @@ class BaseExport /** @var array $status_parameters */ $status_parameters = explode(',', $status); - if((count($status_parameters) == 0) || in_array('all', $status_parameters)) { + if ((count($status_parameters) == 0) || in_array('all', $status_parameters)) { return $query; } @@ -1019,7 +1019,7 @@ class BaseExport $query->whereIn('status_id', $payment_filters); } - if(in_array('partially_unapplied', $status_parameters)) { + if (in_array('partially_unapplied', $status_parameters)) { $query->whereColumn('amount', '>', 'applied')->where('refunded', 0); } }); @@ -1048,7 +1048,7 @@ class BaseExport $recurring_filters = []; - if($this->company->getSetting('report_include_drafts')) { + if ($this->company->getSetting('report_include_drafts')) { $recurring_filters[] = RecurringInvoice::STATUS_DRAFT; } @@ -1127,7 +1127,7 @@ class BaseExport }); } - if(in_array('converted', $status_parameters)) { + if (in_array('converted', $status_parameters)) { $query->orWhere(function ($q) { $q->whereNotNull('invoice_id'); }); @@ -1200,7 +1200,7 @@ class BaseExport /** @var array $status_parameters */ $status_parameters = explode(',', $status); - if(in_array('all', $status_parameters) || count($status_parameters) == 0) { + if (in_array('all', $status_parameters) || count($status_parameters) == 0) { return $query; } @@ -1239,7 +1239,7 @@ class BaseExport ->orWhere('partial_due_date', '<', Carbon::now()); } - if(in_array('viewed', $status_parameters)) { + if (in_array('viewed', $status_parameters)) { $nested->whereHas('invitations', function ($q) { $q->whereNotNull('viewed_date')->whereNotNull('deleted_at'); @@ -1316,7 +1316,7 @@ class BaseExport $first_month_of_year = $this->company->getSetting('first_month_of_year') ?? 1; $fin_year_start = now()->createFromDate(now()->year, $first_month_of_year, 1); - if(now()->lt($fin_year_start)) { + if (now()->lt($fin_year_start)) { $fin_year_start->subYearNoOverflow(); } @@ -1329,7 +1329,7 @@ class BaseExport $fin_year_start = now()->createFromDate(now()->year, $first_month_of_year, 1); $fin_year_start->subYearNoOverflow(); - if(now()->subYear()->lt($fin_year_start)) { + if (now()->subYear()->lt($fin_year_start)) { $fin_year_start->subYearNoOverflow(); } @@ -1374,71 +1374,71 @@ class BaseExport // nlog("{$key} => {$value}"); $prefix = ''; - if(!$key) { + if (!$key) { $prefix = stripos($value, 'client.') !== false ? ctrans('texts.client')." " : ctrans('texts.contact')." "; $key = array_search($value, $this->client_report_keys); } - if(!$key) { + if (!$key) { $prefix = ctrans('texts.invoice')." "; $key = array_search($value, $this->invoice_report_keys); } - if(!$key) { + if (!$key) { $prefix = ctrans('texts.recurring_invoice')." "; $key = array_search($value, $this->recurring_invoice_report_keys); } - if(!$key) { + if (!$key) { $prefix = ctrans('texts.payment')." "; $key = array_search($value, $this->payment_report_keys); } - if(!$key) { + if (!$key) { $prefix = ctrans('texts.quote')." "; $key = array_search($value, $this->quote_report_keys); } - if(!$key) { + if (!$key) { $prefix = ctrans('texts.credit')." "; $key = array_search($value, $this->credit_report_keys); } - if(!$key) { + if (!$key) { $prefix = ctrans('texts.item')." "; $key = array_search($value, $this->item_report_keys); } - if(!$key) { + if (!$key) { $prefix = ctrans('texts.expense')." "; $key = array_search($value, $this->expense_report_keys); - if(!$key && $value == 'expense.category') { + if (!$key && $value == 'expense.category') { $key = 'category'; } } - if(!$key) { + if (!$key) { $prefix = ctrans('texts.task')." "; $key = array_search($value, $this->task_report_keys); } - if(!$key) { + if (!$key) { $prefix = ctrans('texts.vendor')." "; $key = array_search($value, $this->vendor_report_keys); } - if(!$key) { + if (!$key) { $prefix = ctrans('texts.purchase_order')." "; $key = array_search($value, $this->purchase_order_report_keys); } - if(!$key) { + if (!$key) { $prefix = ''; $key = array_search($value, $this->product_report_keys); } - if(!$key) { + if (!$key) { $prefix = ''; } @@ -1459,29 +1459,29 @@ class BaseExport $key = str_replace('product.', '', $key); $key = str_replace('task.', '', $key); - if(stripos($value, 'custom_value') !== false) { + if (stripos($value, 'custom_value') !== false) { $parts = explode(".", $value); - if(count($parts) == 2 && in_array($parts[0], ['credit','quote','invoice','purchase_order','recurring_invoice'])) { + if (count($parts) == 2 && in_array($parts[0], ['credit','quote','invoice','purchase_order','recurring_invoice'])) { $entity = "invoice".substr($parts[1], -1); $prefix = ctrans("texts.".$parts[0]); $fallback = "custom_value".substr($parts[1], -1); $custom_field_label = $helper->makeCustomField($this->company->custom_fields, $entity); - if(strlen($custom_field_label) > 1) { + if (strlen($custom_field_label) > 1) { $header[] = $custom_field_label; } else { $header[] = $prefix . " ". ctrans("texts.{$fallback}"); } - } elseif(count($parts) == 2 && (stripos($parts[0], 'vendor_contact') !== false || stripos($parts[0], 'contact') !== false)) { + } elseif (count($parts) == 2 && (stripos($parts[0], 'vendor_contact') !== false || stripos($parts[0], 'contact') !== false)) { $parts[0] = str_replace('vendor_contact', 'contact', $parts[0]); $entity = "contact".substr($parts[1], -1); $custom_field_string = strlen($helper->makeCustomField($this->company->custom_fields, $entity)) > 1 ? $helper->makeCustomField($this->company->custom_fields, $entity) : ctrans("texts.{$parts[1]}"); $header[] = ctrans("texts.{$parts[0]}") . " " . $custom_field_string; - } elseif(count($parts) == 2 && in_array(substr($original_key, 0, -1), ['credit','quote','invoice','purchase_order','recurring_invoice','task'])) { + } elseif (count($parts) == 2 && in_array(substr($original_key, 0, -1), ['credit','quote','invoice','purchase_order','recurring_invoice','task'])) { $custom_field_string = strlen($helper->makeCustomField($this->company->custom_fields, "product".substr($original_key, -1))) > 1 ? $helper->makeCustomField($this->company->custom_fields, "product".substr($original_key, -1)) : ctrans("texts.{$parts[1]}"); $header[] = ctrans("texts.{$parts[0]}") . " " . $custom_field_string; } else { @@ -1528,12 +1528,12 @@ class BaseExport $column_key = $value; - if($value == 'product_image') { + if ($value == 'product_image') { $column_key = 'image'; $value = 'image'; } - if($value == 'tax_id') { + if ($value == 'tax_id') { $column_key = 'tax_category'; $value = 'tax_category'; } @@ -1575,11 +1575,11 @@ class BaseExport $column_key = $value; - if($value == 'type_id' || $value == 'item.type_id') { + if ($value == 'type_id' || $value == 'item.type_id') { $column_key = 'type'; } - if($value == 'tax_id' || $value == 'item.tax_id') { + if ($value == 'tax_id' || $value == 'item.tax_id') { $column_key = 'tax_category'; } @@ -1595,9 +1595,10 @@ class BaseExport return $clean_row; } - public function queuePdfs(Builder $query) { + public function queuePdfs(Builder $query) + { - if(in_array(get_class($query->getModel()), [Invoice::class, Quote::class, Credit::class, PurchaseOrder::class]) && $query->count() > 0) { + if (in_array(get_class($query->getModel()), [Invoice::class, Quote::class, Credit::class, PurchaseOrder::class]) && $query->count() > 0) { $user = $this->company->owner(); @@ -1617,7 +1618,7 @@ class BaseExport ZipCredits::dispatch($query->pluck('id'), $this->company, $user); break; case PurchaseOrder::class: - ZipPurchaseOrders::dispatch($query->pluck('id'),$this->company, $user); + ZipPurchaseOrders::dispatch($query->pluck('id'), $this->company, $user); break; default: # code... @@ -1629,7 +1630,7 @@ class BaseExport public function queueDocuments(Builder $query) { - if($query->getModel() instanceof Document) { + if ($query->getModel() instanceof Document) { $documents = $query->pluck('id')->toArray(); } else { $documents = $query->cursor() @@ -1639,15 +1640,15 @@ class BaseExport ->toArray(); } - if(count($documents) > 0) { + if (count($documents) > 0) { $user = $this->company->owner(); - if(auth()->user() && auth()->user()->account_id == $this->company->account_id) { + if (auth()->user() && auth()->user()->account_id == $this->company->account_id) { $user = auth()->user(); } - if($this->input['user_id'] ?? false) { + if ($this->input['user_id'] ?? false) { $user = User::where('id', $this->input['user_id'])->where('account_id', $this->company->account_id)->first(); } @@ -1672,7 +1673,7 @@ class BaseExport public function convertFloats(iterable $entity): iterable { $currency = $this->company->currency(); - + foreach ($entity as $key => $value) { if (is_float($value)) { $entity[$key] = \App\Utils\Number::formatValue($value, $currency); diff --git a/app/Export/CSV/ClientExport.php b/app/Export/CSV/ClientExport.php index 65597914da..fa2b32bda3 100644 --- a/app/Export/CSV/ClientExport.php +++ b/app/Export/CSV/ClientExport.php @@ -129,13 +129,13 @@ class ClientExport extends BaseExport ->withTrashed() ->where('company_id', $this->company->id); - if(!$this->input['include_deleted'] ?? false) { + if (!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } $query = $this->addDateRange($query, ' clients'); - if($this->input['document_email_attachment'] ?? false) { + if ($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } @@ -208,7 +208,7 @@ class ClientExport extends BaseExport $clean_row[$key]['value'] = $row[$column_key]; $clean_row[$key]['identifier'] = $value; - if(in_array($clean_row[$key]['id'], ['paid_to_date', 'balance', 'credit_balance','payment_balance'])) { + if (in_array($clean_row[$key]['id'], ['paid_to_date', 'balance', 'credit_balance','payment_balance'])) { $clean_row[$key]['display_value'] = Number::formatMoney($row[$column_key], $resource); } else { $clean_row[$key]['display_value'] = $row[$column_key]; diff --git a/app/Export/CSV/CreditExport.php b/app/Export/CSV/CreditExport.php index 0fa32db99c..7a1a84dd0a 100644 --- a/app/Export/CSV/CreditExport.php +++ b/app/Export/CSV/CreditExport.php @@ -75,7 +75,7 @@ class CreditExport extends BaseExport $clean_row[$key]['value'] = $row[$column_key]; $clean_row[$key]['identifier'] = $value; - if(in_array($clean_row[$key]['id'], ['paid_to_date','total_taxes','amount', 'balance', 'partial', 'refunded', 'applied','unit_cost','cost','price'])) { + if (in_array($clean_row[$key]['id'], ['paid_to_date','total_taxes','amount', 'balance', 'partial', 'refunded', 'applied','unit_cost','cost','price'])) { $clean_row[$key]['display_value'] = Number::formatMoney($row[$column_key], $resource->client); } else { $clean_row[$key]['display_value'] = $row[$column_key]; @@ -114,15 +114,15 @@ class CreditExport extends BaseExport $clients = &$this->input['client_id']; - if($clients) { + if ($clients) { $query = $this->addClientFilter($query, $clients); } - if($this->input['status'] ?? false) { + if ($this->input['status'] ?? false) { $query = $this->addCreditStatusFilter($query, $this->input['status']); } - if($this->input['document_email_attachment'] ?? false) { + if ($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } @@ -168,7 +168,7 @@ class CreditExport extends BaseExport $entity[$keyval] = $transformed_credit[$credit_key]; } elseif (isset($transformed_credit[$keyval])) { $entity[$keyval] = $transformed_credit[$keyval]; - } elseif(isset($transformed_credit[$searched_credit_key])) { + } elseif (isset($transformed_credit[$searched_credit_key])) { $entity[$keyval] = $transformed_credit[$searched_credit_key]; } else { $entity[$key] = $this->decorator->transform($key, $credit); diff --git a/app/Export/CSV/DocumentExport.php b/app/Export/CSV/DocumentExport.php index 37e97cd344..1adb563546 100644 --- a/app/Export/CSV/DocumentExport.php +++ b/app/Export/CSV/DocumentExport.php @@ -80,7 +80,7 @@ class DocumentExport extends BaseExport $query = $this->addDateRange($query, 'documents'); - if($this->input['document_email_attachment'] ?? false) { + if ($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } diff --git a/app/Export/CSV/ExpenseExport.php b/app/Export/CSV/ExpenseExport.php index a0f2189da2..27a775be97 100644 --- a/app/Export/CSV/ExpenseExport.php +++ b/app/Export/CSV/ExpenseExport.php @@ -87,33 +87,33 @@ class ExpenseExport extends BaseExport ->where('company_id', $this->company->id); - if(!$this->input['include_deleted'] ?? false) { // @phpstan-ignore-line + if (!$this->input['include_deleted'] ?? false) { // @phpstan-ignore-line $query->where('is_deleted', 0); } $query = $this->addDateRange($query, 'expenses'); - if($this->input['status'] ?? false) { + if ($this->input['status'] ?? false) { $query = $this->addExpenseStatusFilter($query, $this->input['status']); } - if(isset($this->input['clients'])) { + if (isset($this->input['clients'])) { $query = $this->addClientFilter($query, $this->input['clients']); } - if(isset($this->input['vendors'])) { + if (isset($this->input['vendors'])) { $query = $this->addVendorFilter($query, $this->input['vendors']); } - if(isset($this->input['projects'])) { + if (isset($this->input['projects'])) { $query = $this->addProjectFilter($query, $this->input['projects']); } - if(isset($this->input['categories'])) { + if (isset($this->input['categories'])) { $query = $this->addCategoryFilter($query, $this->input['categories']); } - if($this->input['document_email_attachment'] ?? false) { + if ($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } @@ -264,11 +264,11 @@ class ExpenseExport extends BaseExport { $precision = $expense->currency->precision ?? 2; - if($expense->calculate_tax_by_amount) { + if ($expense->calculate_tax_by_amount) { $total_tax_amount = round($expense->tax_amount1 + $expense->tax_amount2 + $expense->tax_amount3, $precision); - if($expense->uses_inclusive_taxes) { + if ($expense->uses_inclusive_taxes) { $entity['expense.net_amount'] = round($expense->amount, $precision) - $total_tax_amount; } else { $entity['expense.net_amount'] = round($expense->amount, $precision); @@ -276,7 +276,7 @@ class ExpenseExport extends BaseExport } else { - if($expense->uses_inclusive_taxes) { + if ($expense->uses_inclusive_taxes) { $total_tax_amount = ($this->calcInclusiveLineTax($expense->tax_rate1 ?? 0, $expense->amount, $precision)) + ($this->calcInclusiveLineTax($expense->tax_rate2 ?? 0, $expense->amount, $precision)) + ($this->calcInclusiveLineTax($expense->tax_rate3 ?? 0, $expense->amount, $precision)); $entity['expense.net_amount'] = round(($expense->amount - round($total_tax_amount, $precision)), $precision); } else { diff --git a/app/Export/CSV/InvoiceExport.php b/app/Export/CSV/InvoiceExport.php index 2e16e70a4f..8542cf2436 100644 --- a/app/Export/CSV/InvoiceExport.php +++ b/app/Export/CSV/InvoiceExport.php @@ -63,7 +63,7 @@ class InvoiceExport extends BaseExport ->where('company_id', $this->company->id); - if(!$this->input['include_deleted'] ?? false) {// @phpstan-ignore-line + if (!$this->input['include_deleted'] ?? false) {// @phpstan-ignore-line $query->where('is_deleted', 0); } @@ -71,19 +71,19 @@ class InvoiceExport extends BaseExport $clients = &$this->input['client_id']; - if($clients) { + if ($clients) { $query = $this->addClientFilter($query, $clients); } - if($this->input['status'] ?? false) { + if ($this->input['status'] ?? false) { $query = $this->addInvoiceStatusFilter($query, $this->input['status']); } - if($this->input['document_email_attachment'] ?? false) { + if ($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } - if($this->input['pdf_email_attachment'] ?? false) { + if ($this->input['pdf_email_attachment'] ?? false) { $this->queuePdfs($query); } diff --git a/app/Export/CSV/InvoiceItemExport.php b/app/Export/CSV/InvoiceItemExport.php index 02ab11b163..a0cb198c8c 100644 --- a/app/Export/CSV/InvoiceItemExport.php +++ b/app/Export/CSV/InvoiceItemExport.php @@ -78,7 +78,7 @@ class InvoiceItemExport extends BaseExport }) ->where('company_id', $this->company->id); - if(!$this->input['include_deleted'] ?? false) {// @phpstan-ignore-line + if (!$this->input['include_deleted'] ?? false) {// @phpstan-ignore-line $query->where('is_deleted', 0); } @@ -86,17 +86,17 @@ class InvoiceItemExport extends BaseExport $clients = &$this->input['client_id']; - if($clients) { + if ($clients) { $query = $this->addClientFilter($query, $clients); } - if($this->input['status'] ?? false) { + if ($this->input['status'] ?? false) { $query = $this->addInvoiceStatusFilter($query, $this->input['status']); } $query = $this->applyProductFilters($query); - if($this->input['document_email_attachment'] ?? false) { + if ($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } @@ -120,7 +120,7 @@ class InvoiceItemExport extends BaseExport /** @var \App\Models\Invoice $resource */ $this->iterateItems($resource); - foreach($this->storage_array as $row) { + foreach ($this->storage_array as $row) { $this->storage_item_array[] = $this->processItemMetaData($row, $resource); } @@ -171,11 +171,11 @@ class InvoiceItemExport extends BaseExport $tmp_key = str_replace("item.", "", $key); - if($tmp_key == 'type_id') { + if ($tmp_key == 'type_id') { $tmp_key = 'type'; } - if($tmp_key == 'tax_id') { + if ($tmp_key == 'tax_id') { $tmp_key = 'tax_category'; } @@ -203,12 +203,12 @@ class InvoiceItemExport extends BaseExport $entity = []; - + foreach (array_values($this->input['report_keys']) as $key) { $parts = explode('.', $key); - if(is_array($parts) && $parts[0] == 'item') { + if (is_array($parts) && $parts[0] == 'item') { continue; } @@ -220,7 +220,7 @@ class InvoiceItemExport extends BaseExport $entity[$key] = $this->decorator->transform($key, $invoice); } } - + $entity = $this->decorateAdvancedFields($invoice, $entity); return $entity; } diff --git a/app/Export/CSV/PaymentExport.php b/app/Export/CSV/PaymentExport.php index 8f3bd06cd2..35b2037935 100644 --- a/app/Export/CSV/PaymentExport.php +++ b/app/Export/CSV/PaymentExport.php @@ -66,13 +66,13 @@ class PaymentExport extends BaseExport $clients = &$this->input['client_id']; - if($clients) { + if ($clients) { $query = $this->addClientFilter($query, $clients); } $query = $this->addPaymentStatusFilters($query, $this->input['status'] ?? ''); - if($this->input['document_email_attachment'] ?? false) { + if ($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } diff --git a/app/Export/CSV/ProductExport.php b/app/Export/CSV/ProductExport.php index 90f0b2999b..a5476194af 100644 --- a/app/Export/CSV/ProductExport.php +++ b/app/Export/CSV/ProductExport.php @@ -77,13 +77,13 @@ class ProductExport extends BaseExport ->withTrashed() ->where('company_id', $this->company->id); - if(!$this->input['include_deleted'] ?? false) { //@phpstan-ignore-line + if (!$this->input['include_deleted'] ?? false) { //@phpstan-ignore-line $query->where('is_deleted', 0); } $query = $this->addDateRange($query, 'products'); - if($this->input['document_email_attachment'] ?? false) { + if ($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } diff --git a/app/Export/CSV/ProductSalesExport.php b/app/Export/CSV/ProductSalesExport.php index 664db3b023..8ddc83238d 100644 --- a/app/Export/CSV/ProductSalesExport.php +++ b/app/Export/CSV/ProductSalesExport.php @@ -83,7 +83,7 @@ class ProductSalesExport extends BaseExport $keys = explode(",", $product_keys); $query->where(function ($q) use ($keys) { - foreach($keys as $key) { + foreach ($keys as $key) { $q->orWhereJsonContains('line_items', ['product_key' => $key]); } @@ -133,7 +133,7 @@ class ProductSalesExport extends BaseExport $product_keys = &$this->input['product_key']; - if($product_keys) { + if ($product_keys) { $product_keys = explode(",", $product_keys); } @@ -141,8 +141,8 @@ class ProductSalesExport extends BaseExport ->each(function ($invoice) use ($product_keys) { foreach ($invoice->line_items as $item) { - if($product_keys) { - if(in_array($item->product_key, $product_keys)) { + if ($product_keys) { + if (in_array($item->product_key, $product_keys)) { $this->csv->insertOne($this->convertFloats($this->buildRow($invoice, $item))); } } else { @@ -155,7 +155,7 @@ class ProductSalesExport extends BaseExport $grouped = $this->sales->groupBy('product_key')->map(function ($key, $value) use ($product_keys) { - if($product_keys && !in_array($value, $product_keys)) { + if ($product_keys && !in_array($value, $product_keys)) { return false; } @@ -219,15 +219,15 @@ class ProductSalesExport extends BaseExport if (array_key_exists($key, $transformed_entity)) { $entity[$keyval] = $transformed_entity[$key]; - } elseif($key == 'currency') { + } elseif ($key == 'currency') { $entity['currency'] = $invoice->client->currency()->code; } else { $entity[$keyval] = ''; } } - + $entity = $this->decorateAdvancedFields($invoice, $entity); - + $this->sales->push($entity); return $entity; diff --git a/app/Export/CSV/PurchaseOrderExport.php b/app/Export/CSV/PurchaseOrderExport.php index 2edb3d3042..5ef41c199f 100644 --- a/app/Export/CSV/PurchaseOrderExport.php +++ b/app/Export/CSV/PurchaseOrderExport.php @@ -63,7 +63,7 @@ class PurchaseOrderExport extends BaseExport }) ->where('company_id', $this->company->id); - if(!$this->input['include_deleted'] ?? false) { // @phpstan-ignore-line + if (!$this->input['include_deleted'] ?? false) { // @phpstan-ignore-line $query->where('is_deleted', 0); } @@ -72,13 +72,13 @@ class PurchaseOrderExport extends BaseExport $clients = &$this->input['client_id']; - if($clients) { + if ($clients) { $query = $this->addClientFilter($query, $clients); } $query = $this->addPurchaseOrderStatusFilter($query, $this->input['status'] ?? ''); - if($this->input['document_email_attachment'] ?? false) { + if ($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } @@ -151,9 +151,9 @@ class PurchaseOrderExport extends BaseExport } - + $entity = $this->decorateAdvancedFields($purchase_order, $entity); - + return $this->convertFloats($entity); } diff --git a/app/Export/CSV/PurchaseOrderItemExport.php b/app/Export/CSV/PurchaseOrderItemExport.php index 47e3d2e0c3..2bb11b62e9 100644 --- a/app/Export/CSV/PurchaseOrderItemExport.php +++ b/app/Export/CSV/PurchaseOrderItemExport.php @@ -67,7 +67,7 @@ class PurchaseOrderItemExport extends BaseExport }) ->with('vendor')->where('company_id', $this->company->id); - if(!$this->input['include_deleted'] ?? false) { + if (!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } @@ -75,13 +75,13 @@ class PurchaseOrderItemExport extends BaseExport $clients = &$this->input['client_id']; - if($clients) { + if ($clients) { $query = $this->addClientFilter($query, $clients); } $query = $this->addPurchaseOrderStatusFilter($query, $this->input['status'] ?? ''); - if($this->input['document_email_attachment'] ?? false) { + if ($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } @@ -105,7 +105,7 @@ class PurchaseOrderItemExport extends BaseExport /** @var \App\Models\PurchaseOrder $resource */ $this->iterateItems($resource); - foreach($this->storage_array as $row) { + foreach ($this->storage_array as $row) { $this->storage_item_array[] = $this->processItemMetaData($row, $resource); } @@ -155,11 +155,11 @@ class PurchaseOrderItemExport extends BaseExport $tmp_key = str_replace("item.", "", $key); - if($tmp_key == 'type_id') { + if ($tmp_key == 'type_id') { $tmp_key = 'type'; } - if($tmp_key == 'tax_id') { + if ($tmp_key == 'tax_id') { $tmp_key = 'tax_category'; } @@ -174,10 +174,10 @@ class PurchaseOrderItemExport extends BaseExport $transformed_items = array_merge($transformed_purchase_order, $item_array); $entity = $this->decorateAdvancedFields($purchase_order, $transformed_items); $entity = array_merge(array_flip(array_values($this->input['report_keys'])), $entity); - + $this->storage_array[] = $this->convertFloats($entity); } - + } private function buildRow(PurchaseOrder $purchase_order): array @@ -189,7 +189,7 @@ class PurchaseOrderItemExport extends BaseExport foreach (array_values($this->input['report_keys']) as $key) { $parts = explode('.', $key); - if(is_array($parts) && $parts[0] == 'item') { + if (is_array($parts) && $parts[0] == 'item') { continue; } @@ -210,7 +210,7 @@ class PurchaseOrderItemExport extends BaseExport private function decorateAdvancedFields(PurchaseOrder $purchase_order, array $entity): array { - + if (in_array('purchase_order.currency_id', $this->input['report_keys'])) { $entity['purchase_order.currency_id'] = $purchase_order->vendor->currency() ? $purchase_order->vendor->currency()->code : $purchase_order->company->currency()->code; } diff --git a/app/Export/CSV/QuoteExport.php b/app/Export/CSV/QuoteExport.php index 168ed87e0b..93e9bd8678 100644 --- a/app/Export/CSV/QuoteExport.php +++ b/app/Export/CSV/QuoteExport.php @@ -63,7 +63,7 @@ class QuoteExport extends BaseExport }) ->where('company_id', $this->company->id); - if(!$this->input['include_deleted'] ?? false) { + if (!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } @@ -71,13 +71,13 @@ class QuoteExport extends BaseExport $clients = &$this->input['client_id']; - if($clients) { + if ($clients) { $query = $this->addClientFilter($query, $clients); } $query = $this->addQuoteStatusFilter($query, $this->input['status'] ?? ''); - if($this->input['document_email_attachment'] ?? false) { + if ($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } @@ -150,10 +150,10 @@ class QuoteExport extends BaseExport } } - + $entity = $this->decorateAdvancedFields($quote, $entity); return $this->convertFloats($entity); - + } diff --git a/app/Export/CSV/QuoteItemExport.php b/app/Export/CSV/QuoteItemExport.php index 3926f82975..3bfd7a1d06 100644 --- a/app/Export/CSV/QuoteItemExport.php +++ b/app/Export/CSV/QuoteItemExport.php @@ -70,7 +70,7 @@ class QuoteItemExport extends BaseExport }) ->with('client')->where('company_id', $this->company->id); - if(!$this->input['include_deleted'] ?? false) { + if (!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } @@ -78,13 +78,13 @@ class QuoteItemExport extends BaseExport $clients = &$this->input['client_id']; - if($clients) { + if ($clients) { $query = $this->addClientFilter($query, $clients); } $query = $this->addQuoteStatusFilter($query, $this->input['status'] ?? ''); - if($this->input['document_email_attachment'] ?? false) { + if ($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } @@ -108,7 +108,7 @@ class QuoteItemExport extends BaseExport /** @var \App\Models\Quote $resource */ $this->iterateItems($resource); - foreach($this->storage_array as $row) { + foreach ($this->storage_array as $row) { $this->storage_item_array[] = $this->processItemMetaData($row, $resource); } @@ -163,11 +163,11 @@ class QuoteItemExport extends BaseExport $tmp_key = str_replace("item.", "", $key); - if($tmp_key == 'type_id') { + if ($tmp_key == 'type_id') { $tmp_key = 'type'; } - if($tmp_key == 'tax_id') { + if ($tmp_key == 'tax_id') { $tmp_key = 'tax_category'; } @@ -181,7 +181,7 @@ class QuoteItemExport extends BaseExport $transformed_items = array_merge($transformed_quote, $item_array); $entity = $this->decorateAdvancedFields($quote, $transformed_items); - $entity = array_merge(array_flip(array_values($this->input['report_keys'])), $entity); + $entity = array_merge(array_flip(array_values($this->input['report_keys'])), $entity); $entity = $this->convertFloats($entity); $this->storage_array[] = $entity; @@ -198,7 +198,7 @@ class QuoteItemExport extends BaseExport $parts = explode('.', $key); - if(is_array($parts) && $parts[0] == 'item') { + if (is_array($parts) && $parts[0] == 'item') { continue; } @@ -213,7 +213,7 @@ class QuoteItemExport extends BaseExport $entity = $this->decorateAdvancedFields($quote, $entity); return $entity; - + } private function decorateAdvancedFields(Quote $quote, array $entity): array { diff --git a/app/Export/CSV/RecurringInvoiceExport.php b/app/Export/CSV/RecurringInvoiceExport.php index 7d228dcdc3..7a7caada76 100644 --- a/app/Export/CSV/RecurringInvoiceExport.php +++ b/app/Export/CSV/RecurringInvoiceExport.php @@ -61,7 +61,7 @@ class RecurringInvoiceExport extends BaseExport }) ->where('company_id', $this->company->id); - if(!$this->input['include_deleted'] ?? false) { + if (!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } @@ -69,7 +69,7 @@ class RecurringInvoiceExport extends BaseExport $clients = &$this->input['client_id']; - if($clients) { + if ($clients) { $query = $this->addClientFilter($query, $clients); } @@ -137,14 +137,15 @@ class RecurringInvoiceExport extends BaseExport if (is_array($parts) && $parts[0] == 'recurring_invoice' && array_key_exists($parts[1], $transformed_invoice)) { $entity[$key] = $transformed_invoice[$parts[1]]; - } elseif($parts[0] == 'item') { + } elseif ($parts[0] == 'item') { $entity[$key] = ''; } else { $entity[$key] = $this->decorator->transform($key, $invoice); } - if (is_float($entity[$key])) + if (is_float($entity[$key])) { $entity[$key] = \App\Utils\Number::formatValue($entity[$key], $currency); + } } diff --git a/app/Export/CSV/TaskExport.php b/app/Export/CSV/TaskExport.php index 18efab12e8..4c3e09d31b 100644 --- a/app/Export/CSV/TaskExport.php +++ b/app/Export/CSV/TaskExport.php @@ -69,7 +69,7 @@ class TaskExport extends BaseExport ->withTrashed() ->where('company_id', $this->company->id); - if(!$this->input['include_deleted'] ?? false) { + if (!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } @@ -77,13 +77,13 @@ class TaskExport extends BaseExport $clients = &$this->input['client_id']; - if($clients) { + if ($clients) { $query = $this->addClientFilter($query, $clients); } $document_attachments = &$this->input['document_email_attachment']; - if($document_attachments) { + if ($document_attachments) { $this->queueDocuments($query); } @@ -132,7 +132,7 @@ class TaskExport extends BaseExport /** @var \App\Models\Task $resource*/ $this->buildRow($resource); - foreach($this->storage_array as $row) { + foreach ($this->storage_array as $row) { $this->storage_item_array[] = $this->processMetaData($row, $resource); } @@ -233,7 +233,7 @@ class TaskExport extends BaseExport $entity['task.item_notes'] = isset($item[2]) ? (string)$item[2] : ''; } - + $this->storage_array[] = $entity; $entity['task.start_date'] = ''; diff --git a/app/Export/CSV/VendorExport.php b/app/Export/CSV/VendorExport.php index c6f0d32c5a..0f5bc10cb1 100644 --- a/app/Export/CSV/VendorExport.php +++ b/app/Export/CSV/VendorExport.php @@ -64,13 +64,13 @@ class VendorExport extends BaseExport ->withTrashed() ->where('company_id', $this->company->id); - if(!$this->input['include_deleted'] ?? false) { + if (!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } $query = $this->addDateRange($query, 'vendors'); - if($this->input['document_email_attachment'] ?? false) { + if ($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } diff --git a/app/Export/Decorators/ClientDecorator.php b/app/Export/Decorators/ClientDecorator.php index e78ccb1896..52a63e2e24 100644 --- a/app/Export/Decorators/ClientDecorator.php +++ b/app/Export/Decorators/ClientDecorator.php @@ -21,15 +21,15 @@ class ClientDecorator extends Decorator implements DecoratorInterface { $client = false; - if($entity instanceof Client) { + if ($entity instanceof Client) { $client = $entity; - } elseif($entity->client) { + } elseif ($entity->client) { $client = $entity->client; } - if($client && method_exists($this, $key)) { + if ($client && method_exists($this, $key)) { return $this->{$key}($client); - } elseif($client && ($client->{$key} ?? false)) { + } elseif ($client && ($client->{$key} ?? false)) { return $client->{$key}; } diff --git a/app/Export/Decorators/ContactDecorator.php b/app/Export/Decorators/ContactDecorator.php index b6fa3edc72..ef7fafa3d6 100644 --- a/app/Export/Decorators/ContactDecorator.php +++ b/app/Export/Decorators/ContactDecorator.php @@ -19,20 +19,20 @@ class ContactDecorator implements DecoratorInterface { $contact = false; - if($entity instanceof ClientContact) { + if ($entity instanceof ClientContact) { $contact = $entity; - } elseif($entity->contacts) { + } elseif ($entity->contacts) { $contact = $entity->contacts()->first(); - } elseif($entity->client) { + } elseif ($entity->client) { $contact = $entity->client->primary_contact->first() ?? $entity->client->contacts()->whereNotNull('email')->first(); - } elseif($entity->vendor) { + } elseif ($entity->vendor) { $contact = $entity->vendor->primary_contact->first() ?? $entity->vendor->contacts()->whereNotNull('email')->first(); } - if($contact && method_exists($this, $key)) { + if ($contact && method_exists($this, $key)) { return $this->{$key}($contact); - } elseif($contact && ($contact->{$key} ?? false)) { + } elseif ($contact && ($contact->{$key} ?? false)) { return $contact->{$key}; } diff --git a/app/Export/Decorators/CreditDecorator.php b/app/Export/Decorators/CreditDecorator.php index 5752752448..93a7d92d38 100644 --- a/app/Export/Decorators/CreditDecorator.php +++ b/app/Export/Decorators/CreditDecorator.php @@ -19,15 +19,15 @@ class CreditDecorator implements DecoratorInterface { $credit = false; - if($entity instanceof Credit) { + if ($entity instanceof Credit) { $credit = $entity; - } elseif($entity->credit) { + } elseif ($entity->credit) { $credit = $entity->credit; } - if($credit && method_exists($this, $key)) { + if ($credit && method_exists($this, $key)) { return $this->{$key}($credit); - } elseif($credit && ($credit->{$key} ?? false)) { + } elseif ($credit && ($credit->{$key} ?? false)) { return $credit->{$key}; } diff --git a/app/Export/Decorators/ExpenseDecorator.php b/app/Export/Decorators/ExpenseDecorator.php index 0133a5a702..4ea936860e 100644 --- a/app/Export/Decorators/ExpenseDecorator.php +++ b/app/Export/Decorators/ExpenseDecorator.php @@ -19,15 +19,15 @@ class ExpenseDecorator implements DecoratorInterface { $expense = false; - if($entity instanceof Expense) { + if ($entity instanceof Expense) { $expense = $entity; - } elseif($entity->expense) { + } elseif ($entity->expense) { $expense = $entity->expense; } - if($expense && method_exists($this, $key)) { + if ($expense && method_exists($this, $key)) { return $this->{$key}($expense); - } elseif($expense && ($expense->{$key} ?? false)) { + } elseif ($expense && ($expense->{$key} ?? false)) { return $expense->{$key}; } diff --git a/app/Export/Decorators/InvoiceDecorator.php b/app/Export/Decorators/InvoiceDecorator.php index b6579b7f54..f93dcd1767 100644 --- a/app/Export/Decorators/InvoiceDecorator.php +++ b/app/Export/Decorators/InvoiceDecorator.php @@ -19,17 +19,17 @@ class InvoiceDecorator extends Decorator implements DecoratorInterface { $invoice = false; - if($entity instanceof Invoice) { + if ($entity instanceof Invoice) { $invoice = $entity; - } elseif($entity->invoice) { + } elseif ($entity->invoice) { $invoice = $entity->invoice; - } elseif(method_exists($entity, 'invoices') && $entity->invoices()->exists()) { + } elseif (method_exists($entity, 'invoices') && $entity->invoices()->exists()) { $invoice = $entity->invoices()->first(); } - if($invoice && method_exists($this, $key)) { + if ($invoice && method_exists($this, $key)) { return $this->{$key}($invoice); - } elseif($invoice && ($invoice->{$key} ?? false)) { + } elseif ($invoice && ($invoice->{$key} ?? false)) { return $invoice->{$key}; } diff --git a/app/Export/Decorators/PaymentDecorator.php b/app/Export/Decorators/PaymentDecorator.php index 4b36fbedfd..e521e88a78 100644 --- a/app/Export/Decorators/PaymentDecorator.php +++ b/app/Export/Decorators/PaymentDecorator.php @@ -21,27 +21,27 @@ class PaymentDecorator extends Decorator implements DecoratorInterface { $payment = false; - if($entity instanceof Payment) { + if ($entity instanceof Payment) { $payment = $entity; - } elseif($entity->payment) { + } elseif ($entity->payment) { $payment = $entity->payment; - } elseif($entity->payments()->exists()) { + } elseif ($entity->payments()->exists()) { $payment = $entity->payments()->first(); } - if($key == 'amount' && (!$entity instanceof Payment)) { + if ($key == 'amount' && (!$entity instanceof Payment)) { return $entity->payments()->exists() ? $entity->payments()->withoutTrashed()->sum('paymentables.amount') : ctrans('texts.unpaid'); - } elseif($key == 'refunded' && (!$entity instanceof Payment)) { + } elseif ($key == 'refunded' && (!$entity instanceof Payment)) { return $entity->payments()->exists() ? $entity->payments()->withoutTrashed()->sum('paymentables.refunded') : ''; - } elseif($key == 'applied' && (!$entity instanceof Payment)) { + } elseif ($key == 'applied' && (!$entity instanceof Payment)) { $refunded = $entity->payments()->withoutTrashed()->sum('paymentables.refunded'); $amount = $entity->payments()->withoutTrashed()->sum('paymentables.amount'); return $entity->payments()->withoutTrashed()->exists() ? ($amount - $refunded) : ''; } - if($payment && method_exists($this, $key)) { + if ($payment && method_exists($this, $key)) { return $this->{$key}($payment); - } elseif($payment && ($payment->{$key} ?? false)) { + } elseif ($payment && ($payment->{$key} ?? false)) { return $payment->{$key}; } diff --git a/app/Export/Decorators/ProductDecorator.php b/app/Export/Decorators/ProductDecorator.php index 2e3f5b1abc..90e26c137d 100644 --- a/app/Export/Decorators/ProductDecorator.php +++ b/app/Export/Decorators/ProductDecorator.php @@ -19,15 +19,15 @@ class ProductDecorator implements DecoratorInterface { $product = false; - if($entity instanceof Product) { + if ($entity instanceof Product) { $product = $entity; - } elseif($entity->product) { + } elseif ($entity->product) { $product = $entity->product; } - if($product && method_exists($this, $key)) { + if ($product && method_exists($this, $key)) { return $this->{$key}($product); - } elseif($product->{$key} ?? false) { + } elseif ($product->{$key} ?? false) { return $product->{$key} ?? ''; } diff --git a/app/Export/Decorators/PurchaseOrderDecorator.php b/app/Export/Decorators/PurchaseOrderDecorator.php index 0dd9f14f24..ca5cee1796 100644 --- a/app/Export/Decorators/PurchaseOrderDecorator.php +++ b/app/Export/Decorators/PurchaseOrderDecorator.php @@ -19,15 +19,15 @@ class PurchaseOrderDecorator extends Decorator implements DecoratorInterface { $purchase_order = false; - if($entity instanceof PurchaseOrder) { + if ($entity instanceof PurchaseOrder) { $purchase_order = $entity; - } elseif($entity->purchase_order) { + } elseif ($entity->purchase_order) { $purchase_order = $entity->purchase_order; } - if($purchase_order && method_exists($this, $key)) { + if ($purchase_order && method_exists($this, $key)) { return $this->{$key}($purchase_order); - } elseif($purchase_order->{$key} ?? false) { + } elseif ($purchase_order->{$key} ?? false) { return $purchase_order->{$key} ?? ''; } diff --git a/app/Export/Decorators/QuoteDecorator.php b/app/Export/Decorators/QuoteDecorator.php index 2e33cdf464..02bf4e3c36 100644 --- a/app/Export/Decorators/QuoteDecorator.php +++ b/app/Export/Decorators/QuoteDecorator.php @@ -19,15 +19,15 @@ class QuoteDecorator extends Decorator implements DecoratorInterface { $quote = false; - if($entity instanceof Quote) { + if ($entity instanceof Quote) { $quote = $entity; - } elseif($entity->quote) { + } elseif ($entity->quote) { $quote = $entity->quote; } - if($quote && method_exists($this, $key)) { + if ($quote && method_exists($this, $key)) { return $this->{$key}($quote); - } elseif($quote->{$key} ?? false) { + } elseif ($quote->{$key} ?? false) { return $quote->{$key} ?? ''; } diff --git a/app/Export/Decorators/RecurringInvoiceDecorator.php b/app/Export/Decorators/RecurringInvoiceDecorator.php index 486c9e5d9c..3a9e02d554 100644 --- a/app/Export/Decorators/RecurringInvoiceDecorator.php +++ b/app/Export/Decorators/RecurringInvoiceDecorator.php @@ -19,15 +19,15 @@ class RecurringInvoiceDecorator extends Decorator implements DecoratorInterface { $recurring_invoice = false; - if($entity instanceof RecurringInvoice) { + if ($entity instanceof RecurringInvoice) { $recurring_invoice = $entity; - } elseif($entity->recurring_invoice) { + } elseif ($entity->recurring_invoice) { $recurring_invoice = $entity->recurring_invoice; } - if($recurring_invoice && method_exists($this, $key)) { + if ($recurring_invoice && method_exists($this, $key)) { return $this->{$key}($recurring_invoice); - } elseif($recurring_invoice->{$key} ?? false) { + } elseif ($recurring_invoice->{$key} ?? false) { return $recurring_invoice->{$key} ?? ''; } diff --git a/app/Export/Decorators/TaskDecorator.php b/app/Export/Decorators/TaskDecorator.php index 7cf811f468..88f9a5b741 100644 --- a/app/Export/Decorators/TaskDecorator.php +++ b/app/Export/Decorators/TaskDecorator.php @@ -22,15 +22,15 @@ class TaskDecorator extends Decorator implements DecoratorInterface public function transform(string $key, mixed $entity): mixed { $task = false; - if($entity instanceof Task) { + if ($entity instanceof Task) { $task = $entity; - } elseif($entity->task) { + } elseif ($entity->task) { $task = $entity->task; } - if($task && method_exists($this, $key)) { + if ($task && method_exists($this, $key)) { return $this->{$key}($task); - } elseif($task && $task->{$key} ?? false) { + } elseif ($task && $task->{$key} ?? false) { return $task->{$key}; } @@ -58,7 +58,7 @@ class TaskDecorator extends Decorator implements DecoratorInterface $date_format_default = $date_format->format; } - if(is_array($logs)) { + if (is_array($logs)) { $item = $logs[0]; return Carbon::createFromTimeStamp((int)$item[0])->setTimezone($timezone_name)->format($date_format_default); } @@ -87,7 +87,7 @@ class TaskDecorator extends Decorator implements DecoratorInterface $date_format_default = $date_format->format; } - if(is_array($logs)) { + if (is_array($logs)) { $item = $logs[1]; return Carbon::createFromTimeStamp((int)$item[1])->setTimezone($timezone_name)->format($date_format_default); } diff --git a/app/Export/Decorators/VendorContactDecorator.php b/app/Export/Decorators/VendorContactDecorator.php index ad5526bc33..28d3133186 100644 --- a/app/Export/Decorators/VendorContactDecorator.php +++ b/app/Export/Decorators/VendorContactDecorator.php @@ -19,15 +19,15 @@ class VendorContactDecorator implements DecoratorInterface { $contact = false; - if($entity instanceof VendorContact) { + if ($entity instanceof VendorContact) { $contact = $entity; - } elseif($entity->contacts) { + } elseif ($entity->contacts) { $contact = $entity->contacts()->first(); } - if($contact && method_exists($this, $key)) { + if ($contact && method_exists($this, $key)) { return $this->{$key}($contact); - } elseif($contact && ($contact->{$key} ?? false)) { + } elseif ($contact && ($contact->{$key} ?? false)) { return $contact->{$key} ?? ''; } diff --git a/app/Export/Decorators/VendorDecorator.php b/app/Export/Decorators/VendorDecorator.php index 5f3c8f8b55..61ebc34982 100644 --- a/app/Export/Decorators/VendorDecorator.php +++ b/app/Export/Decorators/VendorDecorator.php @@ -19,15 +19,15 @@ class VendorDecorator extends Decorator implements DecoratorInterface { $vendor = false; - if($entity instanceof Vendor) { + if ($entity instanceof Vendor) { $vendor = $entity; - } elseif($entity->vendor) { + } elseif ($entity->vendor) { $vendor = $entity->vendor; } - if($vendor && method_exists($this, $key)) { + if ($vendor && method_exists($this, $key)) { return $this->{$key}($vendor); - } elseif($vendor->{$key} ?? false) { + } elseif ($vendor->{$key} ?? false) { return $vendor->{$key} ?? ''; } diff --git a/app/Factory/InvoiceItemFactory.php b/app/Factory/InvoiceItemFactory.php index 83b0294f9d..6bc15b39ef 100644 --- a/app/Factory/InvoiceItemFactory.php +++ b/app/Factory/InvoiceItemFactory.php @@ -78,23 +78,23 @@ class InvoiceItemFactory } - $item = self::create(); - $item->quantity = rand(1, 10); - $item->cost = $faker->randomFloat(2, 1, 1000); - $item->line_total = $item->quantity * $item->cost; - $item->is_amount_discount = true; - $item->discount = rand(1, 10); - $item->notes = str_replace(['"',"'"], ['',""], $faker->realText(20)); - $item->product_key = $faker->word(); - // $item->custom_value1 = $faker->realText(10); - // $item->custom_value2 = $faker->realText(10); - // $item->custom_value3 = $faker->realText(10); - // $item->custom_value4 = $faker->realText(10); - $item->tax_name1 = 'GST'; - $item->tax_rate1 = 10.00; - $item->type_id = '2'; + $item = self::create(); + $item->quantity = rand(1, 10); + $item->cost = $faker->randomFloat(2, 1, 1000); + $item->line_total = $item->quantity * $item->cost; + $item->is_amount_discount = true; + $item->discount = rand(1, 10); + $item->notes = str_replace(['"',"'"], ['',""], $faker->realText(20)); + $item->product_key = $faker->word(); + // $item->custom_value1 = $faker->realText(10); + // $item->custom_value2 = $faker->realText(10); + // $item->custom_value3 = $faker->realText(10); + // $item->custom_value4 = $faker->realText(10); + $item->tax_name1 = 'GST'; + $item->tax_rate1 = 10.00; + $item->type_id = '2'; - $data[] = $item; + $data[] = $item; return $data; diff --git a/app/Filters/BankTransactionFilters.php b/app/Filters/BankTransactionFilters.php index 1e05a6d037..f7a14c4efc 100644 --- a/app/Filters/BankTransactionFilters.php +++ b/app/Filters/BankTransactionFilters.php @@ -122,7 +122,7 @@ class BankTransactionFilters extends QueryFilters return $this->builder; } - return $this->builder->whereHas('bank_integration', function ($query){ + return $this->builder->whereHas('bank_integration', function ($query) { $query->where('is_deleted', 0)->whereNull('deleted_at'); }); } @@ -135,7 +135,7 @@ class BankTransactionFilters extends QueryFilters */ public function bank_integration_ids(string $ids = ''): Builder { - if(strlen($ids) == 0) { + if (strlen($ids) == 0) { return $this->builder; } diff --git a/app/Filters/ClientFilters.php b/app/Filters/ClientFilters.php index df9a2cb860..3f6b08f3f1 100644 --- a/app/Filters/ClientFilters.php +++ b/app/Filters/ClientFilters.php @@ -124,7 +124,7 @@ class ClientFilters extends QueryFilters */ public function filter(string $filter = ''): Builder { - + if (strlen($filter) == 0) { return $this->builder; } @@ -168,7 +168,7 @@ class ClientFilters extends QueryFilters return $this->builder; } - if($sort_col[0] == 'documents') { + if ($sort_col[0] == 'documents') { return $this->builder; } @@ -178,7 +178,7 @@ class ClientFilters extends QueryFilters $dir = ($sort_col[1] == 'asc') ? 'asc' : 'desc'; - if($sort_col[0] == 'number') { + if ($sort_col[0] == 'number') { return $this->builder->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . $dir); } diff --git a/app/Filters/CreditFilters.php b/app/Filters/CreditFilters.php index 81d3c2dec0..1cb23df4ac 100644 --- a/app/Filters/CreditFilters.php +++ b/app/Filters/CreditFilters.php @@ -155,7 +155,7 @@ class CreditFilters extends QueryFilters } - if($sort_col[0] == 'number') { + if ($sort_col[0] == 'number') { return $this->builder->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . $dir); } diff --git a/app/Filters/DesignFilters.php b/app/Filters/DesignFilters.php index f914bcc4ba..530084ac11 100644 --- a/app/Filters/DesignFilters.php +++ b/app/Filters/DesignFilters.php @@ -59,7 +59,7 @@ class DesignFilters extends QueryFilters public function entities(string $entities = ''): Builder { - if(stripos($entities, 'statement') !== false) { + if (stripos($entities, 'statement') !== false) { $entities = 'client'; } diff --git a/app/Filters/ExpenseFilters.php b/app/Filters/ExpenseFilters.php index d181cc9e91..a558ad934c 100644 --- a/app/Filters/ExpenseFilters.php +++ b/app/Filters/ExpenseFilters.php @@ -117,7 +117,7 @@ class ExpenseFilters extends QueryFilters }); } - if(in_array('uncategorized', $status_parameters)) { + if (in_array('uncategorized', $status_parameters)) { $query->orWhere(function ($query) { $query->whereNull('category_id'); }); @@ -168,7 +168,7 @@ class ExpenseFilters extends QueryFilters { $categories_exploded = explode(",", $categories); - if(empty($categories) || count(array_filter($categories_exploded)) == 0) { + if (empty($categories) || count(array_filter($categories_exploded)) == 0) { return $this->builder; } @@ -238,7 +238,7 @@ class ExpenseFilters extends QueryFilters ->orderByRaw('ISNULL(payment_date), payment_date '. $sort_col[1]); } - if($sort_col[0] == 'number') { + if ($sort_col[0] == 'number') { return $this->builder->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . $dir); } diff --git a/app/Filters/InvoiceFilters.php b/app/Filters/InvoiceFilters.php index 5c2d83be66..89df79b39f 100644 --- a/app/Filters/InvoiceFilters.php +++ b/app/Filters/InvoiceFilters.php @@ -238,7 +238,7 @@ class InvoiceFilters extends QueryFilters try { $date = Carbon::parse($date); - } catch(\Exception $e) { + } catch (\Exception $e) { return $this->builder; } } @@ -289,7 +289,7 @@ class InvoiceFilters extends QueryFilters } - if($sort_col[0] == 'number') { + if ($sort_col[0] == 'number') { return $this->builder->orderByRaw("REGEXP_REPLACE(invoices.number,'[^0-9]+','')+0 " . $dir); } diff --git a/app/Filters/PaymentFilters.php b/app/Filters/PaymentFilters.php index 7927daf089..da5ba9eec4 100644 --- a/app/Filters/PaymentFilters.php +++ b/app/Filters/PaymentFilters.php @@ -113,7 +113,7 @@ class PaymentFilters extends QueryFilters $query->whereIn('status_id', $payment_filters); } - if(in_array('partially_unapplied', $status_parameters)) { + if (in_array('partially_unapplied', $status_parameters)) { $query->whereColumn('amount', '>', 'applied')->where('refunded', 0); } }); @@ -175,7 +175,7 @@ class PaymentFilters extends QueryFilters ->whereColumn('clients.id', 'payments.client_id'), $dir); } - if($sort_col[0] == 'number') { + if ($sort_col[0] == 'number') { return $this->builder->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . $dir); } @@ -190,7 +190,7 @@ class PaymentFilters extends QueryFilters return $this->builder; } - if(!in_array($parts[0], ['date'])) { + if (!in_array($parts[0], ['date'])) { return $this->builder; } @@ -200,7 +200,7 @@ class PaymentFilters extends QueryFilters $end_date = Carbon::parse($parts[2]); return $this->builder->whereBetween($parts[0], [$start_date, $end_date]); - } catch(\Exception $e) { + } catch (\Exception $e) { return $this->builder; } diff --git a/app/Filters/ProjectFilters.php b/app/Filters/ProjectFilters.php index 8b848472bd..5379b70855 100644 --- a/app/Filters/ProjectFilters.php +++ b/app/Filters/ProjectFilters.php @@ -71,7 +71,7 @@ class ProjectFilters extends QueryFilters ->whereColumn('clients.id', 'projects.client_id'), $dir); } - if($sort_col[0] == 'number') { + if ($sort_col[0] == 'number') { return $this->builder->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . $dir); } diff --git a/app/Filters/PurchaseOrderFilters.php b/app/Filters/PurchaseOrderFilters.php index 82fe3f8aa9..e03bfb7200 100644 --- a/app/Filters/PurchaseOrderFilters.php +++ b/app/Filters/PurchaseOrderFilters.php @@ -137,7 +137,7 @@ class PurchaseOrderFilters extends QueryFilters ->whereColumn('vendors.id', 'purchase_orders.vendor_id'), $dir); } - if($sort_col[0] == 'number') { + if ($sort_col[0] == 'number') { return $this->builder->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . $dir); } diff --git a/app/Filters/QueryFilters.php b/app/Filters/QueryFilters.php index de3559937b..06ee7f542d 100644 --- a/app/Filters/QueryFilters.php +++ b/app/Filters/QueryFilters.php @@ -215,7 +215,7 @@ abstract class QueryFilters } return $this->builder->where('created_at', '>=', $created_at); - } catch(\Exception $e) { + } catch (\Exception $e) { return $this->builder; } } @@ -322,7 +322,7 @@ abstract class QueryFilters return $this->builder; } - if($this->with_property == 'id') { + if ($this->with_property == 'id') { $value = $this->decodePrimaryKey($value); } @@ -353,7 +353,7 @@ abstract class QueryFilters $end_date = Carbon::parse($parts[1]); return $this->builder->whereBetween('date', [$start_date, $end_date]); - } catch(\Exception $e) { + } catch (\Exception $e) { return $this->builder; } @@ -380,7 +380,7 @@ abstract class QueryFilters $end_date = Carbon::parse($parts[1]); return $this->builder->whereBetween('due_date', [$start_date, $end_date]); - } catch(\Exception $e) { + } catch (\Exception $e) { return $this->builder; } diff --git a/app/Filters/QuoteFilters.php b/app/Filters/QuoteFilters.php index 5e9776c9a0..6724304ec3 100644 --- a/app/Filters/QuoteFilters.php +++ b/app/Filters/QuoteFilters.php @@ -121,7 +121,7 @@ class QuoteFilters extends QueryFilters }); } - if(in_array('converted', $status_parameters)) { + if (in_array('converted', $status_parameters)) { $query->orWhere(function ($q) { $q->whereNotNull('invoice_id'); }); @@ -156,14 +156,14 @@ class QuoteFilters extends QueryFilters $dir = ($sort_col[1] == 'asc') ? 'asc' : 'desc'; - if($sort_col[0] == 'client_id') { + if ($sort_col[0] == 'client_id') { return $this->builder->orderBy(\App\Models\Client::select('name') ->whereColumn('clients.id', 'quotes.client_id'), $dir); } - if($sort_col[0] == 'number') { + if ($sort_col[0] == 'number') { return $this->builder->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . $dir); } diff --git a/app/Filters/RecurringExpenseFilters.php b/app/Filters/RecurringExpenseFilters.php index cfd8258d6a..5172159e81 100644 --- a/app/Filters/RecurringExpenseFilters.php +++ b/app/Filters/RecurringExpenseFilters.php @@ -164,7 +164,7 @@ class RecurringExpenseFilters extends QueryFilters ->whereColumn('expense_categories.id', 'recurring_expenses.category_id'), $sort_col[1]); } - if($sort_col[0] == 'number') { + if ($sort_col[0] == 'number') { return $this->builder->orderByRaw('ABS(number) ' . $dir); } diff --git a/app/Filters/RecurringInvoiceFilters.php b/app/Filters/RecurringInvoiceFilters.php index b2f5a8cbce..f63755a2bf 100644 --- a/app/Filters/RecurringInvoiceFilters.php +++ b/app/Filters/RecurringInvoiceFilters.php @@ -137,15 +137,15 @@ class RecurringInvoiceFilters extends QueryFilters ->whereColumn('clients.id', 'recurring_invoices.client_id'), $dir); } - if($sort_col[0] == 'number') { + if ($sort_col[0] == 'number') { return $this->builder->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . $dir); } - if($sort_col[0] == 'status_id') { + if ($sort_col[0] == 'status_id') { return $this->builder->orderBy('status_id', $dir)->orderBy('last_sent_date', $dir); } - if($sort_col[0] == 'next_send_datetime') { + if ($sort_col[0] == 'next_send_datetime') { $sort_col[0] = 'next_send_date'; } diff --git a/app/Filters/TaskFilters.php b/app/Filters/TaskFilters.php index c179bb44ab..5e76075ec2 100644 --- a/app/Filters/TaskFilters.php +++ b/app/Filters/TaskFilters.php @@ -146,7 +146,7 @@ class TaskFilters extends QueryFilters ->whereColumn('users.id', 'tasks.user_id'), $dir); } - if($sort_col[0] == 'number') { + if ($sort_col[0] == 'number') { return $this->builder->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . $dir); } @@ -182,7 +182,7 @@ class TaskFilters extends QueryFilters /** @var array $status_parameters */ $status_parameters = explode(',', $value); - if(count($status_parameters) >= 1) { + if (count($status_parameters) >= 1) { $this->builder->where(function ($query) use ($status_parameters) { $query->whereIn('status_id', $this->transformKeys($status_parameters))->whereNull('invoice_id'); diff --git a/app/Filters/VendorFilters.php b/app/Filters/VendorFilters.php index 07d960e796..9d97c000be 100644 --- a/app/Filters/VendorFilters.php +++ b/app/Filters/VendorFilters.php @@ -71,7 +71,7 @@ class VendorFilters extends QueryFilters $dir = ($sort_col[1] == 'asc') ? 'asc' : 'desc'; - if($sort_col[0] == 'number') { + if ($sort_col[0] == 'number') { return $this->builder->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . $dir); } diff --git a/app/Helpers/Bank/Nordigen/Nordigen.php b/app/Helpers/Bank/Nordigen/Nordigen.php index 155c6f4ed7..fc04246b38 100644 --- a/app/Helpers/Bank/Nordigen/Nordigen.php +++ b/app/Helpers/Bank/Nordigen/Nordigen.php @@ -97,17 +97,15 @@ class Nordigen $it = new AccountTransformer(); return $it->transform($out); - } - catch (\GuzzleHttp\Exception\ClientException $e) { + } catch (\GuzzleHttp\Exception\ClientException $e) { $response = $e->getResponse(); $statusCode = $response->getStatusCode(); - + if ($statusCode === 429) { nlog("Nordigen Rate Limit hit for account {$account_id}"); return ['error' => 'Nordigen Institution Rate Limit Reached']; } - } - catch (\Exception $e) { + } catch (\Exception $e) { nlog("Nordigen getAccount() failed => {$account_id} => " . $e->getMessage()); return ['error' => $e->getMessage()]; @@ -133,7 +131,7 @@ class Nordigen return true; } catch (\Exception $e) { - + nlog("Nordigen:: AccountActiveStatus:: {$e->getMessage()} {$e->getCode()}"); if (strpos($e->getMessage(), "Invalid Account ID") !== false) { @@ -164,7 +162,7 @@ class Nordigen { $cache_key = "email_quota:{$bank_integration->company->company_key}:{$bank_integration->id}"; - if(Cache::has($cache_key)) { + if (Cache::has($cache_key)) { return; } diff --git a/app/Helpers/Bank/Yodlee/Transformer/AccountTransformer.php b/app/Helpers/Bank/Yodlee/Transformer/AccountTransformer.php index f2521fbe19..14f259b45f 100644 --- a/app/Helpers/Bank/Yodlee/Transformer/AccountTransformer.php +++ b/app/Helpers/Bank/Yodlee/Transformer/AccountTransformer.php @@ -84,17 +84,17 @@ class AccountTransformer implements AccountTransformerInterface $current_balance = 0; $account_currency = ''; - if(property_exists($account, 'currentBalance')) { + if (property_exists($account, 'currentBalance')) { $current_balance = $account->currentBalance->amount ?? 0; $account_currency = $account->currentBalance->currency ?? ''; - } elseif(property_exists($account, 'balance')) { + } elseif (property_exists($account, 'balance')) { $current_balance = $account->balance->amount ?? 0; $account_currency = $account->balance->currency ?? ''; } $account_status = $account->accountStatus; - if(property_exists($account, 'dataset')) { + if (property_exists($account, 'dataset')) { $dataset = $account->dataset[0]; $status = false; $update = false; @@ -114,7 +114,7 @@ class AccountTransformer implements AccountTransformerInterface default => $status = false }; - if($status) { + if ($status) { $account_status = $status; } @@ -125,9 +125,9 @@ class AccountTransformer implements AccountTransformerInterface default => $update = false, }; - if($status && $update) { + if ($status && $update) { $account_status = $status . ' - ' . $update; - } elseif($update) { + } elseif ($update) { $account_status = $update; } diff --git a/app/Helpers/Bank/Yodlee/Transformer/IncomeTransformer.php b/app/Helpers/Bank/Yodlee/Transformer/IncomeTransformer.php index d14e67bc01..5f074af239 100644 --- a/app/Helpers/Bank/Yodlee/Transformer/IncomeTransformer.php +++ b/app/Helpers/Bank/Yodlee/Transformer/IncomeTransformer.php @@ -132,7 +132,7 @@ class IncomeTransformer implements BankRevenueInterface } //some object do no store amounts ignore these - if(!property_exists($transaction, 'amount')) { + if (!property_exists($transaction, 'amount')) { continue; } diff --git a/app/Helpers/Chorus/Piste.php b/app/Helpers/Chorus/Piste.php index ac3a58667c..df124eec68 100644 --- a/app/Helpers/Chorus/Piste.php +++ b/app/Helpers/Chorus/Piste.php @@ -60,7 +60,7 @@ class Piste { $response = Http::asForm()->post($this->oauthUrl(), $this->oauthHeaders()); - if($response->successful()) { + if ($response->successful()) { return $response->json()['access_token']; } diff --git a/app/Helpers/Epc/EpcQrGenerator.php b/app/Helpers/Epc/EpcQrGenerator.php index 7007034195..a04075cdd1 100644 --- a/app/Helpers/Epc/EpcQrGenerator.php +++ b/app/Helpers/Epc/EpcQrGenerator.php @@ -58,7 +58,7 @@ class EpcQrGenerator return " {$qr}"; - } catch(\Throwable $e) { + } catch (\Throwable $e) { nlog("EPC QR failure => ".$e->getMessage()); return ''; } diff --git a/app/Helpers/Invoice/InvoiceItemSum.php b/app/Helpers/Invoice/InvoiceItemSum.php index ab5dd65456..3d3a487760 100644 --- a/app/Helpers/Invoice/InvoiceItemSum.php +++ b/app/Helpers/Invoice/InvoiceItemSum.php @@ -67,7 +67,7 @@ class InvoiceItemSum 'NO', //NORWAY - EEA 'IS', //ICELAND - EEA 'LI', //Liechtenstein - EEA - + ]; private array $tax_jurisdictions = [ @@ -198,11 +198,11 @@ class InvoiceItemSum if (in_array($this->client->company->country()->iso_3166_2, $this->tax_jurisdictions)) { //only calculate for supported tax jurisdictions /** @var \App\DataMapper\Tax\BaseRule $class */ - $class = "App\DataMapper\Tax\\".str_replace("-","_",$this->client->company->country()->iso_3166_2)."\\Rule"; + $class = "App\DataMapper\Tax\\".str_replace("-", "_", $this->client->company->country()->iso_3166_2)."\\Rule"; $this->rule = new $class(); - if($this->rule->regionWithNoTaxCoverage($this->client->country->iso_3166_2)) { + if ($this->rule->regionWithNoTaxCoverage($this->client->country->iso_3166_2)) { return $this; } @@ -292,7 +292,7 @@ class InvoiceItemSum $this->calcTaxesAutomatically(); } - if($this->client->is_tax_exempt){ + if ($this->client->is_tax_exempt) { $this->item->tax_rate1 = 0; $this->item->tax_rate2 = 0; $this->item->tax_rate3 = 0; @@ -340,8 +340,9 @@ class InvoiceItemSum private function getPeppolSurchargeTaxes(): self { - if(!$this->client->getSetting('e_invoice_type') == 'PEPPOL') + if (!$this->client->getSetting('e_invoice_type') == 'PEPPOL') { return $this; + } collect($this->invoice->line_items) ->flatMap(function ($item) { @@ -355,32 +356,33 @@ class InvoiceItemSum }) ->unique(fn ($tax) => $tax['percentage'] . '_' . $tax['name']) ->values() - ->each(function ($tax){ - - $tax_component = 0; + ->each(function ($tax) { - if ($this->invoice->custom_surcharge1) { - $tax_component += round($this->invoice->custom_surcharge1 * ($tax['percentage'] / 100), 2); - } + $tax_component = 0; - if ($this->invoice->custom_surcharge2) { - $tax_component += round($this->invoice->custom_surcharge2 * ($tax['percentage'] / 100), 2); - } + if ($this->invoice->custom_surcharge1) { + $tax_component += round($this->invoice->custom_surcharge1 * ($tax['percentage'] / 100), 2); + } - if ($this->invoice->custom_surcharge3) { - $tax_component += round($this->invoice->custom_surcharge3 * ($tax['percentage'] / 100), 2); - } + if ($this->invoice->custom_surcharge2) { + $tax_component += round($this->invoice->custom_surcharge2 * ($tax['percentage'] / 100), 2); + } - if ($this->invoice->custom_surcharge4) { - $tax_component += round($this->invoice->custom_surcharge4 * ($tax['percentage'] / 100), 2); - } + if ($this->invoice->custom_surcharge3) { + $tax_component += round($this->invoice->custom_surcharge3 * ($tax['percentage'] / 100), 2); + } - $amount = $this->invoice->custom_surcharge4 + $this->invoice->custom_surcharge3 + $this->invoice->custom_surcharge2 + $this->invoice->custom_surcharge1; + if ($this->invoice->custom_surcharge4) { + $tax_component += round($this->invoice->custom_surcharge4 * ($tax['percentage'] / 100), 2); + } - if($tax_component > 0) - $this->groupTax($tax['name'], $tax['percentage'], $tax_component, $amount, $tax['tax_id']); + $amount = $this->invoice->custom_surcharge4 + $this->invoice->custom_surcharge3 + $this->invoice->custom_surcharge2 + $this->invoice->custom_surcharge1; - }); + if ($tax_component > 0) { + $this->groupTax($tax['name'], $tax['percentage'], $tax_component, $amount, $tax['tax_id']); + } + + }); return $this; } @@ -482,7 +484,7 @@ class InvoiceItemSum try { $amount = $this->item->line_total - ($this->item->line_total * ($this->invoice->discount / $this->sub_total)); - } catch(\DivisionByZeroError $e) { + } catch (\DivisionByZeroError $e) { $amount = $this->item->line_total; } diff --git a/app/Helpers/Invoice/InvoiceItemSumInclusive.php b/app/Helpers/Invoice/InvoiceItemSumInclusive.php index 2c7b0ffb0c..3dab198af1 100644 --- a/app/Helpers/Invoice/InvoiceItemSumInclusive.php +++ b/app/Helpers/Invoice/InvoiceItemSumInclusive.php @@ -425,7 +425,7 @@ class InvoiceItemSumInclusive $this->rule = new $class(); - if($this->rule->regionWithNoTaxCoverage($this->client->country->iso_3166_2 ?? false)) { + if ($this->rule->regionWithNoTaxCoverage($this->client->country->iso_3166_2 ?? false)) { return $this; } diff --git a/app/Helpers/Invoice/InvoiceSum.php b/app/Helpers/Invoice/InvoiceSum.php index 6ad925ab3b..1b3c6de21d 100644 --- a/app/Helpers/Invoice/InvoiceSum.php +++ b/app/Helpers/Invoice/InvoiceSum.php @@ -127,7 +127,7 @@ class InvoiceSum private function calculateInvoiceTaxes(): self { - if($this->client->is_tax_exempt) { + if ($this->client->is_tax_exempt) { $this->invoice->tax_name1 = ''; $this->invoice->tax_name2 = ''; $this->invoice->tax_name3 = ''; @@ -254,7 +254,7 @@ class InvoiceSum */ private function setCalculatedAttributes(): self { - if($this->invoice->status_id == Invoice::STATUS_CANCELLED) { + if ($this->invoice->status_id == Invoice::STATUS_CANCELLED) { $this->invoice->balance = 0; } elseif ($this->invoice->status_id != Invoice::STATUS_DRAFT) { if ($this->invoice->amount != $this->invoice->balance) { @@ -268,14 +268,14 @@ class InvoiceSum $this->invoice->total_taxes = $this->getTotalTaxes(); - if($this->rappen_rounding) { + if ($this->rappen_rounding) { $this->invoice->amount = $this->roundRappen($this->invoice->amount); $this->invoice->balance = $this->roundRappen($this->invoice->balance); $this->total = $this->roundRappen($this->total); $this->invoice->total_taxes = $this->roundRappen($this->invoice->total_taxes); } - + return $this; } @@ -351,11 +351,11 @@ class InvoiceSum $tax_name = $values->filter(function ($value, $k) use ($key) { return $value['key'] == $key; })->pluck('tax_name')->first(); - + $tax_rate = $values->filter(function ($value, $k) use ($key) { return $value['key'] == $key; })->pluck('tax_rate')->first(); - + $tax_id = $values->filter(function ($value, $k) use ($key) { return $value['key'] == $key; })->pluck('tax_id')->first(); @@ -363,14 +363,14 @@ class InvoiceSum $total_line_tax = $values->filter(function ($value, $k) use ($key) { return $value['key'] == $key; })->sum('total'); - + $base_amount = $values->filter(function ($value, $k) use ($key) { return $value['key'] == $key; })->sum('base_amount'); $tax_id = $values->first()['tax_id'] ?? ''; - $this->tax_map[] = ['name' => $tax_name, 'total' => $total_line_tax, 'tax_id' => $tax_id, 'tax_rate' => $tax_rate, 'base_amount' => round($base_amount,2)]; + $this->tax_map[] = ['name' => $tax_name, 'total' => $total_line_tax, 'tax_id' => $tax_id, 'tax_rate' => $tax_rate, 'base_amount' => round($base_amount, 2)]; $this->total_taxes += $total_line_tax; } diff --git a/app/Helpers/Invoice/InvoiceSumInclusive.php b/app/Helpers/Invoice/InvoiceSumInclusive.php index 6aa627f23a..87e4007ea4 100644 --- a/app/Helpers/Invoice/InvoiceSumInclusive.php +++ b/app/Helpers/Invoice/InvoiceSumInclusive.php @@ -147,19 +147,19 @@ class InvoiceSumInclusive } //Handles cases where the surcharge is not taxed - if(is_numeric($this->invoice->custom_surcharge1) && $this->invoice->custom_surcharge1 > 0 && $this->invoice->custom_surcharge_tax1) { + if (is_numeric($this->invoice->custom_surcharge1) && $this->invoice->custom_surcharge1 > 0 && $this->invoice->custom_surcharge_tax1) { $amount += $this->invoice->custom_surcharge1; } - if(is_numeric($this->invoice->custom_surcharge2) && $this->invoice->custom_surcharge2 > 0 && $this->invoice->custom_surcharge_tax2) { + if (is_numeric($this->invoice->custom_surcharge2) && $this->invoice->custom_surcharge2 > 0 && $this->invoice->custom_surcharge_tax2) { $amount += $this->invoice->custom_surcharge2; } - if(is_numeric($this->invoice->custom_surcharge3) && $this->invoice->custom_surcharge3 > 0 && $this->invoice->custom_surcharge_tax3) { + if (is_numeric($this->invoice->custom_surcharge3) && $this->invoice->custom_surcharge3 > 0 && $this->invoice->custom_surcharge_tax3) { $amount += $this->invoice->custom_surcharge3; } - if(is_numeric($this->invoice->custom_surcharge4) && $this->invoice->custom_surcharge4 > 0 && $this->invoice->custom_surcharge_tax4) { + if (is_numeric($this->invoice->custom_surcharge4) && $this->invoice->custom_surcharge4 > 0 && $this->invoice->custom_surcharge_tax4) { $amount += $this->invoice->custom_surcharge4; } @@ -289,7 +289,7 @@ class InvoiceSumInclusive private function setCalculatedAttributes() { /* If amount != balance then some money has been paid on the invoice, need to subtract this difference from the total to set the new balance */ - if($this->invoice->status_id == Invoice::STATUS_CANCELLED) { + if ($this->invoice->status_id == Invoice::STATUS_CANCELLED) { $this->invoice->balance = 0; } elseif ($this->invoice->status_id != Invoice::STATUS_DRAFT) { if ($this->invoice->amount != $this->invoice->balance) { @@ -304,9 +304,9 @@ class InvoiceSumInclusive $this->invoice->total_taxes = $this->getTotalTaxes(); - if($this->rappen_rounding) { + if ($this->rappen_rounding) { $this->invoice->amount = $this->roundRappen($this->invoice->amount); - $this->invoice->balance = $this->roundRappen($this->invoice->balance); + $this->invoice->balance = $this->roundRappen($this->invoice->balance); $this->total = $this->roundRappen($this->total); $this->invoice->total_taxes = $this->roundRappen($this->invoice->total_taxes); } @@ -387,17 +387,17 @@ class InvoiceSumInclusive $total_line_tax = $values->filter(function ($value, $k) use ($key) { return $value['key'] == $key; })->sum('total'); - + $base_amount = $values->filter(function ($value, $k) use ($key) { return $value['key'] == $key; })->sum('base_amount'); $tax_id = $values->first()['tax_id'] ?? ''; - $this->tax_map[] = ['name' => $tax_name, 'total' => $total_line_tax, 'tax_id' => $tax_id, 'tax_rate' => $tax_rate, 'base_amount' => round($base_amount,2)]; + $this->tax_map[] = ['name' => $tax_name, 'total' => $total_line_tax, 'tax_id' => $tax_id, 'tax_rate' => $tax_rate, 'base_amount' => round($base_amount, 2)]; $this->total_taxes += $total_line_tax; - + } return $this; diff --git a/app/Helpers/Sanitizer.php b/app/Helpers/Sanitizer.php index 2c8598b008..7cb40cbd1c 100644 --- a/app/Helpers/Sanitizer.php +++ b/app/Helpers/Sanitizer.php @@ -13,7 +13,6 @@ namespace App\Helpers; class Sanitizer { - public static function removeBlanks($input): array { foreach ($input as &$value) { @@ -25,4 +24,4 @@ class Sanitizer // Use array_filter to remove empty or null values return array_filter($input); } -} \ No newline at end of file +} diff --git a/app/Helpers/SwissQr/SwissQrGenerator.php b/app/Helpers/SwissQr/SwissQrGenerator.php index 0301de5e1a..07ef9c0fc5 100644 --- a/app/Helpers/SwissQr/SwissQrGenerator.php +++ b/app/Helpers/SwissQr/SwissQrGenerator.php @@ -175,7 +175,7 @@ class SwissQrGenerator return $html; } catch (\Exception $e) { - if(is_iterable($qrBill->getViolations())) { + if (is_iterable($qrBill->getViolations())) { foreach ($qrBill->getViolations() as $key => $violation) { // nlog("qr"); diff --git a/app/Http/Controllers/AccountController.php b/app/Http/Controllers/AccountController.php index fd28026b6f..bf3155666c 100644 --- a/app/Http/Controllers/AccountController.php +++ b/app/Http/Controllers/AccountController.php @@ -67,16 +67,16 @@ class AccountController extends BaseController public function store(CreateAccountRequest $request) { - if($request->has('cf-turnstile-response') && config('ninja.cloudflare.turnstile.secret')) { + if ($request->has('cf-turnstile-response') && config('ninja.cloudflare.turnstile.secret')) { $r = \Illuminate\Support\Facades\Http::post('https://challenges.cloudflare.com/turnstile/v0/siteverify', [ 'secret' => config('ninja.cloudflare.turnstile.secret'), 'response' => $request->input('cf-turnstile-response'), 'remoteip' => $request->getClientIp(), ]); - if($r->successful()) { + if ($r->successful()) { - if($r->json()['success'] === true) { + if ($r->json()['success'] === true) { // Captcha passed } else { return response()->json(['message' => 'Captcha Failed'], 400); @@ -85,9 +85,9 @@ class AccountController extends BaseController } - if($request->has('hash') && config('ninja.cloudflare.turnstile.secret')) { //@todo once all platforms are implemented, we disable access to the rest of this route without a success response. + if ($request->has('hash') && config('ninja.cloudflare.turnstile.secret')) { //@todo once all platforms are implemented, we disable access to the rest of this route without a success response. - if(Secure::decrypt($request->input('hash')) !== $request->input('email')) { + if (Secure::decrypt($request->input('hash')) !== $request->input('email')) { return response()->json(['message' => 'Invalid Signup Payload'], 400); } diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index fe47969c5a..5c6a612c4e 100644 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -62,7 +62,7 @@ class ActivityController extends BaseController ->company() ->take($default_activities); - if($request->has('reactv2')) { + if ($request->has('reactv2')) { /** @var \App\Models\User auth()->user() */ $user = auth()->user(); diff --git a/app/Http/Controllers/Auth/ContactLoginController.php b/app/Http/Controllers/Auth/ContactLoginController.php index b35b02016c..fcfed9dccf 100644 --- a/app/Http/Controllers/Auth/ContactLoginController.php +++ b/app/Http/Controllers/Auth/ContactLoginController.php @@ -41,7 +41,7 @@ class ContactLoginController extends Controller $company = false; $account = false; - if($request->query('intended')) { + if ($request->query('intended')) { $request->session()->put('url.intended', $request->query('intended')); } @@ -143,7 +143,7 @@ class ContactLoginController extends Controller $this->setRedirectPath(); - if($intended) { + if ($intended) { $this->redirectTo = $intended; } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index 5df56723fe..0b313d9896 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -403,7 +403,7 @@ class LoginController extends BaseController $cu->each(function ($cu) { /** @var \App\Models\CompanyUser $cu */ - if(CompanyToken::query()->where('company_id', $cu->company_id)->where('user_id', $cu->user_id)->where('is_system', true)->doesntExist()) { + if (CompanyToken::query()->where('company_id', $cu->company_id)->where('user_id', $cu->user_id)->where('is_system', true)->doesntExist()) { (new CreateCompanyToken($cu->company, $cu->user, request()->server('HTTP_USER_AGENT')))->handle(); } }); @@ -539,7 +539,7 @@ class LoginController extends BaseController if (request()->has('id_token')) { $user = $google->getTokenResponse(request()->input('id_token')); - } elseif(request()->has('access_token')) { + } elseif (request()->has('access_token')) { $user = $google->harvestUser(request()->input('access_token')); } else { return response()->json(['message' => 'Illegal request'], 403); @@ -655,7 +655,7 @@ class LoginController extends BaseController $parameters = ['response_type' => 'code', 'redirect_uri' => config('ninja.app_url') . "/auth/microsoft"]; } - if(request()->hasHeader('X-REACT') || request()->query('react')) { + if (request()->hasHeader('X-REACT') || request()->query('react')) { /**@var \App\Models\User $user */ $user = auth()->user(); Cache::put("react_redir:".$user?->account->key, 'true', 300); diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.php index 2e066abeb7..7bf715157f 100644 --- a/app/Http/Controllers/Auth/ResetPasswordController.php +++ b/app/Http/Controllers/Auth/ResetPasswordController.php @@ -111,7 +111,7 @@ class ResetPasswordController extends Controller { auth()->logout(); - if(request()->has('react') || request()->hasHeader('X-React')) { + if (request()->has('react') || request()->hasHeader('X-React')) { return redirect(config('ninja.react_url').'/#/login'); } @@ -131,7 +131,7 @@ class ResetPasswordController extends Controller return new JsonResponse(['message' => trans($response)], 200); } - if($request->hasHeader('X-REACT') || $request->has('react')) { + if ($request->hasHeader('X-REACT') || $request->has('react')) { return redirect(config('ninja.react_url').'/#/login'); } else { return redirect('/#/login'); diff --git a/app/Http/Controllers/Bank/NordigenController.php b/app/Http/Controllers/Bank/NordigenController.php index d02a3cea87..b05f3378c5 100644 --- a/app/Http/Controllers/Bank/NordigenController.php +++ b/app/Http/Controllers/Bank/NordigenController.php @@ -218,8 +218,9 @@ class NordigenController extends BaseController $nordigen_account = $nordigen->getAccount($nordigenAccountId); - if(!$nordigen_account) + if (!$nordigen_account) { continue; + } $existing_bank_integration = BankIntegration::withTrashed()->where('nordigen_account_id', $nordigen_account['id'])->where('company_id', $company->id)->where('is_deleted', 0)->first(); diff --git a/app/Http/Controllers/BankTransactionController.php b/app/Http/Controllers/BankTransactionController.php index 20dd736196..6e811c789c 100644 --- a/app/Http/Controllers/BankTransactionController.php +++ b/app/Http/Controllers/BankTransactionController.php @@ -112,7 +112,7 @@ class BankTransactionController extends BaseController $this->bank_transaction_repo->convert_matched($bank_transactions); } else { $bank_transactions->each(function ($bank_transaction, $key) use ($action, $user) { - if($user->can('edit', $bank_transaction)) { + if ($user->can('edit', $bank_transaction)) { $this->bank_transaction_repo->{$action}($bank_transaction); } }); diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php index a297fb021a..e831575a5a 100644 --- a/app/Http/Controllers/BaseController.php +++ b/app/Http/Controllers/BaseController.php @@ -924,9 +924,9 @@ class BaseController extends Controller if ($this->entity_type == BankIntegration::class && !$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) { $query->exclude(["balance"]); } //allows us to selective display bank integrations back to the user if they can view / create bank transactions but without the bank balance being present in the response - elseif($this->entity_type == TaxRate::class && $user->hasIntersectPermissions(['create_invoice','edit_invoice','create_quote','edit_quote','create_purchase_order','edit_purchase_order'])) { + elseif ($this->entity_type == TaxRate::class && $user->hasIntersectPermissions(['create_invoice','edit_invoice','create_quote','edit_quote','create_purchase_order','edit_purchase_order'])) { // need to show tax rates if the user has the ability to create documents. - } elseif($this->entity_type == ExpenseCategory::class && $user->hasPermission('create_expense')) { + } elseif ($this->entity_type == ExpenseCategory::class && $user->hasPermission('create_expense')) { // need to show expense categories if the user has the ability to create expenses. } else { $query->where('user_id', '=', $user->id); @@ -994,9 +994,9 @@ class BaseController extends Controller $response_data = Statics::company($user->getCompany()->getLocale()); - if(request()->has('einvoice')) { + if (request()->has('einvoice')) { - if(class_exists(Schema::class)) { + if (class_exists(Schema::class)) { $ro = new Schema(); $response_data['einvoice_schema'] = $ro('Peppol'); } @@ -1223,7 +1223,7 @@ class BaseController extends Controller return response()->json(['message' => 'Upgrade to a paid plan for this feature.'], 403); } - + /** * GetEncodedFilename * diff --git a/app/Http/Controllers/BrevoController.php b/app/Http/Controllers/BrevoController.php index 81c02bdcd3..8a4fcda8ed 100644 --- a/app/Http/Controllers/BrevoController.php +++ b/app/Http/Controllers/BrevoController.php @@ -185,8 +185,9 @@ class BrevoController extends BaseController { $input = $request->all(); - if (!($request->has('token') && $request->get('token') == config('ninja.inbound_mailbox.inbound_webhook_token'))) + if (!($request->has('token') && $request->get('token') == config('ninja.inbound_mailbox.inbound_webhook_token'))) { return response()->json(['message' => 'Unauthorized'], 403); + } if (!array_key_exists('items', $input)) { nlog('Failed: Message could not be parsed, because required parameters are missing.'); diff --git a/app/Http/Controllers/ClientController.php b/app/Http/Controllers/ClientController.php index 2401fab5b3..83f638db3b 100644 --- a/app/Http/Controllers/ClientController.php +++ b/app/Http/Controllers/ClientController.php @@ -232,7 +232,7 @@ class ClientController extends BaseController ->whereIn('id', $request->ids) ->get(); - if($action == 'template' && $user->can('view', $clients->first())) { + if ($action == 'template' && $user->can('view', $clients->first())) { $hash_or_response = $request->boolean('send_email') ? 'email sent' : \Illuminate\Support\Str::uuid(); @@ -250,7 +250,7 @@ class ClientController extends BaseController return response()->json(['message' => $hash_or_response], 200); } - if($action == 'assign_group' && $user->can('edit', $clients->first())) { + if ($action == 'assign_group' && $user->can('edit', $clients->first())) { $this->client_repo->assignGroup($clients, $request->group_settings_id); @@ -258,7 +258,7 @@ class ClientController extends BaseController } - if($action == 'bulk_update' && $user->can('edit', $clients->first())) { + if ($action == 'bulk_update' && $user->can('edit', $clients->first())) { $clients = Client::withTrashed() ->company() @@ -314,7 +314,7 @@ class ClientController extends BaseController $client->documents->each(function ($document) { try { Storage::disk(config('filesystems.default'))->delete($document->url); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog($e->getMessage()); } }); @@ -351,7 +351,7 @@ class ClientController extends BaseController return response()->json(['message' => "Client not found"], 400); } - if($m_client->id == $client->id) { + if ($m_client->id == $client->id) { return response()->json(['message' => "Attempting to merge the same client is not possible."], 400); } @@ -369,7 +369,7 @@ class ClientController extends BaseController */ public function updateTaxData(PurgeClientRequest $request, Client $client) { - if($client->company->account->isPaid()) { + if ($client->company->account->isPaid()) { (new UpdateTaxData($client, $client->company))->handle(); } @@ -388,7 +388,7 @@ class ClientController extends BaseController /** @var \App\Models\User $user */ $user = auth()->user(); - if(stripos($bounce_id, '-') !== false) { + if (stripos($bounce_id, '-') !== false) { $log = SystemLog::query() ->where('company_id', $user->company()->id) @@ -400,16 +400,16 @@ class ClientController extends BaseController $resolved_bounce_id = false; - if($log && ($log?->log['ID'] ?? false)) { + if ($log && ($log?->log['ID'] ?? false)) { $resolved_bounce_id = $log->log['ID'] ?? false; } - if(!$resolved_bounce_id) { + if (!$resolved_bounce_id) { $ppwebhook = new ProcessPostmarkWebhook([]); $resolved_bounce_id = $ppwebhook->getBounceId($bounce_id); } - if(!$resolved_bounce_id) { + if (!$resolved_bounce_id) { return response()->json(['message' => 'Bounce ID not found'], 400); } @@ -429,7 +429,7 @@ class ClientController extends BaseController /** @var ?\Postmark\Models\DynamicResponseModel $response */ $response = $postmark->activateBounce((int)$bounce_id); - if($response && $response?->Message == 'OK' && !$response->Bounce->Inactive && $response->Bounce->Email) { // @phpstan-ignore-line + if ($response && $response?->Message == 'OK' && !$response->Bounce->Inactive && $response->Bounce->Email) { // @phpstan-ignore-line $email = $response->Bounce->Email; //remove email from quarantine. //@TODO @@ -437,7 +437,7 @@ class ClientController extends BaseController return response()->json(['message' => 'Success'], 200); - } catch(\Exception $e) { + } catch (\Exception $e) { return response()->json(['message' => $e->getMessage(), 400]); diff --git a/app/Http/Controllers/ClientPortal/DocumentController.php b/app/Http/Controllers/ClientPortal/DocumentController.php index f6bff85412..bfacbbb358 100644 --- a/app/Http/Controllers/ClientPortal/DocumentController.php +++ b/app/Http/Controllers/ClientPortal/DocumentController.php @@ -74,7 +74,7 @@ class DocumentController extends Controller $hash = Cache::pull($hash); - if(!$hash) { + if (!$hash) { abort(404); } diff --git a/app/Http/Controllers/ClientPortal/InvitationController.php b/app/Http/Controllers/ClientPortal/InvitationController.php index 748b7e96df..faffb56c92 100644 --- a/app/Http/Controllers/ClientPortal/InvitationController.php +++ b/app/Http/Controllers/ClientPortal/InvitationController.php @@ -115,7 +115,7 @@ class InvitationController extends Controller ]); } - if(!auth()->guard('contact')->check()) { + if (!auth()->guard('contact')->check()) { $this->middleware('auth:contact'); /** @var \App\Models\InvoiceInvitation | \App\Models\QuoteInvitation | \App\Models\CreditInvitation | \App\Models\RecurringInvoiceInvitation $invitation */ return redirect()->route('client.login', ['intended' => route('client.'.$entity.'.show', [$entity => $this->encodePrimaryKey($invitation->{$key}), 'silent' => $is_silent])]); diff --git a/app/Http/Controllers/ClientPortal/InvoiceController.php b/app/Http/Controllers/ClientPortal/InvoiceController.php index 09bdd38d75..60a58a4e40 100644 --- a/app/Http/Controllers/ClientPortal/InvoiceController.php +++ b/app/Http/Controllers/ClientPortal/InvoiceController.php @@ -59,7 +59,7 @@ class InvoiceController extends Controller public function show(ShowInvoiceRequest $request, Invoice $invoice, ?string $hash = null) { set_time_limit(0); - + $invitation = $invoice->invitations()->where('client_contact_id', auth()->guard('contact')->user()->id)->first(); // @phpstan-ignore-next-line @@ -86,8 +86,9 @@ class InvoiceController extends Controller return render('invoices.show-fullscreen', $data); } - if(!$invoice->isPayable()) - return $this->render('invoices.show',$data); + if (!$invoice->isPayable()) { + return $this->render('invoices.show', $data); + } return auth()->guard('contact')->user()->client->getSetting('payment_flow') == 'default' ? $this->render('invoices.show', $data) : $this->render('invoices.show_smooth', $data); @@ -97,13 +98,14 @@ class InvoiceController extends Controller { $data = Cache::get($hash); - for($x=0; $x<3; $x++){ - + for ($x = 0; $x < 3; $x++) { + $data = Cache::get($hash); - - if($data) + + if ($data) { break; - + } + usleep(200000); } @@ -236,7 +238,7 @@ class InvoiceController extends Controller $settings = auth()->guard('contact')->user()->client->getMergedSettings(); $variables = false; - if(($invitation = $invoices->first()->invitations()->first() ?? false) && $settings->show_accept_invoice_terms) { + if (($invitation = $invoices->first()->invitations()->first() ?? false) && $settings->show_accept_invoice_terms) { $variables = (new HtmlEngine($invitation))->generateLabelsAndValues(); } diff --git a/app/Http/Controllers/ClientPortal/PaymentMethodController.php b/app/Http/Controllers/ClientPortal/PaymentMethodController.php index 24a19a662b..8008efcd0c 100644 --- a/app/Http/Controllers/ClientPortal/PaymentMethodController.php +++ b/app/Http/Controllers/ClientPortal/PaymentMethodController.php @@ -150,10 +150,9 @@ class PaymentMethodController extends Controller $payment_method->save(); - $def_cgt = auth()->guard('contact')->user()->client->gateway_tokens()->orderBy('id','desc')->first(); - - if($def_cgt) - { + $def_cgt = auth()->guard('contact')->user()->client->gateway_tokens()->orderBy('id', 'desc')->first(); + + if ($def_cgt) { $def_cgt->is_default = true; $def_cgt->save(); } diff --git a/app/Http/Controllers/ClientPortal/PrePaymentController.php b/app/Http/Controllers/ClientPortal/PrePaymentController.php index ba190324bf..f0260d23ee 100644 --- a/app/Http/Controllers/ClientPortal/PrePaymentController.php +++ b/app/Http/Controllers/ClientPortal/PrePaymentController.php @@ -41,9 +41,10 @@ class PrePaymentController extends Controller { $client = auth()->guard('contact')->user()->client; - - if(!$client->getSetting('client_initiated_payments')) + + if (!$client->getSetting('client_initiated_payments')) { return redirect()->route('client.dashboard'); + } $minimum = $client->getSetting('client_initiated_payments_minimum'); $minimum_amount = $minimum == 0 ? "" : Number::formatMoney($minimum, $client); @@ -116,7 +117,7 @@ class PrePaymentController extends Controller $variables = false; - if(($invitation = $invoices->first()->invitations()->first() ?? false) && $invoice->client->getSetting('show_accept_invoice_terms')) { + if (($invitation = $invoices->first()->invitations()->first() ?? false) && $invoice->client->getSetting('show_accept_invoice_terms')) { $variables = (new HtmlEngine($invitation))->generateLabelsAndValues(); } diff --git a/app/Http/Controllers/ClientPortal/QuoteController.php b/app/Http/Controllers/ClientPortal/QuoteController.php index 9dce7c6e3e..6b63b228b3 100644 --- a/app/Http/Controllers/ClientPortal/QuoteController.php +++ b/app/Http/Controllers/ClientPortal/QuoteController.php @@ -221,7 +221,7 @@ class QuoteController extends Controller $variables = false; - if($invitation = $quotes->first()->invitations()->first() ?? false) { + if ($invitation = $quotes->first()->invitations()->first() ?? false) { $variables = (new HtmlEngine($invitation))->generateLabelsAndValues(); } diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php index 2be76e52b8..351448f4a5 100644 --- a/app/Http/Controllers/CompanyController.php +++ b/app/Http/Controllers/CompanyController.php @@ -436,7 +436,7 @@ class CompanyController extends BaseController $this->saveDocuments($request->input('documents'), $company, $request->input('is_public', true)); } - if($request->has('e_invoice_certificate') && !is_null($request->file("e_invoice_certificate"))) { + if ($request->has('e_invoice_certificate') && !is_null($request->file("e_invoice_certificate"))) { $company->e_invoice_certificate = base64_encode($request->file("e_invoice_certificate")->get()); @@ -519,7 +519,7 @@ class CompanyController extends BaseController try { Storage::disk(config('filesystems.default'))->deleteDirectory($company->company_key); - } catch(\Exception $e) { + } catch (\Exception $e) { } $account->delete(); @@ -549,7 +549,7 @@ class CompanyController extends BaseController try { Storage::disk(config('filesystems.default'))->deleteDirectory($company->company_key); - } catch(\Exception $e) { + } catch (\Exception $e) { } @@ -693,10 +693,10 @@ class CompanyController extends BaseController public function updateOriginTaxData(DefaultCompanyRequest $request, Company $company) { - if($company->settings->country_id == "840" && !$company->account->isFreeHostedClient()) { + if ($company->settings->country_id == "840" && !$company->account->isFreeHostedClient()) { try { (new CompanyTaxRate($company))->handle(); - } catch(\Exception $e) { + } catch (\Exception $e) { return response()->json(['message' => 'There was a problem updating the tax rates. Please try again.'], 400); } } else { @@ -729,7 +729,7 @@ class CompanyController extends BaseController $logo = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='); } - } catch(\Exception $e) { + } catch (\Exception $e) { $logo = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='); diff --git a/app/Http/Controllers/CompanyGatewayController.php b/app/Http/Controllers/CompanyGatewayController.php index 4d1ce5f8e3..c24286e349 100644 --- a/app/Http/Controllers/CompanyGatewayController.php +++ b/app/Http/Controllers/CompanyGatewayController.php @@ -217,8 +217,8 @@ class CompanyGatewayController extends BaseController $fees_and_limits = $company_gateway->fees_and_limits; - foreach($gateway_types as $key => $gateway_type) { - if(!property_exists($fees_and_limits, $key)) { + foreach ($gateway_types as $key => $gateway_type) { + if (!property_exists($fees_and_limits, $key)) { $fees_and_limits->{$key} = new FeesAndLimits(); } } @@ -237,7 +237,7 @@ class CompanyGatewayController extends BaseController CheckoutSetupWebhook::dispatch($company_gateway->company->company_key, $company_gateway->id); break; - case $this->forte_key: + case $this->forte_key: dispatch(function () use ($company_gateway) { MultiDB::setDb($company_gateway->company->db); $company_gateway->driver()->updateFees(); @@ -245,7 +245,7 @@ class CompanyGatewayController extends BaseController break; - case $this->cbapowerboard_key: + case $this->cbapowerboard_key: dispatch(function () use ($company_gateway) { MultiDB::setDb($company_gateway->company->db); $company_gateway->driver()->init()->settings()->updateSettings(); @@ -262,7 +262,7 @@ class CompanyGatewayController extends BaseController default: # code... break; - + } return $this->itemResponse($company_gateway); @@ -434,8 +434,8 @@ class CompanyGatewayController extends BaseController $fees_and_limits = $company_gateway->fees_and_limits; - foreach($gateway_types as $key => $gateway_type) { - if(!property_exists($fees_and_limits, $key)) { + foreach ($gateway_types as $key => $gateway_type) { + if (!property_exists($fees_and_limits, $key)) { $fees_and_limits->{$key} = new FeesAndLimits(); } } @@ -443,9 +443,9 @@ class CompanyGatewayController extends BaseController $company_gateway->fees_and_limits = $fees_and_limits; $company_gateway->save(); - if($company_gateway->gateway_key == $this->checkout_key) { + if ($company_gateway->gateway_key == $this->checkout_key) { CheckoutSetupWebhook::dispatch($company_gateway->company->company_key, $company_gateway->fresh()->id); - } elseif($company_gateway->gateway_key == $this->forte_key) { + } elseif ($company_gateway->gateway_key == $this->forte_key) { dispatch(function () use ($company_gateway) { MultiDB::setDb($company_gateway->company->db); diff --git a/app/Http/Controllers/CompanyUserController.php b/app/Http/Controllers/CompanyUserController.php index 89dee72a52..da47c9389f 100644 --- a/app/Http/Controllers/CompanyUserController.php +++ b/app/Http/Controllers/CompanyUserController.php @@ -127,7 +127,7 @@ class CompanyUserController extends BaseController $company_user->settings = $request->input('company_user')['settings']; $company_user->notifications = $request->input('company_user')['notifications']; - if(isset($request->input('company_user')['react_settings'])) { + if (isset($request->input('company_user')['react_settings'])) { $company_user->react_settings = $request->input('company_user')['react_settings']; } diff --git a/app/Http/Controllers/CreditController.php b/app/Http/Controllers/CreditController.php index a95af27d83..9dfda61a7c 100644 --- a/app/Http/Controllers/CreditController.php +++ b/app/Http/Controllers/CreditController.php @@ -554,7 +554,7 @@ class CreditController extends BaseController } - if($action == 'template' && $user->can('view', $credits->first())) { + if ($action == 'template' && $user->can('view', $credits->first())) { $hash_or_response = $request->boolean('send_email') ? 'email sent' : \Illuminate\Support\Str::uuid(); diff --git a/app/Http/Controllers/DesignController.php b/app/Http/Controllers/DesignController.php index 6ab00404f8..2fc70aab83 100644 --- a/app/Http/Controllers/DesignController.php +++ b/app/Http/Controllers/DesignController.php @@ -570,61 +570,62 @@ class DesignController extends BaseController case 'invoice': $company->invoices() - ->when($settings_level == 'company', function ($query){ + ->when($settings_level == 'company', function ($query) { $query->where(function ($query) { $query->whereDoesntHave('client.group_settings') - ->orWhereHas('client.group_settings', function ($q){ - + ->orWhereHas('client.group_settings', function ($q) { + $q->whereRaw("JSON_EXTRACT(settings, '$.invoice_design_id') IS NULL") ->orWhereRaw("JSON_EXTRACT(settings, '$.invoice_design_id') = ''"); }); }); }) - ->when($settings_level == 'group_settings' && $group_settings_id, function ($query) use($group_settings_id){ - - $query->whereHas('client', function ($q) use ($group_settings_id) { - $q->where('group_settings_id', $group_settings_id); - }); + ->when($settings_level == 'group_settings' && $group_settings_id, function ($query) use ($group_settings_id) { + + $query->whereHas('client', function ($q) use ($group_settings_id) { + $q->where('group_settings_id', $group_settings_id); + }); }) - ->when($settings_level == 'client' && $client_id, function ($query) use($client_id){ - + ->when($settings_level == 'client' && $client_id, function ($query) use ($client_id) { + $query->where('client_id', $client_id); - + }) ->update(['design_id' => $design_id]); - if($settings_level == 'company') + if ($settings_level == 'company') { $company->recurring_invoices()->update(['design_id' => $design_id]); + } break; case 'quote': - + $company->quotes() - ->when($settings_level == 'company', function ($query){ + ->when($settings_level == 'company', function ($query) { $query->where(function ($query) { $query->whereDoesntHave('client.group_settings') - ->orWhereHas('client.group_settings', function ($q){ - + ->orWhereHas('client.group_settings', function ($q) { + $q->whereRaw("JSON_EXTRACT(settings, '$.invoice_design_id') IS NULL") ->orWhereRaw("JSON_EXTRACT(settings, '$.invoice_design_id') = ''"); }); }); }) - ->when($settings_level == 'group_settings' && $group_settings_id, function ($query) use($group_settings_id){ - - $query->whereHas('client', function ($q) use ($group_settings_id) { - $q->where('group_settings_id', $group_settings_id); - }); + ->when($settings_level == 'group_settings' && $group_settings_id, function ($query) use ($group_settings_id) { + + $query->whereHas('client', function ($q) use ($group_settings_id) { + $q->where('group_settings_id', $group_settings_id); + }); }) - ->when($settings_level == 'client' && $client_id, function ($query) use($client_id){ - + ->when($settings_level == 'client' && $client_id, function ($query) use ($client_id) { + $query->where('client_id', $client_id); - + }) ->update(['design_id' => $design_id]); @@ -632,31 +633,31 @@ class DesignController extends BaseController case 'credit': $company->credits() - ->when($settings_level == 'company', function ($query){ + ->when($settings_level == 'company', function ($query) { $query->where(function ($query) { $query->whereDoesntHave('client.group_settings') - ->orWhereHas('client.group_settings', function ($q){ - + ->orWhereHas('client.group_settings', function ($q) { + $q->whereRaw("JSON_EXTRACT(settings, '$.invoice_design_id') IS NULL") ->orWhereRaw("JSON_EXTRACT(settings, '$.invoice_design_id') = ''"); }); }); }) - ->when($settings_level == 'group_settings' && $group_settings_id, function ($query) use($group_settings_id){ - - $query->whereHas('client', function ($q) use ($group_settings_id) { - $q->where('group_settings_id', $group_settings_id); - }); + ->when($settings_level == 'group_settings' && $group_settings_id, function ($query) use ($group_settings_id) { + + $query->whereHas('client', function ($q) use ($group_settings_id) { + $q->where('group_settings_id', $group_settings_id); + }); }) - ->when($settings_level == 'client' && $client_id, function ($query) use($client_id){ - + ->when($settings_level == 'client' && $client_id, function ($query) use ($client_id) { + $query->where('client_id', $client_id); - + }) ->update(['design_id' => $design_id]); - + break; case 'purchase_order': diff --git a/app/Http/Controllers/DocumentController.php b/app/Http/Controllers/DocumentController.php index d6e28367d1..06f73e9270 100644 --- a/app/Http/Controllers/DocumentController.php +++ b/app/Http/Controllers/DocumentController.php @@ -150,7 +150,7 @@ class DocumentController extends BaseController $document->fill($request->all()); $document->save(); - if($document->documentable) { //@phpstan-ignore-line + if ($document->documentable) { //@phpstan-ignore-line $document->documentable->touch(); } diff --git a/app/Http/Controllers/EInvoiceController.php b/app/Http/Controllers/EInvoiceController.php index f156303e90..c0a8446470 100644 --- a/app/Http/Controllers/EInvoiceController.php +++ b/app/Http/Controllers/EInvoiceController.php @@ -30,12 +30,12 @@ class EInvoiceController extends BaseController private array $einvoice_props = [ 'payment_means', ]; - + /** * Checks a given model for validity for sending * * @param ValidateEInvoiceRequest $request - * + * */ public function validateEntity(ValidateEInvoiceRequest $request) { @@ -43,17 +43,17 @@ class EInvoiceController extends BaseController $data = []; - match($request->entity){ + match($request->entity) { 'invoices' => $data = $el->checkInvoice($request->getEntity()), 'clients' => $data = $el->checkClient($request->getEntity()), 'companies' => $data = $el->checkCompany($request->getEntity()), default => $data['passes'] = false, }; - + return response()->json($data, $data['passes'] ? 200 : 422); } - + /** * Updated the E-Invoice Setting Configurations * @@ -64,16 +64,14 @@ class EInvoiceController extends BaseController { $einvoice = new \InvoiceNinja\EInvoice\Models\Peppol\Invoice(); - foreach($request->input('payment_means', []) as $payment_means) - { + foreach ($request->input('payment_means', []) as $payment_means) { $pm = new PaymentMeans(); $pmc = new PaymentMeansCode(); $pmc->value = $payment_means['code']; $pm->PaymentMeansCode = $pmc; - if(in_array($payment_means['code'], ['54,55'])) - { + if (in_array($payment_means['code'], ['54,55'])) { $ctc = new CardTypeCode(); $ctc->value = $payment_means['card_type']; $card_account = new CardAccount(); @@ -82,8 +80,7 @@ class EInvoiceController extends BaseController $pm->CardAccount = $card_account; } - if(isset($payment_means['iban'])) - { + if (isset($payment_means['iban'])) { $fib = new FinancialInstitutionBranch(); $fi = new FinancialInstitution(); $bic_id = new ID(); @@ -98,23 +95,24 @@ class EInvoiceController extends BaseController $pfa->FinancialInstitutionBranch = $fib; $pm->PayeeFinancialAccount = $pfa; - + } - if(isset($payment_means['information'])) + if (isset($payment_means['information'])) { $pm->InstructionNote = $payment_means['information']; + } $einvoice->PaymentMeans[] = $pm; } - + $stub = new \stdClass(); $stub->Invoice = $einvoice; - + $company = auth()->user()->company(); $company->e_invoice = $stub; $company->save(); } - + /** * Returns the current E-Invoice Quota. * @@ -123,11 +121,11 @@ class EInvoiceController extends BaseController */ public function quota(ShowQuotaRequest $request): JsonResponse { - /** - * @var \App\Models\Company - */ + /** + * @var \App\Models\Company + */ $company = auth()->user()->company(); - + $response = \Illuminate\Support\Facades\Http::baseUrl(config('ninja.hosted_ninja_url')) ->withHeaders([ 'Content-Type' => 'application/json', diff --git a/app/Http/Controllers/EInvoicePeppolController.php b/app/Http/Controllers/EInvoicePeppolController.php index 088e127e05..41b125fd34 100644 --- a/app/Http/Controllers/EInvoicePeppolController.php +++ b/app/Http/Controllers/EInvoicePeppolController.php @@ -23,10 +23,9 @@ use App\Http\Requests\EInvoice\Peppol\UpdateEntityRequest; class EInvoicePeppolController extends BaseController { - /** * Returns the legal entity ID - * + * * @param ShowEntityRequest $request * @return JsonResponse */ @@ -100,7 +99,7 @@ class EInvoicePeppolController extends BaseController /** * Update legal properties such as acting as sender or receiver. - * + * * @param \App\Http\Requests\EInvoice\Peppol\UpdateEntityRequest $request * @return JsonResponse */ @@ -133,8 +132,8 @@ class EInvoicePeppolController extends BaseController * Removed the legal identity from the Peppol network * * @param DisconnectRequest $request - * - */ + * + */ public function disconnect(DisconnectRequest $request, Storecove $storecove): JsonResponse { /** @@ -167,7 +166,7 @@ class EInvoicePeppolController extends BaseController /** * Add an additional tax identifier to * an existing legal entity id - * + * * Response will be the same as show() * * @param AddTaxIdentifierRequest $request @@ -176,17 +175,18 @@ class EInvoicePeppolController extends BaseController */ public function addAdditionalTaxIdentifier(AddTaxIdentifierRequest $request, Storecove $storecove): JsonResponse { - + $company = auth()->user()->company(); $tax_data = $company->tax_data; $vat_number = $request->vat_number; $country = $request->country; - if($country == 'GB') + if ($country == 'GB') { $additional_vat = $tax_data->regions->UK->subregions->{$country}->vat_number ?? null; - else + } else { $additional_vat = $tax_data->regions->EU->subregions->{$country}->vat_number ?? null; + } if (!is_null($additional_vat) && !empty($additional_vat)) { return response()->json(['message' => 'Identifier already exists for this region.'], 400); @@ -201,11 +201,12 @@ class EInvoicePeppolController extends BaseController return response()->json(data_get($response, 'errors', 'message'), status: $response['code']); } - if($country == 'GB') + if ($country == 'GB') { $tax_data->regions->UK->subregions->{$country}->vat_number = $vat_number; - else + } else { $tax_data->regions->EU->subregions->{$country}->vat_number = $vat_number; - + } + $company->tax_data = $tax_data; $company->save(); diff --git a/app/Http/Controllers/EInvoiceTokenController.php b/app/Http/Controllers/EInvoiceTokenController.php index 775985ffda..915be7d39f 100644 --- a/app/Http/Controllers/EInvoiceTokenController.php +++ b/app/Http/Controllers/EInvoiceTokenController.php @@ -17,7 +17,7 @@ use App\Http\Requests\EInvoice\UpdateTokenRequest; use Illuminate\Http\Response; use Illuminate\Support\Facades\Http; -class EInvoiceTokenController extends BaseController +class EInvoiceTokenController extends BaseController { public function __invoke(UpdateTokenRequest $request): Response { diff --git a/app/Http/Controllers/EmailController.php b/app/Http/Controllers/EmailController.php index 850b0b68ac..a049f48bbd 100644 --- a/app/Http/Controllers/EmailController.php +++ b/app/Http/Controllers/EmailController.php @@ -74,7 +74,7 @@ class EmailController extends BaseController if ($request->cc_email && (Ninja::isSelfHost() || $user->account->isPremium())) { - foreach($request->cc_email as $email) { + foreach ($request->cc_email as $email) { $mo->cc[] = new Address($email); } @@ -141,7 +141,7 @@ class EmailController extends BaseController return $this->itemResponse($entity_obj->fresh()); } - private function resolveClass(string $entity): string + private function resolveClass(string $entity): string { $class = ''; diff --git a/app/Http/Controllers/Gateways/BlockonomicsController.php b/app/Http/Controllers/Gateways/BlockonomicsController.php index 4cdbfd5ed8..a663380cad 100644 --- a/app/Http/Controllers/Gateways/BlockonomicsController.php +++ b/app/Http/Controllers/Gateways/BlockonomicsController.php @@ -55,4 +55,4 @@ class BlockonomicsController extends Controller return $qr; } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Gateways/GoCardlessOAuthController.php b/app/Http/Controllers/Gateways/GoCardlessOAuthController.php index 183fc1b328..189e8d6d7b 100644 --- a/app/Http/Controllers/Gateways/GoCardlessOAuthController.php +++ b/app/Http/Controllers/Gateways/GoCardlessOAuthController.php @@ -10,7 +10,6 @@ * @license https://www.elastic.co/licensing/elastic-license */ - namespace App\Http\Controllers\Gateways; use App\DataMapper\FeesAndLimits; @@ -77,7 +76,7 @@ class GoCardlessOAuthController extends Controller if ($response->failed()) { return view('auth.gocardless_connect.access_denied'); } - + $response = $response->json(); $company_gateway = CompanyGateway::query() diff --git a/app/Http/Controllers/GroupSettingController.php b/app/Http/Controllers/GroupSettingController.php index ad1b33d3a6..46a064cd25 100644 --- a/app/Http/Controllers/GroupSettingController.php +++ b/app/Http/Controllers/GroupSettingController.php @@ -140,7 +140,7 @@ class GroupSettingController extends BaseController public function update(UpdateGroupSettingRequest $request, GroupSetting $group_setting) { /** Need this to prevent settings from being overwritten */ - if(!$request->file('company_logo')) { + if (!$request->file('company_logo')) { $group_setting = $this->group_setting_repo->save($request->all(), $group_setting); } diff --git a/app/Http/Controllers/HostedMigrationController.php b/app/Http/Controllers/HostedMigrationController.php index 261221fd29..3d072f4fd5 100644 --- a/app/Http/Controllers/HostedMigrationController.php +++ b/app/Http/Controllers/HostedMigrationController.php @@ -29,7 +29,7 @@ class HostedMigrationController extends Controller MultiDB::findAndSetDbByCompanyKey($request->company_key); $c = Company::where('company_key', $request->company_key)->first(); - if(!$c || $c->is_disabled) { + if (!$c || $c->is_disabled) { return response()->json(['message' => 'ok'], 200); } diff --git a/app/Http/Controllers/ImportController.php b/app/Http/Controllers/ImportController.php index 10b680bcd7..09c0778417 100644 --- a/app/Http/Controllers/ImportController.php +++ b/app/Http/Controllers/ImportController.php @@ -119,19 +119,19 @@ class ImportController extends Controller })->toArray(); //Exact string match - foreach($headers as $key => $value) { + foreach ($headers as $key => $value) { - foreach($translated_keys as $tkey => $tvalue) { + foreach ($translated_keys as $tkey => $tvalue) { $concat_needle = str_ireplace(" ", "", $tvalue['index'].$tvalue['label']); $concat_value = str_ireplace(" ", "", $value); - if($this->testMatch($concat_value, $concat_needle)) { + if ($this->testMatch($concat_value, $concat_needle)) { - $hit = $tvalue['key']; - $hints[$key] = $hit; - unset($translated_keys[$tkey]); - break; + $hit = $tvalue['key']; + $hints[$key] = $hit; + unset($translated_keys[$tkey]); + break; } else { $hints[$key] = null; @@ -142,15 +142,15 @@ class ImportController extends Controller } //Label Match - foreach($headers as $key => $value) { + foreach ($headers as $key => $value) { - if(isset($hints[$key])) { + if (isset($hints[$key])) { continue; } - foreach($translated_keys as $tkey => $tvalue) { + foreach ($translated_keys as $tkey => $tvalue) { - if($this->testMatch($value, $tvalue['label'])) { + if ($this->testMatch($value, $tvalue['label'])) { $hit = $tvalue['key']; $hints[$key] = $hit; unset($translated_keys[$tkey]); @@ -164,13 +164,13 @@ class ImportController extends Controller } //Index matching pass using the index of the translation here - foreach($headers as $key => $value) { - if(isset($hints[$key])) { + foreach ($headers as $key => $value) { + if (isset($hints[$key])) { continue; } - foreach($translated_keys as $tkey => $tvalue) { - if($this->testMatch($value, $tvalue['index'])) { + foreach ($translated_keys as $tkey => $tvalue) { + if ($this->testMatch($value, $tvalue['index'])) { $hit = $tvalue['key']; $hints[$key] = $hit; unset($translated_keys[$tkey]); diff --git a/app/Http/Controllers/ImportQuickbooksController.php b/app/Http/Controllers/ImportQuickbooksController.php index 3b3cf53b21..c2f2953d3f 100644 --- a/app/Http/Controllers/ImportQuickbooksController.php +++ b/app/Http/Controllers/ImportQuickbooksController.php @@ -37,7 +37,7 @@ class ImportQuickbooksController extends BaseController return redirect()->to($authorizationUrl); } - + public function onAuthorized(AuthorizedQuickbooksRequest $request) { diff --git a/app/Http/Controllers/InvoiceController.php b/app/Http/Controllers/InvoiceController.php index 66489a09b8..89263ffb60 100644 --- a/app/Http/Controllers/InvoiceController.php +++ b/app/Http/Controllers/InvoiceController.php @@ -175,7 +175,7 @@ class InvoiceController extends BaseController $invoice->custom_surcharge_tax2 = $company->custom_surcharge_taxes2; $invoice->custom_surcharge_tax3 = $company->custom_surcharge_taxes3; $invoice->custom_surcharge_tax4 = $company->custom_surcharge_taxes4; - + return $this->itemResponse($invoice); } @@ -508,7 +508,7 @@ class InvoiceController extends BaseController return response(['message' => ctrans('texts.email_quota_exceeded_subject')], 400); } - if(in_array($request->action, ['auto_bill', 'mark_paid']) && $user->cannot('create', \App\Models\Payment::class)) { + if (in_array($request->action, ['auto_bill', 'mark_paid']) && $user->cannot('create', \App\Models\Payment::class)) { return response(['message' => ctrans('texts.not_authorized'), 'errors' => ['ids' => [ctrans('texts.not_authorized')]]], 422); } @@ -553,7 +553,7 @@ class InvoiceController extends BaseController }, 'print.pdf', ['Content-Type' => 'application/pdf']); } - if($action == 'template' && $user->can('view', $invoices->first())) { + if ($action == 'template' && $user->can('view', $invoices->first())) { $hash_or_response = $request->boolean('send_email') ? 'email sent' : \Illuminate\Support\Str::uuid(); @@ -571,10 +571,10 @@ class InvoiceController extends BaseController return response()->json(['message' => $hash_or_response], 200); } - if($action == 'set_payment_link' && $request->has('subscription_id')) { + if ($action == 'set_payment_link' && $request->has('subscription_id')) { $invoices->each(function ($invoice) use ($user, $request) { - if($user->can('edit', $invoice)) { + if ($user->can('edit', $invoice)) { $invoice->service()->setPaymentLink($request->subscription_id)->save(); } }); @@ -582,11 +582,11 @@ class InvoiceController extends BaseController return $this->listResponse(Invoice::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()); } - if(in_array($action, ['email','send_email'])) { - + if (in_array($action, ['email','send_email'])) { + $invoice = $invoices->first(); - if($user->can('edit', $invoice)){ + if ($user->can('edit', $invoice)) { $template = $request->input('email_type', $invoice->calculateTemplate('invoice')); @@ -837,7 +837,7 @@ class InvoiceController extends BaseController if (request()->input('inline') == 'true') { $headers = array_merge($headers, ['Content-Disposition' => 'inline']); } - + return response()->streamDownload(function () use ($file) { echo $file; }, $file_name, $headers); diff --git a/app/Http/Controllers/LicenseController.php b/app/Http/Controllers/LicenseController.php index 6321d98335..1179965a0e 100644 --- a/app/Http/Controllers/LicenseController.php +++ b/app/Http/Controllers/LicenseController.php @@ -88,14 +88,14 @@ class LicenseController extends BaseController nlog("License Check::"); nlog(config('ninja.environment')); nlog(request()->has('license_key')); - nlog(request()->input('license_key','No License Found')); + nlog(request()->input('license_key', 'No License Found')); /* Catch claim license requests */ if (config('ninja.environment') == 'selfhost' && request()->has('license_key')) { $license_key = trim(request()->input('license_key')); $product_id = 3; - if(substr($license_key, 0, 3) == 'v5_') { + if (substr($license_key, 0, 3) == 'v5_') { return $this->v5ClaimLicense($license_key, $product_id); } @@ -165,7 +165,7 @@ class LicenseController extends BaseController { $this->checkLicense(); - /* Catch claim license requests */ + /* Catch claim license requests */ if (config('ninja.environment') == 'selfhost') { nlog("Claiming v5 license"); diff --git a/app/Http/Controllers/MailgunController.php b/app/Http/Controllers/MailgunController.php index 261b270d40..4888bbb1d0 100644 --- a/app/Http/Controllers/MailgunController.php +++ b/app/Http/Controllers/MailgunController.php @@ -68,7 +68,7 @@ class MailgunController extends BaseController { $input = $request->all(); - + nlog($input); if (\abs(\time() - $request['signature']['timestamp']) > 15) { @@ -136,12 +136,13 @@ class MailgunController extends BaseController nlog('Failed: Message could not be parsed, because required parameters are missing. Please ensure contacting this api-endpoint with a store & notify operation instead of a forward operation!'); return response()->json(['message' => 'Failed. Missing Parameters. Use store and notify!'], 400); } - + /** @var \App\Models\Company $company */ $company = MultiDB::findAndSetDbByExpenseMailbox($input["recipient"]); - if(!$company) - return response()->json(['message' => 'Ok'], 200); // Fail gracefully + if (!$company) { + return response()->json(['message' => 'Ok'], 200); + } // Fail gracefully ProcessMailgunInboundWebhook::dispatch($input["sender"], $input["recipient"], $input["message-url"], $company)->delay(rand(2, 10)); diff --git a/app/Http/Controllers/MigrationController.php b/app/Http/Controllers/MigrationController.php index d51eb417fb..142f6e409d 100644 --- a/app/Http/Controllers/MigrationController.php +++ b/app/Http/Controllers/MigrationController.php @@ -261,7 +261,7 @@ class MigrationController extends BaseController { nlog('Starting Migration'); - if($request->has('silent_migration')) { + if ($request->has('silent_migration')) { $this->silent_migration = true; } @@ -307,7 +307,7 @@ class MigrationController extends BaseController $nmo->settings = $user->account->companies()->first()->settings; $nmo->to_user = $user; - if(!$this->silent_migration) { + if (!$this->silent_migration) { NinjaMailerJob::dispatch($nmo, true); } @@ -319,7 +319,7 @@ class MigrationController extends BaseController $nmo->settings = $user->account->companies()->first()->settings; $nmo->to_user = $user; - if(!$this->silent_migration) { + if (!$this->silent_migration) { NinjaMailerJob::dispatch($nmo, true); } @@ -341,7 +341,7 @@ class MigrationController extends BaseController $nmo->settings = $user->account->companies()->first(); $nmo->to_user = $user; - if(!$this->silent_migration) { + if (!$this->silent_migration) { NinjaMailerJob::dispatch($nmo, true); } diff --git a/app/Http/Controllers/OneTimeTokenController.php b/app/Http/Controllers/OneTimeTokenController.php index 489297bb20..4ed10d7e56 100644 --- a/app/Http/Controllers/OneTimeTokenController.php +++ b/app/Http/Controllers/OneTimeTokenController.php @@ -73,7 +73,7 @@ class OneTimeTokenController extends BaseController 'is_react' => $request->hasHeader('X-REACT') ? true : false, ]; - if($request->institution_id) { + if ($request->institution_id) { $data['institution_id'] = $request->institution_id; } diff --git a/app/Http/Controllers/PaymentController.php b/app/Http/Controllers/PaymentController.php index db03e8b6aa..5606b36d33 100644 --- a/app/Http/Controllers/PaymentController.php +++ b/app/Http/Controllers/PaymentController.php @@ -517,7 +517,7 @@ class PaymentController extends BaseController return response()->json(['message' => ctrans('texts.record_not_found')]); } - if($action == 'template' && $user->can('view', $payments->first())) { + if ($action == 'template' && $user->can('view', $payments->first())) { $hash_or_response = request()->boolean('send_email') ? 'email sent' : \Illuminate\Support\Str::uuid(); diff --git a/app/Http/Controllers/PostMarkController.php b/app/Http/Controllers/PostMarkController.php index 15660ac2e3..031c873733 100644 --- a/app/Http/Controllers/PostMarkController.php +++ b/app/Http/Controllers/PostMarkController.php @@ -273,8 +273,9 @@ class PostMarkController extends BaseController $input = $request->all(); - if (!$request->has('token') || $request->token != config('ninja.inbound_mailbox.inbound_webhook_token')) + if (!$request->has('token') || $request->token != config('ninja.inbound_mailbox.inbound_webhook_token')) { return response()->json(['message' => 'Unauthorized'], 403); + } if (!(array_key_exists("MessageStream", $input) && $input["MessageStream"] == "inbound") || !array_key_exists("To", $input) || !array_key_exists("From", $input) || !array_key_exists("MessageID", $input)) { nlog('Failed: Message could not be parsed, because required parameters are missing.'); @@ -324,8 +325,9 @@ class PostMarkController extends BaseController $inboundEngine->handleExpenseMailbox($inboundMail); } catch (\Exception $e) { - if ($e->getCode() == 409) + if ($e->getCode() == 409) { return response()->json(['message' => $e->getMessage()], 409); + } throw $e; } diff --git a/app/Http/Controllers/PreviewController.php b/app/Http/Controllers/PreviewController.php index bec13e63d5..c5b72ffc00 100644 --- a/app/Http/Controllers/PreviewController.php +++ b/app/Http/Controllers/PreviewController.php @@ -66,17 +66,17 @@ class PreviewController extends BaseController $entity_obj = $invitation->{$request->entity}; $entity_obj->fill($request->all()); - if(!$entity_obj->id) { + if (!$entity_obj->id) { $entity_obj->design_id = intval($this->decodePrimaryKey($settings->{$entity_prop."_design_id"})); $entity_obj->footer = empty($entity_obj->footer) ? $settings->{$entity_prop."_footer"} : $entity_obj->footer; $entity_obj->terms = empty($entity_obj->terms) ? $settings->{$entity_prop."_terms"} : $entity_obj->terms; $entity_obj->public_notes = empty($entity_obj->public_notes) ? $request->getClient()->public_notes : $entity_obj->public_notes; - + $entity_obj->custom_surcharge_tax1 = $client->company->custom_surcharge_taxes1; $entity_obj->custom_surcharge_tax2 = $client->company->custom_surcharge_taxes2; $entity_obj->custom_surcharge_tax3 = $client->company->custom_surcharge_taxes3; $entity_obj->custom_surcharge_tax4 = $client->company->custom_surcharge_taxes4; - + $invitation->setRelation($request->entity, $entity_obj); } @@ -117,7 +117,7 @@ class PreviewController extends BaseController { $start = microtime(true); - if($request->has('entity_type') && in_array($request->entity_type, ['payment_receipt', 'payment_refund', 'statement', 'delivery_note'])) { + if ($request->has('entity_type') && in_array($request->entity_type, ['payment_receipt', 'payment_refund', 'statement', 'delivery_note'])) { return $this->liveTemplate($request->all()); } @@ -145,7 +145,7 @@ class PreviewController extends BaseController public function show(ShowPreviewRequest $request) { - if($request->input('design.is_template')) { + if ($request->input('design.is_template')) { return $this->template(); } @@ -154,8 +154,9 @@ class PreviewController extends BaseController ! empty(request()->input('entity')) && ! empty(request()->input('entity_id'))) { - if($request->input('entity') == 'purchase_order') + if ($request->input('entity') == 'purchase_order') { return app(\App\Http\Controllers\PreviewPurchaseOrderController::class)->show($request); + } $design_object = json_decode(json_encode(request()->input('design'))); @@ -180,7 +181,7 @@ class PreviewController extends BaseController App::setLocale($entity_obj->client->preferredLocale()); $t->replace(Ninja::transformTranslations($entity_obj->client->getMergedSettings())); - if($entity_obj->client) { + if ($entity_obj->client) { $html = new HtmlEngine($entity_obj->invitations()->first()); } else { $html = new VendorHtmlEngine($entity_obj->invitations()->first()); @@ -270,14 +271,14 @@ class PreviewController extends BaseController try { - if(isset($request_data['settings']) && is_array($request_data['settings'])) { + if (isset($request_data['settings']) && is_array($request_data['settings'])) { $ts->setSettings(json_decode(json_encode($request_data['settings']))); } $ts->setCompany($company) ->compose() ->mock(); - } catch(SyntaxError $e) { + } catch (SyntaxError $e) { // return response()->json(['message' => 'Twig syntax is invalid.', 'errors' => new \stdClass], 422); } @@ -302,13 +303,13 @@ class PreviewController extends BaseController $ts = (new TemplateService()); try { - + $ts->setCompany($company) ->setTemplate($design_object) ->mock(); - } catch(SyntaxError $e) { - } catch(\Exception $e) { + } catch (SyntaxError $e) { + } catch (\Exception $e) { return response()->json(['message' => 'invalid data access', 'errors' => ['design.design.body' => $e->getMessage()]], 422); } @@ -501,7 +502,7 @@ class PreviewController extends BaseController ->build(); DB::connection($company->db)->rollBack(); - } catch(\Exception $e) { + } catch (\Exception $e) { DB::connection($company->db)->rollBack(); return response()->json(['message' => $e->getMessage()], 400); } diff --git a/app/Http/Controllers/PreviewPurchaseOrderController.php b/app/Http/Controllers/PreviewPurchaseOrderController.php index 0d4d16f5b9..922025c88e 100644 --- a/app/Http/Controllers/PreviewPurchaseOrderController.php +++ b/app/Http/Controllers/PreviewPurchaseOrderController.php @@ -185,7 +185,7 @@ class PreviewPurchaseOrderController extends BaseController $entity_obj = $invitation->purchase_order; $entity_obj->fill($request->all()); - if(!$entity_obj->id) { + if (!$entity_obj->id) { $entity_obj->design_id = intval($this->decodePrimaryKey($settings->{"purchase_order_design_id"})); $entity_obj->footer = empty($entity_obj->footer) ? $settings->{"purchase_order_footer"} : $entity_obj->footer; $entity_obj->terms = empty($entity_obj->terms) ? $settings->{"purchase_order_terms"} : $entity_obj->terms; diff --git a/app/Http/Controllers/ProductController.php b/app/Http/Controllers/ProductController.php index e60351e67b..8e958ccd24 100644 --- a/app/Http/Controllers/ProductController.php +++ b/app/Http/Controllers/ProductController.php @@ -475,7 +475,7 @@ class ProductController extends BaseController $products = Product::withTrashed()->whereIn('id', $ids); - if($action == 'set_tax_id') { + if ($action == 'set_tax_id') { $tax_id = $request->input('tax_id'); diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index b41d043b36..60ea0724f7 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -11,7 +11,6 @@ namespace App\Http\Controllers; - use App\Models\Account; use App\Models\Invoice; use App\Models\Project; @@ -507,7 +506,7 @@ class ProjectController extends BaseController $projects = Project::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get(); - if($action == 'template' && $user->can('view', $projects->first())) { + if ($action == 'template' && $user->can('view', $projects->first())) { $hash_or_response = $request->boolean('send_email') ? 'email sent' : \Illuminate\Support\Str::uuid(); diff --git a/app/Http/Controllers/PurchaseOrderController.php b/app/Http/Controllers/PurchaseOrderController.php index 10cbc1635f..4e6f584f45 100644 --- a/app/Http/Controllers/PurchaseOrderController.php +++ b/app/Http/Controllers/PurchaseOrderController.php @@ -526,7 +526,7 @@ class PurchaseOrderController extends BaseController }, 'print.pdf', ['Content-Type' => 'application/pdf']); } - if($action == 'template' && $user->can('view', $purchase_orders->first())) { + if ($action == 'template' && $user->can('view', $purchase_orders->first())) { $hash_or_response = $request->boolean('send_email') ? 'email sent' : \Illuminate\Support\Str::uuid(); diff --git a/app/Http/Controllers/QuoteController.php b/app/Http/Controllers/QuoteController.php index 3dc883ecac..52213d8082 100644 --- a/app/Http/Controllers/QuoteController.php +++ b/app/Http/Controllers/QuoteController.php @@ -585,7 +585,7 @@ class QuoteController extends BaseController } - if($action == 'template' && $user->can('view', $quotes->first())) { + if ($action == 'template' && $user->can('view', $quotes->first())) { $hash_or_response = $request->boolean('send_email') ? 'email sent' : \Illuminate\Support\Str::uuid(); diff --git a/app/Http/Controllers/RecurringInvoiceController.php b/app/Http/Controllers/RecurringInvoiceController.php index 82f867071c..4bc5143e9e 100644 --- a/app/Http/Controllers/RecurringInvoiceController.php +++ b/app/Http/Controllers/RecurringInvoiceController.php @@ -423,7 +423,7 @@ class RecurringInvoiceController extends BaseController } $recurring_invoices = RecurringInvoice::withTrashed()->find($request->ids); - + if ($request->action == 'bulk_update' && $user->can('edit', $recurring_invoices->first())) { $recurring_invoices = RecurringInvoice::withTrashed() @@ -436,10 +436,10 @@ class RecurringInvoiceController extends BaseController } - if($request->action == 'set_payment_link' && $request->has('subscription_id')) { + if ($request->action == 'set_payment_link' && $request->has('subscription_id')) { $recurring_invoices->each(function ($invoice) use ($user, $request) { - if($user->can('edit', $invoice)) { + if ($user->can('edit', $invoice)) { $invoice->service()->setPaymentLink($request->subscription_id)->save(); } }); diff --git a/app/Http/Controllers/Reports/InvoiceReportController.php b/app/Http/Controllers/Reports/InvoiceReportController.php index 65ab27cb79..ad64fc5ea7 100644 --- a/app/Http/Controllers/Reports/InvoiceReportController.php +++ b/app/Http/Controllers/Reports/InvoiceReportController.php @@ -65,7 +65,7 @@ class InvoiceReportController extends BaseController { /** @var \App\Models\User $user */ $user = auth()->user(); -nlog($request->all()); + nlog($request->all()); if ($request->has('send_email') && $request->get('send_email') && $request->missing('output')) { SendToAdmin::dispatch($user->company(), $request->all(), InvoiceExport::class, $this->filename); diff --git a/app/Http/Controllers/Reports/ReportExportController.php b/app/Http/Controllers/Reports/ReportExportController.php index ae3752a9e3..941083de92 100644 --- a/app/Http/Controllers/Reports/ReportExportController.php +++ b/app/Http/Controllers/Reports/ReportExportController.php @@ -32,7 +32,7 @@ class ReportExportController extends BaseController $report = Cache::get($hash); - if(!$report) { + if (!$report) { return response()->json(['message' => 'Still working.....'], 409); } diff --git a/app/Http/Controllers/Reports/ReportPreviewController.php b/app/Http/Controllers/Reports/ReportPreviewController.php index 2eb4eea345..f91b4f1d16 100644 --- a/app/Http/Controllers/Reports/ReportPreviewController.php +++ b/app/Http/Controllers/Reports/ReportPreviewController.php @@ -30,7 +30,7 @@ class ReportPreviewController extends BaseController $report = Cache::get($hash); - if(!$report) { + if (!$report) { return response()->json(['message' => 'Still working.....'], 409); } diff --git a/app/Http/Controllers/SearchController.php b/app/Http/Controllers/SearchController.php index da76ad087c..2cd4ede9ea 100644 --- a/app/Http/Controllers/SearchController.php +++ b/app/Http/Controllers/SearchController.php @@ -27,17 +27,17 @@ class SearchController extends Controller private array $invoices = []; private array $quotes = []; - + public function __invoke(GenericSearchRequest $request) { - if(config('scout.driver') == 'elastic') { - try{ + if (config('scout.driver') == 'elastic') { + try { return $this->search($request->input('search', '*')); - } catch(\Exception $e) { - nlog("elk down?" . $e->getMessage()); + } catch (\Exception $e) { + nlog("elk down?" . $e->getMessage()); } } - + /** @var \App\Models\User $user */ $user = auth()->user(); @@ -57,7 +57,7 @@ class SearchController extends Controller { $user = auth()->user(); $company = $user->company(); - + \Illuminate\Support\Facades\App::setLocale($company->locale()); $elastic = ClientBuilder::fromConfig(config('elastic.client.connections.default')); @@ -101,12 +101,13 @@ class SearchController extends Controller private function mapResults(array $results) { - foreach($results as $result) { - switch($result['_index']) { + foreach ($results as $result) { + switch ($result['_index']) { case 'clients': - if($result['_source']['is_deleted']) //do not return deleted results + if ($result['_source']['is_deleted']) { //do not return deleted results break; + } $this->clients[] = [ 'name' => $result['_source']['name'], @@ -118,9 +119,10 @@ class SearchController extends Controller break; case 'invoices': - if ($result['_source']['is_deleted']) //do not return deleted invoices + if ($result['_source']['is_deleted']) { //do not return deleted invoices break; - + } + $this->invoices[] = [ 'name' => $result['_source']['name'], @@ -131,8 +133,9 @@ class SearchController extends Controller break; case 'client_contacts': - if($result['_source']['__soft_deleted']) // do not return deleted contacts + if ($result['_source']['__soft_deleted']) { // do not return deleted contacts break; + } $this->client_contacts[] = [ 'name' => $result['_source']['name'], @@ -172,7 +175,7 @@ class SearchController extends Controller ->take(1000) ->get(); - foreach($clients as $client) { + foreach ($clients as $client) { $this->clients[] = [ 'name' => $client->present()->name(), 'type' => '/client', @@ -210,7 +213,7 @@ class SearchController extends Controller ->take(3000) ->get(); - foreach($invoices as $invoice) { + foreach ($invoices as $invoice) { $this->invoices[] = [ 'name' => $invoice->client->present()->name() . ' - ' . $invoice->number, 'type' => '/invoice', @@ -295,11 +298,11 @@ class SearchController extends Controller $data = []; - foreach($paths as $key => $value) { + foreach ($paths as $key => $value) { $translation = ''; - foreach(explode(",", $key) as $transkey) { + foreach (explode(",", $key) as $transkey) { $translation .= ctrans("texts.{$transkey}")." "; } diff --git a/app/Http/Controllers/SelfUpdateController.php b/app/Http/Controllers/SelfUpdateController.php index cebdf9d698..583a9b7ab2 100644 --- a/app/Http/Controllers/SelfUpdateController.php +++ b/app/Http/Controllers/SelfUpdateController.php @@ -67,13 +67,13 @@ class SelfUpdateController extends BaseController nlog("Download URL"); nlog($this->getDownloadUrl()); - - if(strlen($this->version) == 1){ + + if (strlen($this->version) == 1) { nlog("version server down, trying github"); $this->version = trim(file_get_contents('https://raw.githubusercontent.com/invoiceninja/invoiceninja/refs/heads/v5-develop/VERSION.txt')); } - if(!is_array($file_headers)) { + if (!is_array($file_headers)) { nlog($file_headers); return response()->json(['message' => 'There was a problem reaching the update server, please try again in a little while.'], 410); } @@ -87,7 +87,7 @@ class SelfUpdateController extends BaseController if (copy($this->getDownloadUrl(), storage_path("app/{$this->filename}"))) { nlog('Copied file from URL'); } - } catch(\Exception $e) { + } catch (\Exception $e) { nlog($e->getMessage()); return response()->json(['message' => 'File exists on the server, however there was a problem downloading and copying to the local filesystem'], 500); } @@ -114,7 +114,7 @@ class SelfUpdateController extends BaseController } } - if(Storage::disk('base')->directoryExists('resources/lang')) { + if (Storage::disk('base')->directoryExists('resources/lang')) { Storage::disk('base')->deleteDirectory('resources/lang'); } @@ -193,7 +193,7 @@ class SelfUpdateController extends BaseController public function checkVersion() { - if(Ninja::isHosted()) { + if (Ninja::isHosted()) { return '5.10.SaaS'; } diff --git a/app/Http/Controllers/StaticController.php b/app/Http/Controllers/StaticController.php index 60294a2a4a..6e744edfe0 100644 --- a/app/Http/Controllers/StaticController.php +++ b/app/Http/Controllers/StaticController.php @@ -59,7 +59,7 @@ class StaticController extends BaseController $response_data = Statics::company($user->getLocale() ?? $user->company()->getLocale()); - if(request()->has('einvoice')) { + if (request()->has('einvoice')) { $schema = new Schema(); $response_data['einvoice_schema'] = $schema('Peppol'); diff --git a/app/Http/Controllers/StripeConnectController.php b/app/Http/Controllers/StripeConnectController.php index 05ae6b4bf9..03494b377c 100644 --- a/app/Http/Controllers/StripeConnectController.php +++ b/app/Http/Controllers/StripeConnectController.php @@ -81,11 +81,11 @@ class StripeConnectController extends BaseController } - if(!$response) { + if (!$response) { return view('auth.connect.access_denied'); } - if(!$request->getTokenContent()) { + if (!$request->getTokenContent()) { return view('auth.connect.session_expired'); } @@ -127,16 +127,16 @@ class StripeConnectController extends BaseController $stripe = $company_gateway->driver()->init(); $a = \Stripe\Account::retrieve($response->stripe_user_id, $stripe->stripe_connect_auth); - if($a->business_name ?? false) { + if ($a->business_name ?? false) { $company_gateway->label = substr("Stripe - {$a->business_name}", 0, 250); $company_gateway->save(); } - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: StripeConnectController::" . $e->getMessage()); nlog("could not harvest stripe company name"); } - if(isset($request->getTokenContent()['is_react']) && $request->getTokenContent()['is_react']) { + if (isset($request->getTokenContent()['is_react']) && $request->getTokenContent()['is_react']) { $redirect_uri = config('ninja.react_url').'/#/settings/online_payments'; } else { $redirect_uri = config('ninja.app_url'); diff --git a/app/Http/Controllers/SubdomainController.php b/app/Http/Controllers/SubdomainController.php index d92130a9ad..d5ee1640eb 100644 --- a/app/Http/Controllers/SubdomainController.php +++ b/app/Http/Controllers/SubdomainController.php @@ -29,7 +29,7 @@ class SubdomainController extends BaseController $user = auth()->user(); $company = $user->company(); - if($company->subdomain == trim(request()->input('subdomain'))){ + if ($company->subdomain == trim(request()->input('subdomain'))) { return response()->json(['message' => 'Current subdomain name.'], 200); } diff --git a/app/Http/Controllers/SubscriptionController.php b/app/Http/Controllers/SubscriptionController.php index 23d162bce7..3b0613bf24 100644 --- a/app/Http/Controllers/SubscriptionController.php +++ b/app/Http/Controllers/SubscriptionController.php @@ -474,7 +474,7 @@ class SubscriptionController extends BaseController $subscriptions = Subscription::withTrashed()->find($request->ids); - if(in_array($request->action, ['assign_invoice'])) { + if (in_array($request->action, ['assign_invoice'])) { $subscriptions->each(function ($subscription, $key) use ($request, $user) { if ($user->can('edit', $subscription)) { diff --git a/app/Http/Controllers/TaskController.php b/app/Http/Controllers/TaskController.php index 97be17e243..79a728c825 100644 --- a/app/Http/Controllers/TaskController.php +++ b/app/Http/Controllers/TaskController.php @@ -281,7 +281,7 @@ class TaskController extends BaseController $task = $this->task_repo->triggeredActions($request, $task); if ($task->status_order != $old_task_status_order) { - // if ($task->status_order != $old_task->status_order) { + // if ($task->status_order != $old_task->status_order) { $this->task_repo->sortStatuses($task); } @@ -512,7 +512,7 @@ class TaskController extends BaseController $tasks = Task::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get(); - if($action == 'template' && $user->can('view', $tasks->first())) { + if ($action == 'template' && $user->can('view', $tasks->first())) { $hash_or_response = request()->boolean('send_email') ? 'email sent' : \Illuminate\Support\Str::uuid(); diff --git a/app/Http/Controllers/TaxRateController.php b/app/Http/Controllers/TaxRateController.php index 640bf1c79e..128051112e 100644 --- a/app/Http/Controllers/TaxRateController.php +++ b/app/Http/Controllers/TaxRateController.php @@ -434,12 +434,12 @@ class TaxRateController extends BaseController $tax_rates->each(function ($tax_rate, $key) use ($action, $user) { if ($user->can('edit', $tax_rate)) { - if(in_array($action, ['archive','delete'])) { + if (in_array($action, ['archive','delete'])) { $settings = $user->company()->settings; - foreach(['tax_name1','tax_name2','tax_name3'] as $tax_name) { + foreach (['tax_name1','tax_name2','tax_name3'] as $tax_name) { - if($settings->{$tax_name} == $tax_rate->name) { + if ($settings->{$tax_name} == $tax_rate->name) { $settings->{$tax_name} = ''; $settings->{str_replace("name", "rate", $tax_name)} = ''; } diff --git a/app/Http/Controllers/TemplatePreviewController.php b/app/Http/Controllers/TemplatePreviewController.php index 4d465ce614..7f7c8e5fb1 100644 --- a/app/Http/Controllers/TemplatePreviewController.php +++ b/app/Http/Controllers/TemplatePreviewController.php @@ -34,7 +34,7 @@ class TemplatePreviewController extends BaseController $report = Storage::disk(config('filesystems.default'))->exists($this->path_prefix.$hash.$this->path_suffix); - if(!$report) { + if (!$report) { return response()->json(['message' => 'Still working.....'], 409); } diff --git a/app/Http/Controllers/TwilioController.php b/app/Http/Controllers/TwilioController.php index f7366d0b8f..1f78ca2492 100644 --- a/app/Http/Controllers/TwilioController.php +++ b/app/Http/Controllers/TwilioController.php @@ -41,13 +41,13 @@ class TwilioController extends BaseController /** @var \App\Models\User $user */ $user = auth()->user(); - if(!$user->email_verified_at) { + if (!$user->email_verified_at) { return response()->json(['message' => 'Please verify your email address before verifying your phone number'], 400); } $account = $user->company()->account; - if(!$this->checkPhoneValidity($request->phone)) { + if (!$this->checkPhoneValidity($request->phone)) { return response()->json(['message' => 'This phone number is not supported'], 400); } @@ -67,7 +67,7 @@ class TwilioController extends BaseController ->services(config('ninja.twilio_verify_sid')) ->verifications ->create($request->phone, "sms"); - } catch(\Exception $e) { + } catch (\Exception $e) { return response()->json(['message' => 'Invalid phone number please use + country code + number ie. +15552343334'], 400); } @@ -80,9 +80,9 @@ class TwilioController extends BaseController private function checkPhoneValidity($phone) { - foreach($this->invalid_codes as $code) { + foreach ($this->invalid_codes as $code) { - if(stripos($phone, $code) !== false) { + if (stripos($phone, $code) !== false) { return false; } @@ -155,12 +155,12 @@ class TwilioController extends BaseController return response()->json(['message' => 'Unable to retrieve user.'], 400); } - if(!$user->email_verified_at) { + if (!$user->email_verified_at) { return response()->json(['message' => 'Please verify your email address before verifying your phone number'], 400); } - if(!$user->first_name || !$user->last_name) { + if (!$user->first_name || !$user->last_name) { return response()->json(['message' => 'Please update your first and/or last name in the User Details before verifying your number.'], 400); } @@ -179,7 +179,7 @@ class TwilioController extends BaseController ->services(config('ninja.twilio_verify_sid')) ->verifications ->create($user->phone, "sms"); - } catch(\Exception $e) { + } catch (\Exception $e) { return response()->json(['message' => 'Invalid phone number on file, we are unable to reset. Please contact support.'], 400); } diff --git a/app/Http/Controllers/TwoFactorController.php b/app/Http/Controllers/TwoFactorController.php index 1707ff2d9e..34641dda06 100644 --- a/app/Http/Controllers/TwoFactorController.php +++ b/app/Http/Controllers/TwoFactorController.php @@ -30,7 +30,7 @@ class TwoFactorController extends BaseController if ($user->google_2fa_secret) { return response()->json(['message' => '2FA already enabled'], 400); - } elseif(Ninja::isSelfHost()) { + } elseif (Ninja::isSelfHost()) { } elseif (! $user->phone) { return response()->json(['message' => ctrans('texts.set_phone_for_two_factor')], 400); diff --git a/app/Http/Controllers/VendorController.php b/app/Http/Controllers/VendorController.php index e0c2e20e5b..605db2a7ec 100644 --- a/app/Http/Controllers/VendorController.php +++ b/app/Http/Controllers/VendorController.php @@ -587,15 +587,15 @@ class VendorController extends BaseController } - /** - * Update the specified resource in storage. - * - * @param PurgeVendorRequest $request - * @param Vendor $vendor - * @param string $mergeable_vendor - * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response - * - */ + /** + * Update the specified resource in storage. + * + * @param PurgeVendorRequest $request + * @param Vendor $vendor + * @param string $mergeable_vendor + * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response + * + */ public function merge(PurgeVendorRequest $request, Vendor $vendor, string $mergeable_vendor) { @@ -611,7 +611,7 @@ class VendorController extends BaseController return response()->json(['message' => "Vendor not found"], 400); } - if($m_vendor->id == $vendor->id) { + if ($m_vendor->id == $vendor->id) { return response()->json(['message' => "Attempting to merge the same vendor is not possible."], 400); } diff --git a/app/Http/Controllers/VendorPortal/VendorContactController.php b/app/Http/Controllers/VendorPortal/VendorContactController.php index 5fcff7ed22..8e89d34b5e 100644 --- a/app/Http/Controllers/VendorPortal/VendorContactController.php +++ b/app/Http/Controllers/VendorPortal/VendorContactController.php @@ -53,8 +53,9 @@ class VendorContactController extends Controller public function edit(VendorContact $vendor_contact) { - if(!$vendor_contact->vendor->country_id) + if (!$vendor_contact->vendor->country_id) { $vendor_contact->vendor->country_id = auth()->guard('vendor')->user()->company->country()->id ?? 840; + } return $this->render('vendor_profile.edit', [ 'contact' => $vendor_contact, diff --git a/app/Http/Middleware/PasswordProtection.php b/app/Http/Middleware/PasswordProtection.php index 1782269216..ce506d2c38 100644 --- a/app/Http/Middleware/PasswordProtection.php +++ b/app/Http/Middleware/PasswordProtection.php @@ -59,7 +59,7 @@ class PasswordProtection Cache::put(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in', Str::random(64), $timeout); return $next($request); - } elseif(strlen(auth()->user()->oauth_provider_id) > 2 && !auth()->user()->company()->oauth_password_required) { + } elseif (strlen(auth()->user()->oauth_provider_id) > 2 && !auth()->user()->company()->oauth_password_required) { return $next($request); } elseif ($request->header('X-API-OAUTH-PASSWORD') && strlen($request->header('X-API-OAUTH-PASSWORD')) > 1) { //user is attempting to reauth with OAuth - check the token value @@ -92,7 +92,7 @@ class PasswordProtection } elseif (auth()->user()->oauth_provider_id == 'microsoft') { try { $payload = json_decode(base64_decode(str_replace('_', '/', str_replace('-', '+', explode('.', request()->header('X-API-OAUTH-PASSWORD'))[1])))); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: PasswordProtection::" . $e->getMessage()); nlog("could not decode microsoft response"); return response()->json(['message' => 'Could not decode the response from Microsoft'], 412); diff --git a/app/Http/Middleware/QueryLogging.php b/app/Http/Middleware/QueryLogging.php index 2bafda5c41..5ee6460a8a 100644 --- a/app/Http/Middleware/QueryLogging.php +++ b/app/Http/Middleware/QueryLogging.php @@ -78,7 +78,7 @@ class QueryLogging if ($request->hasHeader('X-CLIENT-PLATFORM')) { $platform = $request->header('X-CLIENT-PLATFORM'); - } elseif($request->hasHeader('X-React')) { + } elseif ($request->hasHeader('X-React')) { $platform = 'react'; } diff --git a/app/Http/Middleware/ThrottleRequestsWithPredis.php b/app/Http/Middleware/ThrottleRequestsWithPredis.php index c294c6c579..bf1b0d976f 100644 --- a/app/Http/Middleware/ThrottleRequestsWithPredis.php +++ b/app/Http/Middleware/ThrottleRequestsWithPredis.php @@ -47,10 +47,10 @@ class ThrottleRequestsWithPredis extends \Illuminate\Routing\Middleware\Throttle /** @phpstan-ignore-next-line */ public function __construct(RateLimiter $limiter, Redis $redis) { - + /** @phpstan-ignore-next-line */ parent::__construct($limiter); /** @phpstan-ignore-line */ - + /** @phpstan-ignore-next-line */ $this->redis = \Illuminate\Support\Facades\Redis::connection('sentinel-cache'); /** @phpstan-ignore-line */ } diff --git a/app/Http/Requests/Activity/ShowActivityRequest.php b/app/Http/Requests/Activity/ShowActivityRequest.php index 41e9808177..63609e2e85 100644 --- a/app/Http/Requests/Activity/ShowActivityRequest.php +++ b/app/Http/Requests/Activity/ShowActivityRequest.php @@ -40,7 +40,7 @@ class ShowActivityRequest extends Request { $input = $this->all(); - if(isset($input['entity_id'])) { + if (isset($input['entity_id'])) { $input['entity_id'] = $this->decodePrimaryKey($input['entity_id']); } diff --git a/app/Http/Requests/Activity/StoreNoteRequest.php b/app/Http/Requests/Activity/StoreNoteRequest.php index 54c7c79180..cc47a47058 100644 --- a/app/Http/Requests/Activity/StoreNoteRequest.php +++ b/app/Http/Requests/Activity/StoreNoteRequest.php @@ -17,7 +17,6 @@ use Illuminate\Validation\Rule; class StoreNoteRequest extends Request { - /** * Determine if the user is authorized to make this request. * @@ -46,7 +45,7 @@ class StoreNoteRequest extends Request { $input = $this->all(); - if(isset($input['entity_id']) && $input['entity_id'] != null) { + if (isset($input['entity_id']) && $input['entity_id'] != null) { $input['entity_id'] = $this->decodePrimaryKey($input['entity_id']); } @@ -69,7 +68,7 @@ class StoreNoteRequest extends Request public function getEntity() { - if(!$this->entity) { + if (!$this->entity) { return false; } diff --git a/app/Http/Requests/BankIntegration/UploadBankIntegrationRequest.php b/app/Http/Requests/BankIntegration/UploadBankIntegrationRequest.php index 8d71c0be7c..bb537464c9 100644 --- a/app/Http/Requests/BankIntegration/UploadBankIntegrationRequest.php +++ b/app/Http/Requests/BankIntegration/UploadBankIntegrationRequest.php @@ -53,7 +53,7 @@ class UploadBankIntegrationRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/BankTransaction/UploadBankTransactionRequest.php b/app/Http/Requests/BankTransaction/UploadBankTransactionRequest.php index bdb87aa9c1..32024a3538 100644 --- a/app/Http/Requests/BankTransaction/UploadBankTransactionRequest.php +++ b/app/Http/Requests/BankTransaction/UploadBankTransactionRequest.php @@ -53,7 +53,7 @@ class UploadBankTransactionRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/Chart/ShowCalculatedFieldRequest.php b/app/Http/Requests/Chart/ShowCalculatedFieldRequest.php index 3aa6271dc2..72d27fb47f 100644 --- a/app/Http/Requests/Chart/ShowCalculatedFieldRequest.php +++ b/app/Http/Requests/Chart/ShowCalculatedFieldRequest.php @@ -52,7 +52,7 @@ class ShowCalculatedFieldRequest extends Request $input = $this->all(); - if(isset($input['date_range'])) { + if (isset($input['date_range'])) { $dates = $this->calculateStartAndEndDates($input, $user->company()); $input['start_date'] = $dates[0]; $input['end_date'] = $dates[1]; @@ -66,7 +66,7 @@ class ShowCalculatedFieldRequest extends Request $input['end_date'] = now()->format('Y-m-d'); } - if(isset($input['period']) && $input['period'] == 'previous') { + if (isset($input['period']) && $input['period'] == 'previous') { $dates = $this->calculatePreviousPeriodStartAndEndDates($input, $user->company()); $input['start_date'] = $dates[0]; $input['end_date'] = $dates[1]; diff --git a/app/Http/Requests/Chart/ShowChartRequest.php b/app/Http/Requests/Chart/ShowChartRequest.php index 05d0495f32..1db3a5bd96 100644 --- a/app/Http/Requests/Chart/ShowChartRequest.php +++ b/app/Http/Requests/Chart/ShowChartRequest.php @@ -48,7 +48,7 @@ class ShowChartRequest extends Request $input = $this->all(); - if(isset($input['date_range'])) { + if (isset($input['date_range'])) { $dates = $this->calculateStartAndEndDates($input, $user->company()); $input['start_date'] = $dates[0]; $input['end_date'] = $dates[1]; diff --git a/app/Http/Requests/Client/UploadClientRequest.php b/app/Http/Requests/Client/UploadClientRequest.php index fbfef061cc..d483473edf 100644 --- a/app/Http/Requests/Client/UploadClientRequest.php +++ b/app/Http/Requests/Client/UploadClientRequest.php @@ -53,7 +53,7 @@ class UploadClientRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/ClientGatewayToken/StoreClientGatewayTokenRequest.php b/app/Http/Requests/ClientGatewayToken/StoreClientGatewayTokenRequest.php index cfcf21a19d..d076cee8b7 100644 --- a/app/Http/Requests/ClientGatewayToken/StoreClientGatewayTokenRequest.php +++ b/app/Http/Requests/ClientGatewayToken/StoreClientGatewayTokenRequest.php @@ -31,7 +31,7 @@ class StoreClientGatewayTokenRequest extends Request public function rules() { - + /** @var \App\Models\User $user */ $user = auth()->user(); diff --git a/app/Http/Requests/ClientGatewayToken/UpdateClientGatewayTokenRequest.php b/app/Http/Requests/ClientGatewayToken/UpdateClientGatewayTokenRequest.php index 3f8de957c0..1330ddf298 100644 --- a/app/Http/Requests/ClientGatewayToken/UpdateClientGatewayTokenRequest.php +++ b/app/Http/Requests/ClientGatewayToken/UpdateClientGatewayTokenRequest.php @@ -46,13 +46,14 @@ class UpdateClientGatewayTokenRequest extends Request { $input = $this->all(); - if(isset($input['client_id'])) + if (isset($input['client_id'])) { unset($input['client_id']); + } if (isset($input['company_gateway_id'])) { unset($input['company_gateway_id']); } - + $input = $this->decodePrimaryKeys($input); $this->replace($input); diff --git a/app/Http/Requests/ClientPortal/Invoices/ProcessInvoicesInBulkRequest.php b/app/Http/Requests/ClientPortal/Invoices/ProcessInvoicesInBulkRequest.php index 21a91571d6..a4ddb292f1 100644 --- a/app/Http/Requests/ClientPortal/Invoices/ProcessInvoicesInBulkRequest.php +++ b/app/Http/Requests/ClientPortal/Invoices/ProcessInvoicesInBulkRequest.php @@ -36,7 +36,7 @@ class ProcessInvoicesInBulkRequest extends FormRequest { $input = $this->all(); - if(isset($input['invoices'])) { + if (isset($input['invoices'])) { $input['invoices'] = array_unique($input['invoices']); } diff --git a/app/Http/Requests/ClientPortal/Payments/PaymentResponseRequest.php b/app/Http/Requests/ClientPortal/Payments/PaymentResponseRequest.php index 43daef2901..8c5f1658f3 100644 --- a/app/Http/Requests/ClientPortal/Payments/PaymentResponseRequest.php +++ b/app/Http/Requests/ClientPortal/Payments/PaymentResponseRequest.php @@ -56,7 +56,7 @@ class PaymentResponseRequest extends FormRequest ]); } - if($this->has('payment_method_id')) { + if ($this->has('payment_method_id')) { $this->merge([ 'payment_method_id' => preg_replace('~\D~', '', $this->payment_method_id), diff --git a/app/Http/Requests/Company/UpdateCompanyRequest.php b/app/Http/Requests/Company/UpdateCompanyRequest.php index c1bb0f8d23..45a724c879 100644 --- a/app/Http/Requests/Company/UpdateCompanyRequest.php +++ b/app/Http/Requests/Company/UpdateCompanyRequest.php @@ -33,7 +33,7 @@ class UpdateCompanyRequest extends Request 'portal_custom_css', 'portal_custom_head' ]; - + /** * Determine if the user is authorized to make this request. * @@ -48,7 +48,7 @@ class UpdateCompanyRequest extends Request public function rules() { - + /** @var \App\Models\User $user */ $user = auth()->user(); @@ -211,14 +211,14 @@ class UpdateCompanyRequest extends Request return $settings; } - + /** * forceScheme * * @param string $url * @return string */ - private function forceScheme(string $url): string + private function forceScheme(string $url): string { return stripos($url, 'http') !== false ? $url : "https://{$url}"; } diff --git a/app/Http/Requests/CompanyUser/UpdateCompanyUserRequest.php b/app/Http/Requests/CompanyUser/UpdateCompanyUserRequest.php index b32cf382ed..f13776665a 100644 --- a/app/Http/Requests/CompanyUser/UpdateCompanyUserRequest.php +++ b/app/Http/Requests/CompanyUser/UpdateCompanyUserRequest.php @@ -40,7 +40,7 @@ class UpdateCompanyUserRequest extends Request { $input = $this->all(); - if(isset($input['company_user']['user'])) { + if (isset($input['company_user']['user'])) { unset($input['company_user']['user']); } diff --git a/app/Http/Requests/Credit/StoreCreditRequest.php b/app/Http/Requests/Credit/StoreCreditRequest.php index 75827b87ae..4023343e58 100644 --- a/app/Http/Requests/Credit/StoreCreditRequest.php +++ b/app/Http/Requests/Credit/StoreCreditRequest.php @@ -100,7 +100,7 @@ class StoreCreditRequest extends Request $input['design_id'] = $this->decodePrimaryKey($input['design_id']); } - if(isset($input['partial']) && $input['partial'] == 0) { + if (isset($input['partial']) && $input['partial'] == 0) { $input['partial_due_date'] = null; } @@ -113,7 +113,7 @@ class StoreCreditRequest extends Request if (array_key_exists('exchange_rate', $input) && is_null($input['exchange_rate'])) { $input['exchange_rate'] = 1; } - + if (isset($input['footer']) && $this->hasHeader('X-REACT')) { $input['footer'] = str_replace("\n", "", $input['footer']); } diff --git a/app/Http/Requests/Credit/UpdateCreditRequest.php b/app/Http/Requests/Credit/UpdateCreditRequest.php index 117d521360..4915ca1f6e 100644 --- a/app/Http/Requests/Credit/UpdateCreditRequest.php +++ b/app/Http/Requests/Credit/UpdateCreditRequest.php @@ -93,7 +93,7 @@ class UpdateCreditRequest extends Request $input = $this->decodePrimaryKeys($input); - if(isset($input['partial']) && $input['partial'] == 0) { + if (isset($input['partial']) && $input['partial'] == 0) { $input['partial_due_date'] = null; } diff --git a/app/Http/Requests/Credit/UploadCreditRequest.php b/app/Http/Requests/Credit/UploadCreditRequest.php index 25a416cb1d..b3327f4e5b 100644 --- a/app/Http/Requests/Credit/UploadCreditRequest.php +++ b/app/Http/Requests/Credit/UploadCreditRequest.php @@ -53,7 +53,7 @@ class UploadCreditRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/Design/StoreDesignRequest.php b/app/Http/Requests/Design/StoreDesignRequest.php index c9f1039a70..286f05a816 100644 --- a/app/Http/Requests/Design/StoreDesignRequest.php +++ b/app/Http/Requests/Design/StoreDesignRequest.php @@ -88,7 +88,7 @@ class StoreDesignRequest extends Request $input['design']['body'] = ''; } - if(array_key_exists('entities', $input)) { + if (array_key_exists('entities', $input)) { $user_entities = explode(",", $input['entities']); $e = []; diff --git a/app/Http/Requests/Design/UpdateDesignRequest.php b/app/Http/Requests/Design/UpdateDesignRequest.php index 9fae31701d..7b97c2bcad 100644 --- a/app/Http/Requests/Design/UpdateDesignRequest.php +++ b/app/Http/Requests/Design/UpdateDesignRequest.php @@ -79,7 +79,7 @@ class UpdateDesignRequest extends Request $input['design']['body'] = ''; } - if(array_key_exists('entities', $input)) { + if (array_key_exists('entities', $input)) { $user_entities = explode(",", $input['entities']); $e = []; diff --git a/app/Http/Requests/Document/StoreDocumentRequest.php b/app/Http/Requests/Document/StoreDocumentRequest.php index a8b34062d3..010e7a7040 100644 --- a/app/Http/Requests/Document/StoreDocumentRequest.php +++ b/app/Http/Requests/Document/StoreDocumentRequest.php @@ -40,7 +40,7 @@ class StoreDocumentRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/Document/UpdateDocumentRequest.php b/app/Http/Requests/Document/UpdateDocumentRequest.php index b601649ba2..1585e21d34 100644 --- a/app/Http/Requests/Document/UpdateDocumentRequest.php +++ b/app/Http/Requests/Document/UpdateDocumentRequest.php @@ -44,7 +44,7 @@ class UpdateDocumentRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/EInvoice/Peppol/AddTaxIdentifierRequest.php b/app/Http/Requests/EInvoice/Peppol/AddTaxIdentifierRequest.php index dc55074144..b7aeb77293 100644 --- a/app/Http/Requests/EInvoice/Peppol/AddTaxIdentifierRequest.php +++ b/app/Http/Requests/EInvoice/Peppol/AddTaxIdentifierRequest.php @@ -82,14 +82,14 @@ class AddTaxIdentifierRequest extends FormRequest 'required', 'string', 'bail', - function ($attribute, $value, $fail) use($company) { + function ($attribute, $value, $fail) use ($company) { if ($this->country && isset(self::$vat_regex_patterns[$this->country])) { if (!preg_match(self::$vat_regex_patterns[$this->country], $value)) { $fail(ctrans('texts.invalid_vat_number')); } } - if($company->settings->classification == 'individual'){ - $fail("Individuals cannot register additional VAT numbers, only business entities"); + if ($company->settings->classification == 'individual') { + $fail("Individuals cannot register additional VAT numbers, only business entities"); } }, ] diff --git a/app/Http/Requests/EInvoice/Peppol/DisconnectRequest.php b/app/Http/Requests/EInvoice/Peppol/DisconnectRequest.php index 0cbc157825..8960a5640c 100644 --- a/app/Http/Requests/EInvoice/Peppol/DisconnectRequest.php +++ b/app/Http/Requests/EInvoice/Peppol/DisconnectRequest.php @@ -41,7 +41,7 @@ class DisconnectRequest extends FormRequest public function rules(): array { return [ - 'company_key' => ['required'], + 'company_key' => ['required'], ]; } diff --git a/app/Http/Requests/EInvoice/Peppol/StoreEntityRequest.php b/app/Http/Requests/EInvoice/Peppol/StoreEntityRequest.php index 47a53d79c8..84126c41f8 100644 --- a/app/Http/Requests/EInvoice/Peppol/StoreEntityRequest.php +++ b/app/Http/Requests/EInvoice/Peppol/StoreEntityRequest.php @@ -18,7 +18,6 @@ use Illuminate\Foundation\Http\FormRequest; use Illuminate\Auth\Access\AuthorizationException; use App\Http\Requests\EInvoice\Peppol\AddTaxIdentifierRequest; - class StoreEntityRequest extends FormRequest { public function authorize(): bool @@ -53,8 +52,8 @@ class StoreEntityRequest extends FormRequest 'acts_as_sender' => ['required', 'bool'], 'tenant_id' => ['required'], 'classification' => ['required', 'in:business,individual'], - 'vat_number' => [Rule::requiredIf(fn() => $this->input('classification') !== 'individual')], - 'id_number' => [Rule::requiredIf(fn() => $this->input('classification') === 'individual')], + 'vat_number' => [Rule::requiredIf(fn () => $this->input('classification') !== 'individual')], + 'id_number' => [Rule::requiredIf(fn () => $this->input('classification') === 'individual')], ]; } diff --git a/app/Http/Requests/EInvoice/Peppol/UpdateEntityRequest.php b/app/Http/Requests/EInvoice/Peppol/UpdateEntityRequest.php index 3696591e3f..8ea3a9a1d0 100644 --- a/app/Http/Requests/EInvoice/Peppol/UpdateEntityRequest.php +++ b/app/Http/Requests/EInvoice/Peppol/UpdateEntityRequest.php @@ -20,7 +20,6 @@ use Illuminate\Validation\Validator; class UpdateEntityRequest extends FormRequest { - public function authorize(): bool { /** diff --git a/app/Http/Requests/EInvoice/UpdateEInvoiceConfiguration.php b/app/Http/Requests/EInvoice/UpdateEInvoiceConfiguration.php index acff26b85e..09ccd9d9d1 100644 --- a/app/Http/Requests/EInvoice/UpdateEInvoiceConfiguration.php +++ b/app/Http/Requests/EInvoice/UpdateEInvoiceConfiguration.php @@ -129,11 +129,11 @@ class UpdateEInvoiceConfiguration extends Request /** @var \App\Models\User $user */ $user = auth()->user(); - return match($this->entity){ + return match($this->entity) { 'company' => $user->company(), 'invoice' => Invoice::class, 'client' => Client::class, default => $user->company(), }; } -} \ No newline at end of file +} diff --git a/app/Http/Requests/EInvoice/ValidateEInvoiceRequest.php b/app/Http/Requests/EInvoice/ValidateEInvoiceRequest.php index b40aa92c3d..8f084703a2 100644 --- a/app/Http/Requests/EInvoice/ValidateEInvoiceRequest.php +++ b/app/Http/Requests/EInvoice/ValidateEInvoiceRequest.php @@ -33,23 +33,24 @@ class ValidateEInvoiceRequest extends Request $entity = $this->getEntity(); - if($entity instanceof Company) + if ($entity instanceof Company) { return $entity->id == $user->company()->id; + } return $user->can('view', $entity); - + } public function rules() { - + /** @var \App\Models\User $user */ $user = auth()->user(); return [ 'entity' => 'required|bail|in:invoices,clients,companies', 'entity_id' => ['required','bail', Rule::exists($this->entity, 'id') - ->when($this->entity != 'companies', function ($q) use($user){ + ->when($this->entity != 'companies', function ($q) use ($user) { $q->where('company_id', $user->company()->id); }) ], @@ -60,9 +61,9 @@ class ValidateEInvoiceRequest extends Request { $input = $this->all(); - if (isset($input['entity_id']) && $input['entity_id'] != null) { - $input['entity_id'] = $this->decodePrimaryKey($input['entity_id']); - } + if (isset($input['entity_id']) && $input['entity_id'] != null) { + $input['entity_id'] = $this->decodePrimaryKey($input['entity_id']); + } $this->replace($input); @@ -70,22 +71,23 @@ class ValidateEInvoiceRequest extends Request public function getEntity() { - if(!$this->entity) { + if (!$this->entity) { return false; } - - + + $class = Invoice::class; match ($this->entity) { - 'invoices' => $class = Invoice::class, - 'clients' => $class = Client::class, - 'companies' => $class = Company::class, - default => $class = Invoice::class, + 'invoices' => $class = Invoice::class, + 'clients' => $class = Client::class, + 'companies' => $class = Company::class, + default => $class = Invoice::class, }; - if($this->entity == 'companies') + if ($this->entity == 'companies') { return auth()->user()->company(); + } return $class::withTrashed()->find(is_string($this->entity_id) ? $this->decodePrimaryKey($this->entity_id) : $this->entity_id); diff --git a/app/Http/Requests/Email/SendEmailRequest.php b/app/Http/Requests/Email/SendEmailRequest.php index 73f57b7d97..937a9837e7 100644 --- a/app/Http/Requests/Email/SendEmailRequest.php +++ b/app/Http/Requests/Email/SendEmailRequest.php @@ -98,7 +98,7 @@ class SendEmailRequest extends Request $input['entity'] = "App\Models\\".ucfirst(Str::camel($input['entity'])); } - if(isset($input['cc_email'])) { + if (isset($input['cc_email'])) { $input['cc_email'] = collect(explode(",", $input['cc_email']))->map(function ($email) { return trim($email); })->filter(function ($email) { @@ -148,11 +148,10 @@ class SendEmailRequest extends Request /* Check object, check user and company id is same as users, and check user can edit the object */ if ($entity_obj && ($company->id == $entity_obj->company_id) && $user->can('edit', $entity_obj)) { return true; - } - else { + } else { $this->error_message = "Invalid entity or entity_id"; } - } + } return true; } diff --git a/app/Http/Requests/Expense/BulkExpenseRequest.php b/app/Http/Requests/Expense/BulkExpenseRequest.php index ce3ff37103..33592955f2 100644 --- a/app/Http/Requests/Expense/BulkExpenseRequest.php +++ b/app/Http/Requests/Expense/BulkExpenseRequest.php @@ -58,7 +58,7 @@ class BulkExpenseRequest extends Request $input['category_id'] = $this->transformKeys($input['category_id']); } - if(isset($input['newValue'])){ + if (isset($input['newValue'])) { $input['new_value'] = $input['newValue']; } diff --git a/app/Http/Requests/Expense/UpdateExpenseRequest.php b/app/Http/Requests/Expense/UpdateExpenseRequest.php index c8de24ea40..688dfce159 100644 --- a/app/Http/Requests/Expense/UpdateExpenseRequest.php +++ b/app/Http/Requests/Expense/UpdateExpenseRequest.php @@ -78,9 +78,10 @@ class UpdateExpenseRequest extends Request $input['currency_id'] = (string) $user->company()->settings->currency_id; } - if(isset($input['exchange_rate']) && $input['exchange_rate'] == 0) + if (isset($input['exchange_rate']) && $input['exchange_rate'] == 0) { $input['exchnage_rate'] = 1; - + } + /* Ensure the project is related */ if (array_key_exists('project_id', $input) && isset($input['project_id'])) { $project = Project::withTrashed()->where('id', $input['project_id'])->company()->first(); diff --git a/app/Http/Requests/Expense/UploadExpenseRequest.php b/app/Http/Requests/Expense/UploadExpenseRequest.php index d9af321727..92c7240db8 100644 --- a/app/Http/Requests/Expense/UploadExpenseRequest.php +++ b/app/Http/Requests/Expense/UploadExpenseRequest.php @@ -53,7 +53,7 @@ class UploadExpenseRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/Import/ImportRequest.php b/app/Http/Requests/Import/ImportRequest.php index c7b8c489d1..db58c74f0a 100644 --- a/app/Http/Requests/Import/ImportRequest.php +++ b/app/Http/Requests/Import/ImportRequest.php @@ -45,7 +45,7 @@ class ImportRequest extends Request { $input = $this->all(); - if(!isset($input['column_map']['bank_transaction']) && array_key_exists('bank_integration_id', $input)) { + if (!isset($input['column_map']['bank_transaction']) && array_key_exists('bank_integration_id', $input)) { unset($input['bank_integration_id']); } diff --git a/app/Http/Requests/Invoice/BulkInvoiceRequest.php b/app/Http/Requests/Invoice/BulkInvoiceRequest.php index 026c504d24..d56396196c 100644 --- a/app/Http/Requests/Invoice/BulkInvoiceRequest.php +++ b/app/Http/Requests/Invoice/BulkInvoiceRequest.php @@ -40,11 +40,11 @@ class BulkInvoiceRequest extends Request /** @var \App\Models\User $user */ $user = auth()->user(); - if(\Illuminate\Support\Facades\Cache::has($this->ip()."|".$this->input('action', 0)."|".$user->company()->company_key)) { + if (\Illuminate\Support\Facades\Cache::has($this->ip()."|".$this->input('action', 0)."|".$user->company()->company_key)) { throw new DuplicatePaymentException('Action still processing, please wait. ', 429); } - $delay = $this->input('action', 'delete') == 'delete' ? (ceil(count($this->input('ids',4)))) : 1; + $delay = $this->input('action', 'delete') == 'delete' ? (ceil(count($this->input('ids', 4)))) : 1; \Illuminate\Support\Facades\Cache::put(($this->ip()."|".$this->input('action', 0)."|".$user->company()->company_key), true, $delay); } diff --git a/app/Http/Requests/Invoice/DestroyInvoiceRequest.php b/app/Http/Requests/Invoice/DestroyInvoiceRequest.php index 0da03a17b9..591451fafd 100644 --- a/app/Http/Requests/Invoice/DestroyInvoiceRequest.php +++ b/app/Http/Requests/Invoice/DestroyInvoiceRequest.php @@ -37,8 +37,9 @@ class DestroyInvoiceRequest extends Request /** @var \App\Models\User $user */ $user = auth()->user(); - if(\Illuminate\Support\Facades\Cache::has($this->ip()."|".$this->invoice->id."|".$user->company()->company_key)) + if (\Illuminate\Support\Facades\Cache::has($this->ip()."|".$this->invoice->id."|".$user->company()->company_key)) { throw new \App\Exceptions\DuplicatePaymentException('Duplicate request.', 429); + } \Illuminate\Support\Facades\Cache::put(($this->ip()."|".$this->invoice->id."|".$user->company()->company_key), true, 1); diff --git a/app/Http/Requests/Invoice/StoreInvoiceRequest.php b/app/Http/Requests/Invoice/StoreInvoiceRequest.php index 81c6e5a2bd..a10d6944e3 100644 --- a/app/Http/Requests/Invoice/StoreInvoiceRequest.php +++ b/app/Http/Requests/Invoice/StoreInvoiceRequest.php @@ -95,11 +95,11 @@ class StoreInvoiceRequest extends Request $client_id = is_string($this->input('client_id', '')) ? $this->input('client_id') : ''; - if(\Illuminate\Support\Facades\Cache::has($this->ip()."|INVOICE|".$client_id."|".$user->company()->company_key)) { + if (\Illuminate\Support\Facades\Cache::has($this->ip()."|INVOICE|".$client_id."|".$user->company()->company_key)) { usleep(200000); } - \Illuminate\Support\Facades\Cache::put($this->ip()."|INVOICE|".$client_id."|".$user->company()->company_key,1); + \Illuminate\Support\Facades\Cache::put($this->ip()."|INVOICE|".$client_id."|".$user->company()->company_key, 1); $input = $this->all(); @@ -113,7 +113,7 @@ class StoreInvoiceRequest extends Request $input['line_items'] = $this->cleanFeeItems($input['line_items']); $input['amount'] = $this->entityTotalAmount($input['line_items']); } - if(isset($input['partial']) && $input['partial'] == 0) { + if (isset($input['partial']) && $input['partial'] == 0) { $input['partial_due_date'] = null; } if (!isset($input['tax_rate1'])) { @@ -128,20 +128,21 @@ class StoreInvoiceRequest extends Request if (array_key_exists('exchange_rate', $input) && is_null($input['exchange_rate'])) { $input['exchange_rate'] = 1; } - if(!isset($input['date'])) { + if (!isset($input['date'])) { $input['date'] = now()->addSeconds($user->company()->utc_offset())->format('Y-m-d'); } //handles edge case where we need for force set the due date of the invoice. - if((isset($input['partial_due_date']) && strlen($input['partial_due_date']) > 1) && (!array_key_exists('due_date', $input) || (empty($input['due_date']) && empty($this->invoice->due_date)))) { + if ((isset($input['partial_due_date']) && strlen($input['partial_due_date']) > 1) && (!array_key_exists('due_date', $input) || (empty($input['due_date']) && empty($this->invoice->due_date)))) { $client = \App\Models\Client::withTrashed()->find($input['client_id']); - if($client) { + if ($client) { $input['due_date'] = \Illuminate\Support\Carbon::parse($input['date'])->addDays((int)$client->getSetting('payment_terms'))->format('Y-m-d'); } } - if(isset($input['footer']) && $this->hasHeader('X-REACT')) + if (isset($input['footer']) && $this->hasHeader('X-REACT')) { $input['footer'] = str_replace("\n", "", $input['footer']); + } if (isset($input['public_notes']) && $this->hasHeader('X-REACT')) { $input['public_notes'] = str_replace("\n", "", $input['public_notes']); diff --git a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php index 8d77d3421e..77c562d16d 100644 --- a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php +++ b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php @@ -99,7 +99,7 @@ class UpdateInvoiceRequest extends Request $input['id'] = $this->invoice->id; - if(isset($input['partial']) && $input['partial'] == 0) { + if (isset($input['partial']) && $input['partial'] == 0) { $input['partial_due_date'] = null; } @@ -117,11 +117,11 @@ class UpdateInvoiceRequest extends Request } //handles edge case where we need for force set the due date of the invoice. - if((isset($input['partial_due_date']) && strlen($input['partial_due_date']) > 1) && (!array_key_exists('due_date', $input) || (empty($input['due_date']) && empty($this->invoice->due_date)))) { + if ((isset($input['partial_due_date']) && strlen($input['partial_due_date']) > 1) && (!array_key_exists('due_date', $input) || (empty($input['due_date']) && empty($this->invoice->due_date)))) { $client = \App\Models\Client::withTrashed()->find($input['client_id']); $input['due_date'] = \Illuminate\Support\Carbon::parse($input['date'])->addDays((int)$client->getSetting('payment_terms'))->format('Y-m-d'); } - + if (isset($input['e_invoice']) && is_array($input['e_invoice'])) { //ensure it is normalized first! $input['e_invoice'] = $this->invoice->filterNullsRecursive($input['e_invoice']); diff --git a/app/Http/Requests/Invoice/UploadInvoiceRequest.php b/app/Http/Requests/Invoice/UploadInvoiceRequest.php index 812b9402d4..a66caeea9e 100644 --- a/app/Http/Requests/Invoice/UploadInvoiceRequest.php +++ b/app/Http/Requests/Invoice/UploadInvoiceRequest.php @@ -53,7 +53,7 @@ class UploadInvoiceRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/Nordigen/ConnectNordigenBankIntegrationRequest.php b/app/Http/Requests/Nordigen/ConnectNordigenBankIntegrationRequest.php index 783480a5d1..946f979cce 100644 --- a/app/Http/Requests/Nordigen/ConnectNordigenBankIntegrationRequest.php +++ b/app/Http/Requests/Nordigen/ConnectNordigenBankIntegrationRequest.php @@ -45,7 +45,7 @@ class ConnectNordigenBankIntegrationRequest extends Request $context = $this->getTokenContent(); - if(isset($context['institution_id'])) { + if (isset($context['institution_id'])) { $input['institution_id'] = $context['institution_id']; } diff --git a/app/Http/Requests/Payment/StorePaymentRequest.php b/app/Http/Requests/Payment/StorePaymentRequest.php index 23eb235ffc..a18c9ed3a3 100644 --- a/app/Http/Requests/Payment/StorePaymentRequest.php +++ b/app/Http/Requests/Payment/StorePaymentRequest.php @@ -82,7 +82,7 @@ class StorePaymentRequest extends Request $client_id = is_string($this->input('client_id', '')) ? $this->input('client_id') : ''; - if(\Illuminate\Support\Facades\Cache::has($this->ip()."|".$this->input('amount', 0)."|".$client_id."|".$user->company()->company_key)) { + if (\Illuminate\Support\Facades\Cache::has($this->ip()."|".$this->input('amount', 0)."|".$client_id."|".$user->company()->company_key)) { throw new DuplicatePaymentException('Duplicate request.', 429); } diff --git a/app/Http/Requests/Payment/UpdatePaymentRequest.php b/app/Http/Requests/Payment/UpdatePaymentRequest.php index d48fdc8177..1ddc1c72da 100644 --- a/app/Http/Requests/Payment/UpdatePaymentRequest.php +++ b/app/Http/Requests/Payment/UpdatePaymentRequest.php @@ -80,7 +80,7 @@ class UpdatePaymentRequest extends Request if (isset($input['invoices']) && is_array($input['invoices']) !== false) { foreach ($input['invoices'] as $key => $value) { - if(isset($input['invoices'][$key]['invoice_id'])) { + if (isset($input['invoices'][$key]['invoice_id'])) { $input['invoices'][$key]['invoice_id'] = $this->decodePrimaryKey($value['invoice_id']); } } diff --git a/app/Http/Requests/Payment/UploadPaymentRequest.php b/app/Http/Requests/Payment/UploadPaymentRequest.php index a52d0a68f0..b9f42da38f 100644 --- a/app/Http/Requests/Payment/UploadPaymentRequest.php +++ b/app/Http/Requests/Payment/UploadPaymentRequest.php @@ -53,7 +53,7 @@ class UploadPaymentRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/Preview/PreviewInvoiceRequest.php b/app/Http/Requests/Preview/PreviewInvoiceRequest.php index e710790004..ed249e5a3f 100644 --- a/app/Http/Requests/Preview/PreviewInvoiceRequest.php +++ b/app/Http/Requests/Preview/PreviewInvoiceRequest.php @@ -76,7 +76,7 @@ class PreviewInvoiceRequest extends Request $input['balance'] = 0; $input['number'] = isset($input['number']) ? $input['number'] : ctrans('texts.live_preview').' #'.rand(0, 1000); - if($input['entity_id'] ?? false) { + if ($input['entity_id'] ?? false) { $input['entity_id'] = $this->decodePrimaryKey($input['entity_id'], true); } @@ -90,7 +90,7 @@ class PreviewInvoiceRequest extends Request $invitation = false; /** @phpstan-ignore-next-line */ - if(! $this->entity_id ?? false) { + if (! $this->entity_id ?? false) { return $this->stubInvitation(); } @@ -102,7 +102,7 @@ class PreviewInvoiceRequest extends Request default => $invitation = false, }; - if($invitation) { + if ($invitation) { return $invitation; } @@ -111,7 +111,7 @@ class PreviewInvoiceRequest extends Request public function getClient(): ?Client { - if(!$this->client) { + if (!$this->client) { $this->client = Client::query()->with('contacts', 'company', 'user')->withTrashed()->find($this->client_id); } diff --git a/app/Http/Requests/Preview/PreviewPurchaseOrderRequest.php b/app/Http/Requests/Preview/PreviewPurchaseOrderRequest.php index 0af8542f97..4d11f21758 100644 --- a/app/Http/Requests/Preview/PreviewPurchaseOrderRequest.php +++ b/app/Http/Requests/Preview/PreviewPurchaseOrderRequest.php @@ -58,7 +58,7 @@ class PreviewPurchaseOrderRequest extends Request $input['balance'] = 0; $input['number'] = isset($input['number']) ? $input['number'] : ctrans('texts.live_preview').' #'.rand(0, 1000); //30-06-2023 - if($input['entity_id'] ?? false) { + if ($input['entity_id'] ?? false) { $input['entity_id'] = $this->decodePrimaryKey($input['entity_id'], true); } @@ -71,13 +71,13 @@ class PreviewPurchaseOrderRequest extends Request { $invitation = false; - if(! isset($this->entity_id)) { + if (! isset($this->entity_id)) { return $this->stubInvitation(); } $invitation = PurchaseOrderInvitation::withTrashed()->where('purchase_order_id', $this->entity_id)->first(); - if($invitation) { + if ($invitation) { return $invitation; } @@ -88,7 +88,7 @@ class PreviewPurchaseOrderRequest extends Request public function getVendor(): ?Vendor { - if(!$this->vendor) { + if (!$this->vendor) { $this->vendor = Vendor::query()->with('contacts', 'company', 'user')->withTrashed()->find($this->vendor_id); } diff --git a/app/Http/Requests/Product/UploadProductRequest.php b/app/Http/Requests/Product/UploadProductRequest.php index ef6b6d49db..6d2f662e50 100644 --- a/app/Http/Requests/Product/UploadProductRequest.php +++ b/app/Http/Requests/Product/UploadProductRequest.php @@ -52,7 +52,7 @@ class UploadProductRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/Project/InvoiceProjectRequest.php b/app/Http/Requests/Project/InvoiceProjectRequest.php index 48e2fb106f..490587aa7e 100644 --- a/app/Http/Requests/Project/InvoiceProjectRequest.php +++ b/app/Http/Requests/Project/InvoiceProjectRequest.php @@ -31,9 +31,9 @@ class InvoiceProjectRequest extends Request public function rules() { - return []; - - //if we need to restrict a project to only one invoice... + return []; + + //if we need to restrict a project to only one invoice... // $user = auth()->user(); // $company = $user->company(); @@ -54,7 +54,7 @@ class InvoiceProjectRequest extends Request { $input = $this->all(); - // $input['project_id'] = $this->project->id; + // $input['project_id'] = $this->project->id; $this->replace($input); diff --git a/app/Http/Requests/Project/StoreProjectRequest.php b/app/Http/Requests/Project/StoreProjectRequest.php index 88d3c77496..7d518cb7eb 100644 --- a/app/Http/Requests/Project/StoreProjectRequest.php +++ b/app/Http/Requests/Project/StoreProjectRequest.php @@ -76,7 +76,7 @@ class StoreProjectRequest extends Request $input['color'] = ''; } - if(array_key_exists('budgeted_hours', $input) && empty($input['budgeted_hours'])) { + if (array_key_exists('budgeted_hours', $input) && empty($input['budgeted_hours'])) { $input['budgeted_hours'] = 0; } diff --git a/app/Http/Requests/Project/UpdateProjectRequest.php b/app/Http/Requests/Project/UpdateProjectRequest.php index 820940dd0d..dca32ad646 100644 --- a/app/Http/Requests/Project/UpdateProjectRequest.php +++ b/app/Http/Requests/Project/UpdateProjectRequest.php @@ -77,7 +77,7 @@ class UpdateProjectRequest extends Request $input['color'] = ''; } - if(array_key_exists('budgeted_hours', $input) && empty($input['budgeted_hours'])) { + if (array_key_exists('budgeted_hours', $input) && empty($input['budgeted_hours'])) { $input['budgeted_hours'] = 0; } diff --git a/app/Http/Requests/Project/UploadProjectRequest.php b/app/Http/Requests/Project/UploadProjectRequest.php index 6b8f9909b7..df2caeba46 100644 --- a/app/Http/Requests/Project/UploadProjectRequest.php +++ b/app/Http/Requests/Project/UploadProjectRequest.php @@ -53,7 +53,7 @@ class UploadProjectRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php index cb2583bd29..28dfb88347 100644 --- a/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php +++ b/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php @@ -89,7 +89,7 @@ class StorePurchaseOrderRequest extends Request $input['amount'] = 0; $input['balance'] = 0; - if(isset($input['partial']) && $input['partial'] == 0) { + if (isset($input['partial']) && $input['partial'] == 0) { $input['partial_due_date'] = null; } @@ -103,7 +103,7 @@ class StorePurchaseOrderRequest extends Request if (array_key_exists('exchange_rate', $input) && is_null($input['exchange_rate'])) { $input['exchange_rate'] = 1; } - + if (isset($input['footer']) && $this->hasHeader('X-REACT')) { $input['footer'] = str_replace("\n", "", $input['footer']); } diff --git a/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php index 824d567b2e..c501407145 100644 --- a/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php +++ b/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php @@ -88,7 +88,7 @@ class UpdatePurchaseOrderRequest extends Request $input['id'] = $this->purchase_order->id; - if(isset($input['partial']) && $input['partial'] == 0) { + if (isset($input['partial']) && $input['partial'] == 0) { $input['partial_due_date'] = null; } @@ -100,7 +100,7 @@ class UpdatePurchaseOrderRequest extends Request if (array_key_exists('exchange_rate', $input) && is_null($input['exchange_rate'])) { $input['exchange_rate'] = 1; } - + if (isset($input['footer']) && $this->hasHeader('X-REACT')) { $input['footer'] = str_replace("\n", "", $input['footer']); } diff --git a/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php index 9c5b4ed4f5..b8beca6666 100644 --- a/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php +++ b/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php @@ -53,7 +53,7 @@ class UploadPurchaseOrderRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/Quote/StoreQuoteRequest.php b/app/Http/Requests/Quote/StoreQuoteRequest.php index 1c3c8d7147..6906e8fec4 100644 --- a/app/Http/Requests/Quote/StoreQuoteRequest.php +++ b/app/Http/Requests/Quote/StoreQuoteRequest.php @@ -104,7 +104,7 @@ class StoreQuoteRequest extends Request $input['line_items'] = $this->cleanFeeItems($input['line_items']); $input['amount'] = $this->entityTotalAmount($input['line_items']); } - if(isset($input['partial']) && $input['partial'] == 0) { + if (isset($input['partial']) && $input['partial'] == 0) { $input['partial_due_date'] = null; } if (!isset($input['tax_rate1'])) { @@ -119,10 +119,10 @@ class StoreQuoteRequest extends Request if (!isset($input['exchange_rate'])) { $input['exchange_rate'] = 1; } - if(!isset($input['date'])) { + if (!isset($input['date'])) { $input['date'] = now()->addSeconds($user->company()->utc_offset())->format('Y-m-d'); } - if(isset($input['partial_due_date']) && (!isset($input['due_date']) || strlen($input['due_date']) <= 1)) { + if (isset($input['partial_due_date']) && (!isset($input['due_date']) || strlen($input['due_date']) <= 1)) { $client = \App\Models\Client::withTrashed()->find($input['client_id']); $valid_days = ($client && strlen($client->getSetting('valid_until')) >= 1) ? $client->getSetting('valid_until') : 7; $input['due_date'] = \Carbon\Carbon::parse($input['date'])->addDays((int)$valid_days)->format('Y-m-d'); diff --git a/app/Http/Requests/Quote/UpdateQuoteRequest.php b/app/Http/Requests/Quote/UpdateQuoteRequest.php index 32804807f4..739ec65fa7 100644 --- a/app/Http/Requests/Quote/UpdateQuoteRequest.php +++ b/app/Http/Requests/Quote/UpdateQuoteRequest.php @@ -96,10 +96,10 @@ class UpdateQuoteRequest extends Request $input['exchange_rate'] = 1; } - if(isset($input['partial']) && $input['partial'] == 0) { + if (isset($input['partial']) && $input['partial'] == 0) { $input['partial_due_date'] = null; } - + if (isset($input['footer']) && $this->hasHeader('X-REACT')) { $input['footer'] = str_replace("\n", "", $input['footer']); } diff --git a/app/Http/Requests/Quote/UploadQuoteRequest.php b/app/Http/Requests/Quote/UploadQuoteRequest.php index d7883c8b6a..cdc6454e33 100644 --- a/app/Http/Requests/Quote/UploadQuoteRequest.php +++ b/app/Http/Requests/Quote/UploadQuoteRequest.php @@ -53,7 +53,7 @@ class UploadQuoteRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php index 2ff1df711c..d02046b40b 100644 --- a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php @@ -95,7 +95,7 @@ class StoreRecurringInvoiceRequest extends Request $input['due_date_days'] = 'terms'; } - if(!isset($input['next_send_date']) || $input['next_send_date'] == '') { + if (!isset($input['next_send_date']) || $input['next_send_date'] == '') { $input['next_send_date'] = now()->format('Y-m-d'); } diff --git a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php index 6ea38d30ed..df74d4f418 100644 --- a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php @@ -87,7 +87,7 @@ class UpdateRecurringInvoiceRequest extends Request $input['due_date_days'] = 'terms'; } - if(!isset($input['next_send_date']) || $input['next_send_date'] == '') { + if (!isset($input['next_send_date']) || $input['next_send_date'] == '') { $input['next_send_date'] = now()->format('Y-m-d'); } diff --git a/app/Http/Requests/RecurringInvoice/UploadRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/UploadRecurringInvoiceRequest.php index e401ef6958..dd15976d5c 100644 --- a/app/Http/Requests/RecurringInvoice/UploadRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/UploadRecurringInvoiceRequest.php @@ -53,7 +53,7 @@ class UploadRecurringInvoiceRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/Report/GenericReportRequest.php b/app/Http/Requests/Report/GenericReportRequest.php index 84bdf0eb90..94cf3b5751 100644 --- a/app/Http/Requests/Report/GenericReportRequest.php +++ b/app/Http/Requests/Report/GenericReportRequest.php @@ -67,7 +67,7 @@ class GenericReportRequest extends Request $input['user_id'] = auth()->user()->id; - if(!$this->checkAuthority()) { + if (!$this->checkAuthority()) { $input['date_range'] = ''; $input['start_date'] = ''; $input['end_date'] = ''; diff --git a/app/Http/Requests/Report/ProductSalesReportRequest.php b/app/Http/Requests/Report/ProductSalesReportRequest.php index aed50d82fb..73a65e0346 100644 --- a/app/Http/Requests/Report/ProductSalesReportRequest.php +++ b/app/Http/Requests/Report/ProductSalesReportRequest.php @@ -83,7 +83,7 @@ class ProductSalesReportRequest extends Request /** @var \App\Models\User $user */ $user = auth()->user(); - if(Ninja::isHosted() && $user->account->isFreeHostedClient()) { + if (Ninja::isHosted() && $user->account->isFreeHostedClient()) { $this->error_message = ctrans('texts.upgrade_to_view_reports'); return false; } diff --git a/app/Http/Requests/Report/ProfitLossRequest.php b/app/Http/Requests/Report/ProfitLossRequest.php index 908abc092e..53af0b3239 100644 --- a/app/Http/Requests/Report/ProfitLossRequest.php +++ b/app/Http/Requests/Report/ProfitLossRequest.php @@ -60,7 +60,7 @@ class ProfitLossRequest extends Request /** @var \App\Models\User $user */ $user = auth()->user(); - if(Ninja::isHosted() && $user->account->isFreeHostedClient()) { + if (Ninja::isHosted() && $user->account->isFreeHostedClient()) { $this->error_message = ctrans('texts.upgrade_to_view_reports'); return false; } diff --git a/app/Http/Requests/Report/ReportPreviewRequest.php b/app/Http/Requests/Report/ReportPreviewRequest.php index 869f34cd7d..ad467fc19e 100644 --- a/app/Http/Requests/Report/ReportPreviewRequest.php +++ b/app/Http/Requests/Report/ReportPreviewRequest.php @@ -46,7 +46,7 @@ class ReportPreviewRequest extends Request /** @var \App\Models\User $user */ $user = auth()->user(); - if(Ninja::isHosted() && $user->account->isFreeHostedClient()) { + if (Ninja::isHosted() && $user->account->isFreeHostedClient()) { $this->error_message = ctrans('texts.upgrade_to_view_reports'); return false; } diff --git a/app/Http/Requests/Request.php b/app/Http/Requests/Request.php index 9617f48ab3..abec4dc21d 100644 --- a/app/Http/Requests/Request.php +++ b/app/Http/Requests/Request.php @@ -33,7 +33,7 @@ class Request extends FormRequest public function fileValidation() { - if(config('ninja.upload_extensions')) { + if (config('ninja.upload_extensions')) { return $this->file_validation. ",".config('ninja.upload_extensions'); } @@ -47,7 +47,7 @@ class Request extends FormRequest foreach ($this->all() as $key => $value) { - if($key == 'user') { + if ($key == 'user') { continue; } @@ -213,19 +213,19 @@ class Request extends FormRequest } } - if(isset($input['public_notes'])) { + if (isset($input['public_notes'])) { $input['public_notes'] = str_replace("input(); - if(isset($input['smtp_username']) && $input['smtp_username'] == '********') { - + if (isset($input['smtp_username']) && $input['smtp_username'] == '********') { + $input['smtp_username'] = $company->smtp_username; } - if(isset($input['smtp_password']) && $input['smtp_password'] == '********') { + if (isset($input['smtp_password']) && $input['smtp_password'] == '********') { $input['smtp_password'] = $company->smtp_password; } - if(isset($input['smtp_host']) && strlen($input['smtp_host']) >= 3) { + if (isset($input['smtp_host']) && strlen($input['smtp_host']) >= 3) { } else { $input['smtp_host'] = $company->smtp_host; diff --git a/app/Http/Requests/Subscription/BulkSubscriptionRequest.php b/app/Http/Requests/Subscription/BulkSubscriptionRequest.php index 3f5d4da306..9ebcb1c583 100644 --- a/app/Http/Requests/Subscription/BulkSubscriptionRequest.php +++ b/app/Http/Requests/Subscription/BulkSubscriptionRequest.php @@ -53,11 +53,11 @@ class BulkSubscriptionRequest extends Request $input['ids'] = $this->transformKeys($input['ids']); } - if(isset($input['entity']) && $input['entity'] == 'recurring_invoice') { + if (isset($input['entity']) && $input['entity'] == 'recurring_invoice') { $this->entity_table = 'recurring_invoices'; } - if(isset($input['entity_id']) && $input['entity_id'] != null) { + if (isset($input['entity_id']) && $input['entity_id'] != null) { $input['entity_id'] = $this->decodePrimaryKey($input['entity_id']); } diff --git a/app/Http/Requests/Task/StoreTaskRequest.php b/app/Http/Requests/Task/StoreTaskRequest.php index 9c5462add8..f75b6da0fd 100644 --- a/app/Http/Requests/Task/StoreTaskRequest.php +++ b/app/Http/Requests/Task/StoreTaskRequest.php @@ -58,11 +58,11 @@ class StoreTaskRequest extends Request $rules['time_log'] = ['bail',function ($attribute, $values, $fail) { - if(is_string($values)) { + if (is_string($values)) { $values = json_decode($values, true); } - if(!is_array($values)) { + if (!is_array($values)) { $fail('The '.$attribute.' must be a valid array.'); return; } @@ -123,7 +123,7 @@ class StoreTaskRequest extends Request } } - if(!isset($input['time_log']) || empty($input['time_log']) || $input['time_log'] == '{}') { + if (!isset($input['time_log']) || empty($input['time_log']) || $input['time_log'] == '{}') { $input['time_log'] = json_encode([]); } diff --git a/app/Http/Requests/Task/UpdateTaskRequest.php b/app/Http/Requests/Task/UpdateTaskRequest.php index af55eea0b1..16d99fe1c5 100644 --- a/app/Http/Requests/Task/UpdateTaskRequest.php +++ b/app/Http/Requests/Task/UpdateTaskRequest.php @@ -64,11 +64,11 @@ class UpdateTaskRequest extends Request $rules['time_log'] = ['bail', function ($attribute, $values, $fail) { - if(is_string($values)) { + if (is_string($values)) { $values = json_decode($values, true); } - if(!is_array($values)) { + if (!is_array($values)) { $fail('The '.$attribute.' must be a valid array.'); return; } @@ -124,16 +124,16 @@ class UpdateTaskRequest extends Request $input['color'] = ''; } - if(isset($input['project_id']) && isset($input['client_id'])) { + if (isset($input['project_id']) && isset($input['client_id'])) { $search_project_with_client = Project::withTrashed()->where('id', $input['project_id'])->where('client_id', $input['client_id'])->company()->doesntExist(); - if($search_project_with_client) { + if ($search_project_with_client) { unset($input['project_id']); } } - if(!isset($input['time_log']) || empty($input['time_log']) || $input['time_log'] == '{}' || $input['time_log'] == '[""]') { + if (!isset($input['time_log']) || empty($input['time_log']) || $input['time_log'] == '{}' || $input['time_log'] == '[""]') { $input['time_log'] = json_encode([]); } diff --git a/app/Http/Requests/Task/UploadTaskRequest.php b/app/Http/Requests/Task/UploadTaskRequest.php index 4415cf8a99..1ffdf2fbeb 100644 --- a/app/Http/Requests/Task/UploadTaskRequest.php +++ b/app/Http/Requests/Task/UploadTaskRequest.php @@ -53,7 +53,7 @@ class UploadTaskRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php b/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php index f19a67edc4..d1c288019a 100644 --- a/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php +++ b/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php @@ -82,19 +82,19 @@ class StoreSchedulerRequest extends Request $input['next_run_client'] = $input['next_run']; } - if($input['template'] == 'email_record') { + if ($input['template'] == 'email_record') { $input['frequency_id'] = 0; } - if(isset($input['parameters']) && !isset($input['parameters']['clients'])) { + if (isset($input['parameters']) && !isset($input['parameters']['clients'])) { $input['parameters']['clients'] = []; } - if(isset($input['parameters']['status'])) { + if (isset($input['parameters']['status'])) { $task_statuses = []; - if(isset($input['parameters']['report_name']) && $input['parameters']['report_name'] == 'task') { + if (isset($input['parameters']['report_name']) && $input['parameters']['report_name'] == 'task') { $task_statuses = array_diff(explode(",", $input['parameters']['status']), $this->client_statuses); } diff --git a/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php b/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php index 4dbf56e2e6..4e00d6f996 100644 --- a/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php +++ b/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php @@ -82,20 +82,20 @@ class UpdateSchedulerRequest extends Request $input['next_run_client'] = $input['next_run']; } - if($input['template'] == 'email_record') { + if ($input['template'] == 'email_record') { $input['frequency_id'] = 0; } - if(isset($input['parameters']) && !isset($input['parameters']['clients'])) { + if (isset($input['parameters']) && !isset($input['parameters']['clients'])) { $input['parameters']['clients'] = []; } - if(isset($input['parameters']['status'])) { + if (isset($input['parameters']['status'])) { $task_statuses = []; - if(isset($input['parameters']['report_name']) && $input['parameters']['report_name'] == 'task') { + if (isset($input['parameters']['report_name']) && $input['parameters']['report_name'] == 'task') { $task_statuses = array_diff(explode(",", $input['parameters']['status']), $this->client_statuses); } diff --git a/app/Http/Requests/User/BulkUserRequest.php b/app/Http/Requests/User/BulkUserRequest.php index f6ac4d30bd..1abbd72860 100644 --- a/app/Http/Requests/User/BulkUserRequest.php +++ b/app/Http/Requests/User/BulkUserRequest.php @@ -25,7 +25,7 @@ class BulkUserRequest extends Request */ public function authorize(): bool { - if($this->action == 'delete' && in_array(auth()->user()->hashed_id, $this->ids)) { + if ($this->action == 'delete' && in_array(auth()->user()->hashed_id, $this->ids)) { return false; } diff --git a/app/Http/Requests/User/UpdateUserRequest.php b/app/Http/Requests/User/UpdateUserRequest.php index 60331315d1..93a3ade67b 100644 --- a/app/Http/Requests/User/UpdateUserRequest.php +++ b/app/Http/Requests/User/UpdateUserRequest.php @@ -53,9 +53,9 @@ class UpdateUserRequest extends Request if (isset($input['email']) && is_string($input['email']) && strlen($input['email']) > 2) { $input['email'] = trim($input['email']); - } - elseif(isset($input['email'])) + } elseif (isset($input['email'])) { $input['email'] = false; + } if (array_key_exists('first_name', $input)) { $input['first_name'] = strip_tags($input['first_name']); @@ -77,7 +77,7 @@ class UpdateUserRequest extends Request unset($input['oauth_user_token']); } - if(isset($input['password']) && is_string($input['password'])) { + if (isset($input['password']) && is_string($input['password'])) { $input['password'] = trim($input['password']); } diff --git a/app/Http/Requests/Vendor/UpdateVendorRequest.php b/app/Http/Requests/Vendor/UpdateVendorRequest.php index 8a76e1066c..250ddd03d5 100644 --- a/app/Http/Requests/Vendor/UpdateVendorRequest.php +++ b/app/Http/Requests/Vendor/UpdateVendorRequest.php @@ -100,9 +100,8 @@ class UpdateVendorRequest extends Request if (array_key_exists('country_id', $input) && is_null($input['country_id'])) { unset($input['country_id']); - } - elseif(!$this->vendor->country_id){ - + } elseif (!$this->vendor->country_id) { + /** @var \App\Models\User $user */ $user = auth()->user(); diff --git a/app/Http/Requests/Vendor/UploadVendorRequest.php b/app/Http/Requests/Vendor/UploadVendorRequest.php index 826a5ed14d..f53cc45553 100644 --- a/app/Http/Requests/Vendor/UploadVendorRequest.php +++ b/app/Http/Requests/Vendor/UploadVendorRequest.php @@ -50,7 +50,7 @@ class UploadVendorRequest extends Request { $input = $this->all(); - if(isset($input['is_public'])) { + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/ValidationRules/Company/ValidCompanyQuantity.php b/app/Http/ValidationRules/Company/ValidCompanyQuantity.php index 7f67d2b46b..d25ba795cf 100644 --- a/app/Http/ValidationRules/Company/ValidCompanyQuantity.php +++ b/app/Http/ValidationRules/Company/ValidCompanyQuantity.php @@ -20,13 +20,12 @@ use Illuminate\Contracts\Validation\ValidationRule; */ class ValidCompanyQuantity implements ValidationRule { - public function validate(string $attribute, mixed $value, Closure $fail): void { $message = ctrans('texts.company_limit_reached', ['limit' => Ninja::isSelfHost() ? 10 : auth()->user()->company()->account->hosted_company_count]); - $test = Ninja::isSelfHost() ? - auth()->user()->company()->account->companies->count() < 10 : + $test = Ninja::isSelfHost() ? + auth()->user()->company()->account->companies->count() < 10 : (auth()->user()->account->isPaid() || auth()->user()->account->isTrial()) && auth()->user()->company()->account->companies->count() < 10 ; if (!$test) { diff --git a/app/Http/ValidationRules/Company/ValidExpenseMailbox.php b/app/Http/ValidationRules/Company/ValidExpenseMailbox.php index 6d3a26a70a..4c8332cfd3 100644 --- a/app/Http/ValidationRules/Company/ValidExpenseMailbox.php +++ b/app/Http/ValidationRules/Company/ValidExpenseMailbox.php @@ -21,7 +21,6 @@ use Symfony\Component\Validator\Constraints\EmailValidator; */ class ValidExpenseMailbox implements Rule { - private array $endings = []; public function __construct() @@ -34,7 +33,7 @@ class ValidExpenseMailbox implements Rule if (empty($value) || !config('ninja.inbound_mailbox.expense_mailbox_endings')) { return true; } - + foreach ($this->endings as $ending) { if (str_ends_with($value, $ending)) { return true; diff --git a/app/Http/ValidationRules/Company/ValidSubdomain.php b/app/Http/ValidationRules/Company/ValidSubdomain.php index 26aeb32349..6ca30d447d 100644 --- a/app/Http/ValidationRules/Company/ValidSubdomain.php +++ b/app/Http/ValidationRules/Company/ValidSubdomain.php @@ -23,9 +23,10 @@ class ValidSubdomain implements ValidationRule public function validate(string $attribute, mixed $value, Closure $fail): void { - if(empty($value)) + if (empty($value)) { return; - + } + if (!MultiDB::checkDomainAvailable($value)) { $fail(ctrans('texts.subdomain_taken')); } diff --git a/app/Http/ValidationRules/Credit/ValidCreditsRules.php b/app/Http/ValidationRules/Credit/ValidCreditsRules.php index 75ee38190e..78b10145b3 100644 --- a/app/Http/ValidationRules/Credit/ValidCreditsRules.php +++ b/app/Http/ValidationRules/Credit/ValidCreditsRules.php @@ -76,12 +76,12 @@ class ValidCreditsRules implements Rule return false; } - if($cred->status_id == Credit::STATUS_DRAFT) { + if ($cred->status_id == Credit::STATUS_DRAFT) { $cred->service()->markSent()->save(); $cred = $cred->fresh(); } - if($cred->balance < $credit['amount']) { + if ($cred->balance < $credit['amount']) { $this->error_msg = ctrans('texts.insufficient_credit_balance'); return false; } diff --git a/app/Http/ValidationRules/EInvoice/ValidClientScheme.php b/app/Http/ValidationRules/EInvoice/ValidClientScheme.php index 503125e1d8..dacacb17a9 100644 --- a/app/Http/ValidationRules/EInvoice/ValidClientScheme.php +++ b/app/Http/ValidationRules/EInvoice/ValidClientScheme.php @@ -34,7 +34,7 @@ class ValidClientScheme implements ValidationRule, ValidatorAwareRule public function validate(string $attribute, mixed $value, Closure $fail): void { - if(isset($value['Invoice'])) { + if (isset($value['Invoice'])) { $r = new EInvoice(); $errors = $r->validateRequest($value['Invoice'], ClientLevel::class); diff --git a/app/Http/ValidationRules/EInvoice/ValidCompanyScheme.php b/app/Http/ValidationRules/EInvoice/ValidCompanyScheme.php index 7af375d669..9403ffadd1 100644 --- a/app/Http/ValidationRules/EInvoice/ValidCompanyScheme.php +++ b/app/Http/ValidationRules/EInvoice/ValidCompanyScheme.php @@ -34,7 +34,7 @@ class ValidCompanyScheme implements ValidationRule, ValidatorAwareRule public function validate(string $attribute, mixed $value, Closure $fail): void { - if(isset($value['Invoice'])) { + if (isset($value['Invoice'])) { $r = new EInvoice(); $errors = $r->validateRequest($value['Invoice'], CompanyLevel::class); diff --git a/app/Http/ValidationRules/Invoice/LockedInvoiceRule.php b/app/Http/ValidationRules/Invoice/LockedInvoiceRule.php index cb0dcde421..84a3b5500a 100644 --- a/app/Http/ValidationRules/Invoice/LockedInvoiceRule.php +++ b/app/Http/ValidationRules/Invoice/LockedInvoiceRule.php @@ -71,7 +71,7 @@ class LockedInvoiceRule implements Rule //if now is greater than the end of month the invoice was dated - do not modify case 'end_of_month': - if(\Carbon\Carbon::parse($this->invoice->date)->setTimezone($this->invoice->company->timezone()->name)->endOfMonth()->lte(now())) { + if (\Carbon\Carbon::parse($this->invoice->date)->setTimezone($this->invoice->company->timezone()->name)->endOfMonth()->lte(now())) { return false; } diff --git a/app/Http/ValidationRules/Payment/ValidInvoicesRules.php b/app/Http/ValidationRules/Payment/ValidInvoicesRules.php index 6dceddaaaa..404d0a27e0 100644 --- a/app/Http/ValidationRules/Payment/ValidInvoicesRules.php +++ b/app/Http/ValidationRules/Payment/ValidInvoicesRules.php @@ -87,7 +87,7 @@ class ValidInvoicesRules implements Rule } elseif (floatval($invoice['amount']) > floatval($inv->balance)) { $this->error_msg = ctrans('texts.amount_greater_than_balance_v5'); return false; - } elseif($inv->is_deleted) { + } elseif ($inv->is_deleted) { $this->error_msg = 'One or more invoices in this request have since been deleted'; return false; } diff --git a/app/Http/ValidationRules/Payment/ValidRefundableRequest.php b/app/Http/ValidationRules/Payment/ValidRefundableRequest.php index e7477f9b18..5125934512 100644 --- a/app/Http/ValidationRules/Payment/ValidRefundableRequest.php +++ b/app/Http/ValidationRules/Payment/ValidRefundableRequest.php @@ -100,7 +100,7 @@ class ValidRefundableRequest implements Rule { $record_found = false; - foreach($paymentables as $paymentable) { + foreach ($paymentables as $paymentable) { foreach ($request_invoices as $request_invoice) { if ($request_invoice['invoice_id'] == $paymentable->pivot->paymentable_id) { diff --git a/app/Http/ValidationRules/PaymentAppliedValidAmount.php b/app/Http/ValidationRules/PaymentAppliedValidAmount.php index fa9d7f04f1..155bf490e0 100644 --- a/app/Http/ValidationRules/PaymentAppliedValidAmount.php +++ b/app/Http/ValidationRules/PaymentAppliedValidAmount.php @@ -87,7 +87,7 @@ class PaymentAppliedValidAmount implements Rule $inv = $inv_collection->firstWhere('id', $invoice['invoice_id']); - if($inv->status_id == Invoice::STATUS_DRAFT && $inv->amount >= $invoice['amount']) { + if ($inv->status_id == Invoice::STATUS_DRAFT && $inv->amount >= $invoice['amount']) { } elseif ($inv->balance < $invoice['amount']) { $this->message = 'Amount cannot be greater than invoice balance'; @@ -96,7 +96,7 @@ class PaymentAppliedValidAmount implements Rule } } - if(count($this->input['invoices']) >= 1 && $payment->status_id == Payment::STATUS_PENDING) { + if (count($this->input['invoices']) >= 1 && $payment->status_id == Payment::STATUS_PENDING) { $this->message = 'Cannot apply a payment until the status is completed.'; return false; } diff --git a/app/Http/ValidationRules/Project/ValidProjectForClient.php b/app/Http/ValidationRules/Project/ValidProjectForClient.php index 0cf2c4a0ac..b348aeded6 100644 --- a/app/Http/ValidationRules/Project/ValidProjectForClient.php +++ b/app/Http/ValidationRules/Project/ValidProjectForClient.php @@ -51,7 +51,7 @@ class ValidProjectForClient implements Rule return false; } - if(!isset($this->input['client_id'])) { + if (!isset($this->input['client_id'])) { $this->message = 'No Client ID provided.'; return false; } diff --git a/app/Http/ValidationRules/User/HasValidPhoneNumber.php b/app/Http/ValidationRules/User/HasValidPhoneNumber.php index 48cde515fc..086a0cdab6 100644 --- a/app/Http/ValidationRules/User/HasValidPhoneNumber.php +++ b/app/Http/ValidationRules/User/HasValidPhoneNumber.php @@ -71,7 +71,7 @@ class HasValidPhoneNumber implements Rule $user->save(); return true; - } catch(\Exception $e) { + } catch (\Exception $e) { return false; } } diff --git a/app/Http/ViewComposers/Components/Rotessa/AddressComponent.php b/app/Http/ViewComposers/Components/Rotessa/AddressComponent.php index 5923217b2e..26ac8f7e6f 100644 --- a/app/Http/ViewComposers/Components/Rotessa/AddressComponent.php +++ b/app/Http/ViewComposers/Components/Rotessa/AddressComponent.php @@ -36,7 +36,7 @@ class AddressComponent extends Component public function __construct(public array $address) { - if(strlen($this->address['state']) > 2) { + if (strlen($this->address['state']) > 2) { $this->address['state'] = $this->address['country'] == 'US' ? array_search($this->address['state'], USStates::$states) : CAProvinces::getAbbreviation($this->address['state']); } diff --git a/app/Import/Providers/BaseImport.php b/app/Import/Providers/BaseImport.php index c95740c119..44c592b999 100644 --- a/app/Import/Providers/BaseImport.php +++ b/app/Import/Providers/BaseImport.php @@ -196,8 +196,9 @@ class BaseImport public function groupClients($csvData, $key) { - if(!$key || !isset($csvData[0][$key])) + if (!$key || !isset($csvData[0][$key])) { return $csvData; + } $grouped = []; @@ -283,7 +284,7 @@ class BaseImport unset($record['']); - if(!is_array($record)) { + if (!is_array($record)) { continue; } @@ -343,7 +344,7 @@ class BaseImport foreach ($data as $key => $record) { - if(!is_array($record)) { + if (!is_array($record)) { continue; } @@ -410,7 +411,7 @@ class BaseImport foreach ($invoices as $raw_invoice) { - if(!is_array($raw_invoice)) { + if (!is_array($raw_invoice)) { continue; } @@ -505,7 +506,7 @@ class BaseImport foreach ($tasks as $raw_task) { $task_data = []; - if(!is_array($raw_task)) { + if (!is_array($raw_task)) { continue; } @@ -578,7 +579,7 @@ class BaseImport foreach ($invoices as $raw_invoice) { - if(!is_array($raw_invoice)) { + if (!is_array($raw_invoice)) { continue; } @@ -630,7 +631,7 @@ class BaseImport nlog($invoice_data); $saveable_invoice_data = $invoice_data; - if(array_key_exists('payments', $saveable_invoice_data)) { + if (array_key_exists('payments', $saveable_invoice_data)) { unset($saveable_invoice_data['payments']); } @@ -646,11 +647,10 @@ class BaseImport // Check for payment columns if (! empty($invoice_data['payments'])) { foreach ( - $invoice_data['payments'] - as $payment_data + $invoice_data['payments'] as $payment_data ) { - if($payment_data['amount'] == 0 && $invoice_data['status_id'] == 4){ + if ($payment_data['amount'] == 0 && $invoice_data['status_id'] == 4) { $payment_data['amount'] = $invoice->amount; } @@ -678,7 +678,7 @@ class BaseImport $payment_date = Carbon::parse($payment->date); - if(!$payment_date->isToday()) { + if (!$payment_date->isToday()) { $payment->paymentables()->update(['created_at' => $payment_date]); @@ -803,7 +803,7 @@ class BaseImport foreach ($quotes as $raw_quote) { - if(!is_array($raw_quote)) { + if (!is_array($raw_quote)) { continue; } @@ -892,7 +892,7 @@ class BaseImport { $user = false; - if(is_numeric($user_hash)) { + if (is_numeric($user_hash)) { $user = User::query() ->where('account_id', $this->company->account->id) @@ -901,7 +901,7 @@ class BaseImport } - if($user) { + if ($user) { return $user->id; } @@ -964,7 +964,7 @@ class BaseImport $diff = array_diff($key_keys, $row_keys); - if(!empty($diff)) { + if (!empty($diff)) { return false; } /** 12-04-2024 If we do not have matching keys - then this row import is _not_ valid */ diff --git a/app/Import/Providers/Wave.php b/app/Import/Providers/Wave.php index ce936dd01a..7ec5c1be91 100644 --- a/app/Import/Providers/Wave.php +++ b/app/Import/Providers/Wave.php @@ -117,8 +117,8 @@ class Wave extends BaseImport implements ImportInterface $this->transformer = new InvoiceTransformer($this->company); - foreach($data as $key => $invoice) { - if(!isset($invoice['Invoice Number']) || empty($invoice['Invoice Number'])) { + foreach ($data as $key => $invoice) { + if (!isset($invoice['Invoice Number']) || empty($invoice['Invoice Number'])) { unset($data[$key]); } } @@ -233,7 +233,7 @@ class Wave extends BaseImport implements ImportInterface foreach ($expenses as $raw_expense) { - if(!is_array($raw_expense)) { + if (!is_array($raw_expense)) { continue; } @@ -244,7 +244,7 @@ class Wave extends BaseImport implements ImportInterface if (empty($expense_data['vendor_id'])) { $vendor_data['user_id'] = $this->getUserIDForRecord($expense_data); - if(isset($raw_expense['Vendor Name']) || isset($raw_expense['Vendor'])) { + if (isset($raw_expense['Vendor Name']) || isset($raw_expense['Vendor'])) { $vendor_repository->save( ['name' => isset($raw_expense['Vendor Name']) ? $raw_expense['Vendor Name'] : isset($raw_expense['Vendor'])], $vendor = VendorFactory::create( diff --git a/app/Import/Transformer/BaseTransformer.php b/app/Import/Transformer/BaseTransformer.php index 3fe48a5259..96c1a5c597 100644 --- a/app/Import/Transformer/BaseTransformer.php +++ b/app/Import/Transformer/BaseTransformer.php @@ -47,7 +47,7 @@ class BaseTransformer public function parseDate($date) { - if(stripos($date, "/") !== false && $this->company->settings->country_id != 840) { + if (stripos($date, "/") !== false && $this->company->settings->country_id != 840) { $date = str_replace('/', '-', $date); } @@ -55,7 +55,7 @@ class BaseTransformer $parsed_date = Carbon::parse($date); return $parsed_date->format('Y-m-d'); - } catch(\Exception $e) { + } catch (\Exception $e) { $parsed_date = date('Y-m-d', strtotime($date)); if ($parsed_date == '1970-01-01') { @@ -70,11 +70,11 @@ class BaseTransformer { $date = &$data[$field]; - if(!$date || strlen($date) <= 1) { + if (!$date || strlen($date) <= 1) { return null; } - if(stripos($date, "/") !== false && $this->company->settings->country_id != 840) { + if (stripos($date, "/") !== false && $this->company->settings->country_id != 840) { $date = str_replace('/', '-', $date); } @@ -82,7 +82,7 @@ class BaseTransformer $parsed_date = Carbon::parse($date); return $parsed_date->format('Y-m-d'); - } catch(\Exception $e) { + } catch (\Exception $e) { $parsed_date = date('Y-m-d', strtotime($date)); if ($parsed_date == '1970-01-01') { @@ -119,7 +119,7 @@ class BaseTransformer { $code = array_key_exists($key, $data) ? $data[$key] : false; - if(!$code) { + if (!$code) { return $this->company->settings->currency_id; } @@ -230,13 +230,13 @@ class BaseTransformer return $client_name_search->first()->id; } } - if (strlen($client_email ?? '' ) >= 1) { + if (strlen($client_email ?? '') >= 1) { $contacts = ClientContact::query()->whereHas('client', function ($query) { $query->where('is_deleted', false); }) ->where('company_id', $this->company->id) ->where('email', $client_email); - + if ($contacts->count() >= 1) { return $contacts->first()->client_id; } @@ -275,14 +275,14 @@ class BaseTransformer public function hasClient($name) { - $x= Client::query() + $x = Client::query() ->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`name`, ' ' , '')) = ?", [ strtolower(str_replace(' ', '', $name)), ]); - return $x->exists(); + return $x->exists(); } public function hasClientIdNumber($id_number) @@ -347,11 +347,12 @@ class BaseTransformer */ public function getFloat($data, $field) { - + if (array_key_exists($field, $data)) { - if($this->company->use_comma_as_decimal_place) + if ($this->company->use_comma_as_decimal_place) { return $this->parseCommaFloat($data, $field); + } return Number::parseFloat($data[$field]); } @@ -376,7 +377,7 @@ class BaseTransformer $amount = str_replace(".", "", $amount); $amount = str_replace(",", '.', $amount); - + // Convert to float and apply negative sign if necessary $result = (float) $amount; return $isNegative ? -$result : $result; @@ -699,7 +700,7 @@ class BaseTransformer ]) ->first(); - if($ec) { + if ($ec) { return $ec->id; } @@ -736,7 +737,7 @@ class BaseTransformer */ public function getProjectId($name, $clientId = null) { - if(strlen($name) == 0) { + if (strlen($name) == 0) { return null; } diff --git a/app/Import/Transformer/Csv/ClientTransformer.php b/app/Import/Transformer/Csv/ClientTransformer.php index e8d3a8dc11..5746589a29 100644 --- a/app/Import/Transformer/Csv/ClientTransformer.php +++ b/app/Import/Transformer/Csv/ClientTransformer.php @@ -118,7 +118,7 @@ class ClientTransformer extends BaseTransformer $client['contacts'] = $contacts; nlog($client); - + return $client; } diff --git a/app/Import/Transformer/Csv/TaskTransformer.php b/app/Import/Transformer/Csv/TaskTransformer.php index 54636349f0..a4899409f0 100644 --- a/app/Import/Transformer/Csv/TaskTransformer.php +++ b/app/Import/Transformer/Csv/TaskTransformer.php @@ -29,7 +29,7 @@ class TaskTransformer extends BaseTransformer { $this->stubbed_timestamp = time(); - if(count($task_items_data) == count($task_items_data, COUNT_RECURSIVE)) { + if (count($task_items_data) == count($task_items_data, COUNT_RECURSIVE)) { $task_data = $task_items_data; } else { $task_data = reset($task_items_data); @@ -57,7 +57,7 @@ class TaskTransformer extends BaseTransformer 'custom_value4' => $this->getString($task_data, 'task.custom_value4'), ]; - if(count($task_items_data) == count($task_items_data, COUNT_RECURSIVE)) { + if (count($task_items_data) == count($task_items_data, COUNT_RECURSIVE)) { $transformed['time_log'] = json_encode([$this->parseLog($task_items_data)]); return $transformed; } @@ -80,18 +80,18 @@ class TaskTransformer extends BaseTransformer $notes = $item['task.notes'] ?? ''; - if(isset($item['task.billable']) && is_string($item['task.billable']) && in_array($item['task.billable'], ['yes', 'true', '1', 'TRUE', 'YES'])) { + if (isset($item['task.billable']) && is_string($item['task.billable']) && in_array($item['task.billable'], ['yes', 'true', '1', 'TRUE', 'YES'])) { $is_billable = true; - } elseif(isset($item['task.billable']) && is_bool($item['task.billable'])) { + } elseif (isset($item['task.billable']) && is_bool($item['task.billable'])) { $is_billable = $item['task.billable']; } else { $is_billable = true; } - if(isset($item['task.start_date'])) { + if (isset($item['task.start_date'])) { $start_date = $this->resolveStartDate($item); $end_date = $this->resolveEndDate($item); - } elseif(isset($item['task.duration'])) { + } elseif (isset($item['task.duration'])) { $duration = strtotime($item['task.duration']) - strtotime('TODAY'); $start_date = $this->stubbed_timestamp; $end_date = $this->stubbed_timestamp + $duration; @@ -143,7 +143,7 @@ class TaskTransformer extends BaseTransformer $stub_end_date = \Carbon\Carbon::parse($stub_end_date); - if($stub_end_date->timestamp == $this->stubbed_timestamp) { + if ($stub_end_date->timestamp == $this->stubbed_timestamp) { $this->stubbed_timestamp; return $this->stubbed_timestamp; } @@ -174,7 +174,7 @@ class TaskTransformer extends BaseTransformer private function getTaskStatusId($item): ?int { - if(isset($item['task.status'])) { + if (isset($item['task.status'])) { $name = strtolower(trim($item['task.status'])); $ts = TaskStatus::query()->where('company_id', $this->company->id) @@ -184,7 +184,7 @@ class TaskTransformer extends BaseTransformer ]) ->first(); - if($ts) { + if ($ts) { return $ts->id; } } diff --git a/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php b/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php index 55d7fc7445..3d189000c0 100644 --- a/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php +++ b/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php @@ -72,8 +72,8 @@ class InvoiceTransformer extends BaseTransformer if ($client_id) { $transformed['client_id'] = $client_id; - } - + } + $settings = new \stdClass(); $settings->currency_id = $this->getCurrencyByCode($invoice_data, 'Currency'); @@ -102,14 +102,14 @@ class InvoiceTransformer extends BaseTransformer 'amount' => $this->getFloat($invoice_data, 'Payments'), ], ]; - } elseif(isset($invoice_data['AmountPaidAmount']) && isset($invoice_data['DatePaid'])) { + } elseif (isset($invoice_data['AmountPaidAmount']) && isset($invoice_data['DatePaid'])) { $transformed['payments'] = [ [ 'date' => $this->parseDate($invoice_data['DatePaid']), 'amount' => $this->getFloat($invoice_data, 'AmountPaidAmount'), ] ]; - } elseif(isset($invoice_data['DocumentStatus']) && $invoice_data['DocumentStatus'] == 'fully_paid') { + } elseif (isset($invoice_data['DocumentStatus']) && $invoice_data['DocumentStatus'] == 'fully_paid') { $transformed['payments'] = [ [ @@ -130,12 +130,12 @@ class InvoiceTransformer extends BaseTransformer $lines = explode("\n", $address); $billing_address = []; - if(count($lines) == 2) { + if (count($lines) == 2) { $billing_address['address1'] = $lines[0]; $parts = explode(",", $lines[1]); - if(count($parts) == 3) { + if (count($parts) == 3) { $billing_address['city'] = $parts[0]; $billing_address['state'] = $parts[1]; $billing_address['postal_code'] = $parts[2]; @@ -148,12 +148,12 @@ class InvoiceTransformer extends BaseTransformer $lines = explode("\n", $shipaddress); - if(count($lines) == 2) { + if (count($lines) == 2) { $shipping_address['address1'] = $lines[0]; $parts = explode(",", $lines[1]); - if(count($parts) == 3) { + if (count($parts) == 3) { $shipping_address['shipping_city'] = $parts[0]; $shipping_address['shipping_state'] = $parts[1]; $shipping_address['shipping_postal_code'] = $parts[2]; @@ -198,7 +198,7 @@ class InvoiceTransformer extends BaseTransformer ], ]; - if(!isset($invoice_data['Items'])) { + if (!isset($invoice_data['Items'])) { return $default_data; } @@ -207,7 +207,7 @@ class InvoiceTransformer extends BaseTransformer $line_items = []; - foreach($processed as $item) { + foreach ($processed as $item) { $_item['cost'] = $item['unit_price']; $_item['quantity'] = $item['qty'] ?? 1; $_item['discount'] = $item['discount_percentage'] > $item['discount_amount'] ? $item['discount_percentage'] : $item['discount_amount']; @@ -228,7 +228,7 @@ class InvoiceTransformer extends BaseTransformer private function parseTaxes($ninja_item, $i2g_item): array { - if(is_string($i2g_item['applied_taxes'])) { + if (is_string($i2g_item['applied_taxes'])) { return $ninja_item; } @@ -272,19 +272,19 @@ class InvoiceTransformer extends BaseTransformer } - foreach($parsedRows as $key => &$row) { + foreach ($parsedRows as $key => &$row) { - if($key == 0) { + if ($key == 0) { continue; } /** @var array $row */ - if(is_array($row[5])) { + if (is_array($row[5])) { $csv = str_getcsv($row[5][0], ";"); $row[5] = array_combine(explode(",", $csv[0]), explode(",", $csv[1])); } - if(is_array($row[1])) { + if (is_array($row[1])) { $row[1] = $row[1][0]; } diff --git a/app/Import/Transformer/Wave/ExpenseTransformer.php b/app/Import/Transformer/Wave/ExpenseTransformer.php index 9bfa34c0b4..346b3c5d43 100644 --- a/app/Import/Transformer/Wave/ExpenseTransformer.php +++ b/app/Import/Transformer/Wave/ExpenseTransformer.php @@ -38,7 +38,7 @@ class ExpenseTransformer extends BaseTransformer $tax_rate = $total_tax > 0 ? round(($total_tax / $amount) * 100, 3) : 0; - if(isset($data['Notes / Memo']) && strlen($data['Notes / Memo']) > 1) { + if (isset($data['Notes / Memo']) && strlen($data['Notes / Memo']) > 1) { $public_notes = $data['Notes / Memo']; } elseif (isset($data['Transaction Description']) && strlen($data['Transaction Description']) > 1) { $public_notes = $data['Transaction Description']; diff --git a/app/Import/Transformer/Zoho/ClientTransformer.php b/app/Import/Transformer/Zoho/ClientTransformer.php index 4c5e8d839c..b15a06bd2a 100644 --- a/app/Import/Transformer/Zoho/ClientTransformer.php +++ b/app/Import/Transformer/Zoho/ClientTransformer.php @@ -29,7 +29,7 @@ class ClientTransformer extends BaseTransformer { $client_id_proxy = array_key_exists('Customer ID', $data) ? 'Customer ID' : 'Primary Contact ID'; - if(isset($data[$client_id_proxy]) && $this->hasClientIdNumber($data[$client_id_proxy])) { + if (isset($data[$client_id_proxy]) && $this->hasClientIdNumber($data[$client_id_proxy])) { throw new ImportException('Client ID already exists => '. $data[$client_id_proxy]); } elseif (isset($data['Company Name']) && $this->hasClient($data['Company Name'])) { throw new ImportException('Client already exists => '. $data['Company Name']); diff --git a/app/Import/Transformer/Zoho/InvoiceTransformer.php b/app/Import/Transformer/Zoho/InvoiceTransformer.php index 0f5bfcc4d8..292b8b31be 100644 --- a/app/Import/Transformer/Zoho/InvoiceTransformer.php +++ b/app/Import/Transformer/Zoho/InvoiceTransformer.php @@ -101,7 +101,7 @@ class InvoiceTransformer extends BaseTransformer $client_name = $this->getString($invoice_data, 'Customer Name'); - if(strlen($client_name) >= 2) { + if (strlen($client_name) >= 2) { $client_name_search = \App\Models\Client::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ diff --git a/app/Jobs/Bank/MatchBankTransactions.php b/app/Jobs/Bank/MatchBankTransactions.php index c2ff03eee6..8ab3c4619c 100644 --- a/app/Jobs/Bank/MatchBankTransactions.php +++ b/app/Jobs/Bank/MatchBankTransactions.php @@ -332,8 +332,8 @@ class MatchBankTransactions implements ShouldQueue return; } - -nlog("post"); + + nlog("post"); /* Create Payment */ $payment = PaymentFactory::create($this->invoice->company_id, $this->invoice->user_id); @@ -391,7 +391,7 @@ nlog("post"); $hashed_keys = []; - foreach($this->attachable_invoices as $attachable_invoice) { //@phpstan-ignore-line + foreach ($this->attachable_invoices as $attachable_invoice) { //@phpstan-ignore-line $hashed_keys[] = $this->encodePrimaryKey($attachable_invoice['id']); } @@ -400,7 +400,7 @@ nlog("post"); $this->bt->payment_id = $payment->id; $this->bt->save(); -nlog($this->bt->toArray()); + nlog($this->bt->toArray()); } diff --git a/app/Jobs/Bank/ProcessBankTransactionsNordigen.php b/app/Jobs/Bank/ProcessBankTransactionsNordigen.php index 3f7255b5dd..2e0df4a0da 100644 --- a/app/Jobs/Bank/ProcessBankTransactionsNordigen.php +++ b/app/Jobs/Bank/ProcessBankTransactionsNordigen.php @@ -38,7 +38,7 @@ class ProcessBankTransactionsNordigen implements ShouldQueue public Company $company; public Nordigen $nordigen; public $nordigen_account; - + /** * Create a new job instance. */ @@ -113,7 +113,7 @@ class ProcessBankTransactionsNordigen implements ShouldQueue // Perform Matching BankMatchingService::dispatch($this->company->id, $this->company->db); } - + // const DISCOVERED = 'DISCOVERED'; // Account was discovered but not yet processed // const PROCESSING = 'PROCESSING'; // Initial processing of account // const READY = 'READY'; // Account ready to be accessed @@ -125,9 +125,9 @@ class ProcessBankTransactionsNordigen implements ShouldQueue private function updateAccount() { $account_status = $this->nordigen->isAccountActive($this->bank_integration->nordigen_account_id); - + //Return early if the account status is not in a good state - if(isset($account_status['status']) && in_array($account_status['status'], ['EXPIRED','DELETED'])) { + if (isset($account_status['status']) && in_array($account_status['status'], ['EXPIRED','DELETED'])) { $this->bank_integration->disabled_upstream = true; $this->bank_integration->bank_account_status = $account_status['status']; @@ -136,30 +136,30 @@ class ProcessBankTransactionsNordigen implements ShouldQueue nlog("Nordigen: account inactive: " . $this->bank_integration->nordigen_account_id); //Need requisition refresh! - if($account_status['status'] == 'EXPIRED') + if ($account_status['status'] == 'EXPIRED') { $this->nordigen->disabledAccountEmail($this->bank_integration); + } return; - } - elseif(isset($account_status['status']) && $account_status['status'] != 'READY') { + } elseif (isset($account_status['status']) && $account_status['status'] != 'READY') { //There may be other issues, return and await retry nlog($account_status['id']. " Nordigen account status == ". $account_status['status']); return; } - + $account = $this->nordigen->getAccount($this->bank_integration->nordigen_account_id); - if(isset($account['error'])){ - + if (isset($account['error'])) { + $this->bank_integration->bank_account_status = "Error:: " . $account['error']; $this->bank_integration->save(); return; } - if(!$account){ + if (!$account) { $this->bank_integration->bank_account_status = "Error:: Failed to update account."; $this->bank_integration->save(); diff --git a/app/Jobs/Brevo/ProcessBrevoInboundWebhook.php b/app/Jobs/Brevo/ProcessBrevoInboundWebhook.php index ae6660b7ef..6ce61a25fe 100644 --- a/app/Jobs/Brevo/ProcessBrevoInboundWebhook.php +++ b/app/Jobs/Brevo/ProcessBrevoInboundWebhook.php @@ -28,7 +28,10 @@ use Illuminate\Queue\Middleware\WithoutOverlapping; class ProcessBrevoInboundWebhook implements ShouldQueue { - use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; + use Dispatchable; + use InteractsWithQueue; + use Queueable; + use SerializesModels; public $tries = 1; @@ -134,7 +137,7 @@ class ProcessBrevoInboundWebhook implements ShouldQueue // match company $company = MultiDB::findAndSetDbByExpenseMailbox($recipient); - + if (!$company) { nlog('[ProcessBrevoInboundWebhook] unknown Expense Mailbox occured while handling an inbound email from brevo: ' . $recipient); continue; @@ -146,12 +149,12 @@ class ProcessBrevoInboundWebhook implements ShouldQueue try { // important to save meta if something fails here to prevent spam - if(strlen($company->getSetting('brevo_secret') ?? '') < 2 && empty(config('services.brevo.secret'))){ + if (strlen($company->getSetting('brevo_secret') ?? '') < 2 && empty(config('services.brevo.secret'))) { nlog("No Brevo Configuration available for this company"); throw new \Error("[ProcessBrevoInboundWebhook] no brevo credenitals found, we cannot get the attachement"); } - - $company_brevo_secret = strlen($company->getSetting('brevo_secret') ?? '') < 2 ? $company->getSetting('brevo_secret') : config('services.brevo.secret'); + + $company_brevo_secret = strlen($company->getSetting('brevo_secret') ?? '') < 2 ? $company->getSetting('brevo_secret') : config('services.brevo.secret'); // prepare data for ingresEngine $inboundMail = new InboundMail(); @@ -168,8 +171,7 @@ class ProcessBrevoInboundWebhook implements ShouldQueue // @todo - i think this allows switching between client configured brevo AND system configured brevo // download file and save to tmp dir - if (!empty($company_brevo_secret)) - { + if (!empty($company_brevo_secret)) { try { @@ -195,8 +197,9 @@ class ProcessBrevoInboundWebhook implements ShouldQueue true // Mark it as test, since the file isn't from real HTTP POST. ); - } else + } else { throw $e; + } } } else { @@ -223,10 +226,11 @@ class ProcessBrevoInboundWebhook implements ShouldQueue } // document for spam => mark all recipients as handled emails with unmatched mailbox => otherwise dont do any - if (!$foundOneRecipient) + if (!$foundOneRecipient) { foreach ($this->input["Recipients"] as $recipient) { $this->engine->saveMeta($this->input["From"]["Address"], $recipient, true); } + } } public function middleware() diff --git a/app/Jobs/Brevo/ProcessBrevoWebhook.php b/app/Jobs/Brevo/ProcessBrevoWebhook.php index 84c289a8e8..a177d6f175 100644 --- a/app/Jobs/Brevo/ProcessBrevoWebhook.php +++ b/app/Jobs/Brevo/ProcessBrevoWebhook.php @@ -426,7 +426,7 @@ class ProcessBrevoWebhook implements ShouldQueue public function getRawMessage(string $message_id) { - $brevo_secret = !empty ($this->company->settings->brevo_secret) ? $this->company->settings->brevo_secret : config('services.brevo.secret'); + $brevo_secret = !empty($this->company->settings->brevo_secret) ? $this->company->settings->brevo_secret : config('services.brevo.secret'); $brevo = new TransactionalEmailsApi(null, Configuration::getDefaultConfiguration()->setApiKey('api-key', $brevo_secret)); $messageDetail = $brevo->getTransacEmailContent($message_id); diff --git a/app/Jobs/Client/UpdateTaxData.php b/app/Jobs/Client/UpdateTaxData.php index 4801b71e1b..570b92aace 100644 --- a/app/Jobs/Client/UpdateTaxData.php +++ b/app/Jobs/Client/UpdateTaxData.php @@ -51,7 +51,7 @@ class UpdateTaxData implements ShouldQueue { MultiDB::setDb($this->company->db); - if($this->company->account->isFreeHostedClient() || $this->client->country_id != 840) { + if ($this->company->account->isFreeHostedClient() || $this->client->country_id != 840) { return; } @@ -69,7 +69,7 @@ class UpdateTaxData implements ShouldQueue } - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: UpdateTaxData::" . $e->getMessage()); nlog("problem getting tax data => ".$e->getMessage()); } diff --git a/app/Jobs/Company/CompanyExport.php b/app/Jobs/Company/CompanyExport.php index a13dbed61a..86bac45521 100644 --- a/app/Jobs/Company/CompanyExport.php +++ b/app/Jobs/Company/CompanyExport.php @@ -679,15 +679,15 @@ class CompanyExport implements ShouldQueue Storage::disk(config('filesystems.default'))->put('backups/'.str_replace(".json", ".zip", $this->file_name), file_get_contents($zip_path)); - if(file_exists($zip_path)) { + if (file_exists($zip_path)) { unlink($zip_path); } - if(file_exists(sys_get_temp_dir().'/'.$this->file_name)) { + if (file_exists(sys_get_temp_dir().'/'.$this->file_name)) { unlink(sys_get_temp_dir().'/'.$this->file_name); } - if(Ninja::isSelfHost()) { + if (Ninja::isSelfHost()) { $storage_path = 'backups/'.str_replace(".json", ".zip", $this->file_name); } else { $storage_path = Storage::disk(config('filesystems.default'))->path('backups/'.str_replace(".json", ".zip", $this->file_name)); @@ -714,7 +714,7 @@ class CompanyExport implements ShouldQueue if (Ninja::isHosted()) { sleep(3); - if(file_exists(sys_get_temp_dir().'/'.$zip_path)) { + if (file_exists(sys_get_temp_dir().'/'.$zip_path)) { unlink(sys_get_temp_dir().'/'.$zip_path); } } diff --git a/app/Jobs/Company/CompanyImport.php b/app/Jobs/Company/CompanyImport.php index 71336ef0a7..e4b85ab179 100644 --- a/app/Jobs/Company/CompanyImport.php +++ b/app/Jobs/Company/CompanyImport.php @@ -346,18 +346,19 @@ class CompanyImport implements ShouldQueue $nmo->settings = $_company->settings; $nmo->to_user = $_company->owner(); NinjaMailerJob::dispatch($nmo); - } catch(\Exception $e) { + } catch (\Exception $e) { info($e->getMessage()); } } - if(file_exists($tmp_file)) { + if (file_exists($tmp_file)) { unlink($tmp_file); } - if(Storage::exists($this->file_location)) + if (Storage::exists($this->file_location)) { Storage::delete($this->file_location); - + } + } private function miscTransformations() @@ -365,43 +366,41 @@ class CompanyImport implements ShouldQueue Invoice::withTrashed() ->where('company_id', $this->company->id) ->cursor() - ->each(function ($invoice){ + ->each(function ($invoice) { - $items = $invoice->line_items; + $items = $invoice->line_items; - foreach($items as $key => $value) - { + foreach ($items as $key => $value) { - if(isset($value->task_id) && strlen($value->task_id) >1) { + if (isset($value->task_id) && strlen($value->task_id) > 1) { - $t_id = $this->transformId('tasks',$value->task_id); + $t_id = $this->transformId('tasks', $value->task_id); + + if ($t = Task::withTrashed()->where('company_id', $this->company->id)->where('id', $t_id)->first()) { + $items[$key]->task_id = $t->hashed_id; + } - if($t = Task::withTrashed()->where('company_id', $this->company->id)->where('id',$t_id)->first()) - { - $items[$key]->task_id = $t->hashed_id; } - - } - - - if (isset($value->expense_id) && strlen($value->expense_id) > 1) { - - $e_id = $this->transformId('expenses', $value->expense_id); - if ($e = Expense::withTrashed()->where('company_id', $this->company->id)->where('id', $e_id)->first()) { - $items[$key]->expense_id = $e->hashed_id; + + if (isset($value->expense_id) && strlen($value->expense_id) > 1) { + + $e_id = $this->transformId('expenses', $value->expense_id); + + if ($e = Expense::withTrashed()->where('company_id', $this->company->id)->where('id', $e_id)->first()) { + $items[$key]->expense_id = $e->hashed_id; + } + } } - } - - $invoice->line_items = array_values($items); - $invoice->saveQuietly(); + $invoice->line_items = array_values($items); + $invoice->saveQuietly(); - }); + }); return $this; } @@ -562,7 +561,7 @@ class CompanyImport implements ShouldQueue $settings->email_style_custom = str_replace(['{!!','!!}','{{','}}','@dd', '@dump', '@if', '@if(','@endif','@isset','@unless','@auth','@empty','@guest','@env','@section','@switch', '@foreach', '@while', '@include', '@each', '@once', '@push', '@use', '@forelse', '@verbatim', 'email_style_custom); $settings->company_logo = (strlen($settings->company_logo) > 2 && stripos($settings->company_logo, 'http') !== false) ? $settings->company_logo : "https://{$settings->company_logo}"; - foreach($this->protected_input as $protected_var) { + foreach ($this->protected_input as $protected_var) { $settings->{$protected_var} = str_replace("script", "", $settings->{$protected_var}); } @@ -1266,7 +1265,7 @@ class CompanyImport implements ShouldQueue Storage::disk(config('filesystems.default'))->put($document->url, $file); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog($e->getMessage()); nlog("I could not upload {$document->url}"); @@ -1469,7 +1468,7 @@ class CompanyImport implements ShouldQueue private function filterVersionProps($class, array $obj_array): array { - if($this->current_app_version == $this->import_version) { + if ($this->current_app_version == $this->import_version) { return $obj_array; } @@ -1478,7 +1477,7 @@ class CompanyImport implements ShouldQueue $filters = collect($this->version_keys) ->map(function ($value, $key) use (&$version_index, &$index) { - if($this->import_version == $key) { + if ($this->import_version == $key) { $version_index = $index; } @@ -1518,7 +1517,7 @@ class CompanyImport implements ShouldQueue $obj_array['gateway_key'] = 'd14dd26a37cecc30fdd65700bfb55b23'; } - if(!isset($obj_array['fees_and_limits'])) { + if (!isset($obj_array['fees_and_limits'])) { $obj_array['fees_and_limits'] = \json_encode([]); } } @@ -1565,12 +1564,12 @@ class CompanyImport implements ShouldQueue * @property string $entity_id */ - if($class == 'App\Models\Scheduler') { + if ($class == 'App\Models\Scheduler') { /** @var \stdClass $parameters */ $parameters = $obj_array['parameters']; - if(isset($parameters->clients)) { + if (isset($parameters->clients)) { $parameters->clients = collect($parameters->clients)->map(function ($client_hash) { @@ -1579,7 +1578,7 @@ class CompanyImport implements ShouldQueue } - if(isset($parameters->entity_id)) { + if (isset($parameters->entity_id)) { $parameters->entity_id = $this->encodePrimaryKey($this->transformId($parameters->entity."s", $parameters->entity_id)); } diff --git a/app/Jobs/Company/CompanyTaxRate.php b/app/Jobs/Company/CompanyTaxRate.php index d0b7f0864b..61fdeed9b1 100644 --- a/app/Jobs/Company/CompanyTaxRate.php +++ b/app/Jobs/Company/CompanyTaxRate.php @@ -49,27 +49,27 @@ class CompanyTaxRate implements ShouldQueue $tp = new TaxProvider($this->company); $tp->updateCompanyTaxData(); - if(!$tp->updatedTaxStatus() && $this->company->settings->country_id == '840') { + if (!$tp->updatedTaxStatus() && $this->company->settings->country_id == '840') { $calculated_state = false; /** State must be calculated else default to the company state for taxes */ - if(array_key_exists($this->company->settings->state, USStates::get())) { + if (array_key_exists($this->company->settings->state, USStates::get())) { $calculated_state = $this->company->settings->state; } else { try { $calculated_state = USStates::getState($this->company->settings->postal_code); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: CompanyTaxRate::" . $e->getMessage()); nlog("could not calculate state from postal code => {$this->company->settings->postal_code} or from state {$this->company->settings->state}"); } - if(!$calculated_state && $this->company->tax_data?->seller_subregion) { //@phpstan-ignore-line + if (!$calculated_state && $this->company->tax_data?->seller_subregion) { //@phpstan-ignore-line $calculated_state = $this->company->tax_data->seller_subregion; } - if(!$calculated_state) { + if (!$calculated_state) { return; } diff --git a/app/Jobs/Company/CreateCompany.php b/app/Jobs/Company/CreateCompany.php index 9e1c52f199..cc751a9bb5 100644 --- a/app/Jobs/Company/CreateCompany.php +++ b/app/Jobs/Company/CreateCompany.php @@ -54,7 +54,7 @@ class CreateCompany $settings->name = isset($this->request['name']) ? $this->request['name'] : ''; - if($country_id = $this->resolveCountry()) { + if ($country_id = $this->resolveCountry()) { $settings->country_id = $country_id; } @@ -102,11 +102,11 @@ class CreateCompany $ip = request()->ip(); - if(request()->hasHeader('cf-ipcountry')) { + if (request()->hasHeader('cf-ipcountry')) { $c = Country::query()->where('iso_3166_2', request()->header('cf-ipcountry'))->first(); - if($c) { + if ($c) { return (string)$c->id; } @@ -114,16 +114,16 @@ class CreateCompany $details = json_decode(file_get_contents("http://ip-api.com/json/{$ip}")); - if($details && property_exists($details, 'countryCode')) { + if ($details && property_exists($details, 'countryCode')) { $c = Country::query()->where('iso_3166_2', $details->countryCode)->first(); - if($c) { + if ($c) { return (string)$c->id; } } - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: CreateCompany::" . $e->getMessage()); nlog("Could not resolve country => {$e->getMessage()}"); } @@ -173,7 +173,7 @@ class CreateCompany return $company; - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: CreateCompany::" . $e->getMessage()); nlog("SETUP: could not complete setup for Spanish Locale"); } @@ -206,7 +206,7 @@ class CreateCompany return $company; - } catch(\Exception $e) { + } catch (\Exception $e) { nlog($e->getMessage()); nlog("Exception:: CreateCompany::" . $e->getMessage()); nlog("SETUP: could not complete setup for South African Locale"); @@ -240,7 +240,7 @@ class CreateCompany return $company; - } catch(\Exception $e) { + } catch (\Exception $e) { nlog($e->getMessage()); nlog("Exception:: CreateCompany::" . $e->getMessage()); nlog("SETUP: could not complete setup for Australian Locale"); diff --git a/app/Jobs/Credit/ZipCredits.php b/app/Jobs/Credit/ZipCredits.php index 0c90e0a504..d1ca9ae14a 100644 --- a/app/Jobs/Credit/ZipCredits.php +++ b/app/Jobs/Credit/ZipCredits.php @@ -58,11 +58,10 @@ class ZipCredits implements ShouldQueue $invitations = CreditInvitation::query()->with('credit')->whereIn('credit_id', $this->credit_ids)->get(); - if($invitations->count() == 0) - { + if ($invitations->count() == 0) { nlog("no Credit Invitations"); return; - } + } $invitation = $invitations->first(); diff --git a/app/Jobs/Cron/AutoBill.php b/app/Jobs/Cron/AutoBill.php index 1cabec98d0..c01a8fc5d2 100644 --- a/app/Jobs/Cron/AutoBill.php +++ b/app/Jobs/Cron/AutoBill.php @@ -64,7 +64,7 @@ class AutoBill implements ShouldQueue } catch (\Exception $e) { nlog("Failed to capture payment for {$this->invoice_id} ->".$e->getMessage()); - if($this->send_email_on_failure && $invoice) { + if ($this->send_email_on_failure && $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')) { diff --git a/app/Jobs/Cron/RecurringExpensesCron.php b/app/Jobs/Cron/RecurringExpensesCron.php index 04d649966b..cd94d654ba 100644 --- a/app/Jobs/Cron/RecurringExpensesCron.php +++ b/app/Jobs/Cron/RecurringExpensesCron.php @@ -106,7 +106,7 @@ class RecurringExpensesCron $expense = RecurringExpenseToExpenseFactory::create($recurring_expense); $expense->saveQuietly(); - if($expense->company->mark_expenses_paid) { + if ($expense->company->mark_expenses_paid) { $expense->payment_date = now()->format('Y-m-d'); } diff --git a/app/Jobs/Cron/SubscriptionCron.php b/app/Jobs/Cron/SubscriptionCron.php index 43dcb60a07..05a82461b3 100644 --- a/app/Jobs/Cron/SubscriptionCron.php +++ b/app/Jobs/Cron/SubscriptionCron.php @@ -86,7 +86,7 @@ class SubscriptionCron $timezone_now = now()->setTimezone($company->timezone()->name ?? 'Pacific/Midway'); //Capture companies within the window of 00:00 and 00:30 - if($timezone_now->gt($timezone_now->copy()->startOfDay()) && $timezone_now->lt($timezone_now->copy()->startOfDay()->addMinutes(30))) { + if ($timezone_now->gt($timezone_now->copy()->startOfDay()) && $timezone_now->lt($timezone_now->copy()->startOfDay()->addMinutes(30))) { Invoice::query() ->where('company_id', $company->id) diff --git a/app/Jobs/EDocument/CreateEDocument.php b/app/Jobs/EDocument/CreateEDocument.php index be53d0a92a..c8677fc740 100644 --- a/app/Jobs/EDocument/CreateEDocument.php +++ b/app/Jobs/EDocument/CreateEDocument.php @@ -60,7 +60,7 @@ class CreateEDocument implements ShouldQueue App::setLocale($settings_entity->locale()); /* Set customized translations _NOW_ */ - if($this->document->client ?? false) { + if ($this->document->client ?? false) { $t->replace(Ninja::transformTranslations($this->document->client->getMergedSettings())); } diff --git a/app/Jobs/EDocument/ImportEDocument.php b/app/Jobs/EDocument/ImportEDocument.php index fe6c614900..4a741dc6b5 100644 --- a/app/Jobs/EDocument/ImportEDocument.php +++ b/app/Jobs/EDocument/ImportEDocument.php @@ -61,7 +61,7 @@ class ImportEDocument implements ShouldQueue if ($exception) { nlog("EXCEPTION:: ImportEDocument:: " . $exception->getMessage()); } - + $this->fail($exception); //manually fail - prevents future jobs with the same name from being discarded config(['queue.failed.driver' => null]); } diff --git a/app/Jobs/Entity/CreateRawPdf.php b/app/Jobs/Entity/CreateRawPdf.php index df14cbba1f..f7879d36a3 100644 --- a/app/Jobs/Entity/CreateRawPdf.php +++ b/app/Jobs/Entity/CreateRawPdf.php @@ -78,7 +78,7 @@ class CreateRawPdf private function resolveType(): string { - if($this->type) { + if ($this->type) { return $this->type; } @@ -121,7 +121,7 @@ class CreateRawPdf $merge_docs = isset($this->entity->client) ? $this->entity->client->getSetting('embed_documents') : $this->company->getSetting('embed_documents'); - if($merge_docs && ($this->entity->documents()->where('is_public', true)->count() > 0 || $this->company->documents()->where('is_public', true)->count() > 0)) { + if ($merge_docs && ($this->entity->documents()->where('is_public', true)->count() > 0 || $this->company->documents()->where('is_public', true)->count() > 0)) { $pdf = $this->entity->documentMerge($pdf); } diff --git a/app/Jobs/Entity/EmailEntity.php b/app/Jobs/Entity/EmailEntity.php index b6d245299e..f94a7d407a 100644 --- a/app/Jobs/Entity/EmailEntity.php +++ b/app/Jobs/Entity/EmailEntity.php @@ -69,7 +69,7 @@ class EmailEntity implements ShouldQueue * @param array $template_data */ public function __construct($invitation, string $db, ?string $reminder_template = null, $template_data = null) - { + { $this->db = $db; $this->invitation = $invitation; @@ -95,7 +95,7 @@ class EmailEntity implements ShouldQueue */ public function handle(): void { - + /* Set DB */ MultiDB::setDB($this->db); diff --git a/app/Jobs/Expense/VendorExpenseNotify.php b/app/Jobs/Expense/VendorExpenseNotify.php index c3278dc317..4cfd49fc44 100644 --- a/app/Jobs/Expense/VendorExpenseNotify.php +++ b/app/Jobs/Expense/VendorExpenseNotify.php @@ -45,7 +45,7 @@ class VendorExpenseNotify implements ShouldQueue { MultiDB::setDB($this->db); - if(!$this->expense->vendor) { + if (!$this->expense->vendor) { return; } diff --git a/app/Jobs/Invoice/BulkInvoiceJob.php b/app/Jobs/Invoice/BulkInvoiceJob.php index 4a98c834b0..46792d04dc 100644 --- a/app/Jobs/Invoice/BulkInvoiceJob.php +++ b/app/Jobs/Invoice/BulkInvoiceJob.php @@ -33,7 +33,7 @@ class BulkInvoiceJob implements ShouldQueue public $tries = 1; public $timeout = 3600; - + private bool $contact_has_email = false; private array $templates = [ @@ -53,7 +53,9 @@ class BulkInvoiceJob implements ShouldQueue 'email_template_purchase_order', ]; - public function __construct(public array $invoice_ids, public string $db, public string $reminder_template){} + public function __construct(public array $invoice_ids, public string $db, public string $reminder_template) + { + } /** * Execute the job. @@ -62,7 +64,7 @@ class BulkInvoiceJob implements ShouldQueue * @return void */ public function handle() - { + { MultiDB::setDb($this->db); Invoice::with([ @@ -74,48 +76,47 @@ class BulkInvoiceJob implements ShouldQueue ->withTrashed() ->whereIn('id', $this->invoice_ids) ->cursor() - ->each(function ($invoice){ + ->each(function ($invoice) { - $invoice->service()->markSent()->save(); + $invoice->service()->markSent()->save(); - $invoice->invitations->each(function ($invitation) { - - $template = $this->resolveTemplateString($this->reminder_template); + $invoice->invitations->each(function ($invitation) { - if($invitation->contact->email) - { - $this->contact_has_email = true; + $template = $this->resolveTemplateString($this->reminder_template); - $mo = new EmailObject(); - $mo->entity_id = $invitation->invoice_id; - $mo->template = $template; //full template name in use - $mo->email_template_body = $template; - $mo->email_template_subject = str_replace("template", "subject", $template); + if ($invitation->contact->email) { + $this->contact_has_email = true; - $mo->entity_class = get_class($invitation->invoice); - $mo->invitation_id = $invitation->id; - $mo->client_id = $invitation->contact->client_id ?? null; - $mo->vendor_id = $invitation->contact->vendor_id ?? null; - - Email::dispatch($mo, $invitation->company->withoutRelations()); - - sleep(1); // this is needed to slow down the amount of data that is pushed into cache + $mo = new EmailObject(); + $mo->entity_id = $invitation->invoice_id; + $mo->template = $template; //full template name in use + $mo->email_template_body = $template; + $mo->email_template_subject = str_replace("template", "subject", $template); + + $mo->entity_class = get_class($invitation->invoice); + $mo->invitation_id = $invitation->id; + $mo->client_id = $invitation->contact->client_id ?? null; + $mo->vendor_id = $invitation->contact->vendor_id ?? null; + + Email::dispatch($mo, $invitation->company->withoutRelations()); + + sleep(1); // this is needed to slow down the amount of data that is pushed into cache + } + }); + + if ($invoice->invitations->count() >= 1 && $this->contact_has_email) { + $invoice->entityEmailEvent($invoice->invitations->first(), 'invoice', $this->reminder_template); + $invoice->sendEvent(Webhook::EVENT_SENT_INVOICE, "client"); } + + sleep(1); // this is needed to slow down the amount of data that is pushed into cache + $this->contact_has_email = false; }); - - if ($invoice->invitations->count() >= 1 && $this->contact_has_email) { - $invoice->entityEmailEvent($invoice->invitations->first(), 'invoice', $this->reminder_template); - $invoice->sendEvent(Webhook::EVENT_SENT_INVOICE, "client"); - } - - sleep(1); // this is needed to slow down the amount of data that is pushed into cache - $this->contact_has_email = false; - }); } private function resolveTemplateString(string $template): string { - + return match ($template) { 'reminder1' => 'email_template_reminder1', 'reminder2' => 'email_template_reminder2', @@ -126,6 +127,6 @@ class BulkInvoiceJob implements ShouldQueue 'custom3' => 'email_template_custom3', default => "email_template_{$template}", }; - + } } diff --git a/app/Jobs/Invoice/InjectSignature.php b/app/Jobs/Invoice/InjectSignature.php index f312c73e74..57cb655b5f 100644 --- a/app/Jobs/Invoice/InjectSignature.php +++ b/app/Jobs/Invoice/InjectSignature.php @@ -37,10 +37,10 @@ class InjectSignature implements ShouldQueue { $invitation = false; - if($this->entity instanceof PurchaseOrder) { + if ($this->entity instanceof PurchaseOrder) { $invitation = $this->entity->invitations()->where('vendor_contact_id', $this->contact_id)->first(); - if(!$invitation) { + if (!$invitation) { $invitation = $this->entity->invitations->first(); } @@ -48,7 +48,7 @@ class InjectSignature implements ShouldQueue $invitation = $this->entity->invitations()->where('client_contact_id', $this->contact_id)->first(); - if(!$invitation) { + if (!$invitation) { $invitation = $this->entity->invitations->first(); } } diff --git a/app/Jobs/Invoice/ZipInvoices.php b/app/Jobs/Invoice/ZipInvoices.php index 66f98f271e..1d7da9fc1e 100644 --- a/app/Jobs/Invoice/ZipInvoices.php +++ b/app/Jobs/Invoice/ZipInvoices.php @@ -34,7 +34,7 @@ class ZipInvoices implements ShouldQueue use SerializesModels; public $tries = 1; - + public $timeout = 3600; /** @@ -70,7 +70,7 @@ class ZipInvoices implements ShouldQueue $zipFile = new \PhpZip\ZipFile(); $file_name = date('Y-m-d').'_'.str_replace(' ', '_', trans('texts.invoices')).'.zip'; $invitation = $this->invoices->first()->invitations->first(); - + if (!$invitation) { nlog("no Invoice Invitations"); return; @@ -86,8 +86,7 @@ class ZipInvoices implements ShouldQueue try { $xml = $invoice->service()->getEDocument(); $zipFile->addFromString($invoice->getFileName("xml"), $xml); - } - catch(\Exception $e) { + } catch (\Exception $e) { nlog("could not create e invoice for {$invoice->id}"); nlog($e->getMessage()); } diff --git a/app/Jobs/Ledger/UpdateLedger.php b/app/Jobs/Ledger/UpdateLedger.php index dd1975263e..6471bd7de5 100644 --- a/app/Jobs/Ledger/UpdateLedger.php +++ b/app/Jobs/Ledger/UpdateLedger.php @@ -54,7 +54,7 @@ class UpdateLedger implements ShouldQueue nlog($cl->company_ledgerable->company_ledger()->count()); - if(!$cl) { + if (!$cl) { return; } diff --git a/app/Jobs/Mail/NinjaMailerJob.php b/app/Jobs/Mail/NinjaMailerJob.php index 8eccf4af35..efad506eb6 100644 --- a/app/Jobs/Mail/NinjaMailerJob.php +++ b/app/Jobs/Mail/NinjaMailerJob.php @@ -49,7 +49,7 @@ class NinjaMailerJob implements ShouldQueue use MakesHash; public $tries = 4; //number of retries - + public $deleteWhenMissingModels = true; /** @var null|\App\Models\Company $company **/ @@ -155,10 +155,10 @@ class NinjaMailerJob implements ShouldQueue LightLogs::create(new EmailSuccess($this->nmo->company->company_key, $this->nmo->mailable->subject)) ->send(); - } catch(\Symfony\Component\Mailer\Exception\TransportException $e){ + } catch (\Symfony\Component\Mailer\Exception\TransportException $e) { nlog("Mailer failed with a Transport Exception {$e->getMessage()}"); - - if(Ninja::isHosted() && $this->mailer == 'smtp'){ + + if (Ninja::isHosted() && $this->mailer == 'smtp') { $settings = $this->nmo->settings; $settings->email_sending_method = 'default'; $this->company->settings = $settings; @@ -181,7 +181,7 @@ class NinjaMailerJob implements ShouldQueue $this->cleanUpMailers(); $this->logMailError($e->getMessage(), $this->company->clients()->first()); return; - } catch(\Google\Service\Exception $e) { + } catch (\Google\Service\Exception $e) { if ($e->getCode() == '429') { @@ -216,7 +216,7 @@ class NinjaMailerJob implements ShouldQueue return; } - if(stripos($e->getMessage(), 'Dsn') !== false) { + if (stripos($e->getMessage(), 'Dsn') !== false) { nlog("Incorrectly configured mail server - setting to default mail driver."); $this->nmo->settings->email_sending_method = 'default'; @@ -248,9 +248,9 @@ class NinjaMailerJob implements ShouldQueue * this merges a text string with a json object * need to harvest the ->Message property using the following */ - + if ($e instanceof PostmarkException) { //postmark specific failure - + $this->fail(); $this->entityEmailFailed($e->getMessage()); $this->cleanUpMailers(); @@ -283,7 +283,7 @@ class NinjaMailerJob implements ShouldQueue private function incrementEmailCounter(): void { - if(in_array($this->nmo->settings->email_sending_method, ['default','mailgun','postmark'])) { + if (in_array($this->nmo->settings->email_sending_method, ['default','mailgun','postmark'])) { Cache::increment("email_quota".$this->company->account->key); } @@ -327,7 +327,7 @@ class NinjaMailerJob implements ShouldQueue /** Force free/trials onto specific mail driver */ - if($this->nmo->settings->email_sending_method == 'default' && $this->company->account->isNewHostedAccount()) { + if ($this->nmo->settings->email_sending_method == 'default' && $this->company->account->isNewHostedAccount()) { $this->mailer = 'mailgun'; $this->setHostedMailgunMailer(); return $this; @@ -424,7 +424,7 @@ class NinjaMailerJob implements ShouldQueue $smtp_local_domain = strlen($company->smtp_local_domain ?? '') > 2 ? $company->smtp_local_domain : null; $smtp_verify_peer = $company->smtp_verify_peer ?? true; - if(strlen($smtp_host) <= 1 || + if (strlen($smtp_host) <= 1 || strlen($smtp_username) <= 1 || strlen($smtp_password) <= 1 ) { @@ -839,7 +839,7 @@ class NinjaMailerJob implements ShouldQueue 'refresh_token' => $user->oauth_user_refresh_token ], ])->getBody()->getContents()); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Problem getting new Microsoft token for User: {$user->email}"); } diff --git a/app/Jobs/Mail/PaymentFailedMailer.php b/app/Jobs/Mail/PaymentFailedMailer.php index 079c8be6e0..0b02e30c66 100644 --- a/app/Jobs/Mail/PaymentFailedMailer.php +++ b/app/Jobs/Mail/PaymentFailedMailer.php @@ -84,7 +84,7 @@ class PaymentFailedMailer implements ShouldQueue $invoice = false; if ($this->payment_hash) { - + $amount = $this->payment_hash?->amount_with_fee() ?: 0; $invoice = Invoice::query()->whereIn('id', $this->transformKeys(array_column($this->payment_hash->invoices(), 'invoice_id')))->withTrashed()->first(); } diff --git a/app/Jobs/Mail/PaymentFailureMailer.php b/app/Jobs/Mail/PaymentFailureMailer.php index 5ee55662dd..7ee5df3c95 100644 --- a/app/Jobs/Mail/PaymentFailureMailer.php +++ b/app/Jobs/Mail/PaymentFailureMailer.php @@ -90,7 +90,7 @@ class PaymentFailureMailer implements ShouldQueue $use_react_link = false; - if(isset($company_user->react_settings->react_notification_link) && $company_user->react_settings->react_notification_link) { + if (isset($company_user->react_settings->react_notification_link) && $company_user->react_settings->react_notification_link) { $use_react_link = true; } diff --git a/app/Jobs/Mailgun/ProcessMailgunInboundWebhook.php b/app/Jobs/Mailgun/ProcessMailgunInboundWebhook.php index 84ecc06d5b..e89d587253 100644 --- a/app/Jobs/Mailgun/ProcessMailgunInboundWebhook.php +++ b/app/Jobs/Mailgun/ProcessMailgunInboundWebhook.php @@ -25,7 +25,10 @@ use App\Services\InboundMail\InboundMailEngine; class ProcessMailgunInboundWebhook implements ShouldQueue { - use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; + use Dispatchable; + use InteractsWithQueue; + use Queueable; + use SerializesModels; public $tries = 1; @@ -191,8 +194,9 @@ class ProcessMailgunInboundWebhook implements ShouldQueue // fetch message from mailgun-api $company_mailgun_domain = $this->company->getSetting('email_sending_method') == 'client_mailgun' && strlen($this->company->getSetting('mailgun_domain') ?? '') > 2 ? $this->company->getSetting('mailgun_domain') : null; $company_mailgun_secret = $this->company->getSetting('email_sending_method') == 'client_mailgun' && strlen($this->company->getSetting('mailgun_secret') ?? '') > 2 ? $this->company->getSetting('mailgun_secret') : null; - if (!($company_mailgun_domain && $company_mailgun_secret) && !(config('services.mailgun.domain') && config('services.mailgun.secret'))) + if (!($company_mailgun_domain && $company_mailgun_secret) && !(config('services.mailgun.domain') && config('services.mailgun.secret'))) { throw new \Error("[ProcessMailgunInboundWebhook] no mailgun credentials found, we cannot get the attachements and files"); + } $mail = null; if ($company_mailgun_domain && $company_mailgun_secret) { @@ -214,8 +218,9 @@ class ProcessMailgunInboundWebhook implements ShouldQueue $messageUrl = str_replace("https://", "https://" . $credentials, $messageUrl); $mail = json_decode(file_get_contents($messageUrl)); - } else + } else { throw $e; + } } } else { @@ -262,8 +267,9 @@ class ProcessMailgunInboundWebhook implements ShouldQueue $url = str_replace("https://", "https://" . $credentials, $url); $inboundMail->documents[] = TempFile::UploadedFileFromUrl($url, $attachment->name, $attachment->{"content-type"}); - } else + } else { throw $e; + } } } else { diff --git a/app/Jobs/Mailgun/ProcessMailgunWebhook.php b/app/Jobs/Mailgun/ProcessMailgunWebhook.php index 37bc7f8fb8..de9cf830dc 100644 --- a/app/Jobs/Mailgun/ProcessMailgunWebhook.php +++ b/app/Jobs/Mailgun/ProcessMailgunWebhook.php @@ -91,7 +91,7 @@ class ProcessMailgunWebhook implements ShouldQueue { nlog($this->request); - if(!$this->request['event-data']['tags'][0] ?? false) { //@phpstan-ignore-line + if (!$this->request['event-data']['tags'][0] ?? false) { //@phpstan-ignore-line return; } @@ -185,7 +185,7 @@ class ProcessMailgunWebhook implements ShouldQueue $sl = $this->getSystemLog($this->request['MessageID']); /** Prevents Gmail tracking from firing inappropriately */ - if(!$sl || $this->request['signature']['timestamp'] < $sl->log['signature']['timestamp'] + 3) { + if (!$sl || $this->request['signature']['timestamp'] < $sl->log['signature']['timestamp'] + 3) { return; } @@ -199,7 +199,7 @@ class ProcessMailgunWebhook implements ShouldQueue 'date' => \Carbon\Carbon::parse($this->request['event-data']['timestamp'])->format('Y-m-d H:i:s') ?? '', ]; - if($sl instanceof SystemLog) { + if ($sl instanceof SystemLog) { $data = $sl->log; $data['history']['events'][] = $event; $this->updateSystemLog($sl, $data); @@ -277,7 +277,7 @@ class ProcessMailgunWebhook implements ShouldQueue $sl = $this->getSystemLog($this->request['MessageID']); - if($sl) { + if ($sl) { $data = $sl->log; $data['history']['events'][] = $this->getEvent(); $this->updateSystemLog($sl, $data); @@ -382,7 +382,7 @@ class ProcessMailgunWebhook implements ShouldQueue 'date' => \Carbon\Carbon::parse($this->request['event-data']['timestamp'])->format('Y-m-d H:i:s') ?? '', ]; - if($sl) { + if ($sl) { $data = $sl->log; $data['history']['events'][] = $event; $this->updateSystemLog($sl, $data); @@ -456,7 +456,7 @@ class ProcessMailgunWebhook implements ShouldQueue 'date' => \Carbon\Carbon::parse($this->request['event-data']['timestamp'])->format('Y-m-d H:i:s') ?? '', ]; - if($sl) { + if ($sl) { $data = $sl->log; $data['history']['events'][] = $event; $this->updateSystemLog($sl, $data); @@ -490,7 +490,7 @@ class ProcessMailgunWebhook implements ShouldQueue private function fetchMessage(): array { - if(strlen($this->message_id) < 2) { + if (strlen($this->message_id) < 2) { return $this->default_response; } diff --git a/app/Jobs/Ninja/AdjustEmailQuota.php b/app/Jobs/Ninja/AdjustEmailQuota.php index 62ef46f490..15832893bd 100644 --- a/app/Jobs/Ninja/AdjustEmailQuota.php +++ b/app/Jobs/Ninja/AdjustEmailQuota.php @@ -70,7 +70,7 @@ class AdjustEmailQuota implements ShouldQueue if ($email_count > 0) { try { LightLogs::create(new EmailCount($email_count, $account->key))->send(); // this runs syncronously - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: AdjustEmailQuota::" . $e->getMessage()); nlog($e->getMessage()); } diff --git a/app/Jobs/Ninja/BankTransactionSync.php b/app/Jobs/Ninja/BankTransactionSync.php index 90848f3e4b..915d3adf61 100644 --- a/app/Jobs/Ninja/BankTransactionSync.php +++ b/app/Jobs/Ninja/BankTransactionSync.php @@ -92,7 +92,7 @@ class BankTransactionSync implements ShouldQueue $account->bank_integrations()->where('integration_type', BankIntegration::INTEGRATION_TYPE_NORDIGEN)->where('auto_sync', true)->where('disabled_upstream', 0)->cursor()->each(function ($bank_integration) { try { (new ProcessBankTransactionsNordigen($bank_integration))->handle(); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: BankTransactioSync::" . $e->getMessage()); sleep(20); } diff --git a/app/Jobs/Ninja/CheckACHStatus.php b/app/Jobs/Ninja/CheckACHStatus.php index 2e6debca1b..69491bcd9a 100644 --- a/app/Jobs/Ninja/CheckACHStatus.php +++ b/app/Jobs/Ninja/CheckACHStatus.php @@ -65,7 +65,7 @@ class CheckACHStatus implements ShouldQueue $stripe = $token->gateway->driver($token->client)->init(); $pm = $stripe->getStripePaymentMethod($token->token); - if($pm) { + if ($pm) { $meta = $token->meta; $meta->state = 'authorized'; @@ -88,7 +88,7 @@ class CheckACHStatus implements ShouldQueue try { $stripe = $p->company_gateway->driver($p->client)->init(); - } catch(\Exception $e) { + } catch (\Exception $e) { return; } @@ -96,26 +96,26 @@ class CheckACHStatus implements ShouldQueue try { $pi = $stripe->getPaymentIntent($p->transaction_reference); - } catch(\Exception $e) { + } catch (\Exception $e) { } - if(!$pi) { + if (!$pi) { try { $pi = \Stripe\Charge::retrieve($p->transaction_reference, $stripe->stripe_connect_auth); - } catch(\Exception $e) { + } catch (\Exception $e) { return; } } - if($pi && $pi->status == 'succeeded') { + if ($pi && $pi->status == 'succeeded') { $p->status_id = Payment::STATUS_COMPLETED; $p->saveQuietly(); } else { - if($pi) { + if ($pi) { nlog("{$p->id} did not complete {$p->transaction_reference}"); } else { nlog("did not find a payment intent {$p->transaction_reference}"); diff --git a/app/Jobs/Ninja/CompanySizeCheck.php b/app/Jobs/Ninja/CompanySizeCheck.php index 0b0b60847f..d5ab5e1600 100644 --- a/app/Jobs/Ninja/CompanySizeCheck.php +++ b/app/Jobs/Ninja/CompanySizeCheck.php @@ -64,7 +64,7 @@ class CompanySizeCheck implements ShouldQueue $old_credit_balance = $client->credit_balance; $new_credit_balance = $client->service()->getCreditBalance(); - if(floatval($old_credit_balance) !== floatval($new_credit_balance)) { + if (floatval($old_credit_balance) !== floatval($new_credit_balance)) { $client->credit_balance = $client->service()->getCreditBalance(); $client->saveQuietly(); } @@ -106,7 +106,7 @@ class CompanySizeCheck implements ShouldQueue $old_credit_balance = $client->credit_balance; $new_credit_balance = $client->service()->getCreditBalance(); - if(floatval($old_credit_balance) !== floatval($new_credit_balance)) { + if (floatval($old_credit_balance) !== floatval($new_credit_balance)) { $client->credit_balance = $client->service()->getCreditBalance(); $client->saveQuietly(); } diff --git a/app/Jobs/Ninja/TaskScheduler.php b/app/Jobs/Ninja/TaskScheduler.php index c30af04014..377cb604a9 100644 --- a/app/Jobs/Ninja/TaskScheduler.php +++ b/app/Jobs/Ninja/TaskScheduler.php @@ -62,7 +62,7 @@ class TaskScheduler implements ShouldQueue try { //@var \App\Models\Schedule $scheduler $scheduler->service()->runTask(); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: TaskScheduler:: Doing job :: {$scheduler->id} :: {$scheduler->name}" . $e->getMessage()); } @@ -88,7 +88,7 @@ class TaskScheduler implements ShouldQueue try { /** @var \App\Models\Scheduler $scheduler */ $scheduler->service()->runTask(); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: TaskScheduler:: #{$scheduler->id}::" . $e->getMessage()); nlog($e->getMessage()); } diff --git a/app/Jobs/Payment/EmailPayment.php b/app/Jobs/Payment/EmailPayment.php index 5906cce74b..31711f8e8f 100644 --- a/app/Jobs/Payment/EmailPayment.php +++ b/app/Jobs/Payment/EmailPayment.php @@ -76,7 +76,7 @@ class EmailPayment implements ShouldQueue $email_builder = (new PaymentEmailEngine($this->payment, $this->contact))->build(); - if($this->payment->client->getSetting('payment_email_all_contacts') && $this->payment->invoices && $this->payment->invoices->count() >= 1) { + if ($this->payment->client->getSetting('payment_email_all_contacts') && $this->payment->invoices && $this->payment->invoices->count() >= 1) { $this->emailAllContacts($email_builder); return; } @@ -87,13 +87,13 @@ class EmailPayment implements ShouldQueue if ($this->payment->invoices && $this->payment->invoices->count() >= 1) { - if($this->contact) { + if ($this->contact) { $invitation = $this->payment->invoices->first()->invitations()->where('client_contact_id', $this->contact->id)->first(); } else { $invitation = $this->payment->invoices->first()->invitations()->first(); } - if($invitation) { + if ($invitation) { $nmo->invitation = $invitation; } } diff --git a/app/Jobs/Payment/EmailRefundPayment.php b/app/Jobs/Payment/EmailRefundPayment.php index f98ace737d..5ea11a186c 100644 --- a/app/Jobs/Payment/EmailRefundPayment.php +++ b/app/Jobs/Payment/EmailRefundPayment.php @@ -86,13 +86,13 @@ class EmailRefundPayment implements ShouldQueue if ($this->payment->invoices && $this->payment->invoices->count() >= 1) { - if($this->contact) { + if ($this->contact) { $invitation = $this->payment->invoices->first()->invitations()->where('client_contact_id', $this->contact->id)->first(); } else { $invitation = $this->payment->invoices->first()->invitations()->first(); } - if($invitation) { + if ($invitation) { $nmo->invitation = $invitation; } } diff --git a/app/Jobs/PostMark/ProcessPostmarkWebhook.php b/app/Jobs/PostMark/ProcessPostmarkWebhook.php index 323ca7c425..1482017005 100644 --- a/app/Jobs/PostMark/ProcessPostmarkWebhook.php +++ b/app/Jobs/PostMark/ProcessPostmarkWebhook.php @@ -363,7 +363,7 @@ class ProcessPostmarkWebhook implements ShouldQueue try { $messageDetail = $postmark->getOutboundMessageDetails($message_id); - } catch(\Exception $e) { + } catch (\Exception $e) { $postmark_secret = config('services.postmark-outlook.token'); $postmark = new PostmarkClient($postmark_secret); @@ -406,7 +406,7 @@ class ProcessPostmarkWebhook implements ShouldQueue try { $messageDetail = $postmark->getOutboundMessageDetails($this->request['MessageID']); - } catch(\Exception $e) { + } catch (\Exception $e) { $postmark_secret = config('services.postmark-outlook.token'); $postmark = new PostmarkClient($postmark_secret); diff --git a/app/Jobs/Quote/ZipQuotes.php b/app/Jobs/Quote/ZipQuotes.php index cb33491a16..7fd662b87d 100644 --- a/app/Jobs/Quote/ZipQuotes.php +++ b/app/Jobs/Quote/ZipQuotes.php @@ -38,7 +38,7 @@ class ZipQuotes implements ShouldQueue public $tries = 1; public $timeout = 3600; - + public function __construct(protected mixed $quote_ids, protected Company $company, protected User $user) { } diff --git a/app/Jobs/RecurringInvoice/SendRecurring.php b/app/Jobs/RecurringInvoice/SendRecurring.php index 99a9d97b25..f00a245314 100644 --- a/app/Jobs/RecurringInvoice/SendRecurring.php +++ b/app/Jobs/RecurringInvoice/SendRecurring.php @@ -117,7 +117,7 @@ class SendRecurring implements ShouldQueue 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')) { + if (!$invoice->client->getSetting('client_online_payment_notification')) { $this->sendRecurringEmails($invoice); $invoice->sendEvent(Webhook::EVENT_SENT_INVOICE, "client"); } @@ -126,7 +126,7 @@ class SendRecurring implements ShouldQueue 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')) { + if (!$invoice->client->getSetting('client_online_payment_notification')) { $this->sendRecurringEmails($invoice); $invoice->sendEvent(Webhook::EVENT_SENT_INVOICE, "client"); } diff --git a/app/Jobs/Report/PreviewReport.php b/app/Jobs/Report/PreviewReport.php index e66a3641e5..575a9f7a59 100644 --- a/app/Jobs/Report/PreviewReport.php +++ b/app/Jobs/Report/PreviewReport.php @@ -42,7 +42,7 @@ class PreviewReport implements ShouldQueue /** @var \App\Export\CSV\CreditExport $export */ $export = new $this->report_class($this->company, $this->request); - if(isset($this->request['output']) && $this->request['output'] == 'json') { + if (isset($this->request['output']) && $this->request['output'] == 'json') { $report = $export->returnJson(); } else { $report = $export->run(); diff --git a/app/Jobs/Report/SendToAdmin.php b/app/Jobs/Report/SendToAdmin.php index 233de2ff0f..7be8f60235 100644 --- a/app/Jobs/Report/SendToAdmin.php +++ b/app/Jobs/Report/SendToAdmin.php @@ -68,7 +68,7 @@ class SendToAdmin implements ShouldQueue $user = $this->company->owner(); - if(isset($this->request['user_id'])) { + if (isset($this->request['user_id'])) { $user = User::find($this->request['user_id']) ?? $this->company->owner(); } @@ -77,7 +77,7 @@ class SendToAdmin implements ShouldQueue $nmo->company = $this->company; $nmo->settings = $this->company->settings; $nmo->to_user = $user; - + try { (new NinjaMailerJob($nmo))->handle(); } catch (\Throwable $th) { diff --git a/app/Jobs/Subscription/CleanStaleInvoiceOrder.php b/app/Jobs/Subscription/CleanStaleInvoiceOrder.php index 2b94793a11..26aa2823e9 100644 --- a/app/Jobs/Subscription/CleanStaleInvoiceOrder.php +++ b/app/Jobs/Subscription/CleanStaleInvoiceOrder.php @@ -79,14 +79,14 @@ class CleanStaleInvoiceOrder implements ShouldQueue $type_3_count = 0; $type_4_count = 0; - - foreach ($invoice->line_items as $line_item) { - if ($line_item->type_id == '3') { - $type_3_count++; - } elseif ($line_item->type_id == '4') { - $type_4_count++; - } - } + + foreach ($invoice->line_items as $line_item) { + if ($line_item->type_id == '3') { + $type_3_count++; + } elseif ($line_item->type_id == '4') { + $type_4_count++; + } + } if ($type_4_count == 1) { $invoice->service()->removeUnpaidGatewayFees(); @@ -119,7 +119,7 @@ class CleanStaleInvoiceOrder implements ShouldQueue $type_3_count = 0; $type_4_count = 0; - + foreach ($invoice->line_items as $line_item) { if ($line_item->type_id == '3') { $type_3_count++; @@ -226,7 +226,7 @@ class CleanStaleInvoiceOrder implements ShouldQueue $type_3_count = 0; $type_4_count = 0; - + foreach ($invoice->line_items as $line_item) { if ($line_item->type_id == '3') { $type_3_count++; diff --git a/app/Jobs/Task/TaskAssigned.php b/app/Jobs/Task/TaskAssigned.php index 4e72637b03..b3eb269a1a 100644 --- a/app/Jobs/Task/TaskAssigned.php +++ b/app/Jobs/Task/TaskAssigned.php @@ -20,7 +20,6 @@ use App\Services\Email\EmailObject; use Illuminate\Mail\Mailables\Address; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; - use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use App\Utils\Traits\Notifications\UserNotifies; @@ -48,7 +47,7 @@ class TaskAssigned implements ShouldQueue $company_user = $this->task->assignedCompanyUser(); - if(($company_user instanceof CompanyUser) && $this->findEntityAssignedNotification($company_user, 'task')) { + if (($company_user instanceof CompanyUser) && $this->findEntityAssignedNotification($company_user, 'task')) { $mo = new EmailObject(); $mo->subject = ctrans('texts.task_assigned_subject', ['task' => $this->task->number, 'date' => now()->setTimeZone($this->task->company->timezone()->name)->format($this->task->company->date_format()) ]); $mo->body = ctrans('texts.task_assigned_body', ['task' => $this->task->number, 'description' => $this->task->description ?? '', 'client' => $this->task->client ? $this->task->client->present()->name() : ' ']); diff --git a/app/Jobs/User/VerifyPhone.php b/app/Jobs/User/VerifyPhone.php index 58281a07ec..20e7218497 100644 --- a/app/Jobs/User/VerifyPhone.php +++ b/app/Jobs/User/VerifyPhone.php @@ -67,7 +67,7 @@ class VerifyPhone implements ShouldQueue try { $phone_number = $twilio->lookups->v1->phoneNumbers($this->user->phone) ->fetch(["countryCode" => $countryCode]); - } catch(\Exception $e) { + } catch (\Exception $e) { $this->user->verified_phone_number = false; $this->user->save(); return; diff --git a/app/Jobs/Util/Import.php b/app/Jobs/Util/Import.php index 65033f59ea..d4591c4f62 100644 --- a/app/Jobs/Util/Import.php +++ b/app/Jobs/Util/Import.php @@ -265,11 +265,11 @@ class Import implements ShouldQueue $t = app('translator'); $t->replace(Ninja::transformTranslations($this->company->settings)); - if(!$this->silent_migration) { + if (!$this->silent_migration) { Mail::to($this->user->email, $this->user->name())->send(new MigrationCompleted($this->company->id, $this->company->db, implode("
", $check_data))); } - } catch(\Exception $e) { + } catch (\Exception $e) { nlog($e->getMessage()); } @@ -282,7 +282,7 @@ class Import implements ShouldQueue try { unlink($this->file_path); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("problem unsetting file"); } } @@ -369,7 +369,7 @@ class Import implements ShouldQueue } } else { - if(isset($data['plan'])) { + if (isset($data['plan'])) { $account->plan = $data['plan']; } @@ -1215,7 +1215,7 @@ class Import implements ShouldQueue CreditFactory::create($this->company->id, $modified['user_id']) ); - if($credit->status_id == 4) { + if ($credit->status_id == 4) { $client = $credit->client; $client->balance -= $credit->balance; @@ -1509,7 +1509,7 @@ class Import implements ShouldQueue try { $invoice_id = $this->transformId('invoices', $resource['invoice_id']); $entity = Invoice::query()->where('id', $invoice_id)->withTrashed()->first(); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("i couldn't find the invoice document {$resource['invoice_id']}, perhaps it is a quote?"); nlog($e->getMessage()); @@ -1520,7 +1520,7 @@ class Import implements ShouldQueue try { $quote_id = $this->transformId('quotes', $resource['invoice_id']); $entity = Quote::query()->where('id', $quote_id)->withTrashed()->first(); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("i couldn't find the quote document {$resource['invoice_id']}, perhaps it is a quote?"); nlog($e->getMessage()); } @@ -1570,7 +1570,7 @@ class Import implements ShouldQueue ))->handle(); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog($e->getMessage()); //do nothing, gracefully :) } @@ -1640,7 +1640,7 @@ class Import implements ShouldQueue $nmo->settings = $this->company->settings; $nmo->to_user = $this->user; - if(!$this->silent_migration) { + if (!$this->silent_migration) { NinjaMailerJob::dispatch($nmo, true); } @@ -2109,7 +2109,7 @@ class Import implements ShouldQueue if (Ninja::isHosted()) { try { \Modules\Admin\Jobs\Account\NinjaUser::dispatch($data, $this->company); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog($e->getMessage()); } } diff --git a/app/Jobs/Util/ReminderJob.php b/app/Jobs/Util/ReminderJob.php index f6ed6d37c9..0a0775a4c7 100644 --- a/app/Jobs/Util/ReminderJob.php +++ b/app/Jobs/Util/ReminderJob.php @@ -74,7 +74,7 @@ class ReminderJob implements ShouldQueue ->with('invitations') ->cursor() ->each(function ($invoice) { - $this->sendReminderForInvoice($invoice); + $this->sendReminderForInvoice($invoice); }); } else { //multiDB environment, need to @@ -97,14 +97,14 @@ class ReminderJob implements ShouldQueue ->whereHas('company', function ($query) { $query->where('is_disabled', 0); }) - ->whereHas('company.account', function ($q){ + ->whereHas('company.account', function ($q) { $q->whereNotNull('plan')->where('plan_expires', '>', now()->subDays(2)); }) ->with('invitations') ->cursor() ->each(function ($invoice) { - $this->sendReminderForInvoice($invoice); - }); + $this->sendReminderForInvoice($invoice); + }); } } } @@ -128,7 +128,7 @@ class ReminderJob implements ShouldQueue $invoice->service()->touchReminder($reminder_template)->save(); $fees = $this->calcLateFee($invoice, $reminder_template); - if($invoice->isLocked()) { + if ($invoice->isLocked()) { return $this->addFeeToNewInvoice($invoice, $reminder_template, $fees); } @@ -208,7 +208,7 @@ class ReminderJob implements ShouldQueue ->save(); } - if(!$invoice) { + if (!$invoice) { $invoice = $over_due_invoice; } diff --git a/app/Jobs/Util/StartMigration.php b/app/Jobs/Util/StartMigration.php index 77b9ed9f7a..7e8b03c565 100644 --- a/app/Jobs/Util/StartMigration.php +++ b/app/Jobs/Util/StartMigration.php @@ -144,7 +144,7 @@ class StartMigration implements ShouldQueue app('sentry')->captureException($e); } - if(!$this->silent_migration) { + if (!$this->silent_migration) { Mail::to($this->user->email, $this->user->name())->send(new MigrationFailed($e, $this->company, $e->getMessage())); } diff --git a/app/Jobs/Util/VersionCheck.php b/app/Jobs/Util/VersionCheck.php index 1f4ab79536..e829c41f55 100644 --- a/app/Jobs/Util/VersionCheck.php +++ b/app/Jobs/Util/VersionCheck.php @@ -119,4 +119,4 @@ class VersionCheck implements ShouldQueue } } -} \ No newline at end of file +} diff --git a/app/Jobs/Util/WebhookSingle.php b/app/Jobs/Util/WebhookSingle.php index 14f41a4f8e..7f18bf516a 100644 --- a/app/Jobs/Util/WebhookSingle.php +++ b/app/Jobs/Util/WebhookSingle.php @@ -130,7 +130,7 @@ class WebhookSingle implements ShouldQueue $this->resolveClient(), $this->company ))->handle(); - } catch(\GuzzleHttp\Exception\ConnectException $e) { + } catch (\GuzzleHttp\Exception\ConnectException $e) { nlog("connection problem"); nlog($e->getCode()); nlog($e->getMessage()); diff --git a/app/Listeners/Activity/PaymentCreatedActivity.php b/app/Listeners/Activity/PaymentCreatedActivity.php index 83d5b7eb87..f5261b14aa 100644 --- a/app/Listeners/Activity/PaymentCreatedActivity.php +++ b/app/Listeners/Activity/PaymentCreatedActivity.php @@ -46,7 +46,7 @@ class PaymentCreatedActivity implements ShouldQueue $payment = $event->payment; $invoice_id = null; - if($payment->invoices()->exists()) { + if ($payment->invoices()->exists()) { $invoice_id = $payment->invoices()->first()->id; } diff --git a/app/Listeners/Contact/UpdateContactLastLogin.php b/app/Listeners/Contact/UpdateContactLastLogin.php index 75c416bc6c..821072eb81 100644 --- a/app/Listeners/Contact/UpdateContactLastLogin.php +++ b/app/Listeners/Contact/UpdateContactLastLogin.php @@ -38,6 +38,6 @@ class UpdateContactLastLogin implements ShouldQueue $client_contact = $event->client_contact; $client_contact->last_login = now(); $client_contact->save(); - + } } diff --git a/app/Listeners/Invoice/InvoiceAutoBillFailedActivity.php b/app/Listeners/Invoice/InvoiceAutoBillFailedActivity.php index 6db4087daa..a49eb608fa 100644 --- a/app/Listeners/Invoice/InvoiceAutoBillFailedActivity.php +++ b/app/Listeners/Invoice/InvoiceAutoBillFailedActivity.php @@ -52,7 +52,7 @@ class InvoiceAutoBillFailedActivity implements ShouldQueue $fields->activity_type_id = Activity::AUTOBILL_FAILURE; $fields->invoice_id = $event->invoice->id; $fields->notes = $event->notes ?? ''; - + $this->activity_repo->save($fields, $event->invoice, $event->event_vars); } diff --git a/app/Listeners/Invoice/InvoiceFailedEmailNotification.php b/app/Listeners/Invoice/InvoiceFailedEmailNotification.php index 58f0a721cf..8459ea443f 100644 --- a/app/Listeners/Invoice/InvoiceFailedEmailNotification.php +++ b/app/Listeners/Invoice/InvoiceFailedEmailNotification.php @@ -37,7 +37,7 @@ class InvoiceFailedEmailNotification { MultiDB::setDb($event->company->db); - if(Cache::has("invoice_failed_email_notification_{$event->invitation->key}")) { + if (Cache::has("invoice_failed_email_notification_{$event->invitation->key}")) { return; } diff --git a/app/Listeners/Payment/PaymentNotification.php b/app/Listeners/Payment/PaymentNotification.php index e67cf8e0dc..6e5fdbd75a 100644 --- a/app/Listeners/Payment/PaymentNotification.php +++ b/app/Listeners/Payment/PaymentNotification.php @@ -59,7 +59,7 @@ class PaymentNotification implements ShouldQueue } /* Manual Payment Notifications */ - if($payment->is_manual) { + if ($payment->is_manual) { foreach ($payment->company->company_users as $company_user) { $user = $company_user->user; diff --git a/app/Listeners/Quote/QuoteCreatedNotification.php b/app/Listeners/Quote/QuoteCreatedNotification.php index 2643075e2a..679aee5951 100644 --- a/app/Listeners/Quote/QuoteCreatedNotification.php +++ b/app/Listeners/Quote/QuoteCreatedNotification.php @@ -56,7 +56,7 @@ class QuoteCreatedNotification implements ShouldQueue $use_react_link = false; - if(isset($company_user->react_settings->react_notification_link) && $company_user->react_settings->react_notification_link) { + if (isset($company_user->react_settings->react_notification_link) && $company_user->react_settings->react_notification_link) { $use_react_link = true; } diff --git a/app/Listeners/User/UpdatedUserActivity.php b/app/Listeners/User/UpdatedUserActivity.php index 1959ab2a20..63571c75c6 100644 --- a/app/Listeners/User/UpdatedUserActivity.php +++ b/app/Listeners/User/UpdatedUserActivity.php @@ -48,7 +48,7 @@ class UpdatedUserActivity implements ShouldQueue $fields->company_id = $event->company->id; $fields->account_id = $event->company->account_id; - + $fields->activity_type_id = Activity::UPDATE_USER; $this->activityRepo->save($fields, $event->user, $event->event_vars); diff --git a/app/Livewire/BillingPortal/Authentication/Login.php b/app/Livewire/BillingPortal/Authentication/Login.php index a05aee0f23..9ae656f63b 100644 --- a/app/Livewire/BillingPortal/Authentication/Login.php +++ b/app/Livewire/BillingPortal/Authentication/Login.php @@ -176,7 +176,7 @@ class Login extends Component // $this->dispatch('purchase.context', property: 'contact', value: auth()->guard('contact')->user()); $this->dispatch('purchase.next'); } - + } public function render(): \Illuminate\View\View diff --git a/app/Livewire/BillingPortal/Authentication/Register.php b/app/Livewire/BillingPortal/Authentication/Register.php index e9c8e61ca3..448af22d66 100644 --- a/app/Livewire/BillingPortal/Authentication/Register.php +++ b/app/Livewire/BillingPortal/Authentication/Register.php @@ -33,7 +33,7 @@ class Register extends Component public ?int $otp; - public array $formData = []; + public array $formData = []; public array $state = [ 'initial_completed' => false, @@ -50,7 +50,7 @@ class Register extends Component { return Subscription::find($this->decodePrimaryKey($this->subscription_id))->withoutRelations()->makeHidden(['webhook_configuration','steps']); } - + public function initial(): void { $this->validateOnly('email', ['email' => 'required|bail|email:rfc']); @@ -84,7 +84,7 @@ class Register extends Component ); $rules = $service->rules(); - + $data = Validator::make($data, $rules)->validate(); $client = $service->createClient($data); diff --git a/app/Livewire/BillingPortal/Authentication/RegisterOrLogin.php b/app/Livewire/BillingPortal/Authentication/RegisterOrLogin.php index 671a073953..be354c8fef 100644 --- a/app/Livewire/BillingPortal/Authentication/RegisterOrLogin.php +++ b/app/Livewire/BillingPortal/Authentication/RegisterOrLogin.php @@ -37,7 +37,7 @@ class RegisterOrLogin extends Component public ?int $otp; - public array $formData = []; + public array $formData = []; public array $state = [ 'otp' => false, // Use as preference. E-mail/password or OTP. @@ -173,7 +173,7 @@ class RegisterOrLogin extends Component public function register(array $data): void { - + $data = array_merge($data, [ 'country_id' => $this->formData['country_id'] ?? null, 'shipping_country_id' => $this->formData['shipping_country_id'] ?? null, @@ -260,7 +260,7 @@ class RegisterOrLogin extends Component public function mount() { - + if (auth()->guard('contact')->check()) { // $this->dispatch('purchase.context', property: 'contact', value: auth()->guard('contact')->user()); $this->dispatch('purchase.next'); diff --git a/app/Livewire/BillingPortal/Cart/Coupon.php b/app/Livewire/BillingPortal/Cart/Coupon.php index 95e07762f1..a44bd05c19 100644 --- a/app/Livewire/BillingPortal/Cart/Coupon.php +++ b/app/Livewire/BillingPortal/Cart/Coupon.php @@ -32,9 +32,9 @@ class Coupon extends Component public function mount() { $subscription = $this->subscription(); - $this->showCouponCode = ($subscription->promo_discount > 0) && (!array_key_exists('valid_coupon',$this->context)); - - if(isset($this->context['request_data']['coupon']) && $this->context['request_data']['coupon'] == $this->subscription()->promo_code){ + $this->showCouponCode = ($subscription->promo_discount > 0) && (!array_key_exists('valid_coupon', $this->context)); + + if (isset($this->context['request_data']['coupon']) && $this->context['request_data']['coupon'] == $this->subscription()->promo_code) { $this->showCouponCode = false; $this->dispatch('purchase.context', property: "valid_coupon", value: $this->context['request_data']['coupon']); } @@ -55,13 +55,12 @@ class Coupon extends Component ]); try { - - if($this->couponCode == $this->subscription()->promo_code) { + + if ($this->couponCode == $this->subscription()->promo_code) { $this->showCouponCode = false; $this->dispatch('purchase.context', property: "valid_coupon", value: $this->couponCode); $this->dispatch('summary.refresh'); - } - else { + } else { $this->addError('couponCode', ctrans('texts.invalid_coupon')); } diff --git a/app/Livewire/BillingPortal/Cart/OneTimeProducts.php b/app/Livewire/BillingPortal/Cart/OneTimeProducts.php index cb2d69f289..b72b142767 100644 --- a/app/Livewire/BillingPortal/Cart/OneTimeProducts.php +++ b/app/Livewire/BillingPortal/Cart/OneTimeProducts.php @@ -20,7 +20,7 @@ use Livewire\Attributes\Computed; class OneTimeProducts extends Component { use MakesHash; - + public array $context; public string $subscription_id; diff --git a/app/Livewire/BillingPortal/Cart/OptionalOneTimeProducts.php b/app/Livewire/BillingPortal/Cart/OptionalOneTimeProducts.php index 1d839ceb3d..c7b976a229 100644 --- a/app/Livewire/BillingPortal/Cart/OptionalOneTimeProducts.php +++ b/app/Livewire/BillingPortal/Cart/OptionalOneTimeProducts.php @@ -19,7 +19,6 @@ use Livewire\Attributes\Computed; class OptionalOneTimeProducts extends Component { - use MakesHash; public array $context; diff --git a/app/Livewire/BillingPortal/Cart/OptionalRecurringProducts.php b/app/Livewire/BillingPortal/Cart/OptionalRecurringProducts.php index ec6ad00ece..bef245cfc2 100644 --- a/app/Livewire/BillingPortal/Cart/OptionalRecurringProducts.php +++ b/app/Livewire/BillingPortal/Cart/OptionalRecurringProducts.php @@ -19,7 +19,6 @@ use Livewire\Attributes\Computed; class OptionalRecurringProducts extends Component { - use MakesHash; public array $context; diff --git a/app/Livewire/BillingPortal/Cart/RecurringProducts.php b/app/Livewire/BillingPortal/Cart/RecurringProducts.php index 10f79cb69e..46af06035a 100644 --- a/app/Livewire/BillingPortal/Cart/RecurringProducts.php +++ b/app/Livewire/BillingPortal/Cart/RecurringProducts.php @@ -18,7 +18,7 @@ use App\Utils\Traits\MakesHash; use Livewire\Attributes\Computed; class RecurringProducts extends Component -{ +{ use MakesHash; public array $context; diff --git a/app/Livewire/BillingPortal/Payments/Methods.php b/app/Livewire/BillingPortal/Payments/Methods.php index 1dbb2e467a..4af2175823 100644 --- a/app/Livewire/BillingPortal/Payments/Methods.php +++ b/app/Livewire/BillingPortal/Payments/Methods.php @@ -32,7 +32,7 @@ class Methods extends Component $total = collect($this->context['products'])->sum('total_raw'); $methods = auth()->guard('contact')->user()->client->service()->getPaymentMethods($total); //@todo this breaks down when the cart is in front of the login - we have no context on the user - nor their country/currency() - + $this->methods = $methods; } diff --git a/app/Livewire/BillingPortal/Summary.php b/app/Livewire/BillingPortal/Summary.php index 985522393f..b40dca545c 100644 --- a/app/Livewire/BillingPortal/Summary.php +++ b/app/Livewire/BillingPortal/Summary.php @@ -82,12 +82,12 @@ class Summary extends Component } $this->dispatch('purchase.context', property: 'bundle', value: $bundle); - + } - /** - * Base calculations for one-time purchases - */ + /** + * Base calculations for one-time purchases + */ #[Computed] public function oneTimePurchasesTotal(): float { @@ -142,17 +142,17 @@ class Summary extends Component #[Computed] public function discount(): float { - if (!isset($this->context['valid_coupon']) || + if (!isset($this->context['valid_coupon']) || $this->context['valid_coupon'] != $this->subscription()->promo_code) { return 0.0; } $subscription = $this->subscription(); $discount = $subscription->promo_discount; - - return $subscription->is_amount_discount - ? $discount - : ($this->calculateSubtotal() * $discount/100); + + return $subscription->is_amount_discount + ? $discount + : ($this->calculateSubtotal() * $discount / 100); } /** @@ -232,7 +232,7 @@ class Summary extends Component return $products; } - #[On('summary.refresh')] + #[On('summary.refresh')] public function refresh() { // nlog("am i refreshing here?"); diff --git a/app/Livewire/BillingPortalPurchase.php b/app/Livewire/BillingPortalPurchase.php index 5fdbb627c7..81f36eb7c2 100644 --- a/app/Livewire/BillingPortalPurchase.php +++ b/app/Livewire/BillingPortalPurchase.php @@ -363,9 +363,9 @@ class BillingPortalPurchase extends Component $method_values = array_column($this->methods, 'is_paypal'); $is_paypal = in_array('1', $method_values); - if($is_paypal && !$this->steps['check_rff']) { + if ($is_paypal && !$this->steps['check_rff']) { $this->rff(); - } elseif(!$this->steps['check_rff']) { + } elseif (!$this->steps['check_rff']) { $this->steps['fetched_payment_methods'] = true; } @@ -471,9 +471,9 @@ class BillingPortalPurchase extends Component if (config('ninja.ninja_default_company_id') == $this->subscription->company_id && $this->subscription->service()->recurring_products()->first()?->product_key == 'whitelabel') { $context = 'whitelabel'; - } + } - if (config('ninja.ninja_default_company_id') == $this->subscription->company_id && in_array($this->subscription->service()->products()->first()?->product_key,['peppol_500','peppol_1000','selfhost_peppol_500','selfhost_peppol_1000'])) { + if (config('ninja.ninja_default_company_id') == $this->subscription->company_id && in_array($this->subscription->service()->products()->first()?->product_key, ['peppol_500','peppol_1000','selfhost_peppol_500','selfhost_peppol_1000'])) { $context = $this->subscription->service()->products()->first()?->product_key; } diff --git a/app/Livewire/BillingPortalPurchasev2.php b/app/Livewire/BillingPortalPurchasev2.php index ebe0d083a5..c80e37239b 100644 --- a/app/Livewire/BillingPortalPurchasev2.php +++ b/app/Livewire/BillingPortalPurchasev2.php @@ -51,7 +51,7 @@ class BillingPortalPurchasev2 extends Component */ public $email; - + public $subscription_id; @@ -151,7 +151,7 @@ class BillingPortalPurchasev2 extends Component { return Subscription::query()->with('company')->find($this->subscription_id); } - + #[Computed] public function contact() { @@ -184,7 +184,7 @@ class BillingPortalPurchasev2 extends Component $this->price = $subscription->price; // ? $this->float_amount_total = $this->price; - + $this->products = $subscription->service()->products(); $this->recurring_products = $subscription->service()->recurring_products(); $this->optional_recurring_products = $subscription->service()->optional_recurring_products(); @@ -229,7 +229,7 @@ class BillingPortalPurchasev2 extends Component if ($contact) { Auth::guard('contact')->loginUsingId($contact->id, true); - + } else { $this->createBlankClient(); } @@ -280,7 +280,7 @@ class BillingPortalPurchasev2 extends Component */ public function handleCoupon() { - + $subscription = $this->subscription(); $this->resetErrorBag('coupon'); @@ -450,9 +450,9 @@ class BillingPortalPurchasev2 extends Component $this->methods = $contact->client->service()->getPaymentMethods($this->float_amount_total); } - foreach($this->methods as $method) { + foreach ($this->methods as $method) { - if($method['is_paypal'] == '1' && !$this->check_rff) { + if ($method['is_paypal'] == '1' && !$this->check_rff) { $this->rff(); break; } @@ -473,7 +473,7 @@ class BillingPortalPurchasev2 extends Component $this->client_city = $contact->client->city; $this->client_postal_code = $contact->client->postal_code; - if( + if ( strlen($this->contact_first_name ?? '') == 0 || strlen($this->contact_last_name ?? '') == 0 || strlen($this->contact_email ?? '') == 0 || @@ -736,14 +736,14 @@ class BillingPortalPurchasev2 extends Component /** @var \Illuminate\Support\Collection<\App\Models\Currency> */ $currencies = app('currencies'); - $currency = $currencies->first(function ($item) use($subscription) { + $currency = $currencies->first(function ($item) use ($subscription) { return $item->id == $subscription->group_settings->settings->currency_id; }); if ($currency) { $data['settings']->currency_id = $currency->id; } - }else { + } else { $data['settings']->currency_id = $subscription->company->getSetting('currency_id'); } @@ -764,9 +764,9 @@ class BillingPortalPurchasev2 extends Component $client = $client_repo->save($data, ClientFactory::create($company->id, $user->id)); $contact = $client->fresh()->contacts->first(); - + Auth::guard('contact')->loginUsingId($contact->id, true); - + return $contact; } diff --git a/app/Livewire/CreditsTable.php b/app/Livewire/CreditsTable.php index 2b5c2561af..a6a12c7723 100644 --- a/app/Livewire/CreditsTable.php +++ b/app/Livewire/CreditsTable.php @@ -38,7 +38,7 @@ class CreditsTable extends Component public function render() { - + $query = Credit::query() ->where('company_id', auth()->guard('contact')->user()->company_id) ->where('client_id', auth()->guard('contact')->user()->client_id) diff --git a/app/Livewire/Flow2/InvoicePay.php b/app/Livewire/Flow2/InvoicePay.php index d868853f82..17a18cd422 100644 --- a/app/Livewire/Flow2/InvoicePay.php +++ b/app/Livewire/Flow2/InvoicePay.php @@ -41,7 +41,7 @@ class InvoicePay extends Component 'client_postal_code' => 'postal_code', 'client_country_id' => 'country_id', - 'client_shipping_address_line_1' => 'shipping_address1', + 'client_shipping_address_line_1' => 'shipping_address1', 'client_shipping_address_line_2' => 'shipping_address2', 'client_shipping_city' => 'shipping_city', 'client_shipping_state' => 'shipping_state', @@ -178,7 +178,7 @@ class InvoicePay extends Component } } } - + if ($company_gateway->always_show_required_fields) { return $this->required_fields = true; } @@ -212,7 +212,7 @@ class InvoicePay extends Component } return ProcessPayment::class; - + } #[Computed()] @@ -223,14 +223,14 @@ class InvoicePay extends Component public function mount() { - + $this->resetContext(); MultiDB::setDb($this->db); // @phpstan-ignore-next-line $invite = \App\Models\InvoiceInvitation::with('contact.client', 'company')->withTrashed()->find($this->invitation_id); - + $client = $invite->contact->client; $settings = $client->getMergedSettings(); $this->setContext('contact', $invite->contact); // $this->context['contact'] = $invite->contact; @@ -284,9 +284,9 @@ class InvoicePay extends Component return render('flow2.invoice-pay'); } - public function exception($e, $stopPropagation) + public function exception($e, $stopPropagation) { - + app('sentry')->captureException($e); nlog($e->getMessage()); $stopPropagation(); diff --git a/app/Livewire/Flow2/InvoiceSummary.php b/app/Livewire/Flow2/InvoiceSummary.php index c9db227e8a..972ef5c635 100644 --- a/app/Livewire/Flow2/InvoiceSummary.php +++ b/app/Livewire/Flow2/InvoiceSummary.php @@ -29,7 +29,7 @@ class InvoiceSummary extends Component public function mount() { - + $contact = $this->getContext()['contact'] ?? auth()->guard('contact')->user(); $this->invoices = $this->getContext()['payable_invoices']; $this->amount = Number::formatMoney($this->getContext()['amount'], $contact->client); @@ -48,10 +48,10 @@ class InvoiceSummary extends Component } - #[On('payment-view-rendered')] + #[On('payment-view-rendered')] public function handlePaymentViewRendered() { - + $contact = $this->getContext()['contact'] ?? auth()->guard('contact')->user(); $this->amount = Number::formatMoney($this->getContext()['amount'], $contact->client); $this->gateway_fee = isset($this->getContext()['gateway_fee']) ? Number::formatMoney($this->getContext()['gateway_fee'], $contact->client) : false; @@ -63,7 +63,7 @@ class InvoiceSummary extends Component $contact = $this->getContext()['contact'] ?? auth()->guard('contact')->user(); $_invoices = $this->getContext()['invoices']; - $i = $_invoices->first(function ($i) use($invoice_hashed_id){ + $i = $_invoices->first(function ($i) use ($invoice_hashed_id) { return $i->hashed_id == $invoice_hashed_id; }); @@ -82,10 +82,10 @@ class InvoiceSummary extends Component public function render(): \Illuminate\Contracts\View\Factory|\Illuminate\View\View { $contact = $this->getContext()['contact'] ?? auth()->guard('contact')->user(); - + return render('flow2.invoices-summary', [ 'client' => $contact->client, ]); - + } } diff --git a/app/Livewire/Flow2/PaymentMethod.php b/app/Livewire/Flow2/PaymentMethod.php index a1c5a0f502..9542979c56 100644 --- a/app/Livewire/Flow2/PaymentMethod.php +++ b/app/Livewire/Flow2/PaymentMethod.php @@ -76,7 +76,7 @@ class PaymentMethod extends Component return render('flow2.payment-method', ['methods' => $this->methods]); } - public function exception($e, $stopPropagation) + public function exception($e, $stopPropagation) { app('sentry')->captureException($e); $stopPropagation(); diff --git a/app/Livewire/Flow2/ProcessPayment.php b/app/Livewire/Flow2/ProcessPayment.php index bcc4f34d5f..413146bdca 100644 --- a/app/Livewire/Flow2/ProcessPayment.php +++ b/app/Livewire/Flow2/ProcessPayment.php @@ -29,7 +29,7 @@ class ProcessPayment extends Component private array $payment_data_payload = []; public $isLoading = true; - + public function mount() { @@ -58,31 +58,29 @@ class ProcessPayment extends Component throw new PaymentFailed($responder_data['error'], 400); } - if(isset($responder_data['payload']['total']['fee_total'])) - { + if (isset($responder_data['payload']['total']['fee_total'])) { $gateway_fee = data_get($responder_data, 'payload.total.fee_total', false); $amount = data_get($responder_data, 'payload.total.amount_with_fee', 0); - + $this->setContext('amount', $amount); $this->setContext('gateway_fee', $gateway_fee); $this->dispatch('payment-view-rendered'); } - - - if(isset($responder_data['component']) && $responder_data['component'] == 'CreditPaymentComponent'){ + + + if (isset($responder_data['component']) && $responder_data['component'] == 'CreditPaymentComponent') { $this->payment_view = $responder_data['view']; $this->payment_data_payload = $responder_data['payload']; - } - else { + } else { $driver = $company_gateway ->driver($invitation->contact->client) // @phpstan-ignore-line ->setPaymentMethod($data['payment_method_id']) ->setPaymentHash($responder_data['payload']['ph']); $this->payment_data_payload = $driver->processPaymentViewData($responder_data['payload']); - + $this->payment_view = $driver->livewirePaymentView( $this->payment_data_payload, ); @@ -103,9 +101,9 @@ class ProcessPayment extends Component return render($this->payment_view, $this->payment_data_payload); } - public function exception($e, $stopPropagation) + public function exception($e, $stopPropagation) { - + app('sentry')->captureException($e); $errors = session()->get('errors', new \Illuminate\Support\ViewErrorBag()); @@ -113,11 +111,11 @@ class ProcessPayment extends Component $bag = new \Illuminate\Support\MessageBag(); $bag->add('gateway_error', $e->getMessage()); session()->put('errors', $errors->put('default', $bag)); - + $invoice_id = $this->getContext()['payable_invoices'][0]['invoice_id']; $this->redirectRoute('client.invoice.show', ['invoice' => $invoice_id]); $stopPropagation(); } - + } diff --git a/app/Livewire/Flow2/RequiredFields.php b/app/Livewire/Flow2/RequiredFields.php index 39ac7a5ab8..c8d108becf 100644 --- a/app/Livewire/Flow2/RequiredFields.php +++ b/app/Livewire/Flow2/RequiredFields.php @@ -46,7 +46,7 @@ class RequiredFields extends Component public ?string $client_custom_value4; // public $contact; - + /** @var array */ public array $fields = []; @@ -67,7 +67,7 @@ class RequiredFields extends Component $this->company_gateway = CompanyGateway::withTrashed() ->with('company') ->find($this->getContext()['company_gateway_id']); - + $this->client_name = $contact->client->name; $this->contact_first_name = $contact->first_name; $this->contact_last_name = $contact->last_name; @@ -97,10 +97,11 @@ class RequiredFields extends Component /** @var \App\Models\ClientContact $contact */ $rff->check($contact); - if ($rff->unfilled_fields === 0 && !$this->company_gateway->always_show_required_fields) + if ($rff->unfilled_fields === 0 && !$this->company_gateway->always_show_required_fields) { $this->dispatch('required-fields'); - else + } else { $this->is_loading = false; + } } @@ -134,8 +135,8 @@ class RequiredFields extends Component 'contact' => $this->getContext()['contact'], ]); } - - public function exception($e, $stopPropagation) + + public function exception($e, $stopPropagation) { app('sentry')->captureException($e); nlog($e->getMessage()); diff --git a/app/Livewire/Flow2/UnderOverPayment.php b/app/Livewire/Flow2/UnderOverPayment.php index 3d7a6a5ae6..275f69d2aa 100644 --- a/app/Livewire/Flow2/UnderOverPayment.php +++ b/app/Livewire/Flow2/UnderOverPayment.php @@ -18,7 +18,6 @@ use Livewire\Component; class UnderOverPayment extends Component { - use WithSecureContext; public $payableAmount; @@ -45,30 +44,29 @@ class UnderOverPayment extends Component $settings = $this->getContext()['settings']; - foreach($payableInvoices as $key => $invoice){ + foreach ($payableInvoices as $key => $invoice) { $payableInvoices[$key]['amount'] = Number::parseFloat($invoice['formatted_amount']); $payableInvoices[$key]['formatted_currency'] = Number::FormatMoney($payableInvoices[$key]['amount'], $this->getContext()['invitation']->contact->client); } $input_amount = collect($payableInvoices)->sum('amount'); - if($settings->client_portal_allow_under_payment) - { - if($input_amount <= $settings->client_portal_under_payment_minimum || $input_amount <= 0){ + if ($settings->client_portal_allow_under_payment) { + if ($input_amount <= $settings->client_portal_under_payment_minimum || $input_amount <= 0) { // return error message under payment too low. $this->errors = ctrans('texts.minimum_required_payment', ['amount' => max($settings->client_portal_under_payment_minimum, 1)]); $this->dispatch('errorMessageUpdate', errors: $this->errors); } } - if(!$settings->client_portal_allow_over_payment && ($input_amount > $this->invoice_amount)){ + if (!$settings->client_portal_allow_over_payment && ($input_amount > $this->invoice_amount)) { $this->errors = ctrans('texts.over_payments_disabled'); $this->dispatch('errorMessageUpdate', errors: $this->errors); } - if(!$this->errors){ + if (!$this->errors) { $this->setContext('payable_invoices', $payableInvoices); - $this->dispatch('payable-amount', payable_amount: $input_amount ); + $this->dispatch('payable-amount', payable_amount: $input_amount); } } diff --git a/app/Livewire/PaymentMethods/UpdateDefaultMethod.php b/app/Livewire/PaymentMethods/UpdateDefaultMethod.php index 77b20c3a59..ccd63745aa 100644 --- a/app/Livewire/PaymentMethods/UpdateDefaultMethod.php +++ b/app/Livewire/PaymentMethods/UpdateDefaultMethod.php @@ -36,9 +36,9 @@ class UpdateDefaultMethod extends Component public function makeDefault(): void { - + MultiDB::setDb($this->db); - + if ($this->token()->is_default) { return; diff --git a/app/Livewire/PdfSlot.php b/app/Livewire/PdfSlot.php index 1714294abf..cf98151908 100644 --- a/app/Livewire/PdfSlot.php +++ b/app/Livewire/PdfSlot.php @@ -68,7 +68,7 @@ class PdfSlot extends Component { MultiDB::setDb($this->db); - if(!$this->invitation_id) { + if (!$this->invitation_id) { $this->entity()->service()->createInvitations(); } @@ -152,7 +152,7 @@ class PdfSlot extends Component $this->show_line_total = in_array('$product.line_total', $this->settings->pdf_variables->product_columns); $this->show_quantity = in_array('$product.quantity', $this->settings->pdf_variables->product_columns); - if($this->entity_type == 'quote' && !$this->settings->sync_invoice_quote_columns) { + if ($this->entity_type == 'quote' && !$this->settings->sync_invoice_quote_columns) { $this->show_cost = in_array('$product.unit_cost', $this->settings->pdf_variables->product_quote_columns); $this->show_quantity = in_array('$product.quantity', $this->settings->pdf_variables->product_quote_columns); $this->show_line_total = in_array('$product.line_total', $this->settings->pdf_variables->product_quote_columns); @@ -200,7 +200,7 @@ class PdfSlot extends Component $company_address = ""; - foreach($this->settings->pdf_variables->company_address as $variable) { + foreach ($this->settings->pdf_variables->company_address as $variable) { $company_address .= "

{$variable}

"; } @@ -212,7 +212,7 @@ class PdfSlot extends Component { $company_details = ""; - foreach($this->settings->pdf_variables->company_details as $variable) { + foreach ($this->settings->pdf_variables->company_details as $variable) { $company_details .= "

{$variable}

"; } @@ -224,21 +224,21 @@ class PdfSlot extends Component { $entity_details = ""; - if($this->entity_type == 'invoice' || $this->entity_type == 'recurring_invoice') { - foreach($this->settings->pdf_variables->invoice_details as $variable) { + if ($this->entity_type == 'invoice' || $this->entity_type == 'recurring_invoice') { + foreach ($this->settings->pdf_variables->invoice_details as $variable) { $entity_details .= "

{$variable}_label

{$variable}

"; } - } elseif($this->entity_type == 'quote') { - foreach($this->settings->pdf_variables->quote_details ?? [] as $variable) { + } elseif ($this->entity_type == 'quote') { + foreach ($this->settings->pdf_variables->quote_details ?? [] as $variable) { $entity_details .= "

{$variable}_label

{$variable}

"; } - } elseif($this->entity_type == 'credit') { - foreach($this->settings->pdf_variables->credit_details ?? [] as $variable) { + } elseif ($this->entity_type == 'credit') { + foreach ($this->settings->pdf_variables->credit_details ?? [] as $variable) { $entity_details .= "

{$variable}_label

{$variable}

"; } - } elseif($this->entity_type == 'purchase_order') { - foreach($this->settings->pdf_variables->purchase_order_details ?? [] as $variable) { + } elseif ($this->entity_type == 'purchase_order') { + foreach ($this->settings->pdf_variables->purchase_order_details ?? [] as $variable) { $entity_details .= "

{$variable}_label

{$variable}

"; } } @@ -251,10 +251,10 @@ class PdfSlot extends Component { $name = ctrans('texts.details'); - if($this->entity_type == 'purchase_order' && isset($this->settings->pdf_variables->vendor_details[0])) { + if ($this->entity_type == 'purchase_order' && isset($this->settings->pdf_variables->vendor_details[0])) { $name = $this->settings->pdf_variables->vendor_details[0]; - } elseif(isset($this->settings->pdf_variables->client_details[0])) { + } elseif (isset($this->settings->pdf_variables->client_details[0])) { $name = $this->settings->pdf_variables->client_details[0]; } @@ -267,12 +267,12 @@ class PdfSlot extends Component { $user_details = ""; - if($this->entity_type == 'purchase_order') { - foreach(array_slice($this->settings->pdf_variables->vendor_details, 1) as $variable) { + if ($this->entity_type == 'purchase_order') { + foreach (array_slice($this->settings->pdf_variables->vendor_details, 1) as $variable) { $user_details .= "

{$variable}

"; } } else { - foreach(array_slice($this->settings->pdf_variables->client_details, 1) as $variable) { + foreach (array_slice($this->settings->pdf_variables->client_details, 1) as $variable) { $user_details .= "

{$variable}

"; } } diff --git a/app/Livewire/Profile/Settings/General.php b/app/Livewire/Profile/Settings/General.php index e8d5157f8b..7945c82932 100644 --- a/app/Livewire/Profile/Settings/General.php +++ b/app/Livewire/Profile/Settings/General.php @@ -66,7 +66,7 @@ class General extends Component public function submit() { - + $profile = $this->profile(); if ($profile->email != $this->email) { diff --git a/app/Livewire/Profile/Settings/PersonalAddress.php b/app/Livewire/Profile/Settings/PersonalAddress.php index ef3a190251..28ade46b5f 100644 --- a/app/Livewire/Profile/Settings/PersonalAddress.php +++ b/app/Livewire/Profile/Settings/PersonalAddress.php @@ -6,7 +6,6 @@ use Livewire\Component; class PersonalAddress extends Component { - public $address1; public $address2; diff --git a/app/Livewire/Profile/Settings/ShippingAddress.php b/app/Livewire/Profile/Settings/ShippingAddress.php index 475f66d2bb..e356b64ccd 100644 --- a/app/Livewire/Profile/Settings/ShippingAddress.php +++ b/app/Livewire/Profile/Settings/ShippingAddress.php @@ -6,7 +6,6 @@ use Livewire\Component; class ShippingAddress extends Component { - public $shipping_address1; public $shipping_address2; diff --git a/app/Livewire/PurchaseOrdersTable.php b/app/Livewire/PurchaseOrdersTable.php index fc2a1517b2..d34ab74a1d 100644 --- a/app/Livewire/PurchaseOrdersTable.php +++ b/app/Livewire/PurchaseOrdersTable.php @@ -29,7 +29,7 @@ class PurchaseOrdersTable extends Component public $status = []; public $db; - + public function mount() { MultiDB::setDb($this->db); diff --git a/app/Livewire/RecurringInvoiceCancellation.php b/app/Livewire/RecurringInvoiceCancellation.php index a5a123edb2..6f99f3b992 100644 --- a/app/Livewire/RecurringInvoiceCancellation.php +++ b/app/Livewire/RecurringInvoiceCancellation.php @@ -18,7 +18,6 @@ use Livewire\Component; class RecurringInvoiceCancellation extends Component { - public $invoice_id; public $db; @@ -35,7 +34,7 @@ class RecurringInvoiceCancellation extends Component public function processCancellation() { - + MultiDB::setDb($this->db); $ri = RecurringInvoice::withTrashed()->find($this->invoice_id); diff --git a/app/Livewire/RequiredClientInfo.php b/app/Livewire/RequiredClientInfo.php index 66a516aa47..14f2837d48 100644 --- a/app/Livewire/RequiredClientInfo.php +++ b/app/Livewire/RequiredClientInfo.php @@ -188,13 +188,13 @@ class RequiredClientInfo extends Component public function mount() { MultiDB::setDb($this->db); - + $contact = ClientContact::withTrashed()->with(['client' => function ($query) { $query->without('gateway_tokens', 'documents', 'contacts.company', 'contacts'); // Exclude 'grandchildren' relation of 'client' }])->find($this->contact_id); $this->company_gateway = CompanyGateway::withTrashed()->with('company')->find($this->company_gateway_id); - + $company = $this->company_gateway->company; $this->client_name = $contact->client->name; @@ -230,7 +230,7 @@ class RequiredClientInfo extends Component $this->invoice_terms = $invoice->terms; } - if(!$this->company_gateway->always_show_required_fields || $this->is_subscription) { + if (!$this->company_gateway->always_show_required_fields || $this->is_subscription) { $this->checkFields(); } @@ -241,7 +241,7 @@ class RequiredClientInfo extends Component ); } - if($this->unfilled_fields > 0 || ($this->company_gateway->always_show_required_fields || $this->is_subscription)) { + if ($this->unfilled_fields > 0 || ($this->company_gateway->always_show_required_fields || $this->is_subscription)) { $this->show_form = true; } } diff --git a/app/Livewire/SubscriptionPlanSwitch.php b/app/Livewire/SubscriptionPlanSwitch.php index 2909562bb4..7084077818 100644 --- a/app/Livewire/SubscriptionPlanSwitch.php +++ b/app/Livewire/SubscriptionPlanSwitch.php @@ -23,7 +23,6 @@ use Illuminate\Support\Facades\Cache; class SubscriptionPlanSwitch extends Component { - public $recurring_invoice_id; public $subscription_id; @@ -35,7 +34,7 @@ class SubscriptionPlanSwitch extends Component public $contact_id; public $db; - + /** * @var array */ diff --git a/app/Livewire/SubscriptionsTable.php b/app/Livewire/SubscriptionsTable.php index 0092d76617..e832507567 100644 --- a/app/Livewire/SubscriptionsTable.php +++ b/app/Livewire/SubscriptionsTable.php @@ -28,7 +28,7 @@ class SubscriptionsTable extends Component public $company_id; public $db; - + public function mount() { MultiDB::setDb($this->db); diff --git a/app/Mail/Admin/ClientPaymentFailureObject.php b/app/Mail/Admin/ClientPaymentFailureObject.php index a667360930..172396f7f0 100644 --- a/app/Mail/Admin/ClientPaymentFailureObject.php +++ b/app/Mail/Admin/ClientPaymentFailureObject.php @@ -91,11 +91,10 @@ class ClientPaymentFailureObject private function getSubject() { - - if(strlen($this->client->getSetting('email_subject_payment_failed') ?? '') > 2){ + + if (strlen($this->client->getSetting('email_subject_payment_failed') ?? '') > 2) { return $this->client->getSetting('email_subject_payment_failed'); - } - else { + } else { return EmailTemplateDefaults::getDefaultTemplate('email_subject_payment_failed', $this->client->locale()); } @@ -103,8 +102,8 @@ class ClientPaymentFailureObject private function getBody() { - - if(strlen($this->client->getSetting('email_template_payment_failed') ?? '') > 2) { + + if (strlen($this->client->getSetting('email_template_payment_failed') ?? '') > 2) { return $this->client->getSetting('email_template_payment_failed'); } else { return EmailTemplateDefaults::getDefaultTemplate('email_template_payment_failed', $this->client->locale()); @@ -122,7 +121,7 @@ class ClientPaymentFailureObject $signature = $this->client->getSetting('email_signature'); $html_variables = (new HtmlEngine($invitation))->makeValues(); - + $html_variables['$payment_error'] = $this->error ?? ''; $html_variables['$total'] = $this->getAmount(); diff --git a/app/Mail/Admin/VerifyUserObject.php b/app/Mail/Admin/VerifyUserObject.php index 3a435ed28f..468353239d 100644 --- a/app/Mail/Admin/VerifyUserObject.php +++ b/app/Mail/Admin/VerifyUserObject.php @@ -40,7 +40,7 @@ class VerifyUserObject $react_redirect = ''; - if($this->is_react) { + if ($this->is_react) { $react_redirect = '?react=true'; } diff --git a/app/Mail/DownloadReport.php b/app/Mail/DownloadReport.php index 2a67fd18a0..b7691971da 100644 --- a/app/Mail/DownloadReport.php +++ b/app/Mail/DownloadReport.php @@ -50,12 +50,11 @@ class DownloadReport extends Mailable 'greeting' => $this->company->present()->name(), ]); - foreach($this->files as $file) - { - $mailable->attachData(base64_decode($file['file']), $file['file_name'], ['mime' => $file['mime']]); - } + foreach ($this->files as $file) { + $mailable->attachData(base64_decode($file['file']), $file['file_name'], ['mime' => $file['mime']]); + } + + return $mailable; - return $mailable; - } } diff --git a/app/Mail/Engine/CreditEmailEngine.php b/app/Mail/Engine/CreditEmailEngine.php index e774c6d658..9856e41d14 100644 --- a/app/Mail/Engine/CreditEmailEngine.php +++ b/app/Mail/Engine/CreditEmailEngine.php @@ -119,7 +119,7 @@ class CreditEmailEngine extends BaseEmailEngine $pdf = ((new CreateRawPdf($this->invitation))->handle()); - if($this->client->getSetting('embed_documents') && ($this->credit->documents()->where('is_public', true)->count() > 0 || $this->credit->company->documents()->where('is_public', true)->count() > 0)) { + if ($this->client->getSetting('embed_documents') && ($this->credit->documents()->where('is_public', true)->count() > 0 || $this->credit->company->documents()->where('is_public', true)->count() > 0)) { $pdf = $this->credit->documentMerge($pdf); } diff --git a/app/Mail/Engine/InvoiceEmailEngine.php b/app/Mail/Engine/InvoiceEmailEngine.php index 151d3e552c..fd40ee7b9b 100644 --- a/app/Mail/Engine/InvoiceEmailEngine.php +++ b/app/Mail/Engine/InvoiceEmailEngine.php @@ -131,7 +131,7 @@ class InvoiceEmailEngine extends BaseEmailEngine if ($this->client->getSetting('pdf_email_attachment') !== false && $this->invoice->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { $pdf = ((new CreateRawPdf($this->invitation))->handle()); - if($this->client->getSetting('embed_documents') && ($this->invoice->documents()->where('is_public', true)->count() > 0 || $this->invoice->company->documents()->where('is_public', true)->count() > 0)) { + if ($this->client->getSetting('embed_documents') && ($this->invoice->documents()->where('is_public', true)->count() > 0 || $this->invoice->company->documents()->where('is_public', true)->count() > 0)) { $pdf = $this->invoice->documentMerge($pdf); } diff --git a/app/Mail/Engine/PaymentEmailEngine.php b/app/Mail/Engine/PaymentEmailEngine.php index 5d2b6f045c..0a3bf865e0 100644 --- a/app/Mail/Engine/PaymentEmailEngine.php +++ b/app/Mail/Engine/PaymentEmailEngine.php @@ -103,7 +103,7 @@ class PaymentEmailEngine extends BaseEmailEngine $template_in_use = false; - if($this->is_refund && \App\Models\Design::where('id', $this->decodePrimaryKey($this->payment->client->getSetting('payment_refund_design_id')))->where('is_template', true)->exists()) { + if ($this->is_refund && \App\Models\Design::where('id', $this->decodePrimaryKey($this->payment->client->getSetting('payment_refund_design_id')))->where('is_template', true)->exists()) { $pdf = (new TemplateAction( [$this->payment->hashed_id], $this->payment->client->getSetting('payment_refund_design_id'), @@ -120,7 +120,7 @@ class PaymentEmailEngine extends BaseEmailEngine $this->setAttachments([['file' => base64_encode($pdf), 'name' => $file_name]]); $template_in_use = true; - } elseif(!$this->is_refund && \App\Models\Design::where('id', $this->decodePrimaryKey($this->payment->client->getSetting('payment_receipt_design_id')))->where('is_template', true)->exists()) { + } elseif (!$this->is_refund && \App\Models\Design::where('id', $this->decodePrimaryKey($this->payment->client->getSetting('payment_receipt_design_id')))->where('is_template', true)->exists()) { $pdf = (new TemplateAction( [$this->payment->hashed_id], $this->payment->client->getSetting('payment_receipt_design_id'), @@ -141,7 +141,7 @@ class PaymentEmailEngine extends BaseEmailEngine $this->payment->invoices->each(function ($invoice) use ($template_in_use) { - if(!$template_in_use) { + if (!$template_in_use) { $pdf = ((new CreateRawPdf($invoice->invitations->first()))->handle()); $file_name = $invoice->numberFormatter().'.pdf'; $this->setAttachments([['file' => base64_encode($pdf), 'name' => $file_name]]); @@ -411,7 +411,7 @@ class PaymentEmailEngine extends BaseEmailEngine } - if(strlen($invoice_list) < 4) { + if (strlen($invoice_list) < 4) { $invoice_list = Number::formatMoney($this->payment->amount, $this->client) ?: ' '; } diff --git a/app/Mail/Engine/PurchaseOrderEmailEngine.php b/app/Mail/Engine/PurchaseOrderEmailEngine.php index cef7173466..7bfb160a99 100644 --- a/app/Mail/Engine/PurchaseOrderEmailEngine.php +++ b/app/Mail/Engine/PurchaseOrderEmailEngine.php @@ -123,7 +123,7 @@ class PurchaseOrderEmailEngine extends BaseEmailEngine $pdf = (new CreateRawPdf($this->invitation))->handle(); - if($this->vendor->getSetting('embed_documents') && ($this->purchase_order->documents()->where('is_public', true)->count() > 0 || $this->purchase_order->company->documents()->where('is_public', true)->count() > 0)) { + if ($this->vendor->getSetting('embed_documents') && ($this->purchase_order->documents()->where('is_public', true)->count() > 0 || $this->purchase_order->company->documents()->where('is_public', true)->count() > 0)) { $pdf = $this->purchase_order->documentMerge($pdf); } diff --git a/app/Mail/Engine/QuoteEmailEngine.php b/app/Mail/Engine/QuoteEmailEngine.php index 9034af367d..8374066699 100644 --- a/app/Mail/Engine/QuoteEmailEngine.php +++ b/app/Mail/Engine/QuoteEmailEngine.php @@ -118,7 +118,7 @@ class QuoteEmailEngine extends BaseEmailEngine if ($this->client->getSetting('pdf_email_attachment') !== false && $this->quote->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { $pdf = ((new CreateRawPdf($this->invitation))->handle()); - if($this->client->getSetting('embed_documents') && ($this->quote->documents()->where('is_public', true)->count() > 0 || $this->quote->company->documents()->where('is_public', true)->count() > 0)) { + if ($this->client->getSetting('embed_documents') && ($this->quote->documents()->where('is_public', true)->count() > 0 || $this->quote->company->documents()->where('is_public', true)->count() > 0)) { $pdf = $this->quote->documentMerge($pdf); } diff --git a/app/Mail/Ninja/StripeConnectFailed.php b/app/Mail/Ninja/StripeConnectFailed.php index 1511d0f1c8..9e1ce658ad 100644 --- a/app/Mail/Ninja/StripeConnectFailed.php +++ b/app/Mail/Ninja/StripeConnectFailed.php @@ -55,12 +55,12 @@ class StripeConnectFailed extends Mailable view: 'email.einvoice.peppol_purchase_allocation_failed', text: 'email.einvoice.peppol_purchase_allocation_failed_text', with: [ - + ] ); } - + /** * Get the attachments for the message. * diff --git a/app/Mail/TemplateEmail.php b/app/Mail/TemplateEmail.php index 82ae638baf..08c2d81e81 100644 --- a/app/Mail/TemplateEmail.php +++ b/app/Mail/TemplateEmail.php @@ -83,7 +83,7 @@ class TemplateEmail extends Mailable $template_name = 'email.template.client'; } - if($this->build_email->getTemplate() == 'premium') { + if ($this->build_email->getTemplate() == 'premium') { $template_name = 'email.template.client_premium'; } @@ -119,7 +119,7 @@ class TemplateEmail extends Mailable if (strlen($settings->bcc_email) > 1) { if (Ninja::isHosted()) { - if($company->account->isPaid()) { + if ($company->account->isPaid()) { $bccs = explode(',', str_replace(' ', '', $settings->bcc_email)); $this->bcc(array_slice($bccs, 0, 5)); } @@ -159,7 +159,7 @@ class TemplateEmail extends Mailable } } - if(!$this->invitation) { + if (!$this->invitation) { return $this; } diff --git a/app/Mail/VendorTemplateEmail.php b/app/Mail/VendorTemplateEmail.php index 7adbcbcc74..52f589ef3f 100644 --- a/app/Mail/VendorTemplateEmail.php +++ b/app/Mail/VendorTemplateEmail.php @@ -75,7 +75,7 @@ class VendorTemplateEmail extends Mailable $template_name = 'email.template.client'; } - if($this->build_email->getTemplate() == 'premium') { + if ($this->build_email->getTemplate() == 'premium') { $template_name = 'email.template.client_premium'; } @@ -110,7 +110,7 @@ class VendorTemplateEmail extends Mailable if (Ninja::isHosted()) { - if($this->company->account->isPaid()) { + if ($this->company->account->isPaid()) { $bccs = explode(',', str_replace(' ', '', $settings->bcc_email)); $this->bcc(array_slice($bccs, 0, 5)); } diff --git a/app/Models/Account.php b/app/Models/Account.php index 148b237f39..1c4cc36207 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -500,7 +500,7 @@ class Account extends BaseModel return 0; } - if($this->email_quota) { + if ($this->email_quota) { return (int)$this->email_quota; } diff --git a/app/Models/Activity.php b/app/Models/Activity.php index 7b410d0cf0..8fd6a20492 100644 --- a/app/Models/Activity.php +++ b/app/Models/Activity.php @@ -265,9 +265,9 @@ class Activity extends StaticModel public const QUOTE_REMINDER1_SENT = 142; - public const AUTOBILL_SUCCESS = 143; + public const AUTOBILL_SUCCESS = 143; - public const AUTOBILL_FAILURE = 144; + public const AUTOBILL_FAILURE = 144; public const EINVOICE_SENT = 145; @@ -426,29 +426,29 @@ class Activity extends StaticModel $found_variables = array_intersect(explode(" ", trans("texts.activity_{$this->activity_type_id}")), $intersect); - if($this->activity_type_id == 10 && $this->client_contact_id && !$this->token_id) { + if ($this->activity_type_id == 10 && $this->client_contact_id && !$this->token_id) { $found_variables = array_intersect(explode(" ", trans("texts.activity_10_online")), $intersect); } - if($this->activity_type_id == 54 && !$this->token_id) { + if ($this->activity_type_id == 54 && !$this->token_id) { array_push($found_variables, ':contact'); } $replacements = []; - foreach($found_variables as $var) { + foreach ($found_variables as $var) { $replacements = array_merge($replacements, $this->matchVar($var)); } - if($this->client) { + if ($this->client) { $replacements['client'] = ['label' => $this->client?->present()->name() ?? '', 'hashed_id' => $this->client->hashed_id ?? '']; } - if($this->vendor) { + if ($this->vendor) { $replacements['vendor'] = ['label' => $this->vendor?->present()->name() ?? '', 'hashed_id' => $this->vendor->hashed_id ?? '']; } - if($this->activity_type_id == 4 && $this->recurring_invoice) { + if ($this->activity_type_id == 4 && $this->recurring_invoice) { $replacements['recurring_invoice'] = ['label' => $this?->recurring_invoice?->number ?? '', 'hashed_id' => $this->recurring_invoice->hashed_id ?? '']; } @@ -459,7 +459,7 @@ class Activity extends StaticModel $replacements['created_at'] = $this->created_at ?? ''; $replacements['ip'] = $this->ip ?? ''; - if($this->activity_type_id == 141) { + if ($this->activity_type_id == 141) { $replacements = $this->harvestNoteEntities($replacements); } @@ -483,10 +483,10 @@ class Activity extends StaticModel ]; - foreach($entities as $entity) { + foreach ($entities as $entity) { $entity_key = substr($entity, 1); - if($this?->{$entity_key}) { + if ($this?->{$entity_key}) { $replacements = array_merge($replacements, $this->matchVar($entity)); } @@ -533,7 +533,7 @@ class Activity extends StaticModel $contact_entity = $this->contact ? 'clients' : 'vendors'; - if(!$contact) { + if (!$contact) { return []; } diff --git a/app/Models/BaseModel.php b/app/Models/BaseModel.php index 15ed80f66b..4d04da2df1 100644 --- a/app/Models/BaseModel.php +++ b/app/Models/BaseModel.php @@ -328,18 +328,18 @@ class BaseModel extends Model } // special catch here for einvoicing eventing - if($event_id == Webhook::EVENT_SENT_INVOICE && ($this instanceof Invoice) && is_null($this->backup) && $this->client->peppolSendingEnabled()){ + if ($event_id == Webhook::EVENT_SENT_INVOICE && ($this instanceof Invoice) && is_null($this->backup) && $this->client->peppolSendingEnabled()) { \App\Services\EDocument\Jobs\SendEDocument::dispatch(get_class($this), $this->id, $this->company->db); } } - + /** * arrayFilterRecursive nee filterNullsRecursive * * Removes null properties from an array - * + * * @param array $array * @return array */ @@ -394,7 +394,7 @@ class BaseModel extends Model */ public function parseHtmlVariables(string $field, array $variables): string { - if(!$this->{$field}) { + if (!$this->{$field}) { return ''; } @@ -442,7 +442,7 @@ class BaseModel extends Model $pdf = (new PdfMerge($files->flatten()->toArray()))->run(); return $pdf; - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: BaseModel:: PdfMerge::" . $e->getMessage()); } diff --git a/app/Models/Client.php b/app/Models/Client.php index 539392f386..9f22463ac9 100644 --- a/app/Models/Client.php +++ b/app/Models/Client.php @@ -240,15 +240,16 @@ class Client extends BaseModel implements HasLocalePreference public function toSearchableArray() { - + $locale = $this->locale(); App::setLocale($locale); $name = ctrans('texts.client') . " | " . $this->present()->name(); - if(strlen($this->vat_number ?? '') > 1) + if (strlen($this->vat_number ?? '') > 1) { $name .= " | ". $this->vat_number; - + } + return [ 'name' => $name, 'is_deleted' => $this->is_deleted, @@ -280,10 +281,10 @@ class Client extends BaseModel implements HasLocalePreference ]; } - public function getScoutKey() - { - return $this->hashed_id; - } + public function getScoutKey() + { + return $this->hashed_id; + } public function getEntityType() { @@ -522,7 +523,7 @@ class Client extends BaseModel implements HasLocalePreference return $this->settings->{$setting}; } elseif (is_int($this->settings->{$setting})) { return $this->settings->{$setting}; - } elseif(is_float($this->settings->{$setting})) { + } elseif (is_float($this->settings->{$setting})) { return $this->settings->{$setting}; } } @@ -532,8 +533,7 @@ class Client extends BaseModel implements HasLocalePreference return $this->group_settings->settings->{$setting}; } - /*Company Settings*/ - elseif ((property_exists($this->company->settings, $setting) !== false) && (isset($this->company->settings->{$setting}) !== false)) { + /*Company Settings*/ elseif ((property_exists($this->company->settings, $setting) !== false) && (isset($this->company->settings->{$setting}) !== false)) { return $this->company->settings->{$setting}; } elseif (property_exists(CompanySettings::defaults(), $setting)) { return CompanySettings::defaults()->{$setting}; @@ -590,7 +590,7 @@ class Client extends BaseModel implements HasLocalePreference $cg = CompanyGateway::query()->find($pm['company_gateway_id']); - if($cg->gateway_key == '80af24a6a691230bbec33e930ab40666') { //ensure we don't attempt to authorize paypal platform - yet. + if ($cg->gateway_key == '80af24a6a691230bbec33e930ab40666') { //ensure we don't attempt to authorize paypal platform - yet. continue; } @@ -708,7 +708,7 @@ class Client extends BaseModel implements HasLocalePreference } if (in_array($this->currency()->code, ['CAD','USD']) && in_array(GatewayType::ACSS, array_column($pms, 'gateway_type_id'))) { - // if ($this->currency()->code == 'CAD' && in_array(GatewayType::ACSS, array_column($pms, 'gateway_type_id'))) { + // if ($this->currency()->code == 'CAD' && in_array(GatewayType::ACSS, array_column($pms, 'gateway_type_id'))) { foreach ($pms as $pm) { if ($pm['gateway_type_id'] == GatewayType::ACSS) { $cg = CompanyGateway::query()->find($pm['company_gateway_id']); @@ -720,7 +720,7 @@ class Client extends BaseModel implements HasLocalePreference } } - + if (in_array($this->currency()->code, ['GBP']) && in_array(GatewayType::BACS, array_column($pms, 'gateway_type_id'))) { // if ($this->currency()->code == 'CAD' && in_array(GatewayType::ACSS, array_column($pms, 'gateway_type_id'))) { foreach ($pms as $pm) { @@ -769,11 +769,9 @@ class Client extends BaseModel implements HasLocalePreference if ($cg && $cg->fees_and_limits->{GatewayType::SEPA}->is_enabled) { return GatewayType::SEPA; - } - else if ($cg && $cg->fees_and_limits->{GatewayType::BANK_TRANSFER}->is_enabled) { + } elseif ($cg && $cg->fees_and_limits->{GatewayType::BANK_TRANSFER}->is_enabled) { return GatewayType::BANK_TRANSFER; - } - else if ($cg && $cg->fees_and_limits->{GatewayType::DIRECT_DEBIT}->is_enabled) { + } elseif ($cg && $cg->fees_and_limits->{GatewayType::DIRECT_DEBIT}->is_enabled) { return GatewayType::DIRECT_DEBIT; } @@ -936,13 +934,13 @@ class Client extends BaseModel implements HasLocalePreference $terms = &$data['terms']; $footer = &$data['footer']; - if(empty($terms)) { + if (empty($terms)) { $defaults['terms'] = $this->getSetting($entity_name.'_terms'); } elseif ($terms) { $defaults['terms'] = $data['terms']; } - if(empty($footer)) { + if (empty($footer)) { $defaults['footer'] = $this->getSetting($entity_name.'_footer'); } elseif ($footer) { $defaults['footer'] = $data['footer']; @@ -989,8 +987,7 @@ class Client extends BaseModel implements HasLocalePreference if ($entity_send_time == 0) { //Send UTC time return 0; - } - elseif($entity_send_time == 24) { // Step back a few seconds to ensure we do not send exactly at hour 24 as that will be the next day - technically. + } elseif ($entity_send_time == 24) { // Step back a few seconds to ensure we do not send exactly at hour 24 as that will be the next day - technically. $offset -= 10; } @@ -1022,12 +1019,12 @@ class Client extends BaseModel implements HasLocalePreference { return $use_react_url ? config('ninja.react_url'). "/#/clients/{$this->hashed_id}" : config('ninja.app_url'); } - + /** * peppolSendingEnabled - * + * * Determines the sending status of the company - * + * * @return bool */ public function peppolSendingEnabled(): bool diff --git a/app/Models/ClientContact.php b/app/Models/ClientContact.php index 2fb32bb19e..ed2eedde99 100644 --- a/app/Models/ClientContact.php +++ b/app/Models/ClientContact.php @@ -187,7 +187,7 @@ class ClientContact extends Authenticatable implements HasLocalePreference public function getScoutKey() { - return $this->hashed_id; + return $this->hashed_id; } /* diff --git a/app/Models/Company.php b/app/Models/Company.php index 567c94f2c7..736331c27a 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -554,8 +554,8 @@ class Company extends BaseModel } public function activities(): HasMany - { - return $this->hasMany(Activity::class)->orderBy('id', 'DESC')->take(50); + { + return $this->hasMany(Activity::class)->orderBy('id', 'DESC')->take(50); } /** @@ -985,7 +985,7 @@ class Company extends BaseModel return Ninja::isHosted() && $this->account->isPaid() && $this->account->isEnterpriseClient() && $this->account->e_invoice_quota > 0 && $this->settings->e_invoice_type == 'PEPPOL' && $this->tax_data->acts_as_sender; } - + /** * peppolSendingEnabled * diff --git a/app/Models/CompanyGateway.php b/app/Models/CompanyGateway.php index a212a68128..701979fcd2 100644 --- a/app/Models/CompanyGateway.php +++ b/app/Models/CompanyGateway.php @@ -451,7 +451,7 @@ class CompanyGateway extends BaseModel } else { $fee += round(($amount * $fees_and_limits->fee_percent / 100), 2); } - + } } /* Cap fee if we have to here. */ @@ -481,7 +481,7 @@ class CompanyGateway extends BaseModel public function getSettings() { - return $this->settings ?? new \stdClass; + return $this->settings ?? new \stdClass(); } public function setSettings($settings) diff --git a/app/Models/Document.php b/app/Models/Document.php index 9019c34429..8601a58fe8 100644 --- a/app/Models/Document.php +++ b/app/Models/Document.php @@ -88,7 +88,7 @@ class Document extends BaseModel protected $touches = [ // 'documentable' ]; - + /** * @var array */ @@ -182,7 +182,7 @@ class Document extends BaseModel { try { return route('api.documents.show', ['document' => $this->hashed_id]).'/download'; - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: Document::" . $e->getMessage()); return ''; } @@ -242,7 +242,7 @@ class Document extends BaseModel $image = $this->getFile(); $catch_image = $image; - if(!extension_loaded('imagick')) { + if (!extension_loaded('imagick')) { return $catch_image; } @@ -256,7 +256,7 @@ class Document extends BaseModel return $img->getImageBlob(); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: Document::" . $e->getMessage()); nlog($e->getMessage()); return $catch_image; diff --git a/app/Models/EInvoicingToken.php b/app/Models/EInvoicingToken.php index be4994243c..b26c752884 100644 --- a/app/Models/EInvoicingToken.php +++ b/app/Models/EInvoicingToken.php @@ -29,13 +29,12 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; class EInvoicingToken extends Model { - protected $fillable = [ 'license', 'token', 'account_key', ]; - + /** * license_relation * diff --git a/app/Models/Expense.php b/app/Models/Expense.php index f95ead0502..6b4f64519e 100644 --- a/app/Models/Expense.php +++ b/app/Models/Expense.php @@ -243,15 +243,15 @@ class Expense extends BaseModel public function stringStatus() { - if($this->is_deleted) { + if ($this->is_deleted) { return ctrans('texts.deleted'); - } elseif($this->payment_date) { + } elseif ($this->payment_date) { return ctrans('texts.paid'); - } elseif($this->invoice_id) { + } elseif ($this->invoice_id) { return ctrans('texts.invoiced'); - } elseif($this->should_be_invoiced) { + } elseif ($this->should_be_invoiced) { return ctrans('texts.pending'); - } elseif($this->trashed()) { + } elseif ($this->trashed()) { return ctrans('texts.archived'); } diff --git a/app/Models/Gateway.php b/app/Models/Gateway.php index ab62c3200f..59dbedb855 100644 --- a/app/Models/Gateway.php +++ b/app/Models/Gateway.php @@ -106,9 +106,9 @@ class Gateway extends StaticModel } elseif ($this->id == 62) { $link = 'https://docs.btcpayserver.org/InvoiceNinja/'; } elseif ($this->id == 63) { - $link = 'https://rotessa.com'; + $link = 'https://rotessa.com'; } elseif ($this->id == 64) { - $link = 'https://blockonomics.co'; + $link = 'https://blockonomics.co'; } return $link; @@ -234,7 +234,7 @@ class Gateway extends StaticModel 'refund' => false, 'token_billing' => true, 'webhooks' => [], - ], + ], GatewayType::ACSS => ['refund' => false, 'token_billing' => true, 'webhooks' => []] ]; // Rotessa case 64: //b67581d804dbad1743b61c57285142ad - powerboard diff --git a/app/Models/Invoice.php b/app/Models/Invoice.php index 2d7b4c86f8..8540e4379f 100644 --- a/app/Models/Invoice.php +++ b/app/Models/Invoice.php @@ -266,10 +266,10 @@ class Invoice extends BaseModel ]; } - public function getScoutKey() - { - return $this->hashed_id; - } + public function getScoutKey() + { + return $this->hashed_id; + } public function getEntityType() { @@ -467,7 +467,7 @@ class Invoice extends BaseModel public function isPayable(): bool { - if($this->is_deleted || $this->status_id == self::STATUS_PAID || $this->balance < 0) { + if ($this->is_deleted || $this->status_id == self::STATUS_PAID || $this->balance < 0) { return false; } elseif ($this->status_id == self::STATUS_DRAFT && $this->is_deleted == false) { return true; @@ -794,25 +794,25 @@ class Invoice extends BaseModel $days_endless = \App\Models\RecurringInvoice::frequencyForKey($settings->endless_reminder_frequency_id); $label_endless = ctrans('texts.reminder_endless'); - if($schedule_1 == ctrans('texts.disabled') || $settings->schedule_reminder1 == 'disabled' || $settings->schedule_reminder1 == '') { + if ($schedule_1 == ctrans('texts.disabled') || $settings->schedule_reminder1 == 'disabled' || $settings->schedule_reminder1 == '') { $reminder_schedule .= "{$label_1}: " . ctrans('texts.disabled') ."
"; } else { $reminder_schedule .= "{$label_1}: {$days_1} {$schedule_1} [{$sends_email_1}]
"; } - if($schedule_2 == ctrans('texts.disabled') || $settings->schedule_reminder2 == 'disabled' || $settings->schedule_reminder2 == '') { + if ($schedule_2 == ctrans('texts.disabled') || $settings->schedule_reminder2 == 'disabled' || $settings->schedule_reminder2 == '') { $reminder_schedule .= "{$label_2}: " . ctrans('texts.disabled') ."
"; } else { $reminder_schedule .= "{$label_2}: {$days_2} {$schedule_2} [{$sends_email_2}]
"; } - if($schedule_3 == ctrans('texts.disabled') || $settings->schedule_reminder3 == 'disabled' || $settings->schedule_reminder3 == '') { + if ($schedule_3 == ctrans('texts.disabled') || $settings->schedule_reminder3 == 'disabled' || $settings->schedule_reminder3 == '') { $reminder_schedule .= "{$label_3}: " . ctrans('texts.disabled') ."
"; } else { $reminder_schedule .= "{$label_3}: {$days_3} {$schedule_3} [{$sends_email_3}]
"; } - if($sends_email_endless == ctrans('texts.disabled') || $settings->endless_reminder_frequency_id == '0' || $settings->endless_reminder_frequency_id == '') { + if ($sends_email_endless == ctrans('texts.disabled') || $settings->endless_reminder_frequency_id == '0' || $settings->endless_reminder_frequency_id == '') { $reminder_schedule .= "{$label_endless}: " . ctrans('texts.disabled') ."
"; } else { $reminder_schedule .= "{$label_endless}: {$days_endless} [{$sends_email_endless}]
"; diff --git a/app/Models/License.php b/app/Models/License.php index 7b98c36d54..64c81200b4 100644 --- a/app/Models/License.php +++ b/app/Models/License.php @@ -33,7 +33,7 @@ use Illuminate\Database\Eloquent\Casts\AsArrayObject; * @property int|null $recurring_invoice_id * @property int|null $e_invoice_quota * @property bool $is_flagged - * @property array|null $entities + * @property array|null $entities * @property-read \App\Models\RecurringInvoice $recurring_invoice * @property-read \Illuminate\Database\Eloquent\Collection $e_invoicing_tokens * @method static \Illuminate\Database\Eloquent\Builder|StaticModel company() @@ -66,7 +66,7 @@ class License extends StaticModel 'created_at' => 'date', 'entities' => AsTaxEntityCollection::class, ]; - + /** * expiry * @@ -76,7 +76,7 @@ class License extends StaticModel { return $this->created_at->addYear()->format('Y-m-d'); } - + /** * recurring_invoice * @@ -85,7 +85,7 @@ class License extends StaticModel { return $this->belongsTo(RecurringInvoice::class); } - + /** * e_invoicing_tokens * @@ -94,7 +94,7 @@ class License extends StaticModel { return $this->hasMany(EInvoicingToken::class, 'license_key', 'license_key'); } - + /** * addEntity * @@ -112,11 +112,11 @@ class License extends StaticModel } $this->entities = $entities; - + $this->save(); } - + /** * removeEntity * @@ -125,7 +125,7 @@ class License extends StaticModel */ public function removeEntity(TaxEntity $entity) { - + if (!is_array($this->entities)) { return; } @@ -137,7 +137,7 @@ class License extends StaticModel $this->save(); } - + /** * isValid * diff --git a/app/Models/Payment.php b/app/Models/Payment.php index a03e27ae14..da4bc0a8a7 100644 --- a/app/Models/Payment.php +++ b/app/Models/Payment.php @@ -325,7 +325,7 @@ class Payment extends BaseModel return '
'.ctrans('texts.payment_status_3').'
'; case self::STATUS_COMPLETED: - if($this->amount > $this->applied) { + if ($this->amount > $this->applied) { return '
' . ctrans('texts.partially_unapplied') . '
'; } diff --git a/app/Models/Presenters/CompanyPresenter.php b/app/Models/Presenters/CompanyPresenter.php index c755746702..9e0e0b662a 100644 --- a/app/Models/Presenters/CompanyPresenter.php +++ b/app/Models/Presenters/CompanyPresenter.php @@ -94,7 +94,7 @@ class CompanyPresenter extends EntityPresenter public function email() { /** @var \App\Models\Company $this */ - if(str_contains($this->settings->email, "@")) { + if (str_contains($this->settings->email, "@")) { return $this->settings->email; } diff --git a/app/Models/PurchaseOrder.php b/app/Models/PurchaseOrder.php index 57628cf5f1..21bcf713ba 100644 --- a/app/Models/PurchaseOrder.php +++ b/app/Models/PurchaseOrder.php @@ -255,7 +255,7 @@ class PurchaseOrder extends BaseModel } public function activities(): \Illuminate\Database\Eloquent\Relations\HasMany - { + { return $this->hasMany(Activity::class)->where('company_id', $this->company_id)->where('vendor_id', $this->vendor_id)->orderBy('id', 'DESC')->take(50); } diff --git a/app/Models/RecurringInvoice.php b/app/Models/RecurringInvoice.php index ee56c3755f..80265e6ebb 100644 --- a/app/Models/RecurringInvoice.php +++ b/app/Models/RecurringInvoice.php @@ -370,11 +370,11 @@ class RecurringInvoice extends BaseModel public function calculateStatus(bool $new_model = false) //15-02-2024 - $new_model needed { - if($this->remaining_cycles == 0) { + if ($this->remaining_cycles == 0) { return self::STATUS_COMPLETED; } elseif ($new_model && $this->status_id == self::STATUS_ACTIVE && Carbon::parse($this->next_send_date)->isFuture()) { return self::STATUS_PENDING; - } elseif($this->remaining_cycles != 0 && ($this->status_id == self::STATUS_COMPLETED)) { + } elseif ($this->remaining_cycles != 0 && ($this->status_id == self::STATUS_COMPLETED)) { return self::STATUS_ACTIVE; } @@ -679,7 +679,7 @@ class RecurringInvoice extends BaseModel return Carbon::parse($date)->copy(); default: - + $date = now()->addSeconds($this->client->timezone_offset()); return $this->setDayOfMonth($date, $this->due_date_days); } diff --git a/app/Models/Subscription.php b/app/Models/Subscription.php index 2c0dac6998..a5b3461ddf 100644 --- a/app/Models/Subscription.php +++ b/app/Models/Subscription.php @@ -201,7 +201,7 @@ class Subscription extends BaseModel return null; } } - + /** * Calculates the maximum product quantity available * diff --git a/app/Models/SystemLog.php b/app/Models/SystemLog.php index 7be88683ea..beb6030f6d 100644 --- a/app/Models/SystemLog.php +++ b/app/Models/SystemLog.php @@ -155,9 +155,9 @@ class SystemLog extends Model public const TYPE_BTC_PAY = 324; public const TYPE_ROTESSA = 325; - + public const TYPE_BLOCKONOMICS = 326; - + public const TYPE_POWERBOARD = 327; public const TYPE_QUOTA_EXCEEDED = 400; diff --git a/app/Models/Task.php b/app/Models/Task.php index 2008e5b6ef..73b5028bc3 100644 --- a/app/Models/Task.php +++ b/app/Models/Task.php @@ -210,11 +210,11 @@ class Task extends BaseModel public function stringStatus(): string { - if($this->invoice_id) { + if ($this->invoice_id) { return '
'.ctrans('texts.invoiced').'
'; } - if($this->status) { + if ($this->status) { return '
' . $this->status?->name ?? ''; //@phpstan-ignore-line } @@ -280,11 +280,11 @@ class Task extends BaseModel public function getRate(): float { - if($this->project && $this->project->task_rate > 0) { + if ($this->project && $this->project->task_rate > 0) { return $this->project->task_rate; } - if($this->client) { + if ($this->client) { return $this->client->getSetting('default_task_rate'); } @@ -296,7 +296,7 @@ class Task extends BaseModel $client_currency = $this->client->getSetting('currency_id'); $company_currency = $this->company->getSetting('currency_id'); - if($client_currency != $company_currency) { + if ($client_currency != $company_currency) { $converter = new CurrencyApi(); return $converter->convert($this->taskValue(), $client_currency, $company_currency); } @@ -307,7 +307,7 @@ class Task extends BaseModel public function getQuantity(): float { - return round(($this->calcDuration() / 3600) , 2); + return round(($this->calcDuration() / 3600), 2); } public function taskValue(): float @@ -323,11 +323,11 @@ class Task extends BaseModel $parent_entity = $this->client ?? $this->company; - if($log[0]) { + if ($log[0]) { $log[0] = Carbon::createFromTimestamp((int)$log[0])->format($parent_entity->date_format().' H:i:s'); } - if($log[1] && $log[1] != 0) { + if ($log[1] && $log[1] != 0) { $log[1] = Carbon::createFromTimestamp((int)$log[1])->format($parent_entity->date_format().' H:i:s'); } else { $log[1] = ctrans('texts.running'); @@ -341,22 +341,22 @@ class Task extends BaseModel { $parent_entity = $this->client ?? $this->company; $time_format = $parent_entity->getSetting('military_time') ? "H:i:s" : "h:i:s A"; - + $task_description = collect(json_decode($this->time_log, true)) ->filter(function ($log) { $billable = $log[3] ?? false; return $billable || $this->company->settings->allow_billable_task_items; }) - ->map(function ($log) use($parent_entity, $time_format){ + ->map(function ($log) use ($parent_entity, $time_format) { $interval_description = $log[2] ?? ''; $hours = ctrans('texts.hours'); $parts = []; - + $parts[] = '
'; $date_time = []; - + if ($this->company->invoice_task_datelog) { $date_time[] = Carbon::createFromTimestamp((int)$log[0]) ->setTimeZone($this->company->timezone()->name) @@ -366,7 +366,7 @@ class Task extends BaseModel if ($this->company->invoice_task_timelog) { $date_time[] = Carbon::createFromTimestamp((int)$log[0]) ->setTimeZone($this->company->timezone()->name) - ->format($time_format) . " - " . + ->format($time_format) . " - " . Carbon::createFromTimestamp((int)$log[1]) ->setTimeZone($this->company->timezone()->name) ->format($time_format); @@ -388,17 +388,19 @@ class Task extends BaseModel }) ->implode(PHP_EOL); - $body = ''; + $body = ''; - if($this->company->invoice_task_project && $this->project) - $body = "## {$this->project->name} \n"; - - if(strlen($this->description) > 1) - $body .= $this->description. " "; - - $body .= $task_description; + if ($this->company->invoice_task_project && $this->project) { + $body = "## {$this->project->name} \n"; + } - return $body; + if (strlen($this->description) > 1) { + $body .= $this->description. " "; + } + + $body .= $task_description; + + return $body; } public function processLogsExpandedNotation() @@ -410,18 +412,18 @@ class Task extends BaseModel $parent_entity = $this->client ?? $this->company; $logged = []; - if($log[0] && $log[1] != 0) { + if ($log[0] && $log[1] != 0) { $duration = $log[1] - $log[0]; } else { $duration = 0; } - if($log[0]) { + if ($log[0]) { $logged['start_date_raw'] = $log[0]; } $logged['start_date'] = Carbon::createFromTimestamp((int)$log[0])->setTimeZone($this->company->timezone()->name)->format($parent_entity->date_format().' H:i:s'); - if($log[1] && $log[1] != 0) { + if ($log[1] && $log[1] != 0) { $logged['end_date_raw'] = $log[1]; $logged['end_date'] = Carbon::createFromTimestamp((int)$log[1])->setTimeZone($this->company->timezone()->name)->format($parent_entity->date_format().' H:i:s'); } else { @@ -441,7 +443,7 @@ class Task extends BaseModel public function assignedCompanyUser() { - if(!$this->assigned_user_id) { + if (!$this->assigned_user_id) { return false; } diff --git a/app/Models/User.php b/app/Models/User.php index b3b7153559..1bfd577756 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -671,7 +671,7 @@ class User extends Authenticatable implements MustVerifyEmail { $locale = $this->language->locale ?? null; - if($locale) { + if ($locale) { App::setLocale($locale); } diff --git a/app/Notifications/Ninja/GenericNinjaAdminNotification.php b/app/Notifications/Ninja/GenericNinjaAdminNotification.php index 67a5791995..a1002922e7 100644 --- a/app/Notifications/Ninja/GenericNinjaAdminNotification.php +++ b/app/Notifications/Ninja/GenericNinjaAdminNotification.php @@ -57,7 +57,7 @@ class GenericNinjaAdminNotification extends Notification { $content = ''; - foreach($this->message_array as $message) { + foreach ($this->message_array as $message) { $content .= $message . "\n"; } diff --git a/app/Observers/ClientObserver.php b/app/Observers/ClientObserver.php index 821f55c24b..bc3618d7f7 100644 --- a/app/Observers/ClientObserver.php +++ b/app/Observers/ClientObserver.php @@ -65,7 +65,7 @@ class ClientObserver } /** Check VAT records for client */ - if(in_array($client->country_id, $this->eu_country_codes) && $client->company->calculate_taxes) { + if (in_array($client->country_id, $this->eu_country_codes) && $client->company->calculate_taxes) { CheckVat::dispatch($client, $client->company); } @@ -88,12 +88,12 @@ class ClientObserver { /** Monitor postal code changes for US based clients for tax calculations */ - if(($client->getOriginal('shipping_postal_code') != $client->shipping_postal_code || $client->getOriginal('postal_code') != $client->postal_code) && $client->country_id == 840 && $client->company->calculate_taxes && !$client->company->account->isFreeHostedClient()) { + if (($client->getOriginal('shipping_postal_code') != $client->shipping_postal_code || $client->getOriginal('postal_code') != $client->postal_code) && $client->country_id == 840 && $client->company->calculate_taxes && !$client->company->account->isFreeHostedClient()) { UpdateTaxData::dispatch($client, $client->company); } /** Monitor vat numbers for EU based clients for tax calculations */ - if($client->getOriginal('vat_number') != $client->vat_number && in_array($client->country_id, $this->eu_country_codes) && $client->company->calculate_taxes) { + if ($client->getOriginal('vat_number') != $client->vat_number && in_array($client->country_id, $this->eu_country_codes) && $client->company->calculate_taxes) { CheckVat::dispatch($client, $client->company); } diff --git a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php index 0c259bf4d5..f9de3c1171 100644 --- a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php +++ b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php @@ -321,8 +321,8 @@ class AuthorizeCreditCard implements LivewireMethodInterface 'invoices' => $vars['invoices'], ]; } - - public function livewirePaymentView(array $data): string + + public function livewirePaymentView(array $data): string { return 'gateways.authorize.credit_card.pay_livewire'; } diff --git a/app/PaymentDrivers/Authorize/AuthorizeCustomer.php b/app/PaymentDrivers/Authorize/AuthorizeCustomer.php index 887da45dd8..57a3df17e0 100644 --- a/app/PaymentDrivers/Authorize/AuthorizeCustomer.php +++ b/app/PaymentDrivers/Authorize/AuthorizeCustomer.php @@ -161,7 +161,7 @@ class AuthorizeCustomer private function getCountryCode($country_code) { - + /** @var \Illuminate\Support\Collection<\App\Models\Country> */ $countries = app('countries'); diff --git a/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php b/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php index 61a10d2786..9077bb22fa 100644 --- a/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php +++ b/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php @@ -170,7 +170,7 @@ class AuthorizePaymentMethod $billto->setState(substr($this->authorize->client->state, 0, 40)); $billto->setZip(substr($this->authorize->client->postal_code, 0, 20)); - if(isset($contact->email) && str_contains($contact->email, '@')) { + if (isset($contact->email) && str_contains($contact->email, '@')) { $billto->setEmail($contact->email); } diff --git a/app/PaymentDrivers/Authorize/AuthorizeTransaction.php b/app/PaymentDrivers/Authorize/AuthorizeTransaction.php index fe187cab29..abd81d1f21 100644 --- a/app/PaymentDrivers/Authorize/AuthorizeTransaction.php +++ b/app/PaymentDrivers/Authorize/AuthorizeTransaction.php @@ -92,7 +92,7 @@ class AuthorizeTransaction $contact = $this->authorize->client->primary_contact()->first() ?: $this->authorize->client->contacts()->first(); - if($contact) { + if ($contact) { $billto = new \net\authorize\api\contract\v1\CustomerAddressType(); $billto->setFirstName(substr($contact->present()->first_name(), 0, 50)); $billto->setLastName(substr($contact->present()->last_name(), 0, 50)); @@ -122,7 +122,7 @@ class AuthorizeTransaction $transactionRequestType->setPayment($paymentOne); $transactionRequestType->setCurrencyCode($this->authorize->client->currency()->code); - if($billto) { + if ($billto) { $transactionRequestType->setBillTo($billto); } @@ -145,7 +145,7 @@ class AuthorizeTransaction nlog(' Description : '.$tresponse->getMessages()[0]->getDescription()); nlog(print_r($tresponse->getMessages()[0], 1)); - if($tresponse->getResponseCode() == "4") { + if ($tresponse->getResponseCode() == "4") { //notify user that this transaction is being held under FDS review: FDSReview::dispatch((string)$tresponse->getTransId(), $this->authorize->payment_hash, $this->authorize->company_gateway->company->db); } diff --git a/app/PaymentDrivers/Authorize/ChargePaymentProfile.php b/app/PaymentDrivers/Authorize/ChargePaymentProfile.php index 551d5b30f3..144350a8fa 100644 --- a/app/PaymentDrivers/Authorize/ChargePaymentProfile.php +++ b/app/PaymentDrivers/Authorize/ChargePaymentProfile.php @@ -111,7 +111,7 @@ class ChargePaymentProfile nlog(' Description : '.$tresponse->getMessages()[0]->getDescription()); nlog(print_r($tresponse->getMessages()[0], 1)); - if($tresponse->getResponseCode() == "4") { + if ($tresponse->getResponseCode() == "4") { //notify user that this transaction is being held under FDS review: FDSReview::dispatch((string)$tresponse->getTransId(), $this->authorize?->payment_hash, $this->authorize->company_gateway->company->db); } diff --git a/app/PaymentDrivers/Authorize/RefundTransaction.php b/app/PaymentDrivers/Authorize/RefundTransaction.php index fe9b8bce86..a543d867e5 100644 --- a/app/PaymentDrivers/Authorize/RefundTransaction.php +++ b/app/PaymentDrivers/Authorize/RefundTransaction.php @@ -52,7 +52,7 @@ class RefundTransaction $transaction_type = $transaction_status == 'capturedPendingSettlement' ? 'voidTransaction' : 'refundTransaction'; - if($transaction_type == 'voidTransaction') { + if ($transaction_type == 'voidTransaction') { $amount = $transaction_details->getTransaction()->getAuthAmount(); } diff --git a/app/PaymentDrivers/BTCPay/BTCPay.php b/app/PaymentDrivers/BTCPay/BTCPay.php index 99d35c729f..c260b30907 100644 --- a/app/PaymentDrivers/BTCPay/BTCPay.php +++ b/app/PaymentDrivers/BTCPay/BTCPay.php @@ -175,19 +175,19 @@ class BTCPay implements MethodInterface, LivewireMethodInterface throw new PaymentFailed('Error during BTCPay refund : ' . $e->getMessage()); } } - + /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return 'gateways.btcpay.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $data['gateway'] = $this->driver_class; $data['amount'] = $data['total']['amount_with_fee']; diff --git a/app/PaymentDrivers/BTCPayPaymentDriver.php b/app/PaymentDrivers/BTCPayPaymentDriver.php index 27f2186f54..336725b846 100644 --- a/app/PaymentDrivers/BTCPayPaymentDriver.php +++ b/app/PaymentDrivers/BTCPayPaymentDriver.php @@ -91,7 +91,7 @@ class BTCPayPaymentDriver extends BaseDriver public function processWebhookRequest() { - + $webhook_payload = file_get_contents('php://input'); @@ -100,21 +100,21 @@ class BTCPayPaymentDriver extends BaseDriver if ($btcpayRep == null) { throw new PaymentFailed('Empty data'); } - + if (empty($btcpayRep->invoiceId)) { throw new PaymentFailed( 'Invalid BTCPayServer payment notification- did not receive invoice ID.' ); } - if(!isset($btcpayRep->metadata->InvoiceNinjaPaymentHash)){ - + if (!isset($btcpayRep->metadata->InvoiceNinjaPaymentHash)) { + throw new PaymentFailed( 'Invalid BTCPayServer payment notification- did not receive Payment Hashed ID.' ); } - + if ( str_starts_with($btcpayRep->invoiceId, "__test__") || $btcpayRep->type == "InvoiceProcessing" @@ -131,7 +131,7 @@ class BTCPayPaymentDriver extends BaseDriver } } - + $webhookClient = new Webhook($this->btcpay_url, $this->api_key); if (!$webhookClient->isIncomingWebhookRequestValid($webhook_payload, $sig, $this->webhook_secret)) { @@ -140,7 +140,7 @@ class BTCPayPaymentDriver extends BaseDriver ); } - + sleep(1); $this->init(); @@ -173,14 +173,14 @@ class BTCPayPaymentDriver extends BaseDriver break; case "InvoiceInvalid": - + $payment = Payment::query()->withTrashed()->where('client_id', $_invoice->client_id)->where('id', $this->payment_hash->payment_id)->first(); if ($payment && $payment->status_id == Payment::STATUS_PENDING) { $payment->service()->deletePayment(); $this->failedPaymentNotification($payment); $StatusId = Payment::STATUS_FAILED; - + $payment->status_id = $StatusId; $payment->save(); @@ -192,7 +192,7 @@ class BTCPayPaymentDriver extends BaseDriver $payment = Payment::query()->withTrashed()->where('client_id', $_invoice->client_id)->where('id', $this->payment_hash->payment_id)->first(); $StatusId = Payment::STATUS_COMPLETED; - if(!$payment){ + if (!$payment) { $dataPayment = [ @@ -205,11 +205,10 @@ class BTCPayPaymentDriver extends BaseDriver $payment = $this->createPayment($dataPayment, $StatusId); - } - else { + } else { $payment->save(); } - + break; } @@ -217,7 +216,7 @@ class BTCPayPaymentDriver extends BaseDriver private function failedPaymentNotification(Payment $payment): void { - + $error = ctrans('texts.client_payment_failure_body', [ 'invoice' => implode(',', $payment->invoices->pluck('number')->toArray()), 'amount' => array_sum(array_column($this->payment_hash->invoices(), 'amount')) + $this->payment_hash->fee_total, ]); diff --git a/app/PaymentDrivers/BaseDriver.php b/app/PaymentDrivers/BaseDriver.php index 206551f56d..78e106593a 100644 --- a/app/PaymentDrivers/BaseDriver.php +++ b/app/PaymentDrivers/BaseDriver.php @@ -329,8 +329,9 @@ class BaseDriver extends AbstractPaymentDriver $client_contact = $this->getContact(); $client_contact_id = $client_contact ? $client_contact->id : $this->client->contacts()->first()->id; - if(isset($data['idempotency_key'])) + if (isset($data['idempotency_key'])) { $payment->idempotency_key = $data['idempotency_key']; + } $payment->amount = $data['amount']; $payment->type_id = $data['payment_type']; @@ -397,25 +398,26 @@ class BaseDriver extends AbstractPaymentDriver /*Fee charged at gateway*/ $fee_total = $this->payment_hash->fee_total; - if(!$fee_total || $fee_total == 0) + if (!$fee_total || $fee_total == 0) { return; + } $invoice = $this->payment_hash->fee_invoice; $fee_count = collect($invoice->line_items) - ->map(function ($item){ + ->map(function ($item) { $item->gross_line_total = round($item->gross_line_total, 2); return $item; }) ->whereIn('type_id', ['3','4']) ->count(); - if($invoice && $fee_count == 0){ - + if ($invoice && $fee_count == 0) { + nlog("apparently no fee, so injecting here!"); - if(!$invoice->uses_inclusive_taxes){ //must account for taxes! ? line item taxes also - $fee_total = round($fee_total/(1 + (($invoice->tax_rate1+$invoice->tax_rate2+$invoice->tax_rate3)/100)),2); + if (!$invoice->uses_inclusive_taxes) { //must account for taxes! ? line item taxes also + $fee_total = round($fee_total / (1 + (($invoice->tax_rate1 + $invoice->tax_rate2 + $invoice->tax_rate3) / 100)), 2); } $balance = $invoice->balance; @@ -432,7 +434,7 @@ class BaseDriver extends AbstractPaymentDriver $invoice_item->quantity = 1; $invoice_item->cost = (float)$fee_total; - if($invoice->discount > 0 && !$invoice->is_amount_discount){ + if ($invoice->discount > 0 && !$invoice->is_amount_discount) { $invoice_item->discount = -1 * $invoice->discount; $invoice_item->is_amount_discount = false; } @@ -458,17 +460,16 @@ class BaseDriver extends AbstractPaymentDriver $new_balance = $invoice->balance; if (floatval($new_balance) - floatval($balance) != 0) { - $adjustment = $new_balance - $balance; + $adjustment = $new_balance - $balance; $invoice->client->service()->calculateBalance(); } + } else { + + $invoice->service()->toggleFeesPaid()->save(); + } - else { - - $invoice->service()->toggleFeesPaid()->save(); - - } - + } /** @@ -480,8 +481,9 @@ class BaseDriver extends AbstractPaymentDriver */ public function unWindGatewayFees(PaymentHash $payment_hash) { - if($payment_hash->fee_invoice) + if ($payment_hash->fee_invoice) { $payment_hash->fee_invoice->service()->removeUnpaidGatewayFees(); + } } /** @@ -621,7 +623,7 @@ class BaseDriver extends AbstractPaymentDriver $error = array_key_exists('error', $response) ? $response['error'] : 'Undefined Error'; $error_code = array_key_exists('error_code', $response) ? $response['error_code'] : 'Undefined Error Code'; - if($this->payment_hash) { + if ($this->payment_hash) { $this->unWindGatewayFees($this->payment_hash); } @@ -632,7 +634,7 @@ class BaseDriver extends AbstractPaymentDriver $nmo->company = $this->client->company; $nmo->settings = $this->client->company->settings; - if($this->payment_hash) { + if ($this->payment_hash) { $invoices = Invoice::query()->whereIn('id', $this->transformKeys(array_column($this->payment_hash->invoices(), 'invoice_id')))->withTrashed()->get(); $invoices->first()->invitations->each(function ($invitation) use ($nmo) { @@ -662,14 +664,14 @@ class BaseDriver extends AbstractPaymentDriver } } - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return $this->payment_method->livewirePaymentView($data); } public function processPaymentViewData(array $data): array { - return $this->payment_method->paymentData($data); + return $this->payment_method->paymentData($data); } public function checkRequirements() @@ -829,7 +831,7 @@ class BaseDriver extends AbstractPaymentDriver $company_name = $this->client->company->present()->name(); $company_name = str_replace(["*","<",">","'",'"'], "-", $company_name); - if(ctype_digit(substr($company_name, 0, 1))) { + if (ctype_digit(substr($company_name, 0, 1))) { $company_name = "I" . $company_name; } @@ -856,7 +858,7 @@ class BaseDriver extends AbstractPaymentDriver $invoices_string = \implode(', ', collect($this->payment_hash->invoices())->pluck('invoice_number')->toArray()) ?: null; $amount = Number::formatMoney($this->payment_hash?->amount_with_fee() ?? 0, $this->client); // @phpstan-ignore-line - if($abbreviated && $invoices_string) { + if ($abbreviated && $invoices_string) { return $invoices_string; } elseif ($abbreviated || ! $invoices_string) { return ctrans('texts.gateway_payment_text_no_invoice', [ diff --git a/app/PaymentDrivers/Blockonomics/Blockonomics.php b/app/PaymentDrivers/Blockonomics/Blockonomics.php index bade8e4459..bc758d0941 100644 --- a/app/PaymentDrivers/Blockonomics/Blockonomics.php +++ b/app/PaymentDrivers/Blockonomics/Blockonomics.php @@ -51,7 +51,7 @@ class Blockonomics implements LivewireMethodInterface { $api_key = $this->blockonomics->company_gateway->getConfigField('apiKey'); - // $params = config('ninja.environment') == 'development' ? '?reset=1' : ''; + // $params = config('ninja.environment') == 'development' ? '?reset=1' : ''; $url = 'https://www.blockonomics.co/api/new_address'; $r = Http::withToken($api_key) @@ -59,8 +59,9 @@ class Blockonomics implements LivewireMethodInterface nlog($r->body()); - if($r->successful()) + if ($r->successful()) { return $r->object()->address ?? 'Something went wrong'; + } return $r->object()->message ?? 'Something went wrong'; @@ -72,12 +73,12 @@ class Blockonomics implements LivewireMethodInterface $r = Http::get('https://www.blockonomics.co/api/price', ['currency' => $this->blockonomics->client->getCurrencyCode()]); return $r->successful() ? $r->object()->price : 'Something went wrong'; - + } public function paymentData(array $data): array { - + $btc_price = $this->getBTCPrice(); $btc_address = $this->getBTCAddress(); $fiat_amount = $data['total']['amount_with_fee']; @@ -129,7 +130,7 @@ class Blockonomics implements LivewireMethodInterface $statusId = Payment::STATUS_PENDING; $payment = $this->blockonomics->createPayment($data, $statusId); - + SystemLogger::dispatch( ['response' => $payment, 'data' => $data], SystemLog::CATEGORY_GATEWAY_RESPONSE, @@ -138,7 +139,7 @@ class Blockonomics implements LivewireMethodInterface $this->blockonomics->client, $this->blockonomics->client->company, ); - + return redirect()->route('client.payments.show', ['payment' => $payment->hashed_id]); } catch (\Throwable $e) { diff --git a/app/PaymentDrivers/BlockonomicsPaymentDriver.php b/app/PaymentDrivers/BlockonomicsPaymentDriver.php index 05db691d26..cad8b74711 100644 --- a/app/PaymentDrivers/BlockonomicsPaymentDriver.php +++ b/app/PaymentDrivers/BlockonomicsPaymentDriver.php @@ -80,7 +80,7 @@ class BlockonomicsPaymentDriver extends BaseDriver public function processPaymentResponse($request) { - + $this->init(); return $this->payment_method->paymentResponse($request); @@ -88,7 +88,7 @@ class BlockonomicsPaymentDriver extends BaseDriver public function processWebhookRequest(PaymentWebhookRequest $request) { - + $company = $request->getCompany(); $url_callback_secret = $request->secret; @@ -102,12 +102,12 @@ class BlockonomicsPaymentDriver extends BaseDriver $value = $request->value; $status = $request->status; $addr = $request->addr; - + $payment = Payment::query() ->where('company_id', $company->id) ->where('transaction_reference', $txid) ->firstOrFail(); - + if (!$payment) { return response()->json([], 200); // TODO: Implement logic to create new payment in case user sends payment to the address after closing the payment page @@ -127,7 +127,7 @@ class BlockonomicsPaymentDriver extends BaseDriver break; } - if($payment->status_id == $statusId) { + if ($payment->status_id == $statusId) { return response()->json([], 200); } else { $payment->status_id = $statusId; diff --git a/app/PaymentDrivers/Braintree/ACH.php b/app/PaymentDrivers/Braintree/ACH.php index 0be982993a..d5c03e5dbf 100644 --- a/app/PaymentDrivers/Braintree/ACH.php +++ b/app/PaymentDrivers/Braintree/ACH.php @@ -46,7 +46,7 @@ class ACH implements MethodInterface, LivewireMethodInterface try { $data['gateway'] = $this->braintree; $data['client_token'] = $this->braintree->gateway->clientToken()->generate(); - } catch(\Exception $e) { + } catch (\Exception $e) { throw new PaymentFailed("Unable to generate client token, check your Braintree credentials. Error: " . $e->getMessage(), 500); @@ -56,7 +56,7 @@ class ACH implements MethodInterface, LivewireMethodInterface } public function authorizeResponse(Request $request) - { + { $request->validate([ 'nonce' => ['required'], 'gateway_type_id' => ['required'], @@ -206,7 +206,7 @@ class ACH implements MethodInterface, LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { if (array_key_exists('authorize_then_redirect', $data)) { return 'gateways.braintree.ach.authorize_livewire'; @@ -214,11 +214,11 @@ class ACH implements MethodInterface, LivewireMethodInterface return 'gateways.braintree.ach.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $data['gateway'] = $this->braintree; $data['currency'] = $this->braintree->client->getCurrencyCode(); diff --git a/app/PaymentDrivers/Braintree/CreditCard.php b/app/PaymentDrivers/Braintree/CreditCard.php index c6ac4deaaf..e243356371 100644 --- a/app/PaymentDrivers/Braintree/CreditCard.php +++ b/app/PaymentDrivers/Braintree/CreditCard.php @@ -77,7 +77,7 @@ class CreditCard implements LivewireMethodInterface public function paymentView(array $data) { - $data = $this->paymentData($data); + $data = $this->paymentData($data); return render('gateways.braintree.credit_card.pay', $data); } @@ -274,15 +274,15 @@ class CreditCard implements LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return 'gateways.braintree.credit_card.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $data['gateway'] = $this->braintree; $data['client_token'] = $this->braintree->gateway->clientToken()->generate(); diff --git a/app/PaymentDrivers/Braintree/PayPal.php b/app/PaymentDrivers/Braintree/PayPal.php index 87bf40339c..724e8578bc 100644 --- a/app/PaymentDrivers/Braintree/PayPal.php +++ b/app/PaymentDrivers/Braintree/PayPal.php @@ -193,15 +193,15 @@ class PayPal implements LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return 'gateways.braintree.paypal.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $data['gateway'] = $this->braintree; $data['client_token'] = $this->braintree->gateway->clientToken()->generate(); diff --git a/app/PaymentDrivers/BraintreePaymentDriver.php b/app/PaymentDrivers/BraintreePaymentDriver.php index 3e13d9c87f..b3545df872 100644 --- a/app/PaymentDrivers/BraintreePaymentDriver.php +++ b/app/PaymentDrivers/BraintreePaymentDriver.php @@ -248,7 +248,7 @@ class BraintreePaymentDriver extends BaseDriver 'transaction_reference' => $result->transaction->id, 'gateway_type_id' => GatewayType::CREDIT_CARD, ]; - + $this->confirmGatewayFee($data); $payment = $this->createPayment($data, Payment::STATUS_COMPLETED); @@ -339,7 +339,7 @@ class BraintreePaymentDriver extends BaseDriver $ct = $this->init()->gateway->clientToken()->generate(); return true; - } catch(\Exception $e) { + } catch (\Exception $e) { } @@ -351,7 +351,7 @@ class BraintreePaymentDriver extends BaseDriver try { return $this->init()->gateway->customer()->find($customer_id); - } catch(\Exception $e) { + } catch (\Exception $e) { return false; } @@ -386,9 +386,9 @@ class BraintreePaymentDriver extends BaseDriver $this->client = $client; - foreach($cards as $card) { + foreach ($cards as $card) { - if($this->getToken($card->token, $card->customerId) || Carbon::createFromDate($card->expirationYear, $card->expirationMonth, '1')->lt(now())) { //@phpstan-ignore-line + if ($this->getToken($card->token, $card->customerId) || Carbon::createFromDate($card->expirationYear, $card->expirationMonth, '1')->lt(now())) { //@phpstan-ignore-line continue; } @@ -422,7 +422,7 @@ class BraintreePaymentDriver extends BaseDriver $b_shipping_address = count($customer->addresses) > 1 ? $customer->addresses[1] : false; $import_client_data = []; - if($b_business_address) { + if ($b_business_address) { $braintree_address = [ @@ -437,7 +437,7 @@ class BraintreePaymentDriver extends BaseDriver $import_client_data = array_merge($import_client_data, $braintree_address); } - if($b_shipping_address) { + if ($b_shipping_address) { $braintree_shipping_address = [ @@ -500,19 +500,19 @@ class BraintreePaymentDriver extends BaseDriver { $customers = $this->init()->gateway->customer()->all(); - foreach($customers as $c) { + foreach ($customers as $c) { $customer = $this->find($c->id); // nlog(count($customer->creditCards). " Exists for {$c->id}"); - if(!$customer) { + if (!$customer) { continue; } $client = $this->findClient($customer->email); - if(!$this->findTokens($c->id) && !$client) { + if (!$this->findTokens($c->id) && !$client) { //customer is not referenced in the system - create client $client = $this->createNinjaClient($customer); // nlog("Creating new Client"); diff --git a/app/PaymentDrivers/CBAPowerBoard/CreditCard.php b/app/PaymentDrivers/CBAPowerBoard/CreditCard.php index 0f14a71064..dd2d5671e3 100644 --- a/app/PaymentDrivers/CBAPowerBoard/CreditCard.php +++ b/app/PaymentDrivers/CBAPowerBoard/CreditCard.php @@ -46,8 +46,7 @@ class CreditCard implements LivewireMethodInterface public function authorizeResponse($request) { - if($request->browser_details) - { + if ($request->browser_details) { $payment_source = $this->storePaymentSource($request); $browser_details = json_decode($request->browser_details, true); @@ -73,7 +72,7 @@ class CreditCard implements LivewireMethodInterface $r = $this->powerboard->gatewayRequest('/v1/charges/3ds', (\App\Enum\HttpVerb::POST)->value, $payload, []); if ($r->failed()) { - + $error_payload = $this->getErrorFromResponse($r); return response()->json(['message' => $error_payload[0]], 400); @@ -85,8 +84,7 @@ class CreditCard implements LivewireMethodInterface return response()->json($charge['resource']['data'], 200); - } - elseif($request->charge) { + } elseif ($request->charge) { $charge_request = json_decode($request->charge, true); nlog("we have the charge request"); @@ -98,17 +96,17 @@ class CreditCard implements LivewireMethodInterface ], "capture" => false, "authorization" => true, - "amount"=> 1, - "currency"=> $this->powerboard->client->currency()->code, - "store_cvv"=> true, + "amount" => 1, + "currency" => $this->powerboard->client->currency()->code, + "store_cvv" => true, ]; nlog($payload); $r = $this->powerboard->gatewayRequest("/v1/charges", (\App\Enum\HttpVerb::POST)->value, $payload, []); - if($r->failed()){ - + if ($r->failed()) { + $error_payload = $this->getErrorFromResponse($r); throw new PaymentFailed($error_payload[0], $error_payload[1]); @@ -121,7 +119,7 @@ class CreditCard implements LivewireMethodInterface if ($charge->status == 'complete') { $this->powerboard->logSuccessfulGatewayResponse(['response' => $charge, 'data' => $this->powerboard->payment_hash->data], SystemLog::TYPE_POWERBOARD); - + $vt = $charge->customer->payment_source->vault_token; $data = [ @@ -129,7 +127,7 @@ class CreditCard implements LivewireMethodInterface "vault_token" => $vt, ], ]; - + $customer = $this->powerboard->customer()->findOrCreateCustomer($data); $cgt = $this->powerboard->customer()->storePaymentMethod($charge->customer->payment_source, $charge->customer); @@ -137,10 +135,9 @@ class CreditCard implements LivewireMethodInterface } - } - elseif($request->charge_no3d){ + } elseif ($request->charge_no3d) { nlog($request->all()); - + $payment_source = $this->storePaymentSource($request); nlog($payment_source); @@ -191,7 +188,7 @@ class CreditCard implements LivewireMethodInterface $this->powerboard->init(); $payment_source = $request->gateway_response; - + $payload = array_merge($this->getCustomer(), [ 'token' => $payment_source, "vault_type" => "permanent", @@ -202,12 +199,13 @@ class CreditCard implements LivewireMethodInterface $r = $this->powerboard->gatewayRequest('/v1/vault/payment_sources', (\App\Enum\HttpVerb::POST)->value, $payload, []); - if($r->failed()) + if ($r->failed()) { return $this->powerboard->processInternallyFailedPayment($this->powerboard, $r->throw()); + } nlog($r->object()); - $source = (new \App\PaymentDrivers\CBAPowerBoard\Models\Parse())->encode(PaymentSource ::class, $r->object()->resource->data); + $source = (new \App\PaymentDrivers\CBAPowerBoard\Models\Parse())->encode(PaymentSource::class, $r->object()->resource->data); return $source; @@ -218,7 +216,7 @@ class CreditCard implements LivewireMethodInterface { $this->powerboard->init(); - $available_cards = [ + $available_cards = [ "amex", "ausbc", "discover", @@ -229,13 +227,13 @@ class CreditCard implements LivewireMethodInterface "visa", "visa_white", ]; - + $supported_cards = $this->powerboard->company_gateway->getConfig(); $supported_cards_array = []; - foreach($available_cards as $card){ - if($supported_cards->{$card}){ + foreach ($available_cards as $card) { + if ($supported_cards->{$card}) { $supported_cards_array[] = $card; } } @@ -282,7 +280,7 @@ class CreditCard implements LivewireMethodInterface nlog($r->body()); - if($r->failed()){ + if ($r->failed()) { $error_payload = $this->getErrorFromResponse($r); throw new PaymentFailed($error_payload[0], $error_payload[1]); } @@ -301,7 +299,7 @@ class CreditCard implements LivewireMethodInterface $payment_hash = PaymentHash::query()->where('hash', $request->payment_hash)->first(); - $browser_details = json_decode($request->browser_details,true); + $browser_details = json_decode($request->browser_details, true); $payload = [ "amount" => $payment_hash->data->amount_with_fee, @@ -336,15 +334,14 @@ class CreditCard implements LivewireMethodInterface public function paymentResponse(PaymentResponseRequest $request) { nlog($request->all()); - + $this->powerboard->payment_hash->data = array_merge((array) $this->powerboard->payment_hash->data, ['response' => $request->all()]); $this->powerboard->payment_hash->save(); $payload = []; /** Token Payment */ - if($request->input('token', false)) - { + if ($request->input('token', false)) { $cgt = $this->powerboard ->client ->gateway_tokens() @@ -353,36 +350,34 @@ class CreditCard implements LivewireMethodInterface ->first(); return $this->tokenBilling($cgt, true); - - } - elseif($request->browser_details) - { - $payment_source = $this->storePaymentSource($request); + + } elseif ($request->browser_details) { + $payment_source = $this->storePaymentSource($request); nlog($payment_source); return $this->get3dsToken($payment_source, $request); - - } - elseif($request->charge) { + + } elseif ($request->charge) { $charge_request = json_decode($request->charge, true); - + nlog($charge_request); $payload = [ '_3ds' => [ 'id' => array_key_exists('charge_3ds_id', $charge_request) ? $charge_request['charge_3ds_id'] : $charge_request['_3ds']['id'], ], - "amount"=> $this->powerboard->payment_hash->data->amount_with_fee, //@phpstan-ignore-line - "currency"=> $this->powerboard->client->currency()->code, - "store_cvv"=> true, + "amount" => $this->powerboard->payment_hash->data->amount_with_fee, //@phpstan-ignore-line + "currency" => $this->powerboard->client->currency()->code, + "store_cvv" => true, ]; $r = $this->powerboard->gatewayRequest("/v1/charges", (\App\Enum\HttpVerb::POST)->value, $payload, []); - if($r->failed()) + if ($r->failed()) { return $this->processUnsuccessfulPayment($r); + } $charge = (new \App\PaymentDrivers\CBAPowerBoard\Models\Parse())->encode(Charge::class, $r->object()->resource->data) ?? $r->throw(); @@ -390,24 +385,23 @@ class CreditCard implements LivewireMethodInterface if ($charge->status == 'complete') { $this->powerboard->logSuccessfulGatewayResponse(['response' => $charge, 'data' => $this->powerboard->payment_hash->data], SystemLog::TYPE_POWERBOARD); - + $vt = $charge->customer->payment_source->vault_token; - if($request->store_card){ + if ($request->store_card) { $data = [ "payment_source" => [ "vault_token" => $vt, ], ]; - + $customer = $this->powerboard->customer()->findOrCreateCustomer($data); $cgt = $this->powerboard->customer()->storePaymentMethod($charge->customer->payment_source, $charge->customer); } return $this->processSuccessfulPayment($charge); - } - elseif($charge->error){ - + } elseif ($charge->error) { + $this->powerboard->logUnsuccessfulGatewayResponse($charge, SystemLog::TYPE_POWERBOARD); throw new PaymentFailed($charge->error->message, $charge->status); @@ -454,7 +448,7 @@ class CreditCard implements LivewireMethodInterface private function getErrorFromResponse($response) { - + try { $response->throw(); } catch (RequestException $exception) { @@ -473,7 +467,7 @@ class CreditCard implements LivewireMethodInterface }; return [$error_message, $exception->getCode()]; - + } } diff --git a/app/PaymentDrivers/CBAPowerBoard/Customer.php b/app/PaymentDrivers/CBAPowerBoard/Customer.php index 9ac9e75da6..fd67c0f691 100644 --- a/app/PaymentDrivers/CBAPowerBoard/Customer.php +++ b/app/PaymentDrivers/CBAPowerBoard/Customer.php @@ -24,7 +24,7 @@ class Customer { } - public function findOrCreateCustomer(array $customer_data): mixed + public function findOrCreateCustomer(array $customer_data): mixed { $token = $this->powerboard ->client @@ -33,12 +33,13 @@ class Customer ->where('company_gateway_id', $this->powerboard->company_gateway->id) ->first(); - if($token && $customer = $this->getCustomer($token->gateway_customer_reference)){ + if ($token && $customer = $this->getCustomer($token->gateway_customer_reference)) { return (new \App\PaymentDrivers\CBAPowerBoard\Models\Parse())->encode(ModelsCustomer::class, $customer->resource->data); } - if($customer = $this->findCustomer()) + if ($customer = $this->findCustomer()) { return (new \App\PaymentDrivers\CBAPowerBoard\Models\Parse())->encode(ModelsCustomer::class, $customer); + } return $this->createCustomer($customer_data); @@ -53,8 +54,9 @@ class Customer nlog($r->json()); - if($r->successful()) + if ($r->successful()) { return $r->object(); + } return false; } @@ -81,7 +83,7 @@ class Customer public function createCustomer(array $data = []): object { - + $payload = [ 'company_name' => $this->powerboard->client->present()->name(), 'first_name' => $this->powerboard->client->present()->first_name(), @@ -91,9 +93,9 @@ class Customer // 'phone' => $this->powerboard->client->present()->phone(), ]; - + $payload = array_merge($payload, $data); - + $payload = Sanitizer::removeBlanks($payload); nlog($payload); @@ -102,8 +104,9 @@ class Customer $r = $this->powerboard->gatewayRequest($uri, (\App\Enum\HttpVerb::POST)->value, $payload, []); - if($r->failed()) + if ($r->failed()) { $r->throw(); + } return (new \App\PaymentDrivers\CBAPowerBoard\Models\Parse())->encode(ModelsCustomer::class, $r->object()->resource->data) ?? $r->throw(); @@ -132,7 +135,7 @@ class Customer $cgt = $this->powerboard->storeGatewayToken($data, ['gateway_customer_reference' => $source->gateway_id]); return $cgt; - + } @@ -141,7 +144,7 @@ class Customer nlog("add token to customer"); $uri = "/v1/customers/{$customer->_id}"; - + $payload = [ 'payment_source' => [ 'vault_token' => $token, @@ -150,16 +153,16 @@ class Customer $r = $this->powerboard->gatewayRequest($uri, (\App\Enum\HttpVerb::POST)->value, $payload, []); - if($r->failed()){ + if ($r->failed()) { nlog($r->body()); - return $r->throw(); + return $r->throw(); } nlog($r->object()); $customer = (new \App\PaymentDrivers\CBAPowerBoard\Models\Parse())->encode(ModelsCustomer::class, $r->object()->resource->data); - - $source = collect($customer->payment_sources)->first(function (PaymentSource $source) use ($token){ + + $source = collect($customer->payment_sources)->first(function (PaymentSource $source) use ($token) { return $token == $source->vault_token; }); @@ -183,4 +186,3 @@ class Customer } } - diff --git a/app/PaymentDrivers/CBAPowerBoard/Models/Charge.php b/app/PaymentDrivers/CBAPowerBoard/Models/Charge.php index a165876c06..291a918c8e 100644 --- a/app/PaymentDrivers/CBAPowerBoard/Models/Charge.php +++ b/app/PaymentDrivers/CBAPowerBoard/Models/Charge.php @@ -42,7 +42,7 @@ class Charge /** @var ?bool */ public ?bool $capture; /** @var ?string */ - public? string $status; + public ?string $status; /** @var ?array */ public ?array $items; diff --git a/app/PaymentDrivers/CBAPowerBoard/Models/Customer.php b/app/PaymentDrivers/CBAPowerBoard/Models/Customer.php index a207b79ec7..d1aa8b6014 100644 --- a/app/PaymentDrivers/CBAPowerBoard/Models/Customer.php +++ b/app/PaymentDrivers/CBAPowerBoard/Models/Customer.php @@ -11,75 +11,74 @@ namespace App\PaymentDrivers\CBAPowerBoard\Models; - class Customer { - /** @var ?string */ - public ?string $_id; - /** @var ?string */ - public ?string $_source_ip_address; - /** @var ?string */ - public ?string $first_name; - /** @var ?string */ - public ?string $last_name; - /** @var ?string */ - public ?string $email; - /** @var ?string */ - public ?string $reference; - /** @var ?string */ - public ?string $default_source; - /** @var ?string */ - public ?string $status; - /** @var ?bool */ - public ?bool $archived; - /** @var ?string */ - public ?string $created_at; - /** @var ?string */ - public ?string $updated_at; - /** @var ?bool */ - public ?bool $_check_expire_date; - /** @var ?PaymentSource[] */ - public ?array $payment_sources; - /** @var ?PaymentSource */ - public ?PaymentSource $payment_source; - /** @var ?array */ - public ?array $payment_destinations; - /** @var ?string */ - public ?string $company_id; + /** @var ?string */ + public ?string $_id; + /** @var ?string */ + public ?string $_source_ip_address; + /** @var ?string */ + public ?string $first_name; + /** @var ?string */ + public ?string $last_name; + /** @var ?string */ + public ?string $email; + /** @var ?string */ + public ?string $reference; + /** @var ?string */ + public ?string $default_source; + /** @var ?string */ + public ?string $status; + /** @var ?bool */ + public ?bool $archived; + /** @var ?string */ + public ?string $created_at; + /** @var ?string */ + public ?string $updated_at; + /** @var ?bool */ + public ?bool $_check_expire_date; + /** @var ?PaymentSource[] */ + public ?array $payment_sources; + /** @var ?PaymentSource */ + public ?PaymentSource $payment_source; + /** @var ?array */ + public ?array $payment_destinations; + /** @var ?string */ + public ?string $company_id; - public function __construct( - ?string $_id, - ?string $_source_ip_address, - ?string $first_name, - ?string $last_name, - ?string $email, - ?string $reference, - ?string $default_source, - ?string $status, - ?bool $archived, - ?string $created_at, - ?string $updated_at, - ?bool $_check_expire_date, - ?array $payment_sources, - ?array $payment_destinations, - ?string $company_id, - ?PaymentSource $payment_source - ) { - $this->_id = $_id; - $this->_source_ip_address = $_source_ip_address; - $this->first_name = $first_name; - $this->last_name = $last_name; - $this->email = $email; - $this->reference = $reference; - $this->default_source = $default_source; - $this->status = $status; - $this->archived = $archived; - $this->created_at = $created_at; - $this->updated_at = $updated_at; - $this->_check_expire_date = $_check_expire_date; - $this->payment_sources = $payment_sources; - $this->payment_destinations = $payment_destinations; - $this->company_id = $company_id; - $this->payment_source = $payment_source; - } -} \ No newline at end of file + public function __construct( + ?string $_id, + ?string $_source_ip_address, + ?string $first_name, + ?string $last_name, + ?string $email, + ?string $reference, + ?string $default_source, + ?string $status, + ?bool $archived, + ?string $created_at, + ?string $updated_at, + ?bool $_check_expire_date, + ?array $payment_sources, + ?array $payment_destinations, + ?string $company_id, + ?PaymentSource $payment_source + ) { + $this->_id = $_id; + $this->_source_ip_address = $_source_ip_address; + $this->first_name = $first_name; + $this->last_name = $last_name; + $this->email = $email; + $this->reference = $reference; + $this->default_source = $default_source; + $this->status = $status; + $this->archived = $archived; + $this->created_at = $created_at; + $this->updated_at = $updated_at; + $this->_check_expire_date = $_check_expire_date; + $this->payment_sources = $payment_sources; + $this->payment_destinations = $payment_destinations; + $this->company_id = $company_id; + $this->payment_source = $payment_source; + } +} diff --git a/app/PaymentDrivers/CBAPowerBoard/Models/Gateway.php b/app/PaymentDrivers/CBAPowerBoard/Models/Gateway.php index 2bf85301ed..e699fa268e 100644 --- a/app/PaymentDrivers/CBAPowerBoard/Models/Gateway.php +++ b/app/PaymentDrivers/CBAPowerBoard/Models/Gateway.php @@ -13,7 +13,6 @@ namespace App\PaymentDrivers\CBAPowerBoard\Models; class Gateway { - public function __construct( public string $_id, public string $name, diff --git a/app/PaymentDrivers/CBAPowerBoard/Models/Parse.php b/app/PaymentDrivers/CBAPowerBoard/Models/Parse.php index 55d213a33e..647a2a2a25 100644 --- a/app/PaymentDrivers/CBAPowerBoard/Models/Parse.php +++ b/app/PaymentDrivers/CBAPowerBoard/Models/Parse.php @@ -28,10 +28,10 @@ class Parse public function __construct() { } - + public function encode($object_type, $document) { - + $phpDocExtractor = new PhpDocExtractor(); $reflectionExtractor = new ReflectionExtractor(); @@ -67,4 +67,4 @@ class Parse return $data; } -} \ No newline at end of file +} diff --git a/app/PaymentDrivers/CBAPowerBoard/Models/Transaction.php b/app/PaymentDrivers/CBAPowerBoard/Models/Transaction.php index 7ed6fef8bc..8062b82ff2 100644 --- a/app/PaymentDrivers/CBAPowerBoard/Models/Transaction.php +++ b/app/PaymentDrivers/CBAPowerBoard/Models/Transaction.php @@ -13,67 +13,69 @@ namespace App\PaymentDrivers\CBAPowerBoard\Models; class Threeds { - public function __construct(public ?string $token){} + public function __construct(public ?string $token) + { + } } class Transaction { - public ?Threeds $_3ds; - public ?string $gateway_specific_code; - public ?string $gateway_specific_description; - public ?string $error_message; - public ?string $error_code; - public ?string $status_code; - public ?string $status_code_description; - public ?string $type; - public ?string $status; - public float $amount; - public ?string $currency; - public ?string $_id; - public ?string $created_at; - public ?string $updated_at; - public ?string $processed_at; - public ?string $external_id; - public ?string $external_reference; - public ?string $authorization_code; + public ?Threeds $_3ds; + public ?string $gateway_specific_code; + public ?string $gateway_specific_description; + public ?string $error_message; + public ?string $error_code; + public ?string $status_code; + public ?string $status_code_description; + public ?string $type; + public ?string $status; + public float $amount; + public ?string $currency; + public ?string $_id; + public ?string $created_at; + public ?string $updated_at; + public ?string $processed_at; + public ?string $external_id; + public ?string $external_reference; + public ?string $authorization_code; - public function __construct( - ?Threeds $_3ds, - ?string $gateway_specific_code, - ?string $gateway_specific_description, - ?string $error_message, - ?string $error_code, - ?string $status_code, - ?string $status_code_description, - ?string $type, - ?string $status, - float $amount, - ?string $currency, - ?string $_id, - ?string $created_at, - ?string $updated_at, - ?string $processed_at, - ?string $external_id, - ?string $external_reference, - ?string $authorization_code - ) { - $this->_3ds = $_3ds; - $this->gateway_specific_code = $gateway_specific_code; - $this->gateway_specific_description = $gateway_specific_description; - $this->error_message = $error_message; - $this->error_code = $error_code; - $this->status_code = $status_code; - $this->status_code_description = $status_code_description; - $this->type = $type; - $this->status = $status; - $this->amount = $amount; - $this->currency = $currency; - $this->_id = $_id; - $this->created_at = $created_at; - $this->updated_at = $updated_at; - $this->processed_at = $processed_at; - $this->external_id = $external_id; - $this->external_reference = $external_reference; - $this->authorization_code = $authorization_code; - } + public function __construct( + ?Threeds $_3ds, + ?string $gateway_specific_code, + ?string $gateway_specific_description, + ?string $error_message, + ?string $error_code, + ?string $status_code, + ?string $status_code_description, + ?string $type, + ?string $status, + float $amount, + ?string $currency, + ?string $_id, + ?string $created_at, + ?string $updated_at, + ?string $processed_at, + ?string $external_id, + ?string $external_reference, + ?string $authorization_code + ) { + $this->_3ds = $_3ds; + $this->gateway_specific_code = $gateway_specific_code; + $this->gateway_specific_description = $gateway_specific_description; + $this->error_message = $error_message; + $this->error_code = $error_code; + $this->status_code = $status_code; + $this->status_code_description = $status_code_description; + $this->type = $type; + $this->status = $status; + $this->amount = $amount; + $this->currency = $currency; + $this->_id = $_id; + $this->created_at = $created_at; + $this->updated_at = $updated_at; + $this->processed_at = $processed_at; + $this->external_id = $external_id; + $this->external_reference = $external_reference; + $this->authorization_code = $authorization_code; + } } diff --git a/app/PaymentDrivers/CBAPowerBoard/Settings.php b/app/PaymentDrivers/CBAPowerBoard/Settings.php index 896e538871..b16561ce0b 100644 --- a/app/PaymentDrivers/CBAPowerBoard/Settings.php +++ b/app/PaymentDrivers/CBAPowerBoard/Settings.php @@ -12,9 +12,7 @@ namespace App\PaymentDrivers\CBAPowerBoard; - use App\Models\GatewayType; - use App\PaymentDrivers\CBAPowerBoardPaymentDriver; use App\PaymentDrivers\CBAPowerBoard\Models\Gateway; use App\PaymentDrivers\CBAPowerBoard\Models\Gateways; @@ -25,11 +23,11 @@ class Settings protected const GATEWAY_AFTERPAY = 'Afterpay'; protected const GATEWAY_PAYPAL = 'Paypal'; protected const GATEWAY_ZIP = 'Zipmoney'; - + public function __construct(public CBAPowerBoardPaymentDriver $powerboard) { } - + /** * Returns the API response for the gateways * @@ -39,20 +37,21 @@ class Settings { $r = $this->powerboard->gatewayRequest('/v1/gateways', (\App\Enum\HttpVerb::GET)->value, [], []); - if($r->failed()) + if ($r->failed()) { $r->throw(); - + } + return (new \App\PaymentDrivers\CBAPowerBoard\Models\Parse())->encode(Gateway::class."[]", $r->object()->resource->data); } - /** We will need to have a process that updates this at intervals */ + /** We will need to have a process that updates this at intervals */ /** * updateSettings from the API * * @return self */ - public function updateSettings():self + public function updateSettings(): self { $gateways = $this->getGateways(); @@ -62,7 +61,7 @@ class Settings return $this; } - + /** * getSettings * @@ -72,7 +71,7 @@ class Settings { return $this->powerboard->company_gateway->getSettings(); } - + /** * Entry point for getting the payment gateway configuration * @@ -83,14 +82,14 @@ class Settings { $type = self::GATEWAY_CBA; - match($gateway_type_id){ + match($gateway_type_id) { \App\Models\GatewayType::CREDIT_CARD => $type = self::GATEWAY_CBA, default => $type = self::GATEWAY_CBA, }; return $this->getGatewayByType($type); } - + /** * Returns the CBA gateway object for a given gateway type * @@ -101,26 +100,26 @@ class Settings { $settings = $this->getSettings(); - if(!property_exists($settings, 'gateways')){ + if (!property_exists($settings, 'gateways')) { $this->updateSettings(); $settings = $this->getSettings(); } - + $gateways = (new \App\PaymentDrivers\CBAPowerBoard\Models\Parse())->encode(Gateway::class."[]", $settings->gateways); if ($gateway_type_const == self::GATEWAY_CBA && strlen($this->powerboard->company_gateway->getConfigField('gatewayId') ?? '') > 1) { - - return collect($gateways)->first(function (Gateway $gateway) { - return $gateway->_id == $this->powerboard->company_gateway->getConfigField('gatewayId'); - }); + + return collect($gateways)->first(function (Gateway $gateway) { + return $gateway->_id == $this->powerboard->company_gateway->getConfigField('gatewayId'); + }); } - return collect($gateways)->first(function (Gateway $gateway) use ($gateway_type_const){ + return collect($gateways)->first(function (Gateway $gateway) use ($gateway_type_const) { return $gateway->type == $gateway_type_const; }); } - + /** * Returns the CBA gateway ID for a given gateway type * diff --git a/app/PaymentDrivers/CBAPowerBoardPaymentDriver.php b/app/PaymentDrivers/CBAPowerBoardPaymentDriver.php index 578efe80d8..aeaa21cc7f 100644 --- a/app/PaymentDrivers/CBAPowerBoardPaymentDriver.php +++ b/app/PaymentDrivers/CBAPowerBoardPaymentDriver.php @@ -72,10 +72,10 @@ class CBAPowerBoardPaymentDriver extends BaseDriver public function init(): self { - if($this->company_gateway->getConfigField('testMode')) { + if ($this->company_gateway->getConfigField('testMode')) { $this->widget_endpoint = 'https://widget.preproduction.powerboard.commbank.com.au/sdk/latest/widget.umd.min.js'; - $this->api_endpoint = 'https://api.preproduction.powerboard.commbank.com.au'; - $this->environment = 'preproduction_cba'; + $this->api_endpoint = 'https://api.preproduction.powerboard.commbank.com.au'; + $this->environment = 'preproduction_cba'; } return $this; @@ -134,7 +134,7 @@ class CBAPowerBoardPaymentDriver extends BaseDriver * @return mixed */ public function processPaymentResponse($request) - { + { return $this->payment_method->paymentResponse($request); } @@ -175,7 +175,7 @@ class CBAPowerBoardPaymentDriver extends BaseDriver public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash) { - + $this->init(); $this->setPaymentMethod($cgt->gateway_type_id); @@ -195,7 +195,7 @@ class CBAPowerBoardPaymentDriver extends BaseDriver $this->init(); $this->settings()->updateSettings(); - + return true; @@ -204,7 +204,7 @@ class CBAPowerBoardPaymentDriver extends BaseDriver public function gatewayRequest(string $uri, string $verb, array $payload, array $headers = []) { $this->init(); - + $r = Http::withHeaders($this->getHeaders($headers)) ->{$verb}($this->api_endpoint.$uri, $payload); @@ -215,11 +215,13 @@ class CBAPowerBoardPaymentDriver extends BaseDriver public function getHeaders(array $headers = []): array { - return array_merge([ + return array_merge( + [ 'x-user-secret-key' => $this->company_gateway->getConfigField('secretKey'), 'Content-Type' => 'application/json', ], - $headers); + $headers + ); } public function customer(): Customer @@ -231,4 +233,4 @@ class CBAPowerBoardPaymentDriver extends BaseDriver { return new Settings($this); } -} \ No newline at end of file +} diff --git a/app/PaymentDrivers/CheckoutCom/CheckoutSetupWebhook.php b/app/PaymentDrivers/CheckoutCom/CheckoutSetupWebhook.php index fbd84eac8d..db8b8e3075 100644 --- a/app/PaymentDrivers/CheckoutCom/CheckoutSetupWebhook.php +++ b/app/PaymentDrivers/CheckoutCom/CheckoutSetupWebhook.php @@ -65,7 +65,7 @@ class CheckoutSetupWebhook implements ShouldQueue return $workflow['name'] == $this->authentication_webhook_name; }); - if($wf) { + if ($wf) { return; } diff --git a/app/PaymentDrivers/CheckoutCom/CheckoutWebhook.php b/app/PaymentDrivers/CheckoutCom/CheckoutWebhook.php index 0873dbcdf9..5922fa3226 100644 --- a/app/PaymentDrivers/CheckoutCom/CheckoutWebhook.php +++ b/app/PaymentDrivers/CheckoutCom/CheckoutWebhook.php @@ -52,7 +52,7 @@ class CheckoutWebhook implements ShouldQueue $this->company_gateway = CompanyGateway::withTrashed()->find($this->company_gateway_id); - if(!isset($this->webhook_array['type'])) { + if (!isset($this->webhook_array['type'])) { nlog("Checkout Webhook type not set"); } @@ -77,17 +77,17 @@ class CheckoutWebhook implements ShouldQueue $payment = Payment::query()->withTrashed()->where('transaction_reference', $payment_object['id'])->first(); - if($payment && $payment->status_id == Payment::STATUS_COMPLETED) { + if ($payment && $payment->status_id == Payment::STATUS_COMPLETED) { return; } - if($payment) { + if ($payment) { $payment->status_id = Payment::STATUS_COMPLETED; $payment->save(); return; } - if(isset($this->webhook_array['metadata'])) { + if (isset($this->webhook_array['metadata'])) { $metadata = $this->webhook_array['metadata']; diff --git a/app/PaymentDrivers/CheckoutCom/CreditCard.php b/app/PaymentDrivers/CheckoutCom/CreditCard.php index b41bb57891..a504bb7401 100644 --- a/app/PaymentDrivers/CheckoutCom/CreditCard.php +++ b/app/PaymentDrivers/CheckoutCom/CreditCard.php @@ -153,7 +153,7 @@ class CreditCard implements MethodInterface, LivewireMethodInterface return $data; } - + public function paymentView($data, $livewire = false) { $data = $this->paymentData($data); @@ -167,7 +167,7 @@ class CreditCard implements MethodInterface, LivewireMethodInterface public function livewirePaymentView(array $data): string { - return 'gateways.checkout.credit_card.pay_livewire'; + return 'gateways.checkout.credit_card.pay_livewire'; } public function paymentResponse(PaymentResponseRequest $request) @@ -249,7 +249,7 @@ class CreditCard implements MethodInterface, LivewireMethodInterface try { $response = $this->checkout->gateway->getPaymentsClient()->requestPayment($paymentRequest); - if($this->checkout->company_gateway->update_details && isset($response['customer'])) { + if ($this->checkout->company_gateway->update_details && isset($response['customer'])) { $this->checkout->updateCustomer($response['customer']['id'] ?? ''); } diff --git a/app/PaymentDrivers/CheckoutCom/Utilities.php b/app/PaymentDrivers/CheckoutCom/Utilities.php index 059fb1049c..9f86603918 100644 --- a/app/PaymentDrivers/CheckoutCom/Utilities.php +++ b/app/PaymentDrivers/CheckoutCom/Utilities.php @@ -93,7 +93,7 @@ trait Utilities $error_message = 'Error processing payment.'; } - if(isset($_payment['actions'][0]['response_summary']) ?? false) { + if (isset($_payment['actions'][0]['response_summary']) ?? false) { $error_message = $_payment['actions'][0]['response_summary']; } diff --git a/app/PaymentDrivers/CheckoutComPaymentDriver.php b/app/PaymentDrivers/CheckoutComPaymentDriver.php index 1611b898cf..f245bb7ee0 100644 --- a/app/PaymentDrivers/CheckoutComPaymentDriver.php +++ b/app/PaymentDrivers/CheckoutComPaymentDriver.php @@ -215,7 +215,7 @@ class CheckoutComPaymentDriver extends BaseDriver { $this->init(); - if($this->company_gateway->update_details) { + if ($this->company_gateway->update_details) { $this->updateCustomer(); } @@ -334,7 +334,7 @@ class CheckoutComPaymentDriver extends BaseDriver public function updateCustomer($customer_id = null) { - if(!$customer_id) { + if (!$customer_id) { return; } @@ -406,7 +406,7 @@ class CheckoutComPaymentDriver extends BaseDriver $response = $this->gateway->getPaymentsClient()->requestPayment($paymentRequest); if ($response['status'] == 'Authorized') { - + $data = [ 'payment_method' => $response['source']['id'], 'payment_type' => PaymentType::parseCardType(strtolower($response['source']['scheme'])), @@ -491,7 +491,7 @@ class CheckoutComPaymentDriver extends BaseDriver header('Content-Type: text/plain'); $webhook_payload = file_get_contents('php://input'); - if($request->header('cko-signature') == hash_hmac('sha256', $webhook_payload, $this->company_gateway->company->company_key)) { + if ($request->header('cko-signature') == hash_hmac('sha256', $webhook_payload, $this->company_gateway->company->company_key)) { CheckoutWebhook::dispatch($request->all(), $request->company_key, $this->company_gateway->id)->delay(10); } else { nlog("Hash Mismatch = {$request->header('cko-signature')} ".hash_hmac('sha256', $webhook_payload, $this->company_gateway->company->company_key)); @@ -543,7 +543,7 @@ class CheckoutComPaymentDriver extends BaseDriver try { $this->init()->gateway->getCustomersClient('x'); return true; - } catch(\Exception $e) { + } catch (\Exception $e) { } return false; @@ -576,13 +576,13 @@ class CheckoutComPaymentDriver extends BaseDriver ->cursor() ->each(function ($client) { - if(!str_contains($client->present()->email(), "@")) { + if (!str_contains($client->present()->email(), "@")) { return; } try { $customer = $this->gateway->getCustomersClient()->get($client->present()->email()); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Checkout: Customer not found"); return; } @@ -591,8 +591,8 @@ class CheckoutComPaymentDriver extends BaseDriver nlog($customer['instruments']); - foreach($customer['instruments'] as $card) { - if( + foreach ($customer['instruments'] as $card) { + if ( $card['type'] != 'card' || Carbon::createFromDate($card['expiry_year'], $card['expiry_month'], '1')->lt(now()) || //@phpstan-ignore-line $this->getToken($card['id'], $customer['id']) @@ -619,7 +619,7 @@ class CheckoutComPaymentDriver extends BaseDriver }); } - + public function livewirePaymentView(array $data): string { return $this->payment_method->livewirePaymentView($data); diff --git a/app/PaymentDrivers/CustomPaymentDriver.php b/app/PaymentDrivers/CustomPaymentDriver.php index b399c52aed..f7d33d8167 100644 --- a/app/PaymentDrivers/CustomPaymentDriver.php +++ b/app/PaymentDrivers/CustomPaymentDriver.php @@ -106,7 +106,7 @@ class CustomPaymentDriver extends BaseDriver public function processPaymentViewData(array $data): array { - return $this->paymentData($data); + return $this->paymentData($data); } /** diff --git a/app/PaymentDrivers/Eway/CreditCard.php b/app/PaymentDrivers/Eway/CreditCard.php index a3fbb56d5f..a6171755b3 100644 --- a/app/PaymentDrivers/Eway/CreditCard.php +++ b/app/PaymentDrivers/Eway/CreditCard.php @@ -71,7 +71,7 @@ class CreditCard implements LivewireMethodInterface $response = $this->eway_driver->init()->eway->createCustomer(\Eway\Rapid\Enum\ApiMethod::DIRECT, $transaction); - if($response->getErrors()) { + if ($response->getErrors()) { $response_status['message'] = \Eway\Rapid::getMessage($response->getErrors()[0]); @@ -284,7 +284,7 @@ class CreditCard implements LivewireMethodInterface return $payment; } - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return 'gateways.eway.pay_livewire'; } diff --git a/app/PaymentDrivers/Factory/ForteCustomerFactory.php b/app/PaymentDrivers/Factory/ForteCustomerFactory.php index acc5256254..6bbfcab2b8 100644 --- a/app/PaymentDrivers/Factory/ForteCustomerFactory.php +++ b/app/PaymentDrivers/Factory/ForteCustomerFactory.php @@ -17,10 +17,9 @@ use App\Models\Company; class ForteCustomerFactory { - public function convertToForte(Client $client): array { - + return [ "first_name" => $client->present()->first_name(), "last_name" => $client->present()->last_name(), @@ -95,11 +94,11 @@ class ForteCustomerFactory private function getBillingAddress(array $customer): array { nlog($customer); - if(isset($customer['default_billing_address_token']) && isset($customer['addresses'])) { + if (isset($customer['default_billing_address_token']) && isset($customer['addresses'])) { - foreach($customer['addresses'] as $address) { + foreach ($customer['addresses'] as $address) { - if($address['address_token'] != $customer['default_billing_address_token']) { + if ($address['address_token'] != $customer['default_billing_address_token']) { continue; } @@ -118,7 +117,7 @@ class ForteCustomerFactory } - if(isset($customer['addresses'][0])) { + if (isset($customer['addresses'][0])) { $address = $customer['addresses'][0]; @@ -142,11 +141,11 @@ class ForteCustomerFactory private function getShippingAddress(array $customer): array { - if(isset($customer['default_shipping_address_token'])) { + if (isset($customer['default_shipping_address_token'])) { - foreach($customer['addresses'] as $address) { + foreach ($customer['addresses'] as $address) { - if($address['address_token'] != $customer['default_shipping_address_token']) { + if ($address['address_token'] != $customer['default_shipping_address_token']) { continue; } @@ -163,7 +162,7 @@ class ForteCustomerFactory } - if(isset($customer['addresses'][1])) { + if (isset($customer['addresses'][1])) { $address = $customer['addresses'][1]; diff --git a/app/PaymentDrivers/Factory/SquareCustomerFactory.php b/app/PaymentDrivers/Factory/SquareCustomerFactory.php index 00070b93a7..75ef4f1f60 100644 --- a/app/PaymentDrivers/Factory/SquareCustomerFactory.php +++ b/app/PaymentDrivers/Factory/SquareCustomerFactory.php @@ -82,7 +82,7 @@ class SquareCustomerFactory $cards = []; - foreach($customer->getCards() ?? [] as $card) { + foreach ($customer->getCards() ?? [] as $card) { $meta = new \stdClass(); $meta->exp_month = $card->getExpMonth(); diff --git a/app/PaymentDrivers/Forte/ACH.php b/app/PaymentDrivers/Forte/ACH.php index 09071ac39c..c944732b25 100644 --- a/app/PaymentDrivers/Forte/ACH.php +++ b/app/PaymentDrivers/Forte/ACH.php @@ -175,7 +175,7 @@ class ACH implements LivewireMethodInterface $payment = $this->forte->createPayment($data, Payment::STATUS_COMPLETED); // return redirect('client/invoices')->withSuccess('Invoice paid.'); - + return redirect()->route('client.payments.show', ['payment' => $payment->hashed_id]); } @@ -183,15 +183,15 @@ class ACH implements LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return 'gateways.forte.ach.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $this->forte->payment_hash->data = array_merge((array) $this->forte->payment_hash->data, $data); $this->forte->payment_hash->save(); diff --git a/app/PaymentDrivers/Forte/CreditCard.php b/app/PaymentDrivers/Forte/CreditCard.php index 9b3bd359c7..cfa1da8096 100644 --- a/app/PaymentDrivers/Forte/CreditCard.php +++ b/app/PaymentDrivers/Forte/CreditCard.php @@ -75,7 +75,7 @@ class CreditCard implements LivewireMethodInterface $response = $this->forte->stubRequest() ->post("{$this->forte->baseUri()}/organizations/{$this->forte->getOrganisationId()}/locations/{$this->forte->getLocationId()}/customers/{$cst}/paymethods", $data); - if($response->successful()){ + if ($response->successful()) { $token = $response->object(); @@ -134,7 +134,7 @@ class CreditCard implements LivewireMethodInterface $response = $this->forte->stubRequest() ->post("{$this->forte->baseUri()}/organizations/{$this->forte->getOrganisationId()}/locations/{$this->forte->getLocationId()}/customers/{$cst}/paymethods", $data); - if($response->successful()){ + if ($response->successful()) { $token = $response->object(); @@ -159,7 +159,7 @@ class CreditCard implements LivewireMethodInterface public function paymentView(array $data) { $data = $this->paymentData($data); - + return render('gateways.forte.credit_card.pay', $data); } @@ -168,17 +168,17 @@ class CreditCard implements LivewireMethodInterface $payment_hash = PaymentHash::where('hash', $request->input('payment_hash'))->firstOrFail(); - if(strlen($request->token ?? '') > 3){ + if (strlen($request->token ?? '') > 3) { $cgt = \App\Models\ClientGatewayToken::find($this->decodePrimaryKey($request->token)); $payment = $this->forte->tokenBilling($cgt, $payment_hash); - + return redirect()->route('client.payments.show', ['payment' => $payment->hashed_id]); } - + $amount_with_fee = $payment_hash->data->total->amount_with_fee; $invoice_totals = $payment_hash->data->total->invoice_totals; $fee_total = null; @@ -282,7 +282,7 @@ class CreditCard implements LivewireMethodInterface ]; $payment = $this->forte->createPayment($data, Payment::STATUS_COMPLETED); - if($request->store_card) { + if ($request->store_card) { $this->createPaymentToken($request); } @@ -293,15 +293,15 @@ class CreditCard implements LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { - return 'gateways.forte.credit_card.pay_livewire'; + return 'gateways.forte.credit_card.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $this->forte->payment_hash->data = array_merge((array) $this->forte->payment_hash->data, $data); $this->forte->payment_hash->save(); diff --git a/app/PaymentDrivers/FortePaymentDriver.php b/app/PaymentDrivers/FortePaymentDriver.php index a73c25ab92..820885556d 100644 --- a/app/PaymentDrivers/FortePaymentDriver.php +++ b/app/PaymentDrivers/FortePaymentDriver.php @@ -248,8 +248,9 @@ class FortePaymentDriver extends BaseDriver private function getClient(?string $email) { - if(!$email) + if (!$email) { return false; + } return ClientContact::query() ->where('company_id', $this->company_gateway->company_id) @@ -263,9 +264,9 @@ class FortePaymentDriver extends BaseDriver $amount_with_fee = $payment_hash->data->amount_with_fee; $fee_total = $payment_hash->fee_total; - $data = + $data = [ - "action" => "sale", + "action" => "sale", "authorization_amount" => $amount_with_fee, "paymethod_token" => $cgt->token, "billing_address" => [ @@ -274,16 +275,16 @@ class FortePaymentDriver extends BaseDriver ], ]; - if($fee_total > 0){ + if ($fee_total > 0) { $data["service_fee_amount"] = $fee_total; } $response = $this->stubRequest() ->post("{$this->baseUri()}/organizations/{$this->getOrganisationId()}/locations/{$this->getLocationId()}/transactions", $data); - + $forte_response = $response->object(); - if($response->successful()){ + if ($response->successful()) { $data = [ 'payment_method' => $cgt->gateway_type_id, @@ -339,7 +340,7 @@ class FortePaymentDriver extends BaseDriver ->withQueryParameters(['page_size' => 10000]) ->get("{$this->baseUri()}/organizations/{$this->getOrganisationId()}/locations/{$this->getLocationId()}"); - if($response->successful()) { + if ($response->successful()) { return $response->json(); } @@ -352,18 +353,18 @@ class FortePaymentDriver extends BaseDriver { $response = $this->getLocation(); - if($response && $response['services']) { + if ($response && $response['services']) { $body = $response['services']; $fees_and_limits = $this->company_gateway->fees_and_limits; - if((isset($body['card']['service_fee_percentage']) && $body['card']['service_fee_percentage'] > 0) || (isset($body['card']['service_fee_additional_amount']) && $body['card']['service_fee_additional_amount'] > 0)) { + if ((isset($body['card']['service_fee_percentage']) && $body['card']['service_fee_percentage'] > 0) || (isset($body['card']['service_fee_additional_amount']) && $body['card']['service_fee_additional_amount'] > 0)) { $fees_and_limits->{1}->fee_amount = $body['card']['service_fee_additional_amount']; $fees_and_limits->{1}->fee_percent = $body['card']['service_fee_percentage']; } - if((isset($body['debit']['service_fee_percentage']) && $body['debit']['service_fee_percentage'] > 0) || (isset($body['card']['service_fee_additional_amount']) && $body['card']['service_fee_additional_amount'] > 0)) { + if ((isset($body['debit']['service_fee_percentage']) && $body['debit']['service_fee_percentage'] > 0) || (isset($body['card']['service_fee_additional_amount']) && $body['card']['service_fee_additional_amount'] > 0)) { $fees_and_limits->{2}->fee_amount = $body['debit']['service_fee_additional_amount']; $fees_and_limits->{2}->fee_percent = $body['debit']['service_fee_percentage']; @@ -380,17 +381,16 @@ class FortePaymentDriver extends BaseDriver public function findOrCreateCustomer() { - + $client_gateway_token = \App\Models\ClientGatewayToken::query() ->where('client_id', $this->client->id) ->where('company_gateway_id', $this->company_gateway->id) ->whereNotLike('token', 'ott_%') ->first(); - if($client_gateway_token){ + if ($client_gateway_token) { return $client_gateway_token->gateway_customer_reference; - } - else { + } else { $factory = new ForteCustomerFactory(); $data = $factory->convertToForte($this->client); @@ -400,11 +400,11 @@ class FortePaymentDriver extends BaseDriver //create customer - if($response->successful()){ + if ($response->successful()) { $customer = $response->object(); nlog($customer); return $customer->customer_token; - } + } nlog($response->body()); @@ -412,7 +412,7 @@ class FortePaymentDriver extends BaseDriver //@todo add syslog here } - + } public function importCustomers() @@ -422,16 +422,16 @@ class FortePaymentDriver extends BaseDriver ->withQueryParameters(['page_size' => 10000]) ->get("{$this->baseUri()}/organizations/{$this->getOrganisationId()}/locations/{$this->getLocationId()}/customers"); - if($response->successful()) { + if ($response->successful()) { - foreach($response->json()['results'] as $customer) { + foreach ($response->json()['results'] as $customer) { $client_repo = new ClientRepository(new ClientContactRepository()); $factory = new ForteCustomerFactory(); $data = $factory->convertToNinja($customer, $this->company_gateway->company); - if(strlen($data['email']) == 0 || $this->getClient($data['email'])) { + if (strlen($data['email']) == 0 || $this->getClient($data['email'])) { continue; } diff --git a/app/PaymentDrivers/GoCardless/ACH.php b/app/PaymentDrivers/GoCardless/ACH.php index e5c38ab7b6..911f958596 100644 --- a/app/PaymentDrivers/GoCardless/ACH.php +++ b/app/PaymentDrivers/GoCardless/ACH.php @@ -259,15 +259,15 @@ class ACH implements MethodInterface, LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return 'gateways.gocardless.ach.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $data['gateway'] = $this->go_cardless; $data['amount'] = $this->go_cardless->convertToGoCardlessAmount($data['total']['amount_with_fee'], $this->go_cardless->client->currency()->precision); diff --git a/app/PaymentDrivers/GoCardless/DirectDebit.php b/app/PaymentDrivers/GoCardless/DirectDebit.php index 107e6bcdde..379e806e1c 100644 --- a/app/PaymentDrivers/GoCardless/DirectDebit.php +++ b/app/PaymentDrivers/GoCardless/DirectDebit.php @@ -127,7 +127,7 @@ class DirectDebit implements MethodInterface, LivewireMethodInterface */ public function authorizeResponse(Request $request) { - + try { $billing_request = $this->go_cardless->gateway->billingRequests()->get($request->billing_request); @@ -155,12 +155,12 @@ class DirectDebit implements MethodInterface, LivewireMethodInterface 'invoices' => collect($this->go_cardless->payment_hash->data->invoices)->map(fn ($invoice) => $invoice->invoice_id)->toArray(), 'action' => 'payment', ]; - + $request = new ProcessInvoicesInBulkRequest(); $request->replace($data); - + session()->flash('message', ctrans('texts.payment_method_added')); - + return app(InvoiceController::class)->bulk($request); } @@ -193,8 +193,9 @@ class DirectDebit implements MethodInterface, LivewireMethodInterface { $data = $this->paymentData($data); - if(isset($data['authorize_then_redirect'])) + if (isset($data['authorize_then_redirect'])) { return $this->authorizeView($data); + } return render('gateways.gocardless.direct_debit.pay', $data); } @@ -308,15 +309,15 @@ class DirectDebit implements MethodInterface, LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string - { + public function livewirePaymentView(array $data): string + { return 'gateways.gocardless.direct_debit.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $data['gateway'] = $this->go_cardless; $data['amount'] = $this->go_cardless->convertToGoCardlessAmount($data['total']['amount_with_fee'], $this->go_cardless->client->currency()->precision); diff --git a/app/PaymentDrivers/GoCardless/InstantBankPay.php b/app/PaymentDrivers/GoCardless/InstantBankPay.php index 1eb38f5b1d..32ef3b5bd3 100644 --- a/app/PaymentDrivers/GoCardless/InstantBankPay.php +++ b/app/PaymentDrivers/GoCardless/InstantBankPay.php @@ -110,7 +110,7 @@ class InstantBankPay implements MethodInterface, LivewireMethodInterface ); nlog($billing_request); - + $payment = $this->go_cardless->gateway->payments()->get( $billing_request->payment_request->links->payment @@ -232,17 +232,17 @@ class InstantBankPay implements MethodInterface, LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { // not supported, this is offsite payment method. return ''; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $this->paymentView($data); diff --git a/app/PaymentDrivers/GoCardless/SEPA.php b/app/PaymentDrivers/GoCardless/SEPA.php index 9c55ed7f41..a056cbe31a 100644 --- a/app/PaymentDrivers/GoCardless/SEPA.php +++ b/app/PaymentDrivers/GoCardless/SEPA.php @@ -144,12 +144,12 @@ class SEPA implements MethodInterface, LivewireMethodInterface 'invoices' => collect($this->go_cardless->payment_hash->data->invoices)->map(fn ($invoice) => $invoice->invoice_id)->toArray(), 'action' => 'payment', ]; - + $request = new ProcessInvoicesInBulkRequest(); $request->replace($data); - + session()->flash('message', ctrans('texts.payment_method_added')); - + return app(InvoiceController::class)->bulk($request); } @@ -277,19 +277,19 @@ class SEPA implements MethodInterface, LivewireMethodInterface throw new PaymentFailed('Failed to process the payment.', 500); } - + /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return 'gateways.gocardless.sepa.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $data['gateway'] = $this->go_cardless; $data['amount'] = $this->go_cardless->convertToGoCardlessAmount($data['total']['amount_with_fee'], $this->go_cardless->client->currency()->precision); diff --git a/app/PaymentDrivers/GoCardlessPaymentDriver.php b/app/PaymentDrivers/GoCardlessPaymentDriver.php index ad317ecd8b..d514632d67 100644 --- a/app/PaymentDrivers/GoCardlessPaymentDriver.php +++ b/app/PaymentDrivers/GoCardlessPaymentDriver.php @@ -102,7 +102,7 @@ class GoCardlessPaymentDriver extends BaseDriver 'access_token' => $this->company_gateway->getConfigField('accessToken'), 'environment' => $this->company_gateway->getConfigField('testMode') ? \GoCardlessPro\Environment::SANDBOX : \GoCardlessPro\Environment::LIVE, ]); - } catch(\GoCardlessPro\Core\Exception\AuthenticationException $e) { + } catch (\GoCardlessPro\Core\Exception\AuthenticationException $e) { throw new \Exception('GoCardless: Invalid Access Token', 403); @@ -165,7 +165,7 @@ class GoCardlessPaymentDriver extends BaseDriver ]); if (in_array($payment->status, ['submitted', 'pending_submission'])) { - + $data = [ 'payment_method' => $cgt->hashed_id, 'payment_type' => PaymentType::ACH, @@ -267,9 +267,8 @@ class GoCardlessPaymentDriver extends BaseDriver foreach ($request->events as $event) { if ( - ($event['resource_type'] == 'payments' && $event['action'] == 'confirmed') || - $event['action'] === 'paid_out') - { + ($event['resource_type'] == 'payments' && $event['action'] == 'confirmed') || + $event['action'] === 'paid_out') { nlog('Searching for transaction reference'); $payment = Payment::query() @@ -407,7 +406,7 @@ class GoCardlessPaymentDriver extends BaseDriver $this->init(); $mandate = $this->gateway->mandates()->get($token); - if(!in_array($mandate->status, ['pending_submission', 'submitted', 'active','pending_customer_approval'])) { + if (!in_array($mandate->status, ['pending_submission', 'submitted', 'active','pending_customer_approval'])) { // if ($mandate->status !== 'active') { throw new \Exception(ctrans('texts.gocardless_mandate_not_ready')); @@ -568,7 +567,7 @@ class GoCardlessPaymentDriver extends BaseDriver try { $customers = $this->init()->gateway->customers()->list(); return true; - } catch(\Exception $e) { + } catch (\Exception $e) { } diff --git a/app/PaymentDrivers/Mollie/Bancontact.php b/app/PaymentDrivers/Mollie/Bancontact.php index 3a19ac358f..f894ab0a42 100644 --- a/app/PaymentDrivers/Mollie/Bancontact.php +++ b/app/PaymentDrivers/Mollie/Bancontact.php @@ -214,17 +214,17 @@ class Bancontact implements MethodInterface, LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { // Doesn't support, it's offsite payment method. return ''; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $this->paymentView($data); diff --git a/app/PaymentDrivers/Mollie/BankTransfer.php b/app/PaymentDrivers/Mollie/BankTransfer.php index 642d4bfc84..11305ee104 100644 --- a/app/PaymentDrivers/Mollie/BankTransfer.php +++ b/app/PaymentDrivers/Mollie/BankTransfer.php @@ -207,21 +207,21 @@ class BankTransfer implements MethodInterface, LivewireMethodInterface { return $this->processSuccessfulPayment($payment, 'open'); } - + /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { // Doesn't support, it's offsite payment method. return ''; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $this->paymentView($data); diff --git a/app/PaymentDrivers/Mollie/CreditCard.php b/app/PaymentDrivers/Mollie/CreditCard.php index 3ba25ee2ff..1d683c12f4 100644 --- a/app/PaymentDrivers/Mollie/CreditCard.php +++ b/app/PaymentDrivers/Mollie/CreditCard.php @@ -262,15 +262,15 @@ class CreditCard implements LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return 'gateways.mollie.credit_card.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $data['gateway'] = $this->mollie; diff --git a/app/PaymentDrivers/Mollie/IDEAL.php b/app/PaymentDrivers/Mollie/IDEAL.php index 88c9b35fe4..1bf4523296 100644 --- a/app/PaymentDrivers/Mollie/IDEAL.php +++ b/app/PaymentDrivers/Mollie/IDEAL.php @@ -182,7 +182,7 @@ class IDEAL implements MethodInterface, LivewireMethodInterface ->where('transaction_reference', $payment->id) ->first(); - if($p) { + if ($p) { $p->status_id = Payment::STATUS_COMPLETED; $p->save(); @@ -194,7 +194,7 @@ class IDEAL implements MethodInterface, LivewireMethodInterface 'amount' => array_sum(array_column($this->mollie->payment_hash->invoices(), 'amount')) + $this->mollie->payment_hash->fee_total, 'payment_type' => PaymentType::IDEAL, 'transaction_reference' => $payment->id, - 'idempotency_key' => substr("{$payment->id}{$this->mollie->payment_hash}",0,64) + 'idempotency_key' => substr("{$payment->id}{$this->mollie->payment_hash}", 0, 64) ]; $payment_record = $this->mollie->createPayment( @@ -224,21 +224,21 @@ class IDEAL implements MethodInterface, LivewireMethodInterface { return $this->processSuccessfulPayment($payment, 'open'); } - + /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { // Doesn't support, it's offsite payment method. return ''; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $this->paymentView($data); diff --git a/app/PaymentDrivers/Mollie/KBC.php b/app/PaymentDrivers/Mollie/KBC.php index 0811d75674..16dbce0e51 100644 --- a/app/PaymentDrivers/Mollie/KBC.php +++ b/app/PaymentDrivers/Mollie/KBC.php @@ -194,21 +194,21 @@ class KBC implements MethodInterface, LivewireMethodInterface return redirect()->route('client.payments.show', ['payment' => $this->mollie->encodePrimaryKey($payment_record->id)]); } - + /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { // Doesn't support, it's offsite payment method. return ''; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $this->paymentView($data); diff --git a/app/PaymentDrivers/MolliePaymentDriver.php b/app/PaymentDrivers/MolliePaymentDriver.php index ae0abf7f49..c695830a7f 100644 --- a/app/PaymentDrivers/MolliePaymentDriver.php +++ b/app/PaymentDrivers/MolliePaymentDriver.php @@ -223,7 +223,7 @@ class MolliePaymentDriver extends BaseDriver ]); if ($payment->status === 'paid') { - + $data = [ 'payment_method' => $cgt->token, @@ -336,7 +336,7 @@ class MolliePaymentDriver extends BaseDriver 'amount' => $amount = array_sum(array_column($payment_hash->invoices(), 'amount')) + $payment_hash->fee_total, 'payment_type' => $payment->metadata->payment_type_id, 'transaction_reference' => $payment->id, - 'idempotency_key' => substr("{$payment->id}{$payment_hash->hash}",0,64) + 'idempotency_key' => substr("{$payment->id}{$payment_hash->hash}", 0, 64) ]; $this->confirmGatewayFee($data); @@ -434,7 +434,7 @@ class MolliePaymentDriver extends BaseDriver try { $p = $this->gateway->payments->page(); return true; - } catch(\Exception $e) { + } catch (\Exception $e) { } diff --git a/app/PaymentDrivers/PayFast/CreditCard.php b/app/PaymentDrivers/PayFast/CreditCard.php index c03130a091..7bbbc5b32b 100644 --- a/app/PaymentDrivers/PayFast/CreditCard.php +++ b/app/PaymentDrivers/PayFast/CreditCard.php @@ -252,21 +252,21 @@ class CreditCard implements LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return 'gateways.payfast.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $payfast_data = [ 'merchant_id' => $this->payfast->company_gateway->getConfigField('merchantId'), 'merchant_key' => $this->payfast->company_gateway->getConfigField('merchantKey'), - 'return_url' => route('client.invoice.show',['invoice' => $this->payfast->payment_hash->fee_invoice->hashed_id]), //route('client.payments.index'), - 'cancel_url' => route('client.invoice.show',['invoice' => $this->payfast->payment_hash->fee_invoice->hashed_id]), //route('client.payment_methods.index'), + 'return_url' => route('client.invoice.show', ['invoice' => $this->payfast->payment_hash->fee_invoice->hashed_id]), //route('client.payments.index'), + 'cancel_url' => route('client.invoice.show', ['invoice' => $this->payfast->payment_hash->fee_invoice->hashed_id]), //route('client.payment_methods.index'), 'notify_url' => $this->payfast->genericWebhookUrl(), 'm_payment_id' => $data['payment_hash'], 'amount' => $data['amount_with_fee'], diff --git a/app/PaymentDrivers/PayPal/PayPalBasePaymentDriver.php b/app/PaymentDrivers/PayPal/PayPalBasePaymentDriver.php index 375b9c7420..fc6a87943c 100644 --- a/app/PaymentDrivers/PayPal/PayPalBasePaymentDriver.php +++ b/app/PaymentDrivers/PayPal/PayPalBasePaymentDriver.php @@ -81,7 +81,7 @@ class PayPalBasePaymentDriver extends BaseDriver })->toArray(); /** Parse funding options and remove card option if advanced cards is enabled. */ - if(in_array(1, $funding_options) && in_array(29, $funding_options)) { + if (in_array(1, $funding_options) && in_array(29, $funding_options)) { if (($key = array_search(1, $funding_options)) !== false) { unset($funding_options[$key]); @@ -115,17 +115,16 @@ class PayPalBasePaymentDriver extends BaseDriver $this->api_endpoint_url = $this->company_gateway->getConfigField('testMode') ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com'; - if(\App\Utils\Ninja::isHosted() && $this->company_gateway->gateway_key != '80af24a6a691230bbec33e930ab40665') { - $secret = config('ninja.paypal.secret'); - $client_id = config('ninja.paypal.client_id'); - } - else { + if (\App\Utils\Ninja::isHosted() && $this->company_gateway->gateway_key != '80af24a6a691230bbec33e930ab40665') { + $secret = config('ninja.paypal.secret'); + $client_id = config('ninja.paypal.client_id'); + } else { $secret = $this->company_gateway->getConfigField('secret'); $client_id = $this->company_gateway->getConfigField('clientId'); } - if($this->access_token && $this->token_expiry && $this->token_expiry->isFuture()) { + if ($this->access_token && $this->token_expiry && $this->token_expiry->isFuture()) { return $this; } @@ -134,7 +133,7 @@ class PayPalBasePaymentDriver extends BaseDriver ->withQueryParameters(['grant_type' => 'client_credentials']) ->post("{$this->api_endpoint_url}/v1/oauth2/token"); - if($response->successful()) { + if ($response->successful()) { $this->access_token = $response->json()['access_token']; $this->token_expiry = now()->addSeconds($response->json()['expires_in'] - 60); } else { @@ -175,9 +174,9 @@ class PayPalBasePaymentDriver extends BaseDriver $funding_options = ''; - foreach($this->company_gateway->fees_and_limits as $key => $value) { + foreach ($this->company_gateway->fees_and_limits as $key => $value) { - if($value->is_enabled) { + if ($value->is_enabled) { $funding_options .= $enums[$key].','; @@ -198,7 +197,7 @@ class PayPalBasePaymentDriver extends BaseDriver $cgt = ClientGatewayToken::where('company_gateway_id', $this->company_gateway->id) ->where('client_id', $this->client->id) ->first(); - if(!$cgt) { + if (!$cgt) { return ''; } @@ -212,7 +211,7 @@ class PayPalBasePaymentDriver extends BaseDriver ->withQueryParameters(['grant_type' => 'client_credentials','response_type' => 'id_token', 'target_customer_id' => $client_reference]) ->post("{$this->api_endpoint_url}/v1/oauth2/token"); - if($response->successful()) { + if ($response->successful()) { $data = $response->json(); @@ -283,7 +282,7 @@ class PayPalBasePaymentDriver extends BaseDriver public function getPaymentSource(): array { //@todo - roll back here for advanced payments vs hosted card fields. - if($this->gateway_type_id == GatewayType::PAYPAL_ADVANCED_CARDS) { + if ($this->gateway_type_id == GatewayType::PAYPAL_ADVANCED_CARDS) { return [ "card" => [ @@ -324,7 +323,7 @@ class PayPalBasePaymentDriver extends BaseDriver ]; /** If we have a complete address, add it to the order, otherwise leave it blank! */ - if( + if ( strlen($this->client->shipping_address1 ?? '') > 2 && strlen($this->client->shipping_city ?? '') > 2 && strlen($this->client->shipping_state ?? '') >= 2 && @@ -339,7 +338,7 @@ class PayPalBasePaymentDriver extends BaseDriver "postal_code" => $this->client->shipping_postal_code, "country_code" => $this->client->present()->shipping_country_code(), ]; - } elseif( + } elseif ( strlen($this->client->address1 ?? '') > 2 && strlen($this->client->city ?? '') > 2 && strlen($this->client->state ?? '') >= 2 && @@ -368,7 +367,7 @@ class PayPalBasePaymentDriver extends BaseDriver */ public function setPaymentMethod($payment_method_id): self { - if(!$payment_method_id) { + if (!$payment_method_id) { return $this; } @@ -410,7 +409,7 @@ class PayPalBasePaymentDriver extends BaseDriver ->withHeaders($this->getHeaders($headers)) ->{$verb}("{$this->api_endpoint_url}{$uri}", $data); - if($r->status() <= 422) { + if ($r->status() <= 422) { // if($r->successful()) { return $r; } @@ -450,11 +449,11 @@ class PayPalBasePaymentDriver extends BaseDriver switch ($response['name']) { case 'NOT_AUTHORIZED': throw new PaymentFailed("There was a permissions issue processing this payment, please contact the merchant. ", 401); - + default: throw new PaymentFailed("Unknown error occurred processing payment. Please contact merchant.", 500); - + } } @@ -492,7 +491,7 @@ class PayPalBasePaymentDriver extends BaseDriver $r = $this->gatewayRequest('/v1/identity/generate-token', 'post', ['body' => '']); - if($r->successful()) { + if ($r->successful()) { return $r->json()['client_token']; } @@ -506,7 +505,7 @@ class PayPalBasePaymentDriver extends BaseDriver try { $this->init()->getClientToken(); return true; - } catch(\Exception $e) { + } catch (\Exception $e) { } @@ -524,14 +523,13 @@ class PayPalBasePaymentDriver extends BaseDriver $this->init(); PayPalWebhook::dispatch($request->all(), $request->headers->all(), $this->access_token); - + } public function createNinjaPayment($request, $response) { - if(isset($response['purchase_units'][0]['payments']['captures'][0]['status']) && in_array($response['purchase_units'][0]['payments']['captures'][0]['status'], ['COMPLETED', 'PENDING'])) - { + if (isset($response['purchase_units'][0]['payments']['captures'][0]['status']) && in_array($response['purchase_units'][0]['payments']['captures'][0]['status'], ['COMPLETED', 'PENDING'])) { $payment_status = $response['purchase_units'][0]['payments']['captures'][0]['status'] == 'COMPLETED' ? \App\Models\Payment::STATUS_COMPLETED : \App\Models\Payment::STATUS_PENDING; @@ -547,7 +545,7 @@ class PayPalBasePaymentDriver extends BaseDriver if ($request->has('store_card') && $request->input('store_card') === true) { $payment_source = $response->json()['payment_source'] ?? false; - if(isset($payment_source['card']) && ($payment_source['card']['attributes']['vault']['status'] ?? false) && $payment_source['card']['attributes']['vault']['status'] == 'VAULTED') { + if (isset($payment_source['card']) && ($payment_source['card']['attributes']['vault']['status'] ?? false) && $payment_source['card']['attributes']['vault']['status'] == 'VAULTED') { $last4 = $payment_source['card']['last_digits']; $expiry = $payment_source['card']['expiry']; //'2025-01' @@ -588,9 +586,9 @@ class PayPalBasePaymentDriver extends BaseDriver } SystemLogger::dispatch($response, SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_FAILURE, SystemLog::TYPE_PAYPAL, $this->client, $this->client->company); - + $error = isset($response['purchase_units'][0]['payments']['captures'][0]['status_details'][0]) ? $response['purchase_units'][0]['payments']['captures'][0]['status_details'][0] : $response['purchase_units'][0]['payments']['captures'][0]['status']; - + return response()->json(['message' => $error], 400); } diff --git a/app/PaymentDrivers/PayPal/PayPalWebhook.php b/app/PaymentDrivers/PayPal/PayPalWebhook.php index 3a42bdf97c..3579e0fc06 100644 --- a/app/PaymentDrivers/PayPal/PayPalWebhook.php +++ b/app/PaymentDrivers/PayPal/PayPalWebhook.php @@ -56,11 +56,11 @@ class PayPalWebhook implements ShouldQueue // $this->endpoint = $this->test_endpoint; //this can cause problems verifying the webhook, so unset it if it exists - if(isset($this->webhook_request['q'])) { + if (isset($this->webhook_request['q'])) { unset($this->webhook_request['q']); } - if($this->verifyWebhook()) { + if ($this->verifyWebhook()) { nlog('verified'); match($this->webhook_request['event_type']) {//@phpstan-ignore-line @@ -200,7 +200,7 @@ class PayPalWebhook implements ShouldQueue $amount = $order['purchase_units'][0]['payments']['captures'][0]['amount']['value']; $payment_hash = MultiDB::findAndSetByPaymentHash($order['purchase_units'][0]['custom_id']); $merchant_id = $order['purchase_units'][0]['payee']['merchant_id']; - if(!$payment_hash) { + if (!$payment_hash) { $ninja_company = Company::on('db-ninja-01')->find(config('ninja.ninja_default_company_id')); $ninja_company->notification(new PayPalUnlinkedTransaction($order['id'], $transaction_reference))->ninja(); @@ -208,15 +208,15 @@ class PayPalWebhook implements ShouldQueue } nlog("payment completed check"); - if($payment_hash->payment && $payment_hash->payment->status_id == Payment::STATUS_COMPLETED) { // Payment made, all good! + if ($payment_hash->payment && $payment_hash->payment->status_id == Payment::STATUS_COMPLETED) { // Payment made, all good! return; } nlog("invoice paid check"); - if($payment_hash->fee_invoice && $payment_hash->fee_invoice->status_id == Invoice::STATUS_PAID) { // Payment made, all good! + if ($payment_hash->fee_invoice && $payment_hash->fee_invoice->status_id == Invoice::STATUS_PAID) { // Payment made, all good! nlog("payment status check"); - if($payment_hash->payment && $payment_hash->payment->status_id != Payment::STATUS_COMPLETED) { // Make sure the payment is marked as completed + if ($payment_hash->payment && $payment_hash->payment->status_id != Payment::STATUS_COMPLETED) { // Make sure the payment is marked as completed $payment_hash->payment->status_id = Payment::STATUS_COMPLETED; $payment_hash->push(); } @@ -224,11 +224,11 @@ class PayPalWebhook implements ShouldQueue } nlog("create payment check"); - if($payment_hash->fee_invoice && in_array($payment_hash->fee_invoice->status_id, [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])) { + if ($payment_hash->fee_invoice && in_array($payment_hash->fee_invoice->status_id, [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])) { $payment = Payment::where('transaction_reference', $transaction_reference)->first(); - if(!$payment) { + if (!$payment) { nlog("make payment here!"); $payment = $this->createPayment($payment_hash, [ 'amount' => $amount, @@ -268,7 +268,7 @@ class PayPalWebhook implements ShouldQueue $order = $driver->getOrder($this->webhook_request['resource']['id']); $source = 'paypal'; - if(isset($order['payment_source'])) { + if (isset($order['payment_source'])) { $source = array_key_first($order['payment_source']); } @@ -300,7 +300,7 @@ class PayPalWebhook implements ShouldQueue ->first(function ($cg) use ($merchant_id) { //@phpstan-ignore-line $config = $cg->getConfig(); - if($config->merchantId == $merchant_id) { + if ($config->merchantId == $merchant_id) { return $cg; } @@ -336,7 +336,7 @@ class PayPalWebhook implements ShouldQueue nlog($r); nlog($r->json()); - if($r->successful() && $r->json()['verification_status'] == 'SUCCESS') { + if ($r->successful() && $r->json()['verification_status'] == 'SUCCESS') { return true; } diff --git a/app/PaymentDrivers/PayPalPPCPPaymentDriver.php b/app/PaymentDrivers/PayPalPPCPPaymentDriver.php index 161700a6ce..148fac6846 100644 --- a/app/PaymentDrivers/PayPalPPCPPaymentDriver.php +++ b/app/PaymentDrivers/PayPalPPCPPaymentDriver.php @@ -55,7 +55,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver private function checkPaymentsReceivable(): self { - if($this->company_gateway->getConfigField('status') != 'activated') { + if ($this->company_gateway->getConfigField('status') != 'activated') { if (class_exists(\Modules\Admin\Services\PayPal\PayPalService::class)) { $pp = new \Modules\Admin\Services\PayPal\PayPalService($this->company_gateway->company, $this->company_gateway->user); @@ -64,7 +64,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver $this->company_gateway = $this->company_gateway->fresh(); $config = $this->company_gateway->getConfig(); - if($config->status == 'activated') { + if ($config->status == 'activated') { return $this; } @@ -87,7 +87,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver { $data = $this->processPaymentViewData($data); - if($this->gateway_type_id == 29) { + if ($this->gateway_type_id == 29) { return render('gateways.paypal.ppcp.card', $data); } else { return render('gateways.paypal.ppcp.pay', $data); @@ -111,14 +111,14 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver nlog($response); - if($request->has('token') && strlen($request->input('token','')) > 2) { + if ($request->has('token') && strlen($request->input('token', '')) > 2) { return $this->processTokenPayment($request, $response); } //capture $orderID = $response['orderID'] ?? $this->payment_hash->data->orderID; - if($this->company_gateway->require_shipping_address) { + if ($this->company_gateway->require_shipping_address) { $shipping_data = [[ @@ -141,7 +141,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver try { $r = $this->gatewayRequest("/v2/checkout/orders/{$orderID}/capture", 'post', ['body' => '']); - if($r->status() == 422) { + if ($r->status() == 422) { //handle conditions where the client may need to try again. // return $this->handleRetry($r, $request); @@ -149,10 +149,10 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver } - } catch(\Exception $e) { + } catch (\Exception $e) { //Rescue for duplicate invoice_id - if(stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { + if (stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { $r = $this->handleDuplicateInvoiceId($orderID); } @@ -163,7 +163,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver nlog("Process response =>"); nlog($response->json()); - if(isset($response['status']) && $response['status'] == 'COMPLETED' && isset($response['purchase_units'])) { + if (isset($response['status']) && $response['status'] == 'COMPLETED' && isset($response['purchase_units'])) { return $this->createNinjaPayment($request, $response); @@ -171,7 +171,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver } else { - if(isset($response['headers']) ?? false) { + if (isset($response['headers']) ?? false) { unset($response['headers']); } @@ -256,18 +256,21 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver ] ]; - if($shipping = $this->getShippingAddress()) + if ($shipping = $this->getShippingAddress()) { $order['purchase_units'][0]["shipping"] = $shipping; + } - if(isset($data['payment_source'])) + if (isset($data['payment_source'])) { $order['payment_source'] = $data['payment_source']; + } - if(isset($data['payer'])) + if (isset($data['payer'])) { $order['payer'] = $data['payer']; + } $r = $this->gatewayRequest('/v2/checkout/orders', 'post', $order); - if(!isset($r->json()['id'])) { + if (!isset($r->json()['id'])) { $this->handleProcessingFailure($r->json()); } @@ -328,7 +331,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver $r = $this->gatewayRequest("/v2/checkout/orders/{$orderId}", 'get', ['body' => '']); - if($r->status() == 422) { + if ($r->status() == 422) { //handle conditions where the client may need to try again. nlog("hit 422"); $r = $this->handleDuplicateInvoiceId($orderId); @@ -336,10 +339,10 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver } - } catch(\Exception $e) { + } catch (\Exception $e) { //Rescue for duplicate invoice_id - if(stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { + if (stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { nlog("hit 422 in exception"); @@ -351,9 +354,8 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver } $response = $r->json(); - - if(isset($response['purchase_units'][0]['payments']['captures'][0]['status']) && $response['purchase_units'][0]['payments']['captures'][0]['status'] == 'COMPLETED') - { + + if (isset($response['purchase_units'][0]['payments']['captures'][0]['status']) && $response['purchase_units'][0]['payments']['captures'][0]['status'] == 'COMPLETED') { $data = [ 'payment_type' => $this->getPaymentMethod($request->gateway_type_id), @@ -413,7 +415,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver $r = $this->gatewayRequest("/v2/checkout/orders/{$orderId}", 'get', ['body' => '']); - if($r->status() == 422) { + if ($r->status() == 422) { //handle conditions where the client may need to try again. $r = $this->handleDuplicateInvoiceId($orderId); @@ -421,10 +423,10 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver } - } catch(\Exception $e) { + } catch (\Exception $e) { //Rescue for duplicate invoice_id - if(stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { + if (stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { $r = $this->handleDuplicateInvoiceId($orderId); @@ -434,8 +436,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver } $response = $r->json(); - if(isset($response['purchase_units'][0]['payments']['captures'][0]['status']) && $response['purchase_units'][0]['payments']['captures'][0]['status'] == 'COMPLETED') - { + if (isset($response['purchase_units'][0]['payments']['captures'][0]['status']) && $response['purchase_units'][0]['payments']['captures'][0]['status'] == 'COMPLETED') { $data = [ 'payment_type' => $this->getPaymentMethod((string)$cgt->gateway_type_id), @@ -484,9 +485,9 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver $data['invoice_hash'] = $this->payment_hash->fee_invoice->hashed_id; return $data; - } + } - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { if ($this->gateway_type_id == 29) { return 'gateways.paypal.ppcp.card_livewire'; diff --git a/app/PaymentDrivers/PayPalRestPaymentDriver.php b/app/PaymentDrivers/PayPalRestPaymentDriver.php index fd466c6c86..339dc32d22 100644 --- a/app/PaymentDrivers/PayPalRestPaymentDriver.php +++ b/app/PaymentDrivers/PayPalRestPaymentDriver.php @@ -33,7 +33,7 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver { $data = $this->processPaymentViewData($data); - if($this->gateway_type_id == 29) { + if ($this->gateway_type_id == 29) { return render('gateways.paypal.ppcp.card', $data); } else { return render('gateways.paypal.pay', $data); @@ -54,7 +54,7 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver $request['gateway_response'] = str_replace("Error: ", "", $request['gateway_response']); $response = json_decode($request['gateway_response'], true); - if($request->has('token') && strlen($request->input('token')) > 2) { + if ($request->has('token') && strlen($request->input('token')) > 2) { return $this->processTokenPayment($request, $response); } @@ -62,7 +62,7 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver $orderID = $response['orderID'] ?? $this->payment_hash->data->orderID; - if($this->company_gateway->require_shipping_address) { + if ($this->company_gateway->require_shipping_address) { $shipping_data = [[ @@ -86,7 +86,7 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver $r = $this->gatewayRequest("/v2/checkout/orders/{$orderID}/capture", 'post', ['body' => '']); - if($r->status() == 422) { + if ($r->status() == 422) { //handle conditions where the client may need to try again. $r = $this->handleDuplicateInvoiceId($orderID); @@ -94,10 +94,10 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver } - } catch(\Exception $e) { + } catch (\Exception $e) { //Rescue for duplicate invoice_id - if(stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { + if (stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { $r = $this->handleDuplicateInvoiceId($orderID); @@ -111,13 +111,13 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver nlog("Process response =>"); nlog($response->json()); - if(isset($response['status']) && $response['status'] == 'COMPLETED' && isset($response['purchase_units'])) { + if (isset($response['status']) && $response['status'] == 'COMPLETED' && isset($response['purchase_units'])) { return $this->createNinjaPayment($request, $response); } else { - if(isset($response['headers']) ?? false) { + if (isset($response['headers']) ?? false) { unset($response['headers']); } @@ -182,15 +182,15 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver ] ]; - if($shipping = $this->getShippingAddress()) { + if ($shipping = $this->getShippingAddress()) { $order['purchase_units'][0]["shipping"] = $shipping; } - if(isset($data['payment_source'])) { + if (isset($data['payment_source'])) { $order['payment_source'] = $data['payment_source']; } - if(isset($data["payer"])){ + if (isset($data["payer"])) { $order['payer'] = $data["payer"]; } @@ -200,7 +200,7 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver $response = $r->json(); - if($r->status() == 422) { + if ($r->status() == 422) { //handle conditions where the client may need to try again. $_invoice = collect($this->payment_hash->data->invoices)->first(); @@ -216,7 +216,7 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver } - if(!isset($response['id'])) { + if (!isset($response['id'])) { $this->handleProcessingFailure($response); } @@ -280,7 +280,7 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver $r = $this->gatewayRequest("/v2/checkout/orders/{$orderId}", 'get', ['body' => '']); - if($r->status() == 422) { + if ($r->status() == 422) { //handle conditions where the client may need to try again. nlog("hit 422"); $r = $this->handleDuplicateInvoiceId($orderId); @@ -288,10 +288,10 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver } - } catch(\Exception $e) { + } catch (\Exception $e) { //Rescue for duplicate invoice_id - if(stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { + if (stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { nlog("hit 422 in exception"); @@ -304,8 +304,7 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver $response = $r->json(); - if(isset($response['purchase_units'][0]['payments']['captures'][0]['status']) && $response['purchase_units'][0]['payments']['captures'][0]['status'] == 'COMPLETED') - { + if (isset($response['purchase_units'][0]['payments']['captures'][0]['status']) && $response['purchase_units'][0]['payments']['captures'][0]['status'] == 'COMPLETED') { $data = [ 'payment_type' => $this->getPaymentMethod($request->gateway_type_id), 'amount' => $response['purchase_units'][0]['payments']['captures'][0]['amount']['value'], @@ -365,17 +364,17 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver $r = $this->gatewayRequest("/v2/checkout/orders/{$orderId}", 'get', ['body' => '']); - if($r->status() == 422) { + if ($r->status() == 422) { //handle conditions where the client may need to try again. $r = $this->handleDuplicateInvoiceId($orderId); } - } catch(\Exception $e) { + } catch (\Exception $e) { //Rescue for duplicate invoice_id - if(stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { + if (stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { $r = $this->handleDuplicateInvoiceId($orderId); @@ -385,8 +384,7 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver $response = $r->json(); - if(isset($response['purchase_units'][0]['payments']['captures'][0]['status']) && $response['purchase_units'][0]['payments']['captures'][0]['status'] == 'COMPLETED') - { + if (isset($response['purchase_units'][0]['payments']['captures'][0]['status']) && $response['purchase_units'][0]['payments']['captures'][0]['status'] == 'COMPLETED') { $data = [ 'payment_type' => $this->getPaymentMethod((string)$cgt->gateway_type_id), @@ -433,11 +431,11 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver $data['identifier'] = "s:INN_ACDC_CHCK"; $data['pp_client_reference'] = $this->getClientHash(); $data['invoice_hash'] = $this->payment_hash->fee_invoice->hashed_id; - + return $data; } - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { if ($this->gateway_type_id == 29) { return 'gateways.paypal.ppcp.card_livewire'; diff --git a/app/PaymentDrivers/PayTrace/CreditCard.php b/app/PaymentDrivers/PayTrace/CreditCard.php index a11cc1a103..c04936cb2f 100644 --- a/app/PaymentDrivers/PayTrace/CreditCard.php +++ b/app/PaymentDrivers/PayTrace/CreditCard.php @@ -38,7 +38,7 @@ class CreditCard implements LivewireMethodInterface public function authorizeView($data) { $data = $this->paymentData($data); - + return render('gateways.paytrace.authorize', $data); } @@ -239,7 +239,7 @@ class CreditCard implements LivewireMethodInterface ]; return $this->paytrace->processUnsuccessfulTransaction($data); - } + } /** * @inheritDoc @@ -248,7 +248,7 @@ class CreditCard implements LivewireMethodInterface { return 'gateways.paytrace.pay_livewire'; } - + /** * @inheritDoc */ diff --git a/app/PaymentDrivers/PaytracePaymentDriver.php b/app/PaymentDrivers/PaytracePaymentDriver.php index e573136041..bca071da49 100644 --- a/app/PaymentDrivers/PaytracePaymentDriver.php +++ b/app/PaymentDrivers/PaytracePaymentDriver.php @@ -254,7 +254,7 @@ class PaytracePaymentDriver extends BaseDriver public function getClientRequiredFields(): array { - + $fields = []; if ($this->company_gateway->require_client_name) { @@ -312,7 +312,7 @@ class PaytracePaymentDriver extends BaseDriver try { $this->init()->generateAuthHeaders() && strlen($this->company_gateway->getConfigField('integratorId')) > 2; return true; - } catch(\Exception $e) { + } catch (\Exception $e) { } @@ -336,25 +336,25 @@ class PaytracePaymentDriver extends BaseDriver $client_repo = new ClientRepository(new ClientContactRepository()); $factory = new PaytraceCustomerFactory(); - foreach($response->customers as $customer) { + foreach ($response->customers as $customer) { $data = $factory->convertToNinja($customer, $this->company_gateway->company); $client = false; - if(str_contains($data['contacts'][0]['email'], "@")) { + if (str_contains($data['contacts'][0]['email'], "@")) { $client = ClientContact::query() ->where('company_id', $this->company_gateway->company_id) ->where('email', $data['contacts'][0]['email']) ->first()->client ?? false; } - if(!$client) { + if (!$client) { $client = $client_repo->save($data, ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id)); } $this->client = $client; - if(ClientGatewayToken::query()->where('client_id', $client->id)->where('token', $data['card']['token'])->exists()) { + if (ClientGatewayToken::query()->where('client_id', $client->id)->where('token', $data['card']['token'])->exists()) { continue; } diff --git a/app/PaymentDrivers/Razorpay/Hosted.php b/app/PaymentDrivers/Razorpay/Hosted.php index 9003349cb7..6cf7012f3e 100644 --- a/app/PaymentDrivers/Razorpay/Hosted.php +++ b/app/PaymentDrivers/Razorpay/Hosted.php @@ -163,15 +163,15 @@ class Hosted implements MethodInterface, LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return 'gateways.razorpay.hosted.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $order = $this->razorpay->gateway->order->create([ 'currency' => $this->razorpay->client->currency()->code, diff --git a/app/PaymentDrivers/Rotessa/Jobs/TransactionReport.php b/app/PaymentDrivers/Rotessa/Jobs/TransactionReport.php index c62c35f1f3..47294f3a79 100644 --- a/app/PaymentDrivers/Rotessa/Jobs/TransactionReport.php +++ b/app/PaymentDrivers/Rotessa/Jobs/TransactionReport.php @@ -44,66 +44,64 @@ class TransactionReport implements ShouldQueue public function handle() { set_time_limit(0); - - foreach(MultiDB::$dbs as $db) - { + + foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); CompanyGateway::query() ->where('gateway_key', '91be24c7b792230bced33e930ac61676') ->cursor() - ->each(function ($cg){ + ->each(function ($cg) { $driver = $cg->driver()->init(); //Approved Transactions $transactions = $driver->gatewayRequest("get", "transaction_report", ['page' => 1, 'status' => 'Approved', 'start_date' => now()->subMonths(2)->format('Y-m-d')]); - if($transactions->successful()) - { + if ($transactions->successful()) { $transactions = $transactions->json(); nlog($transactions); - Payment::query() - ->where('company_id', $cg->company_id) - ->where('status_id', Payment::STATUS_PENDING) - ->whereIn('transaction_reference', array_column($transactions, "transaction_schedule_id")) - ->cursor() - ->each(function ($payment) use ($transactions) { - - $payment->status_id = Payment::STATUS_COMPLETED; - $payment->save(); + Payment::query() + ->where('company_id', $cg->company_id) + ->where('status_id', Payment::STATUS_PENDING) + ->whereIn('transaction_reference', array_column($transactions, "transaction_schedule_id")) + ->cursor() + ->each(function ($payment) use ($transactions) { - SystemLogger::dispatch( - ['response' => collect($transactions)->where('id', $payment->transaction_reference)->first()->toArray(), 'data' => []], - SystemLog::CATEGORY_GATEWAY_RESPONSE, - SystemLog::EVENT_GATEWAY_SUCCESS, - SystemLog::TYPE_ROTESSA, - $payment->client, - $payment->company, - ); + $payment->status_id = Payment::STATUS_COMPLETED; + $payment->save(); + + SystemLogger::dispatch( + ['response' => collect($transactions)->where('id', $payment->transaction_reference)->first()->toArray(), 'data' => []], + SystemLog::CATEGORY_GATEWAY_RESPONSE, + SystemLog::EVENT_GATEWAY_SUCCESS, + SystemLog::TYPE_ROTESSA, + $payment->client, + $payment->company, + ); }); - + } //Declined / Charged Back Transactions $declined_transactions = $driver->gatewayRequest("get", "transaction_report", ['page' => 1, 'status' => 'Declined', 'start_date' => now()->subMonths(2)->format('Y-m-d')]); $chargeback_transactions = $driver->gatewayRequest("get", "transaction_report", ['page' => 1, 'status' => 'Chargeback', 'start_date' => now()->subMonths(2)->format('Y-m-d')]); - - if($declined_transactions->successful() && $chargeback_transactions->successful()) { + + if ($declined_transactions->successful() && $chargeback_transactions->successful()) { $transactions = array_merge($declined_transactions->json(), $chargeback_transactions->json()); - + nlog($transactions); - Payment::query() - ->where('company_id', $cg->company_id) - ->where('status_id', Payment::STATUS_PENDING) - ->whereIn('transaction_reference', array_column($transactions, "transaction_schedule_id")) - ->cursor() - ->each(function ($payment) use ($transactions){ + Payment::query() + ->where('company_id', $cg->company_id) + ->where('status_id', Payment::STATUS_PENDING) + ->whereIn('transaction_reference', array_column($transactions, "transaction_schedule_id")) + ->cursor() + ->each(function ($payment) use ($transactions) { $client = $payment->client; @@ -145,11 +143,11 @@ class TransactionReport implements ShouldQueue $payment->company, ); - }); + }); } }); } } -} \ No newline at end of file +} diff --git a/app/PaymentDrivers/Rotessa/PaymentMethod.php b/app/PaymentDrivers/Rotessa/PaymentMethod.php index 51459d7428..2797f17739 100755 --- a/app/PaymentDrivers/Rotessa/PaymentMethod.php +++ b/app/PaymentDrivers/Rotessa/PaymentMethod.php @@ -34,11 +34,10 @@ use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest; class PaymentMethod implements MethodInterface, LivewireMethodInterface { - private array $transaction = [ "financial_transactions" => [], - "frequency" =>'Once', - "installments" =>1 + "frequency" => 'Once', + "installments" => 1 ]; public function __construct(protected RotessaPaymentDriver $rotessa) @@ -50,16 +49,16 @@ class PaymentMethod implements MethodInterface, LivewireMethodInterface * Show the authorization page for Rotessa. * * @param array $data - * @return \Illuminate\View\View + * @return \Illuminate\View\View */ public function authorizeView(array $data): View { $data['contact'] = collect($data['client']->contacts->first()->toArray())->merge([ - 'home_phone' => $data['client']->phone, + 'home_phone' => $data['client']->phone, 'custom_identifier' => $data['client']->number, 'name' => $data['client']->name, 'id' => null - ] )->all(); + ])->all(); $data['gateway'] = $this->rotessa; $data['gateway_type_id'] = GatewayType::ACSS ; $data['account'] = [ @@ -67,8 +66,8 @@ class PaymentMethod implements MethodInterface, LivewireMethodInterface 'country' => $data['client']->country->iso_3166_2 ]; $data['address'] = collect($data['client']->toArray())->merge(['country' => $data['client']->country->iso_3166_2 ])->all(); - - return render('gateways.rotessa.bank_transfer.authorize', $data ); + + return render('gateways.rotessa.bank_transfer.authorize', $data); } /** * Handle the authorization page for Rotessa. @@ -93,24 +92,23 @@ class PaymentMethod implements MethodInterface, LivewireMethodInterface 'bank_name' => ['required'], 'phone' => ['required'], 'home_phone' => ['required','size:10'], - 'bank_account_type'=>['required_if:country,US'], - 'routing_number'=>['required_if:country,US'], - 'institution_number'=>['required_if:country,CA','numeric','digits:3'], - 'transit_number'=>['required_if:country,CA','numeric','digits:5'], - 'custom_identifier'=>['required_without:customer_id'], - 'customer_id'=>['required_without:custom_identifier','integer'], + 'bank_account_type' => ['required_if:country,US'], + 'routing_number' => ['required_if:country,US'], + 'institution_number' => ['required_if:country,CA','numeric','digits:3'], + 'transit_number' => ['required_if:country,CA','numeric','digits:5'], + 'custom_identifier' => ['required_without:customer_id'], + 'customer_id' => ['required_without:custom_identifier','integer'], 'customer_type' => ['required', 'in:Personal,Business'], ]); - $customer = array_merge(['address' => $request->only('address_1','address_2','city','postal_code','province_code','country'), 'custom_identifier' => $request->input('custom_identifier') ], $request->all()); + $customer = array_merge(['address' => $request->only('address_1', 'address_2', 'city', 'postal_code', 'province_code', 'country'), 'custom_identifier' => $request->input('custom_identifier') ], $request->all()); - try{ + try { $this->rotessa->findOrCreateCustomer($customer); - } - catch(\Exception $e){ + } catch (\Exception $e) { + + $message = json_decode($e->getMessage(), true); - $message = json_decode($e->getMessage(), true); - return redirect()->route('client.payment_methods.index')->withErrors(array_values($message['errors'] ?? [$e->getMessage()])); } @@ -138,7 +136,7 @@ class PaymentMethod implements MethodInterface, LivewireMethodInterface * Payment view for the Rotessa. * * @param array $data - * @return \Illuminate\View\View + * @return \Illuminate\View\View */ public function paymentView(array $data): View { @@ -148,7 +146,7 @@ class PaymentMethod implements MethodInterface, LivewireMethodInterface return $this->authorizeView($data); } - return render('gateways.rotessa.bank_transfer.pay', $data ); + return render('gateways.rotessa.bank_transfer.pay', $data); } /** @@ -159,7 +157,7 @@ class PaymentMethod implements MethodInterface, LivewireMethodInterface public function paymentResponse(PaymentResponseRequest $request) { - $response= null; + $response = null; $customer = null; try { @@ -171,35 +169,38 @@ class PaymentMethod implements MethodInterface, LivewireMethodInterface ->where('token', $request->input('source')) ->first(); - if(!$customer) throw new \Exception('Client gateway token not found!', SystemLog::TYPE_ROTESSA); + if (!$customer) { + throw new \Exception('Client gateway token not found!', SystemLog::TYPE_ROTESSA); + } - $transaction = array_merge($this->transaction,[ + $transaction = array_merge($this->transaction, [ 'amount' => $request->input('amount'), 'process_date' => now()->addSeconds($customer->client->utc_offset())->format('Y-m-d'), 'comment' => $this->rotessa->getDescription(false), 'customer_id' => $customer->gateway_customer_reference, ]); - $response = $this->rotessa->gatewayRequest('post','transaction_schedules', $transaction); - - if($response->failed()) - $response->throw(); - + $response = $this->rotessa->gatewayRequest('post', 'transaction_schedules', $transaction); + + if ($response->failed()) { + $response->throw(); + } + $response = $response->json(); - return $this->processPendingPayment($response['id'], (float) $response['amount'], PaymentType::ACSS , $customer->token); - } catch(\Throwable $e) { - $this->processUnsuccessfulPayment( new \Exception($e->getMessage(), (int) $e->getCode()) ); + return $this->processPendingPayment($response['id'], (float) $response['amount'], PaymentType::ACSS, $customer->token); + } catch (\Throwable $e) { + $this->processUnsuccessfulPayment(new \Exception($e->getMessage(), (int) $e->getCode())); } } - public function processPendingPayment($payment_id, float $amount, int $gateway_type_id, $payment_method ) + public function processPendingPayment($payment_id, float $amount, int $gateway_type_id, $payment_method) { $data = [ 'payment_method' => $payment_method, 'payment_type' => $gateway_type_id, 'amount' => $amount, - 'transaction_reference' =>$payment_id, + 'transaction_reference' => $payment_id, 'gateway_type_id' => $gateway_type_id, ]; $payment = $this->rotessa->createPayment($data, Payment::STATUS_PENDING); @@ -241,7 +242,7 @@ class PaymentMethod implements MethodInterface, LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { if (array_key_exists('authorize_then_redirect', $data)) { return 'gateways.rotessa.bank_transfer.authorize_livewire'; @@ -249,11 +250,11 @@ class PaymentMethod implements MethodInterface, LivewireMethodInterface return 'gateways.rotessa.bank_transfer.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $data['gateway'] = $this->rotessa; $data['amount'] = $data['total']['amount_with_fee']; @@ -262,18 +263,18 @@ class PaymentMethod implements MethodInterface, LivewireMethodInterface $data['currency'] = $this->rotessa->client->getCurrencyCode(); $data['frequency'] = 'Once'; $data['installments'] = 1; - $data['invoice_nums'] = $data['invoices']->pluck('invoice_number')->join(', '); + $data['invoice_nums'] = $data['invoices']->pluck('invoice_number')->join(', '); $data['payment_hash'] = $this->rotessa->payment_hash->hash; if (count($data['tokens']) === 0) { $data['authorize_then_redirect'] = true; $data['contact'] = collect($data['client']->contacts->first()->toArray())->merge([ - 'home_phone' => $data['client']->phone, + 'home_phone' => $data['client']->phone, 'custom_identifier' => $data['client']->number, 'name' => $data['client']->name, 'id' => null - ] )->all(); + ])->all(); $data['gateway'] = $this->rotessa; $data['gateway_type_id'] = GatewayType::ACSS ; $data['account'] = [ diff --git a/app/PaymentDrivers/RotessaPaymentDriver.php b/app/PaymentDrivers/RotessaPaymentDriver.php index 05d941c4dc..833a312f4d 100644 --- a/app/PaymentDrivers/RotessaPaymentDriver.php +++ b/app/PaymentDrivers/RotessaPaymentDriver.php @@ -51,15 +51,15 @@ class RotessaPaymentDriver extends BaseDriver { $types = []; - /* - // TODO: needs to test with US test account - if ($this->client - && $this->client->currency() - && in_array($this->client->currency()->code, ['USD']) - && isset($this->client->country) - && in_array($this->client->country->iso_3166_2, ['US'])) { - $types[] = GatewayType::BANK_TRANSFER; - }*/ + /* + // TODO: needs to test with US test account + if ($this->client + && $this->client->currency() + && in_array($this->client->currency()->code, ['USD']) + && isset($this->client->country) + && in_array($this->client->country->iso_3166_2, ['US'])) { + $types[] = GatewayType::BANK_TRANSFER; + }*/ if ($this->client && $this->client->currency() @@ -68,11 +68,11 @@ class RotessaPaymentDriver extends BaseDriver && in_array($this->client->country->iso_3166_2, ['CA'])) { $types[] = GatewayType::ACSS; } - + return $types; } - + public function setPaymentMethod($payment_method_id) { $class = self::$methods[$payment_method_id]; @@ -80,7 +80,7 @@ class RotessaPaymentDriver extends BaseDriver return $this; } - + public function authorizeView(array $data) { return $this->payment_method->authorizeView($data); @@ -101,57 +101,59 @@ class RotessaPaymentDriver extends BaseDriver return $this->payment_method->paymentResponse($request); } - public function importCustomers() { - - try { - $result = $this->gatewayRequest('get','customers',[]); //Rotessa customers + public function importCustomers() + { - if($result->failed()) + try { + $result = $this->gatewayRequest('get', 'customers', []); //Rotessa customers + + if ($result->failed()) { $result->throw(); - + } + $customers = collect($result->json())->unique('email'); //Rotessa customer emails - + $client_emails = $customers->pluck('email')->all(); $company_id = $this->company_gateway->company->id; // get existing customers $client_contacts = ClientContact::where('company_id', $company_id) - ->whereIn('email', $client_emails ) - ->whereHas('client', function ($q){ + ->whereIn('email', $client_emails) + ->whereHas('client', function ($q) { $q->where('is_deleted', false); }) ->whereNull('deleted_at') ->get(); - $client_contacts = $client_contacts->map(function($item, $key) use ($customers) { - return array_merge($customers->firstWhere("email", $item->email),['custom_identifier' => $item->client->number, 'identifier' => $item->client->number, 'client_id' => $item->client->id ]); - } ); + $client_contacts = $client_contacts->map(function ($item, $key) use ($customers) { + return array_merge($customers->firstWhere("email", $item->email), ['custom_identifier' => $item->client->number, 'identifier' => $item->client->number, 'client_id' => $item->client->id ]); + }); // create payment methods collect($client_contacts)->each( - function($contact) { - + function ($contact) { + $contact = (object)$contact; - - $result = $this->gatewayRequest("get","customers/{$contact->id}"); + + $result = $this->gatewayRequest("get", "customers/{$contact->id}"); $result = $result->json(); - + $this->client = Client::query()->find($contact->client_id); - + $customer = array_merge($result, ['id' => $contact->id, 'custom_identifier' => $contact->custom_identifier ]); $this->findOrCreateCustomer($customer); } ); - + // create new clients from rotessa customers $client_emails = $client_contacts->pluck('email')->all(); $client_contacts = $customers->filter(function ($value, $key) use ($client_emails) { return !in_array(((object) $value)->email, $client_emails); - })->each( function($customer) use ($company_id) { - + })->each(function ($customer) use ($company_id) { + $customer = $this->gatewayRequest("get", "customers/{$customer['id']}")->json(); $settings = ClientSettings::defaults(); @@ -160,13 +162,13 @@ class RotessaPaymentDriver extends BaseDriver $client = (\App\Factory\ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id))->fill( [ 'address1' => $customer->address['address_1'] ?? '', - 'address2' =>$customer->address['address_2'] ?? '', + 'address2' => $customer->address['address_2'] ?? '', 'city' => $customer->address['city'] ?? '', 'postal_code' => $customer->address['postal_code'] ?? '', 'state' => $customer->address['province_code'] ?? '', 'country_id' => empty($customer->transit_number) ? 840 : 124, - 'routing_id' => empty(($r = $customer->routing_number))? null : $r, - "number" => str_pad($customer->account_number,3,'0',STR_PAD_LEFT), + 'routing_id' => empty(($r = $customer->routing_number)) ? null : $r, + "number" => str_pad($customer->account_number, 3, '0', STR_PAD_LEFT), "settings" => $settings, ] ); @@ -185,61 +187,63 @@ class RotessaPaymentDriver extends BaseDriver }); } catch (\Throwable $th) { - $data = [ - 'transaction_reference' => null, - 'transaction_response' => $th->getMessage(), - 'success' => false, - 'description' => $th->getMessage(), - 'code' =>(int) $th->getCode() - ]; - SystemLogger::dispatch(['server_response' => $th->getMessage(), 'data' => $data], SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_FAILURE, SystemLog::TYPE_ROTESSA , $this->company_gateway->client , $this->company_gateway->company); - + $data = [ + 'transaction_reference' => null, + 'transaction_response' => $th->getMessage(), + 'success' => false, + 'description' => $th->getMessage(), + 'code' => (int) $th->getCode() + ]; + SystemLogger::dispatch(['server_response' => $th->getMessage(), 'data' => $data], SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_FAILURE, SystemLog::TYPE_ROTESSA, $this->company_gateway->client, $this->company_gateway->company); + throw $th; } return true; } - + public function findOrCreateCustomer(array $data) { - $result = null; + $result = null; try { - + $existing = ClientGatewayToken::query() ->where('company_gateway_id', $this->company_gateway->id) ->where('client_id', $this->client->id) - ->where('is_deleted',0) - ->where('gateway_customer_reference', Arr::only($data,'id')) + ->where('is_deleted', 0) + ->where('gateway_customer_reference', Arr::only($data, 'id')) ->exists(); - if ($existing) + if ($existing) { return true; - - if(!isset($data['id'])) { + } + + if (!isset($data['id'])) { $result = $this->gatewayRequest('post', 'customers', $data); - if($result->failed()) + if ($result->failed()) { $result->throw(); + } $data = $result->json(); nlog($data); } - + $payment_method_id = GatewayType::ACSS; - $gateway_token = $this->storeGatewayToken( [ + $gateway_token = $this->storeGatewayToken([ 'payment_meta' => ['brand' => 'Bank Transfer', 'last4' => substr($data['account_number'], -4), 'type' => GatewayType::ACSS ], 'token' => join(".", Arr::only($data, ['id','custom_identifier'])), 'payment_method_id' => $payment_method_id , ], [ - 'gateway_customer_reference' => $data['id'], - 'routing_number' => Arr::has($data,'routing_number') ? $data['routing_number'] : $data['transit_number'] + 'gateway_customer_reference' => $data['id'], + 'routing_number' => Arr::has($data, 'routing_number') ? $data['routing_number'] : $data['transit_number'] ]); - + return $data['id']; - + } catch (\Throwable $th) { $data = [ @@ -250,14 +254,13 @@ class RotessaPaymentDriver extends BaseDriver 'code' => 500 ]; - SystemLogger::dispatch(['server_response' => $data, 'data' => []], SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_FAILURE, 880 , $this->client, $this->company_gateway->company); - - try{ - $errors = explode("422:", $th->getMessage())[1]; - } - catch(\Exception){ - $errors = 'Unknown error occured'; - } + SystemLogger::dispatch(['server_response' => $data, 'data' => []], SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_FAILURE, 880, $this->client, $this->company_gateway->company); + + try { + $errors = explode("422:", $th->getMessage())[1]; + } catch (\Exception) { + $errors = 'Unknown error occured'; + } throw new \Exception($errors, $th->getCode()); } diff --git a/app/PaymentDrivers/Square/CreditCard.php b/app/PaymentDrivers/Square/CreditCard.php index f95428c04e..d11e67f8d6 100644 --- a/app/PaymentDrivers/Square/CreditCard.php +++ b/app/PaymentDrivers/Square/CreditCard.php @@ -132,14 +132,14 @@ class CreditCard implements MethodInterface, LivewireMethodInterface $body = json_decode($response->getBody()); - if($request->store_card) { + if ($request->store_card) { $this->createCard($body->payment->id); } return $this->processSuccessfulPayment($response); } - if(is_array($response)) { + if (is_array($response)) { nlog("square"); nlog($response); } @@ -239,15 +239,15 @@ class CreditCard implements MethodInterface, LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return 'gateways.square.credit_card.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { $data['gateway'] = $this->square_driver; $data['amount'] = $this->square_driver->payment_hash->data->amount_with_fee; diff --git a/app/PaymentDrivers/Square/SquareWebhook.php b/app/PaymentDrivers/Square/SquareWebhook.php index bdb372905d..f474396891 100644 --- a/app/PaymentDrivers/Square/SquareWebhook.php +++ b/app/PaymentDrivers/Square/SquareWebhook.php @@ -84,7 +84,7 @@ class SquareWebhook implements ShouldQueue default => $payment_status = false, }; - if(!$payment_status) { + if (!$payment_status) { nlog("Square Webhook - Payment Status Not Found or not worthy of processing"); nlog($this->webhook_array); } @@ -92,7 +92,7 @@ class SquareWebhook implements ShouldQueue $payment = $this->retrieveOrCreatePayment($payment_id, $payment_status); /** If the status was pending and now is reporting as Failed / Cancelled - process failure path */ - if($payment->status_id == Payment::STATUS_PENDING && in_array($payment_status, [Payment::STATUS_CANCELLED, Payment::STATUS_FAILED])) { + if ($payment->status_id == Payment::STATUS_PENDING && in_array($payment_status, [Payment::STATUS_CANCELLED, Payment::STATUS_FAILED])) { $payment->service()->deletePayment(); if ($this->driver->payment_hash) { @@ -111,7 +111,7 @@ class SquareWebhook implements ShouldQueue $error ); - } elseif($payment->status_id == Payment::STATUS_PENDING && in_array($payment_status, [Payment::STATUS_COMPLETED, Payment::STATUS_COMPLETED])) { + } elseif ($payment->status_id == Payment::STATUS_PENDING && in_array($payment_status, [Payment::STATUS_COMPLETED, Payment::STATUS_COMPLETED])) { $payment->status_id = Payment::STATUS_COMPLETED; $payment->save(); } @@ -123,7 +123,7 @@ class SquareWebhook implements ShouldQueue $payment = Payment::withTrashed()->where('transaction_reference', $payment_reference)->first(); - if($payment) { + if ($payment) { nlog("payment found, returning"); return $payment; } @@ -133,7 +133,7 @@ class SquareWebhook implements ShouldQueue nlog("searching square for payment"); - if($apiResponse->isSuccess()) { + if ($apiResponse->isSuccess()) { nlog("Searching by payment hash"); diff --git a/app/PaymentDrivers/SquarePaymentDriver.php b/app/PaymentDrivers/SquarePaymentDriver.php index 456d69586e..c2f05e100e 100644 --- a/app/PaymentDrivers/SquarePaymentDriver.php +++ b/app/PaymentDrivers/SquarePaymentDriver.php @@ -133,7 +133,7 @@ class SquarePaymentDriver extends BaseDriver $status = $refundPaymentResponse->getRefund()->getStatus(); - if(in_array($status, ['COMPLETED', 'PENDING'])) { + if (in_array($status, ['COMPLETED', 'PENDING'])) { $transaction_reference = $refundPaymentResponse->getRefund()->getId(); @@ -158,7 +158,7 @@ class SquarePaymentDriver extends BaseDriver ); return $data; - } elseif(in_array($status, ['REJECTED', 'FAILED'])) { + } elseif (in_array($status, ['REJECTED', 'FAILED'])) { $transaction_reference = $refundPaymentResponse->getRefund()->getId(); @@ -296,8 +296,8 @@ class SquarePaymentDriver extends BaseDriver if ($api_response->isSuccess()) { //array of WebhookSubscription objects - foreach($api_response->getResult()->getSubscriptions() ?? [] as $subscription) { - if($subscription->getName() == 'Invoice_Ninja_Webhook_Subscription') { + foreach ($api_response->getResult()->getSubscriptions() ?? [] as $subscription) { + if ($subscription->getName() == 'Invoice_Ninja_Webhook_Subscription') { return $subscription->getId(); } } @@ -331,7 +331,7 @@ class SquarePaymentDriver extends BaseDriver public function createWebhooks(): void { - if($this->checkWebhooks()) { + if ($this->checkWebhooks()) { return; } @@ -374,7 +374,7 @@ class SquarePaymentDriver extends BaseDriver $body = ''; $handle = fopen('php://input', 'r'); - while(!feof($handle)) { + while (!feof($handle)) { $body .= fread($handle, 1024); } @@ -399,7 +399,7 @@ class SquarePaymentDriver extends BaseDriver //getsubscriptionid here $subscription_id = $this->checkWebhooks(); - if(!$subscription_id) { + if (!$subscription_id) { nlog('No Subscription Found'); return; } @@ -471,20 +471,20 @@ class SquarePaymentDriver extends BaseDriver $client_repo = new ClientRepository(new ClientContactRepository()); - foreach($customers as $customer) { + foreach ($customers as $customer) { $data = (new SquareCustomerFactory())->convertToNinja($customer, $this->company_gateway->company); $client = ClientContact::where('company_id', $this->company_gateway->company_id)->where('email', $customer->getEmailAddress())->first()->client ?? false; - if(!$client) { + if (!$client) { $client = $client_repo->save($data, ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id)); } $this->client = $client; - foreach($data['cards'] as $card) { + foreach ($data['cards'] as $card) { - if(ClientGatewayToken::where('company_id', $this->company_gateway->company_id)->where('token', $card['token'])->exists()) { + if (ClientGatewayToken::where('company_id', $this->company_gateway->company_id)->where('token', $card['token'])->exists()) { continue; } @@ -560,7 +560,7 @@ class SquarePaymentDriver extends BaseDriver public function findOrCreateClient() { - if($customer_id = $this->findClient()) { + if ($customer_id = $this->findClient()) { return $customer_id; } diff --git a/app/PaymentDrivers/Stripe/ACH.php b/app/PaymentDrivers/Stripe/ACH.php index 90a0e042d9..68d651fa18 100644 --- a/app/PaymentDrivers/Stripe/ACH.php +++ b/app/PaymentDrivers/Stripe/ACH.php @@ -114,10 +114,10 @@ class ACH implements LivewireMethodInterface //double check here if we need to show the verification view. $this->stripe->init(); - if(substr($token->token, 0, 2) == 'pm') { + if (substr($token->token, 0, 2) == 'pm') { $pm = $this->stripe->getStripePaymentMethod($token->token); - if(!$pm->customer) { + if (!$pm->customer) { $meta = $token->meta; $meta->state = 'unauthorized'; @@ -135,7 +135,7 @@ class ACH implements LivewireMethodInterface ->with('message', __('texts.payment_method_verified')); } - if($token->meta->next_action) { + if ($token->meta->next_action) { return redirect($token->meta->next_action); } @@ -202,7 +202,7 @@ class ACH implements LivewireMethodInterface { $data = $this->paymentData($data); - if(!$data['authorized']){ + if (!$data['authorized']) { $token = $data['tokens'][0]; return redirect()->route('client.payment_methods.show', $token->hashed_id); } @@ -585,7 +585,7 @@ class ACH implements LivewireMethodInterface 'company_id' => $this->stripe->client->company_id, ])->first(); - if($token) { + if ($token) { return $token; } @@ -619,7 +619,7 @@ class ACH implements LivewireMethodInterface $meta = $token->meta; - if(isset($meta->state) && $meta->state == 'unauthorized') { + if (isset($meta->state) && $meta->state == 'unauthorized') { $data['authorized'] = false; // return redirect()->route('client.payment_methods.show', $token->hashed_id); } diff --git a/app/PaymentDrivers/Stripe/ACSS.php b/app/PaymentDrivers/Stripe/ACSS.php index 7e5f12f67e..056e3583cb 100644 --- a/app/PaymentDrivers/Stripe/ACSS.php +++ b/app/PaymentDrivers/Stripe/ACSS.php @@ -168,7 +168,7 @@ class ACSS implements LivewireMethodInterface public function paymentData(array $data): array { - if(count($data['tokens']) == 0) { + if (count($data['tokens']) == 0) { $hash = Str::random(32); Cache::put($hash, $data, 3600); @@ -180,7 +180,7 @@ class ACSS implements LivewireMethodInterface $data['company_gateway'] = $this->stripe->company_gateway; $data['customer'] = $this->stripe->findOrCreateCustomer()->id; $data['country'] = $this->stripe->client->country->iso_3166_2; - + $intent = \Stripe\SetupIntent::create([ 'usage' => 'off_session', 'payment_method_types' => ['acss_debit'], @@ -197,7 +197,7 @@ class ACSS implements LivewireMethodInterface ], ], ], $this->stripe->stripe_connect_auth); - + $data['pi_client_secret'] = $intent->client_secret; return $data; @@ -235,7 +235,7 @@ class ACSS implements LivewireMethodInterface 'invoices' => collect($data['invoices'])->map(fn ($invoice) => $invoice['invoice_id'])->toArray(), 'action' => 'payment', ]; - + $request = new ProcessInvoicesInBulkRequest(); $request->replace($data); @@ -407,8 +407,8 @@ class ACSS implements LivewireMethodInterface return $this->stripe->processInternallyFailedPayment($this->stripe, $e); } } - - public function livewirePaymentView(array $data): string + + public function livewirePaymentView(array $data): string { if (array_key_exists('needs_mandate_generate', $data)) { return 'gateways.stripe.acss.authorize_livewire'; diff --git a/app/PaymentDrivers/Stripe/Alipay.php b/app/PaymentDrivers/Stripe/Alipay.php index 7ab38a7d1d..074393aaeb 100644 --- a/app/PaymentDrivers/Stripe/Alipay.php +++ b/app/PaymentDrivers/Stripe/Alipay.php @@ -36,9 +36,9 @@ class Alipay implements LivewireMethodInterface public function paymentView(array $data) { - + $data = $this->paymentData($data); - + return render('gateways.stripe.alipay.pay', $data); } @@ -134,15 +134,15 @@ class Alipay implements LivewireMethodInterface /** * @inheritDoc */ - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return 'gateways.stripe.alipay.pay_livewire'; } - + /** * @inheritDoc */ - public function paymentData(array $data): array + public function paymentData(array $data): array { try { $intent = \Stripe\PaymentIntent::create([ @@ -156,11 +156,10 @@ class Alipay implements LivewireMethodInterface 'gateway_type_id' => GatewayType::ALIPAY, ], ], $this->stripe->stripe_connect_auth); - } - catch(\Throwable $e){ + } catch (\Throwable $e) { throw new PaymentFailed($e->getMessage(), $e->getCode()); - + } $data['gateway'] = $this->stripe; diff --git a/app/PaymentDrivers/Stripe/Bancontact.php b/app/PaymentDrivers/Stripe/Bancontact.php index e776377c93..e161cb11eb 100644 --- a/app/PaymentDrivers/Stripe/Bancontact.php +++ b/app/PaymentDrivers/Stripe/Bancontact.php @@ -96,7 +96,7 @@ class Bancontact implements LivewireMethodInterface ); -return redirect()->route('client.payments.show', ['payment' => $payment->hashed_id]); + return redirect()->route('client.payments.show', ['payment' => $payment->hashed_id]); } public function processUnsuccessfulPayment() diff --git a/app/PaymentDrivers/Stripe/BankTransfer.php b/app/PaymentDrivers/Stripe/BankTransfer.php index f8d0e26b88..a3c909bc91 100644 --- a/app/PaymentDrivers/Stripe/BankTransfer.php +++ b/app/PaymentDrivers/Stripe/BankTransfer.php @@ -331,4 +331,4 @@ class BankTransfer implements LivewireMethodInterface { return 'gateways.stripe.bank_transfer.pay_livewire'; } -} \ No newline at end of file +} diff --git a/app/PaymentDrivers/Stripe/EPS.php b/app/PaymentDrivers/Stripe/EPS.php index fc70a60793..10f39b917d 100644 --- a/app/PaymentDrivers/Stripe/EPS.php +++ b/app/PaymentDrivers/Stripe/EPS.php @@ -96,7 +96,7 @@ class EPS implements LivewireMethodInterface ); -return redirect()->route('client.payments.show', ['payment' => $payment->hashed_id]); + return redirect()->route('client.payments.show', ['payment' => $payment->hashed_id]); } public function processUnsuccessfulPayment() diff --git a/app/PaymentDrivers/Stripe/FPX.php b/app/PaymentDrivers/Stripe/FPX.php index 0922b8c77d..c734f960ec 100644 --- a/app/PaymentDrivers/Stripe/FPX.php +++ b/app/PaymentDrivers/Stripe/FPX.php @@ -89,7 +89,7 @@ class FPX implements LivewireMethodInterface $this->stripe->client, $this->stripe->client->company, ); - + return redirect()->route('client.payments.show', ['payment' => $payment->hashed_id]); } diff --git a/app/PaymentDrivers/Stripe/ImportCustomers.php b/app/PaymentDrivers/Stripe/ImportCustomers.php index c58193f104..70779a2f2b 100644 --- a/app/PaymentDrivers/Stripe/ImportCustomers.php +++ b/app/PaymentDrivers/Stripe/ImportCustomers.php @@ -126,12 +126,12 @@ class ImportCustomers $client->settings = $settings; } - }else { + } else { $settings = $client->settings; $settings->currency_id = (string) $this->stripe->company_gateway->company->settings->currency_id; $client->settings = $settings; - + } $client->name = $customer->name ? $customer->name : $customer->email; diff --git a/app/PaymentDrivers/Stripe/Jobs/ChargeRefunded.php b/app/PaymentDrivers/Stripe/Jobs/ChargeRefunded.php index 524139527e..351425bfb1 100644 --- a/app/PaymentDrivers/Stripe/Jobs/ChargeRefunded.php +++ b/app/PaymentDrivers/Stripe/Jobs/ChargeRefunded.php @@ -59,7 +59,7 @@ class ChargeRefunded implements ShouldQueue $payment_hash_key = $source['metadata']['payment_hash'] ?? null; - if(is_null($payment_hash_key)){ + if (is_null($payment_hash_key)) { nlog("charge.refunded not found"); return; } @@ -79,7 +79,7 @@ class ChargeRefunded implements ShouldQueue ->first(); //don't touch if already refunded - if(!$payment || $payment->status_id == Payment::STATUS_REFUNDED || $payment->is_deleted){ + if (!$payment || $payment->status_id == Payment::STATUS_REFUNDED || $payment->is_deleted) { return; } @@ -94,79 +94,79 @@ class ChargeRefunded implements ShouldQueue return; } - usleep(rand(200000,300000)); + usleep(rand(200000, 300000)); $payment = $payment->fresh(); - if($payment->status_id == Payment::STATUS_PARTIALLY_REFUNDED){ + if ($payment->status_id == Payment::STATUS_PARTIALLY_REFUNDED) { //determine the delta in the refunded amount - how much has already been refunded and only apply the delta. - - if(floatval($payment->refunded) >= floatval($amount_refunded)) + + if (floatval($payment->refunded) >= floatval($amount_refunded)) { return; + } $amount_refunded -= $payment->refunded; } - + + $invoice_collection = $payment->paymentables + ->where('paymentable_type', 'invoices') + ->map(function ($pivot) { + return [ + 'invoice_id' => $pivot->paymentable_id, + 'amount' => $pivot->amount - $pivot->refunded + ]; + }); + + if ($invoice_collection->count() == 1 && $invoice_collection->first()['amount'] >= $amount_refunded) { + //If there is only one invoice- and we are refunding _less_ than the amount of the invoice, we can just refund the payment + $invoice_collection = $payment->paymentables - ->where('paymentable_type', 'invoices') - ->map(function ($pivot) { - return [ - 'invoice_id' => $pivot->paymentable_id, - 'amount' => $pivot->amount - $pivot->refunded - ]; - }); + ->where('paymentable_type', 'invoices') + ->map(function ($pivot) use ($amount_refunded) { + return [ + 'invoice_id' => $pivot->paymentable_id, + 'amount' => $amount_refunded + ]; + }); - if($invoice_collection->count() == 1 && $invoice_collection->first()['amount'] >= $amount_refunded) { - //If there is only one invoice- and we are refunding _less_ than the amount of the invoice, we can just refund the payment + } elseif ($invoice_collection->sum('amount') != $amount_refunded) { - $invoice_collection = $payment->paymentables - ->where('paymentable_type', 'invoices') - ->map(function ($pivot) use ($amount_refunded) { - return [ - 'invoice_id' => $pivot->paymentable_id, - 'amount' => $amount_refunded - ]; - }); + $refund_text = "A partial refund was processed for Payment #{$payment_hash->payment->number}.

This payment is associated with multiple invoices, so you will need to manually apply the refund to the correct invoice/s."; - } - elseif($invoice_collection->sum('amount') != $amount_refunded) { - - $refund_text = "A partial refund was processed for Payment #{$payment_hash->payment->number}.

This payment is associated with multiple invoices, so you will need to manually apply the refund to the correct invoice/s."; + App::setLocale($payment_hash->payment->company->getLocale()); - App::setLocale($payment_hash->payment->company->getLocale()); + $mo = new EmailObject(); + $mo->subject = "Refund processed in Stripe for multiple invoices, action required."; + $mo->body = $refund_text; + $mo->text_body = $refund_text; + $mo->company_key = $payment_hash->payment->company->company_key; + $mo->html_template = 'email.template.generic'; + $mo->to = [new Address($payment_hash->payment->company->owner()->email, $payment_hash->payment->company->owner()->present()->name())]; - $mo = new EmailObject(); - $mo->subject = "Refund processed in Stripe for multiple invoices, action required."; - $mo->body = $refund_text; - $mo->text_body = $refund_text; - $mo->company_key = $payment_hash->payment->company->company_key; - $mo->html_template = 'email.template.generic'; - $mo->to = [new Address($payment_hash->payment->company->owner()->email, $payment_hash->payment->company->owner()->present()->name())]; + Email::dispatch($mo, $payment_hash->payment->company); + return; - Email::dispatch($mo, $payment_hash->payment->company); - return; + } - } + $invoices = $invoice_collection->toArray(); - $invoices = $invoice_collection->toArray(); + $data = [ + 'id' => $payment->id, + 'amount' => $amount_refunded, + 'invoices' => $invoices, + 'date' => now()->format('Y-m-d'), + 'gateway_refund' => false, + 'email_receipt' => false, + 'via_webhook' => true, + ]; - $data = [ - 'id' => $payment->id, - 'amount' => $amount_refunded, - 'invoices' => $invoices, - 'date' => now()->format('Y-m-d'), - 'gateway_refund' => false, - 'email_receipt' => false, - 'via_webhook' => true, - ]; + nlog($data); - nlog($data); + $payment->refund($data); - $payment->refund($data); + $payment->private_notes .= 'Refunded via Stripe '; - $payment->private_notes .= 'Refunded via Stripe '; - - $payment->saveQuietly(); + $payment->saveQuietly(); } diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php index 28b4db9d7b..46b535ad85 100644 --- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php @@ -67,15 +67,15 @@ class PaymentIntentFailureWebhook implements ShouldQueue ->where('company_id', $company->id) ->where(function ($query) use ($transaction) { - if(isset($transaction['payment_intent'])) { + if (isset($transaction['payment_intent'])) { $query->where('transaction_reference', $transaction['payment_intent']); } - if(isset($transaction['payment_intent']) && isset($transaction['id'])) { + if (isset($transaction['payment_intent']) && isset($transaction['id'])) { $query->orWhere('transaction_reference', $transaction['id']); } - if(!isset($transaction['payment_intent']) && isset($transaction['id'])) { + if (!isset($transaction['payment_intent']) && isset($transaction['id'])) { $query->where('transaction_reference', $transaction['id']); } diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php index 42c4739f77..dac234d63e 100644 --- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php @@ -246,7 +246,7 @@ class PaymentIntentProcessingWebhook implements ShouldQueue } $driver->storeGatewayToken($data, $additional_data); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("failed to import payment methods"); nlog($e->getMessage()); } diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php index 1cde9a8fff..188e250e0b 100644 --- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php @@ -68,15 +68,15 @@ class PaymentIntentWebhook implements ShouldQueue ->where('company_id', $company->id) ->where(function ($query) use ($transaction) { - if(isset($transaction['payment_intent'])) { + if (isset($transaction['payment_intent'])) { $query->where('transaction_reference', $transaction['payment_intent']); } - if(isset($transaction['payment_intent']) && isset($transaction['id'])) { + if (isset($transaction['payment_intent']) && isset($transaction['id'])) { $query->orWhere('transaction_reference', $transaction['id']); } - if(!isset($transaction['payment_intent']) && isset($transaction['id'])) { + if (!isset($transaction['payment_intent']) && isset($transaction['id'])) { $query->where('transaction_reference', $transaction['id']); } @@ -100,7 +100,7 @@ class PaymentIntentWebhook implements ShouldQueue $company_gateway = CompanyGateway::query()->find($this->company_gateway_id); - if(!$company_gateway) { + if (!$company_gateway) { return; } @@ -278,7 +278,7 @@ class PaymentIntentWebhook implements ShouldQueue } $driver->storeGatewayToken($data, $additional_data); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("failed to import payment methods"); nlog($e->getMessage()); } diff --git a/app/PaymentDrivers/Stripe/Klarna.php b/app/PaymentDrivers/Stripe/Klarna.php index 9ec9f56d4b..1bd348158d 100644 --- a/app/PaymentDrivers/Stripe/Klarna.php +++ b/app/PaymentDrivers/Stripe/Klarna.php @@ -70,7 +70,7 @@ class Klarna implements LivewireMethodInterface //catch duplicate submissions. if ($pay_exists = Payment::query()->where('transaction_reference', $payment_intent)->first()) { - + return redirect()->route('client.payments.show', ['payment' => $pay_exists->hashed_id]); } diff --git a/app/PaymentDrivers/Stripe/SEPA.php b/app/PaymentDrivers/Stripe/SEPA.php index c82c1b6f29..b57b7a4f2c 100644 --- a/app/PaymentDrivers/Stripe/SEPA.php +++ b/app/PaymentDrivers/Stripe/SEPA.php @@ -201,7 +201,7 @@ class SEPA implements LivewireMethodInterface return $data; } - public function livewirePaymentView(array $data): string + public function livewirePaymentView(array $data): string { return 'gateways.stripe.sepa.pay_livewire'; } diff --git a/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php b/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php index 3d073bd18e..00c648640c 100644 --- a/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php +++ b/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php @@ -229,12 +229,13 @@ class UpdatePaymentMethods private function buildPaymentMethodMeta(PaymentMethod $method, $type_id) { - + switch ($type_id) { case GatewayType::CREDIT_CARD: - if($method->type == 'link') + if ($method->type == 'link') { return new \stdClass(); + } /** * @class \Stripe\PaymentMethod $method @@ -256,7 +257,7 @@ class UpdatePaymentMethods return $payment_meta; case GatewayType::ALIPAY: case GatewayType::SOFORT: - + return new \stdClass(); case GatewayType::SEPA: diff --git a/app/PaymentDrivers/Stripe/iDeal.php b/app/PaymentDrivers/Stripe/iDeal.php index 701b07ce8e..f9b73db56a 100644 --- a/app/PaymentDrivers/Stripe/iDeal.php +++ b/app/PaymentDrivers/Stripe/iDeal.php @@ -94,7 +94,7 @@ class iDeal implements LivewireMethodInterface $this->stripe->client->company, ); - return redirect()->route('client.payments.show', ['payment' => $payment->hashed_id]); + return redirect()->route('client.payments.show', ['payment' => $payment->hashed_id]); } public function processUnsuccessfulPayment() diff --git a/app/PaymentDrivers/StripePaymentDriver.php b/app/PaymentDrivers/StripePaymentDriver.php index 220cc1fc50..bb7f516e10 100644 --- a/app/PaymentDrivers/StripePaymentDriver.php +++ b/app/PaymentDrivers/StripePaymentDriver.php @@ -421,7 +421,7 @@ class StripePaymentDriver extends BaseDriver public function processPaymentViewData(array $data): array { - $data = $this->payment_method->paymentData($data); + $data = $this->payment_method->paymentData($data); $data['stripe_account_id'] = $this->company_gateway->getConfigField('account_id'); @@ -433,7 +433,7 @@ class StripePaymentDriver extends BaseDriver $token_billing_string = 'true'; - if($this->company_gateway->token_billing == 'off' || $this->company_gateway->token_billing == 'optin') { + if ($this->company_gateway->token_billing == 'off' || $this->company_gateway->token_billing == 'optin') { $token_billing_string = 'false'; } @@ -728,7 +728,7 @@ class StripePaymentDriver extends BaseDriver return response()->json([], 200); } - + if ($request->type === 'charge.refunded' && $request->data['object']['status'] == 'succeeded') { ChargeRefunded::dispatch($request->data, $request->company_key)->delay(now()->addSeconds(5)); @@ -742,15 +742,15 @@ class StripePaymentDriver extends BaseDriver ->where('company_id', $this->company_gateway->company_id) ->where(function ($query) use ($transaction) { - if(isset($transaction['payment_intent'])) { + if (isset($transaction['payment_intent'])) { $query->where('transaction_reference', $transaction['payment_intent']); } - if(isset($transaction['payment_intent']) && isset($transaction['id'])) { + if (isset($transaction['payment_intent']) && isset($transaction['id'])) { $query->orWhere('transaction_reference', $transaction['id']); } - if(!isset($transaction['payment_intent']) && isset($transaction['id'])) { + if (!isset($transaction['payment_intent']) && isset($transaction['id'])) { $query->where('transaction_reference', $transaction['id']); } @@ -760,7 +760,7 @@ class StripePaymentDriver extends BaseDriver if ($payment) { - if(isset($transaction['payment_method_details']['au_becs_debit'])) { + if (isset($transaction['payment_method_details']['au_becs_debit'])) { $payment->transaction_reference = $transaction['id']; } @@ -789,15 +789,15 @@ class StripePaymentDriver extends BaseDriver ->where('company_id', $this->company_gateway->company_id) ->where(function ($query) use ($transaction) { - if(isset($transaction['payment_intent'])) { + if (isset($transaction['payment_intent'])) { $query->where('transaction_reference', $transaction['payment_intent']); } - if(isset($transaction['payment_intent']) && isset($transaction['id'])) { + if (isset($transaction['payment_intent']) && isset($transaction['id'])) { $query->orWhere('transaction_reference', $transaction['id']); } - if(!isset($transaction['payment_intent']) && isset($transaction['id'])) { + if (!isset($transaction['payment_intent']) && isset($transaction['id'])) { $query->where('transaction_reference', $transaction['id']); } @@ -838,7 +838,7 @@ class StripePaymentDriver extends BaseDriver ->where('token', $request->data['object']['payment_method']) ->first(); - if($clientgateway) { + if ($clientgateway) { $clientgateway->delete(); } @@ -1041,7 +1041,7 @@ class StripePaymentDriver extends BaseDriver try { $this->verifyConnect(); return true; - } catch(\Exception $e) { + } catch (\Exception $e) { } @@ -1050,4 +1050,3 @@ class StripePaymentDriver extends BaseDriver } } - diff --git a/app/Providers/StaticServiceProvider.php b/app/Providers/StaticServiceProvider.php index 848bddb77b..e7c50eaf47 100644 --- a/app/Providers/StaticServiceProvider.php +++ b/app/Providers/StaticServiceProvider.php @@ -39,7 +39,7 @@ class StaticServiceProvider extends ServiceProvider /** @return \Illuminate\Support\Collection */ app()->singleton('currencies', function ($app) { - if($resource = Cache::get('currencies')) { + if ($resource = Cache::get('currencies')) { return $resource; } @@ -54,7 +54,7 @@ class StaticServiceProvider extends ServiceProvider /** @return \Illuminate\Support\Collection */ app()->singleton('languages', function ($app) { - if($resource = Cache::get('languages')) { + if ($resource = Cache::get('languages')) { return $resource; } @@ -69,7 +69,7 @@ class StaticServiceProvider extends ServiceProvider /** @return \Illuminate\Support\Collection */ app()->singleton('countries', function ($app) { - if($resource = Cache::get('countries')) { + if ($resource = Cache::get('countries')) { return $resource; } @@ -84,7 +84,7 @@ class StaticServiceProvider extends ServiceProvider /** @return \Illuminate\Support\Collection */ app()->singleton('payment_types', function ($app) { - if($resource = Cache::get('payment_types')) { + if ($resource = Cache::get('payment_types')) { return $resource; } @@ -101,7 +101,7 @@ class StaticServiceProvider extends ServiceProvider app()->singleton('banks', function ($app) { - if($resource = Cache::get('banks')) { + if ($resource = Cache::get('banks')) { return $resource; } @@ -117,7 +117,7 @@ class StaticServiceProvider extends ServiceProvider app()->singleton('date_formats', function ($app) { - if($resource = Cache::get('date_formats')) { + if ($resource = Cache::get('date_formats')) { return $resource; } @@ -133,7 +133,7 @@ class StaticServiceProvider extends ServiceProvider app()->singleton('timezones', function ($app) { - if($resource = Cache::get('timezones')) { + if ($resource = Cache::get('timezones')) { return $resource; } @@ -148,7 +148,7 @@ class StaticServiceProvider extends ServiceProvider /** @return \Illuminate\Support\Collection */ app()->singleton('gateways', function ($app) { - if($resource = Cache::get('gateways')) { + if ($resource = Cache::get('gateways')) { return $resource; } @@ -165,7 +165,7 @@ class StaticServiceProvider extends ServiceProvider app()->singleton('industries', function ($app) { - if($resource = Cache::get('industries')) { + if ($resource = Cache::get('industries')) { return $resource; } @@ -181,7 +181,7 @@ class StaticServiceProvider extends ServiceProvider app()->singleton('sizes', function ($app) { - if($resource = Cache::get('sizes')) { + if ($resource = Cache::get('sizes')) { return $resource; } @@ -196,7 +196,7 @@ class StaticServiceProvider extends ServiceProvider /** @return \Illuminate\Support\Collection */ app()->singleton('datetime_formats', function ($app) { - if($resource = Cache::get('datetime_formats')) { + if ($resource = Cache::get('datetime_formats')) { return $resource; } diff --git a/app/Repositories/ActivityRepository.php b/app/Repositories/ActivityRepository.php index 8882c963d6..7828f1243e 100644 --- a/app/Repositories/ActivityRepository.php +++ b/app/Repositories/ActivityRepository.php @@ -52,7 +52,7 @@ class ActivityRepository extends BaseRepository $activity->{$key} = $value; } - if($entity->company) { + if ($entity->company) { $activity->account_id = $entity->company->account_id; } @@ -100,7 +100,7 @@ class ActivityRepository extends BaseRepository return; } - if(get_class($entity) == PurchaseOrder::class) { + if (get_class($entity) == PurchaseOrder::class) { $backup = new Backup(); $entity->load('client'); diff --git a/app/Repositories/BankIntegrationRepository.php b/app/Repositories/BankIntegrationRepository.php index f4e3eddf92..7a71ae2405 100644 --- a/app/Repositories/BankIntegrationRepository.php +++ b/app/Repositories/BankIntegrationRepository.php @@ -43,7 +43,7 @@ class BankIntegrationRepository extends BaseRepository return $bank_integration; } - if(Ninja::isHosted()) { + if (Ninja::isHosted()) { $account = $bank_integration->account; @@ -53,7 +53,7 @@ class BankIntegrationRepository extends BaseRepository try { $yodlee->deleteAccount($bank_integration->bank_account_id); - } catch(\Exception $e) { + } catch (\Exception $e) { } diff --git a/app/Repositories/BankTransactionRepository.php b/app/Repositories/BankTransactionRepository.php index 8488f12938..b6bee0b605 100644 --- a/app/Repositories/BankTransactionRepository.php +++ b/app/Repositories/BankTransactionRepository.php @@ -48,7 +48,7 @@ class BankTransactionRepository extends BaseRepository public function unlink($bt) { - if($bt->payment()->exists()) { + if ($bt->payment()->exists()) { $bt->payment->transaction_id = null; $bt->payment_id = null; } diff --git a/app/Repositories/BaseRepository.php b/app/Repositories/BaseRepository.php index b20d346cb9..a9e9c3b450 100644 --- a/app/Repositories/BaseRepository.php +++ b/app/Repositories/BaseRepository.php @@ -147,7 +147,7 @@ class BaseRepository * @throws \ReflectionException */ protected function alternativeSave($data, $model) - { + { if (array_key_exists('client_id', $data)) { $model->client_id = $data['client_id']; } @@ -202,9 +202,10 @@ class BaseRepository $model->saveQuietly(); - if(method_exists($model, 'searchable')) + if (method_exists($model, 'searchable')) { $model->searchable(); - + } + /* Model now persisted, now lets do some child tasks */ if ($model instanceof Invoice) { @@ -324,12 +325,10 @@ class BaseRepository } /** If Peppol is enabled - we will save the e_invoice document here at this point, document will not update after being sent */ - if((!isset($model->backup) || !property_exists($model->backup, 'guid')) && $client->getSetting('e_invoice_type') == 'PEPPOL' && $model->company->legal_entity_id) - { - try{ + if ((!isset($model->backup) || !property_exists($model->backup, 'guid')) && $client->getSetting('e_invoice_type') == 'PEPPOL' && $model->company->legal_entity_id) { + try { $model->service()->getEInvoice(); - } - catch(\Throwable $e){ + } catch (\Throwable $e) { nlog("EXCEPTION:: BASEREPOSITORY:: Error generating e_invoice for model {$model->id}"); nlog($e->getMessage()); } @@ -396,24 +395,23 @@ class BaseRepository public function bulkUpdate(\Illuminate\Database\Eloquent\Builder $model, string $column, mixed $new_value): void { /** Handle taxes being updated */ - if(in_array($column, ['tax1','tax2','tax3'])) { + if (in_array($column, ['tax1','tax2','tax3'])) { $parts = explode("||", $new_value); $tax_name_column = str_replace("tax", "tax_name", $column); $tax_rate_column = str_replace("tax", "tax_rate", $column); /** Harvest the tax name and rate */ - if (count($parts) == 2) - { - + if (count($parts) == 2) { + $rate = filter_var($parts[1], FILTER_VALIDATE_FLOAT); $tax_name = $parts[0]; - - if ($rate === false) + + if ($rate === false) { return; - - } - else { //else we need to clear the value + } + + } else { //else we need to clear the value $rate = 0; $tax_name = ""; diff --git a/app/Repositories/ClientGatewayTokenRepository.php b/app/Repositories/ClientGatewayTokenRepository.php index 0c1a7e3192..7546b2f2c1 100644 --- a/app/Repositories/ClientGatewayTokenRepository.php +++ b/app/Repositories/ClientGatewayTokenRepository.php @@ -21,10 +21,11 @@ class ClientGatewayTokenRepository extends BaseRepository public function save(array $data, ClientGatewayToken $client_gateway_token): ClientGatewayToken { $client_gateway_token->fill($data); - - if(isset($data['company_gateway_id'])) + + if (isset($data['company_gateway_id'])) { $client_gateway_token->company_gateway_id = $data['company_gateway_id']; - + } + if (isset($data['is_default']) && !boolval($data['is_default'])) { $client_gateway_token->is_default = false; } diff --git a/app/Repositories/ClientRepository.php b/app/Repositories/ClientRepository.php index 535e160637..5b6a3015d8 100644 --- a/app/Repositories/ClientRepository.php +++ b/app/Repositories/ClientRepository.php @@ -106,7 +106,7 @@ class ClientRepository extends BaseRepository if (array_key_exists('contacts', $contact_data) || $client->contacts()->count() == 0) { $this->contact_repo->save($contact_data, $client); } - + return $client; } diff --git a/app/Repositories/CompanyRepository.php b/app/Repositories/CompanyRepository.php index 46716a0a90..1536617240 100644 --- a/app/Repositories/CompanyRepository.php +++ b/app/Repositories/CompanyRepository.php @@ -43,7 +43,7 @@ class CompanyRepository extends BaseRepository // nlog($data); /** Only required to handle v4 migration workloads */ - if(Ninja::isHosted() && $company->isDirty('is_disabled') && !$company->is_disabled) { + if (Ninja::isHosted() && $company->isDirty('is_disabled') && !$company->is_disabled) { Ninja::triggerForwarding($company->company_key, $company->owner()->email); } @@ -51,14 +51,14 @@ class CompanyRepository extends BaseRepository $company->saveSettings($data['settings'], $company); } - if(isset($data['smtp_username'])) { + if (isset($data['smtp_username'])) { $company->smtp_username = $data['smtp_username']; } - if(isset($data['smtp_password'])) { + if (isset($data['smtp_password'])) { $company->smtp_password = $data['smtp_password']; } - + if (isset($data['e_invoice'])) { $company->e_invoice = $data['e_invoice']; } diff --git a/app/Repositories/DocumentRepository.php b/app/Repositories/DocumentRepository.php index e9c104c2a9..851c27b217 100644 --- a/app/Repositories/DocumentRepository.php +++ b/app/Repositories/DocumentRepository.php @@ -23,8 +23,9 @@ class DocumentRepository extends BaseRepository $document->deleteFile(); $document->forceDelete(); - if($document->documentable) + if ($document->documentable) { $document->documentable->touch(); + } } public function restore($document) diff --git a/app/Repositories/ExpenseRepository.php b/app/Repositories/ExpenseRepository.php index b42b2b3710..e84c1fbde7 100644 --- a/app/Repositories/ExpenseRepository.php +++ b/app/Repositories/ExpenseRepository.php @@ -48,9 +48,9 @@ class ExpenseRepository extends BaseRepository $payment_date = isset($data['payment_date']) ? $data['payment_date'] : false; - if($payment_date && $payment_date == $expense->payment_date) { + if ($payment_date && $payment_date == $expense->payment_date) { //do nothing - } elseif($payment_date && strlen($payment_date) > 1 && $user->company()->notify_vendor_when_paid && (isset($data['vendor_id']) || $expense->vendor_id)) { + } elseif ($payment_date && strlen($payment_date) > 1 && $user->company()->notify_vendor_when_paid && (isset($data['vendor_id']) || $expense->vendor_id)) { $this->notify_vendor = true; } @@ -70,11 +70,11 @@ class ExpenseRepository extends BaseRepository $this->saveDocuments($data['documents'], $expense); } - if($this->notify_vendor) { + if ($this->notify_vendor) { VendorExpenseNotify::dispatch($expense, $expense->company->db); } - if($payment_date && strlen($payment_date) > 1 && $expense->purchase_order) { + if ($payment_date && strlen($payment_date) > 1 && $expense->purchase_order) { $purchase_order = $expense->purchase_order; $purchase_order->balance = round($purchase_order->amount - $expense->amount, 2); $purchase_order->paid_to_date = $expense->amount; @@ -122,7 +122,7 @@ class ExpenseRepository extends BaseRepository $expense->exchange_rate = $exchange_rate->exchangeRate($expense_currency, $company_currency, Carbon::parse($expense->date)); $expense->invoice_currency_id = $company_currency; - + return $expense; } @@ -144,7 +144,7 @@ class ExpenseRepository extends BaseRepository $expense->transaction->expense_id = $exp_ids; - if(strlen($exp_ids) <= 2) { + if (strlen($exp_ids) <= 2) { $expense->transaction->status_id = 1; } diff --git a/app/Repositories/GroupSettingRepository.php b/app/Repositories/GroupSettingRepository.php index dc19f07af3..53c8ca4f9d 100644 --- a/app/Repositories/GroupSettingRepository.php +++ b/app/Repositories/GroupSettingRepository.php @@ -19,11 +19,11 @@ class GroupSettingRepository extends BaseRepository public function save($data, GroupSetting $group_setting): ?GroupSetting { - if(isset($data['settings']['translations'])) { + if (isset($data['settings']['translations'])) { unset($data['settings']['translations']); } - if(isset($data['settings']['pdf_variables'])) { + if (isset($data['settings']['pdf_variables'])) { unset($data['settings']['pdf_variables']); } diff --git a/app/Repositories/Import/Quickbooks/Transformers/Transformer.php b/app/Repositories/Import/Quickbooks/Transformers/Transformer.php index 656e3288f6..7dbc85e061 100644 --- a/app/Repositories/Import/Quickbooks/Transformers/Transformer.php +++ b/app/Repositories/Import/Quickbooks/Transformers/Transformer.php @@ -8,7 +8,7 @@ class Transformer { public function transform(array $items, string $type): Collection { - if(!method_exists($this, ($method = "transform{$type}s"))) { + if (!method_exists($this, ($method = "transform{$type}s"))) { throw new \InvalidArgumentException("Unknown type: $type"); } diff --git a/app/Repositories/InvoiceRepository.php b/app/Repositories/InvoiceRepository.php index 2ecef3fe4b..3b6812f2c8 100644 --- a/app/Repositories/InvoiceRepository.php +++ b/app/Repositories/InvoiceRepository.php @@ -100,7 +100,7 @@ class InvoiceRepository extends BaseRepository $invoice = $invoice->service()->handleRestore()->save(); /* If the reverse did not succeed due to rules, then do not restore / unarchive */ - if($invoice->is_deleted) { + if ($invoice->is_deleted) { return $invoice; } diff --git a/app/Repositories/PaymentRepository.php b/app/Repositories/PaymentRepository.php index 13b4a4f7c7..0349a5b335 100644 --- a/app/Repositories/PaymentRepository.php +++ b/app/Repositories/PaymentRepository.php @@ -109,7 +109,7 @@ class PaymentRepository extends BaseRepository /*Fill the payment*/ $fill_data = $data; - if($this->import_mode && isset($fill_data['invoices'])) { + if ($this->import_mode && isset($fill_data['invoices'])) { unset($fill_data['invoices']); } diff --git a/app/Repositories/ProjectRepository.php b/app/Repositories/ProjectRepository.php index 80fb7a1f1b..fb37139098 100644 --- a/app/Repositories/ProjectRepository.php +++ b/app/Repositories/ProjectRepository.php @@ -32,9 +32,9 @@ class ProjectRepository extends BaseRepository $uninvoiced_tasks = $project->tasks() ->withTrashed() ->whereNull('invoice_id') - ->where('is_deleted',0) + ->where('is_deleted', 0) ->cursor() - ->each(function ($task) use(&$lines){ + ->each(function ($task) use (&$lines) { $item = new InvoiceItem(); $item->quantity = $task->getQuantity(); @@ -48,36 +48,36 @@ class ProjectRepository extends BaseRepository $lines[] = $item; }); - + $unpaid_expenses = $project->expenses() ->withTrashed() ->where('should_be_invoiced', true) ->whereNull('payment_date') ->cursor() - ->each(function ($expense) use(&$lines){ - - $item = new InvoiceItem(); - $item->quantity = 1; - $item->cost = $expense->foreign_amount > 0 ? $expense->foreign_amount : $expense->amount; - $item->product_key = $expense->category()->exists() ? $expense->category->name : ''; - $item->notes = $expense->public_notes ?? ''; - $item->line_total = round($item->cost * $item->quantity,2); - $item->tax_name1 = $expense->tax_name1; - $item->tax_rate1 = $expense->calculatedTaxRate($expense->tax_amount1, $expense->tax_rate1); - $item->tax_name2 = $expense->tax_name2; - $item->tax_rate2 = $expense->calculatedTaxRate($expense->tax_amount2, $expense->tax_rate2); - $item->tax_name3 = $expense->tax_name3; - $item->tax_rate3 = $expense->calculatedTaxRate($expense->tax_amount3, $expense->tax_rate3); - $item->tax_id = (string) Product::PRODUCT_TYPE_PHYSICAL; - $item->expense_id = $expense->hashed_id; - $item->type_id = '1'; + ->each(function ($expense) use (&$lines) { - $lines[] = $item; + $item = new InvoiceItem(); + $item->quantity = 1; + $item->cost = $expense->foreign_amount > 0 ? $expense->foreign_amount : $expense->amount; + $item->product_key = $expense->category()->exists() ? $expense->category->name : ''; + $item->notes = $expense->public_notes ?? ''; + $item->line_total = round($item->cost * $item->quantity, 2); + $item->tax_name1 = $expense->tax_name1; + $item->tax_rate1 = $expense->calculatedTaxRate($expense->tax_amount1, $expense->tax_rate1); + $item->tax_name2 = $expense->tax_name2; + $item->tax_rate2 = $expense->calculatedTaxRate($expense->tax_amount2, $expense->tax_rate2); + $item->tax_name3 = $expense->tax_name3; + $item->tax_rate3 = $expense->calculatedTaxRate($expense->tax_amount3, $expense->tax_rate3); + $item->tax_id = (string) Product::PRODUCT_TYPE_PHYSICAL; + $item->expense_id = $expense->hashed_id; + $item->type_id = '1'; + + $lines[] = $item; }); $invoice->uses_inclusive_taxes = $project->company->settings->inclusive_taxes ?? false; $invoice->line_items = $lines; return $invoice; - + } } diff --git a/app/Repositories/SubscriptionRepository.php b/app/Repositories/SubscriptionRepository.php index eb53fc6e03..5a4adf0d9c 100644 --- a/app/Repositories/SubscriptionRepository.php +++ b/app/Repositories/SubscriptionRepository.php @@ -129,13 +129,13 @@ class SubscriptionRepository extends BaseRepository */ private function convertV3Bundle($bundle): array { - if(is_object($bundle)) { + if (is_object($bundle)) { $bundle = json_decode(json_encode($bundle), true); } $items = []; - foreach($bundle['recurring_products'] as $key => $value) { + foreach ($bundle['recurring_products'] as $key => $value) { $line_item = new \stdClass(); $line_item->product_key = $value['product']['product_key']; @@ -146,7 +146,7 @@ class SubscriptionRepository extends BaseRepository $items[] = $line_item; } - foreach($bundle['recurring_products'] as $key => $value) { + foreach ($bundle['recurring_products'] as $key => $value) { $line_item = new \stdClass(); $line_item->product_key = $value['product']['product_key']; @@ -164,7 +164,7 @@ class SubscriptionRepository extends BaseRepository public function generateBundleLineItems($bundle, $is_recurring = false, $is_credit = false) { - if(isset($bundle->recurring_products)) { + if (isset($bundle->recurring_products)) { $bundle = $this->convertV3Bundle($bundle); } @@ -218,7 +218,7 @@ class SubscriptionRepository extends BaseRepository $entity = $class::withTrashed()->find($request->entity_id); - if($entity) { + if ($entity) { $entity->subscription_id = $subscription->id; $entity->save(); } diff --git a/app/Repositories/TaskRepository.php b/app/Repositories/TaskRepository.php index b7fd235b6e..b5786d0f05 100644 --- a/app/Repositories/TaskRepository.php +++ b/app/Repositories/TaskRepository.php @@ -46,14 +46,14 @@ class TaskRepository extends BaseRepository $this->new_task = false; } - if(!is_numeric($task->rate) && !isset($data['rate'])) { + if (!is_numeric($task->rate) && !isset($data['rate'])) { $data['rate'] = 0; } $task->fill($data); $task->saveQuietly(); - if(isset($data['assigned_user_id']) && $data['assigned_user_id'] != $task->assigned_user_id) { + if (isset($data['assigned_user_id']) && $data['assigned_user_id'] != $task->assigned_user_id) { TaskAssigned::dispatch($task, $task->company->db)->delay(2); } @@ -63,7 +63,7 @@ class TaskRepository extends BaseRepository $task->status_id = $this->setDefaultStatus($task); } - if($this->new_task && (!$task->rate || $task->rate <= 0)) { + if ($this->new_task && (!$task->rate || $task->rate <= 0)) { $task->rate = $task->getRate(); } @@ -119,13 +119,13 @@ class TaskRepository extends BaseRepository $key_values = array_column($time_log, 0); - if(count($key_values) > 0) { + if (count($key_values) > 0) { array_multisort($key_values, SORT_ASC, $time_log); } - foreach($time_log as $key => $value) { + foreach ($time_log as $key => $value) { - if(is_array($time_log[$key]) && count($time_log[$key]) >= 2) { + if (is_array($time_log[$key]) && count($time_log[$key]) >= 2) { $time_log[$key][1] = $this->roundTimeLog($time_log[$key][0], $time_log[$key][1]); } @@ -150,7 +150,7 @@ class TaskRepository extends BaseRepository $task->calculated_start_date = $this->harvestStartDate($time_log, $task); - if(isset(end($time_log)[1])) { + if (isset(end($time_log)[1])) { $task->is_running = end($time_log)[1] == 0; } @@ -170,7 +170,7 @@ class TaskRepository extends BaseRepository private function harvestStartDate($time_log, $task) { - if(isset($time_log[0][0])) { + if (isset($time_log[0][0])) { return \Carbon\Carbon::createFromTimestamp((int)$time_log[0][0])->addSeconds($task->company->utc_offset()); } @@ -276,17 +276,17 @@ class TaskRepository extends BaseRepository public function roundTimeLog(int $start_time, int $end_time): int { - if(in_array($this->task_round_to_nearest, [0,1]) || $end_time == 0) { + if (in_array($this->task_round_to_nearest, [0,1]) || $end_time == 0) { return $end_time; } $interval = $end_time - $start_time; - if($this->task_round_up) { + if ($this->task_round_up) { return $start_time + (int)ceil($interval / $this->task_round_to_nearest) * $this->task_round_to_nearest; } - if($interval <= $this->task_round_to_nearest) { + if ($interval <= $this->task_round_to_nearest) { return $start_time; } @@ -351,7 +351,7 @@ class TaskRepository extends BaseRepository $task->number = $this->getNextTaskNumber($task); $task->saveQuietly(); $this->completed = false; - } catch(QueryException $e) { + } catch (QueryException $e) { $x++; if ($x > 50) { @@ -366,17 +366,17 @@ class TaskRepository extends BaseRepository private function calculateProjectDuration(Task $task) { - if($task->project) { + if ($task->project) { $duration = 0; - $task->project->tasks()->withTrashed()->where('is_deleted',0)->each(function ($task) use (&$duration) { + $task->project->tasks()->withTrashed()->where('is_deleted', 0)->each(function ($task) use (&$duration) { - if(is_iterable(json_decode($task->time_log))) { + if (is_iterable(json_decode($task->time_log))) { - foreach(json_decode($task->time_log) as $log) { + foreach (json_decode($task->time_log) as $log) { - if(!is_array($log)) { + if (!is_array($log)) { continue; } diff --git a/app/Repositories/TaskStatusRepository.php b/app/Repositories/TaskStatusRepository.php index 0062af5532..3acc04673a 100644 --- a/app/Repositories/TaskStatusRepository.php +++ b/app/Repositories/TaskStatusRepository.php @@ -66,10 +66,10 @@ class TaskStatusRepository extends BaseRepository ->cursor() ->each(function ($ts, $key) use ($task_status) { - if($ts->status_order < $task_status->status_order) { + if ($ts->status_order < $task_status->status_order) { $ts->status_order--; $ts->save(); - } elseif($ts->status_order >= $task_status->status_order) { + } elseif ($ts->status_order >= $task_status->status_order) { $ts->status_order++; $ts->save(); } else { diff --git a/app/Repositories/UserRepository.php b/app/Repositories/UserRepository.php index 709062525b..8b16c54bee 100644 --- a/app/Repositories/UserRepository.php +++ b/app/Repositories/UserRepository.php @@ -73,8 +73,8 @@ class UserRepository extends BaseRepository } //@18-10-2024 - ensure no cross account linkage. - if(is_numeric($user->account_id) && $user->account_id != $account->id){ - throw new \Illuminate\Auth\Access\AuthorizationException("Illegal operation encountered for {$user->hashed_id}",401); + if (is_numeric($user->account_id) && $user->account_id != $account->id) { + throw new \Illuminate\Auth\Access\AuthorizationException("Illegal operation encountered for {$user->hashed_id}", 401); } $user->account_id = $account->id;//@todo we should never change the account_id if it is set at this point. diff --git a/app/Repositories/VendorRepository.php b/app/Repositories/VendorRepository.php index eee61e300b..ef6cf8f0c9 100644 --- a/app/Repositories/VendorRepository.php +++ b/app/Repositories/VendorRepository.php @@ -45,14 +45,15 @@ class VendorRepository extends BaseRepository { $saveable_vendor = $data; - if(array_key_exists('contacts', $data)) { + if (array_key_exists('contacts', $data)) { unset($saveable_vendor['contacts']); } $vendor->fill($saveable_vendor); - if(!$vendor->country_id) - $vendor->country_id = auth()->user()->company()->country()->id ?? 840; + if (!$vendor->country_id) { + $vendor->country_id = auth()->user()->company()->country()->id ?? 840; + } $vendor->saveQuietly(); diff --git a/app/Services/Bank/ProcessBankRules.php b/app/Services/Bank/ProcessBankRules.php index b4ce0ae867..9181745b3d 100644 --- a/app/Services/Bank/ProcessBankRules.php +++ b/app/Services/Bank/ProcessBankRules.php @@ -111,7 +111,7 @@ class ProcessBankRules extends AbstractService // foreach ($bank_transaction_rule['rules'] as $rule) { // $results = []; - + // $payments = Payment::query() // ->withTrashed() // ->whereIn('status_id', [1,4]) @@ -162,8 +162,8 @@ class ProcessBankRules extends AbstractService // $match_set[] = $results; // } // } - - // if (($bank_transaction_rule['matches_on_all'] && $this->checkMatchSetForKey($match_set, $rule_count)) || (!$bank_transaction_rule['matches_on_all'] && count($match_set) > 0)) + + // if (($bank_transaction_rule['matches_on_all'] && $this->checkMatchSetForKey($match_set, $rule_count)) || (!$bank_transaction_rule['matches_on_all'] && count($match_set) > 0)) // { // $this->bank_transaction->status_id = BankTransaction::STATUS_MATCHED; @@ -174,10 +174,10 @@ class ProcessBankRules extends AbstractService // $invoice_id = false; // $payment_id = false; - + // if($first_result[0] == Payment::class) { // $payment_id = $first_result[1][0]; - // } + // } // elseif($first_result[0] == Invoice::class) { // $invoice_id = $first_result[1][0]; // } @@ -237,7 +237,7 @@ class ProcessBankRules extends AbstractService // { // return $payments->when($column != 'amount', function ($q) use ($rule, $column) { // return $q->filter(function ($record) use ($rule, $column) { - + // $bool = $this->matchStringOperator($this->bank_transaction->description, $record->{$column}, $rule['operator']); // return $bool; // }); @@ -297,7 +297,7 @@ class ProcessBankRules extends AbstractService // return [Client::class, collect([])]; // } - + private function matchDebit() { $this->debit_rules = $this->bank_transaction->company->debit_rules(); @@ -408,9 +408,9 @@ class ProcessBankRules extends AbstractService $bt_value = strtolower(str_replace(" ", "", $bt_value)); $rule_value = strtolower(str_replace(" ", "", $rule_value)); $rule_length = iconv_strlen($rule_value); -// nlog($bt_value); -// nlog($rule_value); -// nlog($rule_length); + // nlog($bt_value); + // nlog($rule_value); + // nlog($rule_length); return match ($operator) { 'is' => $bt_value == $rule_value, 'contains' => stripos($bt_value, $rule_value) !== false && strlen($rule_value) > 1, diff --git a/app/Services/Chart/ChartCalculations.php b/app/Services/Chart/ChartCalculations.php index 9db8feefc2..ad89d413ec 100644 --- a/app/Services/Chart/ChartCalculations.php +++ b/app/Services/Chart/ChartCalculations.php @@ -33,7 +33,7 @@ trait ChartCalculations ->where('is_deleted', 0) ->whereIn('status_id', [2,3,4]); - if(in_array($data['period'], ['current,previous'])) { + if (in_array($data['period'], ['current,previous'])) { $q->whereBetween('date', [$data['start_date'], $data['end_date']]); } @@ -58,7 +58,7 @@ trait ChartCalculations ->where('is_deleted', 0) ->whereIn('status_id', [2,3]); - if(in_array($data['period'], ['current,previous'])) { + if (in_array($data['period'], ['current,previous'])) { $q->whereBetween('date', [$data['start_date'], $data['end_date']]); } @@ -83,7 +83,7 @@ trait ChartCalculations ->where('is_deleted', 0) ->where('status_id', 4); - if(in_array($data['period'], ['current,previous'])) { + if (in_array($data['period'], ['current,previous'])) { $q->whereBetween('date', [$data['start_date'], $data['end_date']]); } @@ -108,7 +108,7 @@ trait ChartCalculations ->where('is_deleted', 0) ->whereIn('status_id', [5,6]); - if(in_array($data['period'], ['current,previous'])) { + if (in_array($data['period'], ['current,previous'])) { $q->whereBetween('date', [$data['start_date'], $data['end_date']]); } @@ -136,7 +136,7 @@ trait ChartCalculations $qq->where('due_date', '>=', now()->toDateString())->orWhereNull('due_date'); }); - if(in_array($data['period'], ['current,previous'])) { + if (in_array($data['period'], ['current,previous'])) { $q->whereBetween('date', [$data['start_date'], $data['end_date']]); } @@ -164,7 +164,7 @@ trait ChartCalculations $qq->where('due_date', '>=', now()->toDateString())->orWhereNull('due_date'); }); - if(in_array($data['period'], ['current,previous'])) { + if (in_array($data['period'], ['current,previous'])) { $q->whereBetween('date', [$data['start_date'], $data['end_date']]); } @@ -311,7 +311,7 @@ trait ChartCalculations ->where('company_id', $this->company->id) ->where('is_deleted', 0); - if(in_array($data['period'], ['current,previous'])) { + if (in_array($data['period'], ['current,previous'])) { $query->whereBetween('date', [$data['start_date'], $data['end_date']]); } @@ -345,7 +345,7 @@ trait ChartCalculations ->where('company_id', $this->company->id) ->where('is_deleted', 0); - if(in_array($data['period'], ['current,previous'])) { + if (in_array($data['period'], ['current,previous'])) { $q->whereBetween('calculated_start_date', [$data['start_date'], $data['end_date']]); } @@ -359,8 +359,8 @@ trait ChartCalculations $result = 0; $calculated = collect(); - if($data['calculation'] != 'count' && $data['format'] == 'money') { - if($data['currency_id'] != '999') { + if ($data['calculation'] != 'count' && $data['format'] == 'money') { + if ($data['currency_id'] != '999') { $q->whereHas('client', function ($query) use ($data) { $query->where('settings->currency_id', $data['currency_id']); @@ -372,7 +372,7 @@ trait ChartCalculations } - if($data['calculation'] != 'count' && $data['format'] == 'time') { + if ($data['calculation'] != 'count' && $data['format'] == 'time') { $calculated = $q->get()->map(function ($t) { return $t->calcDuration(); }); diff --git a/app/Services/Chart/ChartQueries.php b/app/Services/Chart/ChartQueries.php index dd93b697e8..b485a98ceb 100644 --- a/app/Services/Chart/ChartQueries.php +++ b/app/Services/Chart/ChartQueries.php @@ -90,7 +90,7 @@ trait ChartQueries $user_filter = $this->is_admin ? '' : 'AND expenses.user_id = '.$this->user->id; - + return DB::select(" SELECT sum(expenses.amount) as total, @@ -207,8 +207,8 @@ trait ChartQueries $user_filter = $this->is_admin ? '' : 'AND payments.user_id = '.$this->user->id; - -return DB::select(" + + return DB::select(" SELECT sum(payments.amount - payments.refunded) as total, payments.date @@ -221,12 +221,12 @@ return DB::select(" AND IFNULL(payments.currency_id, :company_currency) = :currency_id GROUP BY payments.date ", [ - 'company_currency' => $this->company->settings->currency_id, - 'currency_id' => $currency_id, - 'company_id' => $this->company->id, - 'start_date' => $start_date, - 'end_date' => $end_date, -]); + 'company_currency' => $this->company->settings->currency_id, + 'currency_id' => $currency_id, + 'company_id' => $this->company->id, + 'start_date' => $start_date, + 'end_date' => $end_date, + ]); // return DB::select(" // SELECT @@ -421,8 +421,8 @@ return DB::select(" { $user_filter = $this->is_admin ? '' : 'AND clients.user_id = '.$this->user->id; - -return DB::select(" + + return DB::select(" SELECT sum(invoices.balance) as total, invoices.date @@ -438,12 +438,12 @@ return DB::select(" AND IFNULL(CAST(JSON_UNQUOTE(JSON_EXTRACT(clients.settings, '$.currency_id')) AS SIGNED), :company_currency) = :currency_id GROUP BY invoices.date ", [ - 'company_currency' => (int) $this->company->settings->currency_id, - 'currency_id' => $currency_id, - 'company_id' => $this->company->id, - 'start_date' => $start_date, - 'end_date' => $end_date, -]); + 'company_currency' => (int) $this->company->settings->currency_id, + 'currency_id' => $currency_id, + 'company_id' => $this->company->id, + 'start_date' => $start_date, + 'end_date' => $end_date, + ]); // return DB::select(" // SELECT diff --git a/app/Services/Chart/ChartService.php b/app/Services/Chart/ChartService.php index 0e6698bbe1..bb5eaf6bf7 100644 --- a/app/Services/Chart/ChartService.php +++ b/app/Services/Chart/ChartService.php @@ -138,7 +138,7 @@ class ChartService $aggregate_outstanding = $this->getAggregateOutstandingQuery($start_date, $end_date); $aggregate_expenses = $this->getAggregateExpenseQuery($start_date, $end_date); $aggregate_invoices = $this->getAggregateInvoicesQuery($start_date, $end_date); - + $data[999]['invoices'] = $aggregate_invoices !== false ? reset($aggregate_invoices) : new \stdClass(); $data[999]['expenses'] = $aggregate_expenses !== false ? reset($aggregate_expenses) : new \stdClass(); $data[999]['outstanding'] = $aggregate_outstanding !== false ? reset($aggregate_outstanding) : new \stdClass(); diff --git a/app/Services/Client/ClientService.php b/app/Services/Client/ClientService.php index af9211dbbf..61e9342ae9 100644 --- a/app/Services/Client/ClientService.php +++ b/app/Services/Client/ClientService.php @@ -61,7 +61,7 @@ class ClientService nlog("DB ERROR " . $throwable->getMessage()); } - if($invoice && floatval($this->client->balance) != floatval($pre_client_balance)) { + if ($invoice && floatval($this->client->balance) != floatval($pre_client_balance)) { $diff = $this->client->balance - $pre_client_balance; $invoice->ledger()->insertInvoiceBalance($diff, $this->client->balance, "Update Adjustment Invoice # {$invoice->number} => {$diff}"); } @@ -89,7 +89,7 @@ class ClientService DB::connection(config('database.default'))->rollBack(); } - } + } return $this; } @@ -97,35 +97,35 @@ class ClientService public function updateBalanceAndPaidToDate(float $balance, float $paid_to_date) { -// refactor to calculated balances. -// $ib = Invoice::withTrashed() -// ->where('client_id', $this->client->id) -// ->whereIn('status_id', [2,3]) -// ->where('is_deleted',0) -// ->where('is_proforma',0) -// ->sum('balance'); + // refactor to calculated balances. + // $ib = Invoice::withTrashed() + // ->where('client_id', $this->client->id) + // ->whereIn('status_id', [2,3]) + // ->where('is_deleted',0) + // ->where('is_proforma',0) + // ->sum('balance'); -// $payments = Payment::withTrashed() -// ->where('client_id', $this->client->id) -// ->whereIn('status_id', [1,4,5,6]) -// ->where('is_deleted',0) -// ->sum(\DB::raw('amount - refunded')); + // $payments = Payment::withTrashed() + // ->where('client_id', $this->client->id) + // ->whereIn('status_id', [1,4,5,6]) + // ->where('is_deleted',0) + // ->sum(\DB::raw('amount - refunded')); -// $credit_payments = Payment::where('client_id', $this->client->id) -// ->where('is_deleted', 0) -// ->join('paymentables', 'payments.id', '=', 'paymentables.payment_id') -// ->where('paymentables.paymentable_type', \App\Models\Credit::class) -// ->whereNull('paymentables.deleted_at') -// ->where('paymentables.amount', '>', 0) -// ->sum(DB::raw('paymentables.amount - paymentables.refunded')); + // $credit_payments = Payment::where('client_id', $this->client->id) + // ->where('is_deleted', 0) + // ->join('paymentables', 'payments.id', '=', 'paymentables.payment_id') + // ->where('paymentables.paymentable_type', \App\Models\Credit::class) + // ->whereNull('paymentables.deleted_at') + // ->where('paymentables.amount', '>', 0) + // ->sum(DB::raw('paymentables.amount - paymentables.refunded')); -// $credits_from_reversal = \App\Models\Credit::withTrashed() -// ->where('client_id', $this->client->id) -// ->where('is_deleted', 0) -// ->whereNotNull('invoice_id') -// ->sum('amount'); + // $credits_from_reversal = \App\Models\Credit::withTrashed() + // ->where('client_id', $this->client->id) + // ->where('is_deleted', 0) + // ->whereNotNull('invoice_id') + // ->sum('amount'); -// $paid_to_date = $payments+$credit_payments-$credits_from_reversal; + // $paid_to_date = $payments+$credit_payments-$credits_from_reversal; try { DB::connection(config('database.default'))->transaction(function () use ($balance, $paid_to_date) { @@ -141,7 +141,7 @@ class ClientService DB::connection(config('database.default'))->rollBack(); } - } + } return $this; } @@ -161,7 +161,7 @@ class ClientService DB::connection(config('database.default'))->rollBack(); } - } + } return $this; } @@ -170,7 +170,7 @@ class ClientService { $x = 1; - if(isset($this->client->number)) { + if (isset($this->client->number)) { return $this; } diff --git a/app/Services/Client/RFFService.php b/app/Services/Client/RFFService.php index f5b5f6ae9f..9f4293aa1c 100644 --- a/app/Services/Client/RFFService.php +++ b/app/Services/Client/RFFService.php @@ -128,7 +128,7 @@ class RFFService $contact = []; MultiDB::setDb($this->database); - + foreach ($data as $field => $value) { if (Str::startsWith($field, 'client_')) { $client[$this->mappings[$field]] = $value; diff --git a/app/Services/Client/Statement.php b/app/Services/Client/Statement.php index 7167cf7be6..641163f296 100644 --- a/app/Services/Client/Statement.php +++ b/app/Services/Client/Statement.php @@ -69,7 +69,7 @@ class Statement $custom_statement_template = \App\Models\Design::where('id', $this->decodePrimaryKey($this->client->getSetting('statement_design_id')))->where('is_template', true)->first(); - if($custom_statement_template || $option_template && $option_template != '') { + if ($custom_statement_template || $option_template && $option_template != '') { $variables['values']['$start_date'] = $this->translateDate($this->options['start_date'], $this->client->date_format(), $this->client->locale()); $variables['values']['$end_date'] = $this->translateDate($this->options['end_date'], $this->client->date_format(), $this->client->locale()); @@ -119,7 +119,7 @@ class Statement $html = $maker->getCompiledHTML(true); // nlog($html); - + if ($this->rollback) { \DB::connection(config('database.default'))->rollBack(); $this->rollback = false; @@ -133,9 +133,8 @@ class Statement $state = null; return $pdf; - } - catch(\Throwable $th){ - + } catch (\Throwable $th) { + nlog("STATEMENT:: Throwable::" . $th->getMessage()); if ($this->rollback) { @@ -162,7 +161,7 @@ class Statement private function templateStatement($variables) { - if(isset($this->options['template'])) { + if (isset($this->options['template'])) { $statement_design_id = $this->options['template']; } else { $statement_design_id = $this->client->getSetting('statement_design_id'); @@ -222,7 +221,7 @@ class Statement DB::connection(config('database.default'))->beginTransaction(); $this->rollback = true; - + $invoice = InvoiceFactory::create($this->client->company->id, $this->client->user->id); $invoice->client_id = $this->client->id; $invoice->line_items = $this->buildLineItems(); @@ -456,7 +455,7 @@ class Statement ->where('balance', '>', 0) ->where('is_deleted', 0); - if($range == '0') { + if ($range == '0') { $query->where(function ($q) use ($to, $from) { $q->whereBetween('due_date', [$to, $from])->orWhereNull('due_date'); }); diff --git a/app/Services/Company/CompanyService.php b/app/Services/Company/CompanyService.php index d8464347b0..5db6ba8729 100644 --- a/app/Services/Company/CompanyService.php +++ b/app/Services/Company/CompanyService.php @@ -56,21 +56,21 @@ class CompanyService case '724': // Spain $taxes[] = ['name' => 'IVA', 'rate' => 21]; break; - case '554': // New Zealand + case '554': // New Zealand $taxes[] = ['name' => 'GST', 'rate' => 15]; break; - + default: return; } - foreach($taxes as $tax) { + foreach ($taxes as $tax) { $tax_rate = TaxRateFactory::create($this->company->id, $user->id); $tax_rate->fill($tax); $tax_rate->save(); } - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: CompanyService::" . $e->getMessage()); nlog($e->getMessage()); } diff --git a/app/Services/Credit/MarkSent.php b/app/Services/Credit/MarkSent.php index 1e53a34d83..089d851dff 100644 --- a/app/Services/Credit/MarkSent.php +++ b/app/Services/Credit/MarkSent.php @@ -52,7 +52,7 @@ class MarkSent event(new CreditWasMarkedSent($this->credit, $this->credit->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); - if($fire_event) { + if ($fire_event) { event('eloquent.updated: App\Models\Credit', $this->credit); $this->credit->sendEvent(Webhook::EVENT_SENT_CREDIT); diff --git a/app/Services/EDocument/Adapters/CII/PaymentMeans.php b/app/Services/EDocument/Adapters/CII/PaymentMeans.php index af7b9e4111..06f8b5c290 100644 --- a/app/Services/EDocument/Adapters/CII/PaymentMeans.php +++ b/app/Services/EDocument/Adapters/CII/PaymentMeans.php @@ -15,7 +15,6 @@ use App\Services\EDocument\Interfaces\PaymentMeansInterface; class PaymentMeans implements PaymentMeansInterface { - public static array $payment_means_codelist = [ '1' => 'Instrument not defined', '2' => 'Automated clearing house credit', @@ -363,90 +362,90 @@ class PaymentMeans implements PaymentMeansInterface ]; - public static array $payment_means_requirements_codes = [ - '1' => [], // Instrument not defined - '2' => ['iban', 'bic_swift'], // ACH credit - '3' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH debit - '4' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH demand debit reversal - '5' => ['iban', 'bic_swift'], // ACH demand credit reversal - '6' => ['iban', 'bic_swift'], // ACH demand credit - '7' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH demand debit - '8' => [], // Hold - '9' => ['iban', 'bic_swift'], // National or regional clearing - '10' => [], // In cash - '11' => ['iban', 'bic_swift'], // ACH savings credit reversal - '12' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH savings debit reversal - '13' => ['iban', 'bic_swift'], // ACH savings credit - '14' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH savings debit - '15' => ['account_holder', 'bsb_sort'], // Bookentry credit - '16' => ['account_holder', 'bsb_sort'], // Bookentry debit - '17' => ['iban', 'bic_swift'], // ACH demand CCD credit - '18' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH demand CCD debit - '19' => ['iban', 'bic_swift'], // ACH demand CTP credit - '20' => [], // Cheque - '21' => [], // Banker's draft - '22' => [], // Certified banker's draft - '23' => [], // Bank cheque - '24' => [], // Bill of exchange awaiting acceptance - '25' => [], // Certified cheque - '26' => [], // Local cheque - '27' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH demand CTP debit - '28' => ['iban', 'bic_swift'], // ACH demand CTX credit - '29' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH demand CTX debit - '30' => ['iban', 'bic_swift','account_holder'], // Credit transfer - '31' => ['iban', 'bic_swift','account_holder'], // Debit transfer - '32' => ['iban', 'bic_swift','account_holder'], // ACH demand CCD+ credit - '33' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH demand CCD+ debit - '34' => ['iban', 'bic_swift','account_holder'], // ACH PPD - '35' => ['iban', 'bic_swift','account_holder'], // ACH savings CCD credit - '36' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH savings CCD debit - '37' => ['iban', 'bic_swift','account_holder'], // ACH savings CTP credit - '38' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH savings CTP debit - '39' => ['iban', 'bic_swift','account_holder'], // ACH savings CTX credit - '40' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH savings CTX debit - '41' => ['iban', 'bic_swift','account_holder'], // ACH savings CCD+ credit - '42' => ['iban', 'bic_swift','account_holder'], // Payment to bank account - '43' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH savings CCD+ debit - '44' => [], // Accepted bill of exchange - '45' => ['iban', 'bic_swift'], // Referenced home-banking credit transfer - '46' => ['iban', 'bic_swift'], // Interbank debit transfer - '47' => ['iban', 'bic_swift'], // Home-banking debit transfer - '48' => ['card_type', 'card_number'], // Bank card - '49' => ['payer_bank_account', 'iban', 'bic_swift'], // Direct debit - '50' => ['account_holder'], // Payment by postgiro - '51' => ['iban', 'bic_swift'], // FR, norme 6 97-Telereglement CFONB - '52' => ['iban', 'bic_swift'], // Urgent commercial payment - '53' => ['iban', 'bic_swift'], // Urgent Treasury Payment - '54' => ['card_type', 'card_number', 'card_holder'], // Credit card - '55' => ['card_type', 'card_number', 'card_holder'], // Debit card - '56' => ['account_holder'], // Bankgiro - '57' => ['iban', 'bic_swift'], // Standing agreement - '58' => ['iban', 'bic_swift'], // SEPA credit transfer - '59' => ['payer_bank_account', 'iban', 'bic_swift'], // SEPA direct debit - '60' => [], // Promissory note - '61' => [], // Promissory note signed by debtor - '62' => ['bic_swift'], // Promissory note signed by debtor and endorsed by bank - '63' => [], // Promissory note signed by debtor and endorsed - '64' => ['bic_swift'], // Promissory note signed by bank - '65' => ['bic_swift'], // Promissory note signed by bank and endorsed by another - '66' => [], // Promissory note signed by third party - '67' => ['bic_swift'], // Promissory note signed by third party and endorsed by bank - '68' => ['iban'], // Online payment service - '69' => ['iban', 'bic_swift'], // Transfer Advice - '70' => [], // Bill drawn by creditor on debtor - '74' => ['bic_swift'], // Bill drawn by creditor on bank - '75' => ['bic_swift'], // Bill drawn by creditor, endorsed by bank - '76' => ['bic_swift'], // Bill drawn by creditor on bank and endorsed - '77' => [], // Bill drawn by creditor on third party - '78' => [], // Bill drawn by creditor on third party, accepted - '91' => [], // Not transferable banker's draft - '92' => [], // Not transferable local cheque - '93' => ['iban', 'bic_swift'], // Reference giro - '94' => ['iban', 'bic_swift'], // Urgent giro - '95' => ['iban', 'bic_swift'], // Free format giro - '96' => [], // Requested method not used - '97' => ['account_holder'], // Clearing between partners - 'ZZZ' => [], // Mutually defined + public static array $payment_means_requirements_codes = [ + '1' => [], // Instrument not defined + '2' => ['iban', 'bic_swift'], // ACH credit + '3' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH debit + '4' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH demand debit reversal + '5' => ['iban', 'bic_swift'], // ACH demand credit reversal + '6' => ['iban', 'bic_swift'], // ACH demand credit + '7' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH demand debit + '8' => [], // Hold + '9' => ['iban', 'bic_swift'], // National or regional clearing + '10' => [], // In cash + '11' => ['iban', 'bic_swift'], // ACH savings credit reversal + '12' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH savings debit reversal + '13' => ['iban', 'bic_swift'], // ACH savings credit + '14' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH savings debit + '15' => ['account_holder', 'bsb_sort'], // Bookentry credit + '16' => ['account_holder', 'bsb_sort'], // Bookentry debit + '17' => ['iban', 'bic_swift'], // ACH demand CCD credit + '18' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH demand CCD debit + '19' => ['iban', 'bic_swift'], // ACH demand CTP credit + '20' => [], // Cheque + '21' => [], // Banker's draft + '22' => [], // Certified banker's draft + '23' => [], // Bank cheque + '24' => [], // Bill of exchange awaiting acceptance + '25' => [], // Certified cheque + '26' => [], // Local cheque + '27' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH demand CTP debit + '28' => ['iban', 'bic_swift'], // ACH demand CTX credit + '29' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH demand CTX debit + '30' => ['iban', 'bic_swift','account_holder'], // Credit transfer + '31' => ['iban', 'bic_swift','account_holder'], // Debit transfer + '32' => ['iban', 'bic_swift','account_holder'], // ACH demand CCD+ credit + '33' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH demand CCD+ debit + '34' => ['iban', 'bic_swift','account_holder'], // ACH PPD + '35' => ['iban', 'bic_swift','account_holder'], // ACH savings CCD credit + '36' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH savings CCD debit + '37' => ['iban', 'bic_swift','account_holder'], // ACH savings CTP credit + '38' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH savings CTP debit + '39' => ['iban', 'bic_swift','account_holder'], // ACH savings CTX credit + '40' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH savings CTX debit + '41' => ['iban', 'bic_swift','account_holder'], // ACH savings CCD+ credit + '42' => ['iban', 'bic_swift','account_holder'], // Payment to bank account + '43' => ['payer_bank_account', 'iban', 'bic_swift'], // ACH savings CCD+ debit + '44' => [], // Accepted bill of exchange + '45' => ['iban', 'bic_swift'], // Referenced home-banking credit transfer + '46' => ['iban', 'bic_swift'], // Interbank debit transfer + '47' => ['iban', 'bic_swift'], // Home-banking debit transfer + '48' => ['card_type', 'card_number'], // Bank card + '49' => ['payer_bank_account', 'iban', 'bic_swift'], // Direct debit + '50' => ['account_holder'], // Payment by postgiro + '51' => ['iban', 'bic_swift'], // FR, norme 6 97-Telereglement CFONB + '52' => ['iban', 'bic_swift'], // Urgent commercial payment + '53' => ['iban', 'bic_swift'], // Urgent Treasury Payment + '54' => ['card_type', 'card_number', 'card_holder'], // Credit card + '55' => ['card_type', 'card_number', 'card_holder'], // Debit card + '56' => ['account_holder'], // Bankgiro + '57' => ['iban', 'bic_swift'], // Standing agreement + '58' => ['iban', 'bic_swift'], // SEPA credit transfer + '59' => ['payer_bank_account', 'iban', 'bic_swift'], // SEPA direct debit + '60' => [], // Promissory note + '61' => [], // Promissory note signed by debtor + '62' => ['bic_swift'], // Promissory note signed by debtor and endorsed by bank + '63' => [], // Promissory note signed by debtor and endorsed + '64' => ['bic_swift'], // Promissory note signed by bank + '65' => ['bic_swift'], // Promissory note signed by bank and endorsed by another + '66' => [], // Promissory note signed by third party + '67' => ['bic_swift'], // Promissory note signed by third party and endorsed by bank + '68' => ['iban'], // Online payment service + '69' => ['iban', 'bic_swift'], // Transfer Advice + '70' => [], // Bill drawn by creditor on debtor + '74' => ['bic_swift'], // Bill drawn by creditor on bank + '75' => ['bic_swift'], // Bill drawn by creditor, endorsed by bank + '76' => ['bic_swift'], // Bill drawn by creditor on bank and endorsed + '77' => [], // Bill drawn by creditor on third party + '78' => [], // Bill drawn by creditor on third party, accepted + '91' => [], // Not transferable banker's draft + '92' => [], // Not transferable local cheque + '93' => ['iban', 'bic_swift'], // Reference giro + '94' => ['iban', 'bic_swift'], // Urgent giro + '95' => ['iban', 'bic_swift'], // Free format giro + '96' => [], // Requested method not used + '97' => ['account_holder'], // Clearing between partners + 'ZZZ' => [], // Mutually defined ]; public static array $payment_means_field_map = [ @@ -483,8 +482,8 @@ class PaymentMeans implements PaymentMeansInterface public function __construct(mixed $existing_payment_means = null) { - if($existing_payment_means){ - + if ($existing_payment_means) { + $properties = get_object_vars($this); foreach ($properties as $property => $value) { if (property_exists($existing_payment_means, $property)) { @@ -495,27 +494,27 @@ class PaymentMeans implements PaymentMeansInterface } } //requires an object which looks like this - // @param string $typecode __BT-81, From BASIC WL__ The expected or used means of payment, expressed as a code. The entries from the UNTDID 4461 code list must be used. A distinction should be made between SEPA and non-SEPA payments as well - // as between credit payments, direct debits, card payments and other means of payment + // @param string $typecode __BT-81, From BASIC WL__ The expected or used means of payment, expressed as a code. The entries from the UNTDID 4461 code list must be used. A distinction should be made between SEPA and non-SEPA payments as well + // as between credit payments, direct debits, card payments and other means of payment // In particular, the following codes can be used: - // * // 10: cash - - // 20: check - - // 30: transfer - - // 42: Payment to bank account - - // 48: Card payment - - // 49: direct debit - - // 57: Standing order - - // 58: SEPA Credit Transfer - - // 59: SEPA Direct Debit - - // 97: Report + // * // 10: cash - + // 20: check - + // 30: transfer - + // 42: Payment to bank account - + // 48: Card payment - + // 49: direct debit - + // 57: Standing order - + // 58: SEPA Credit Transfer - + // 59: SEPA Direct Debit - + // 97: Report // * // * @param string|null $information __BT-82, From EN 16931__ The expected or used means of payment expressed in text form, e.g. cash, bank transfer, direct debit, credit card, etc. // * @param string|null $card_type __BT-, From __ The type of the card - // * @param string|null $cardId __BT-84, From BASIC WL__ The primary account number (PAN) to which the card used for payment belongs. In accordance with card payment security standards, an invoice should never contain a full payment card master account number. + // * @param string|null $cardId __BT-84, From BASIC WL__ The primary account number (PAN) to which the card used for payment belongs. In accordance with card payment security standards, an invoice should never contain a full payment card master account number. //The following specification of the PCI Security Standards Council currently applies: The first 6 and last 4 digits at most are to be displayed // * @param string|null $cardholder_name __BT-, From __ Name of the payment card holder // * @param string|null $buyerIban __BT-91, From BASIC WL__ Direct debit: ID of the account to be debited - // * @param string|null $iban __BT-, From __ Transfer: A unique identifier for the financial account held with a payment service provider to which the payment should be made, e.g. Use an IBAN (in the case of a SEPA payment) for a national + // * @param string|null $iban __BT-, From __ Transfer: A unique identifier for the financial account held with a payment service provider to which the payment should be made, e.g. Use an IBAN (in the case of a SEPA payment) for a national //ProprietaryID account number // * @param string|null $payeeAccountName __BT-, From __ The name of the payment account held with a payment service provider to which the payment should be made. Information only required if different from the name of the payee / seller // * @param string|null $payeePropId __BT-, From __ National account number (not for SEPA) @@ -538,7 +537,7 @@ class PaymentMeans implements PaymentMeansInterface $CreditorFinancialInstitutionType = new \horstoeko\zugferd\entities\extended\ram\CreditorFinancialInstitutionType(); $CreditorFinancialInstitutionType->setBICID(new \horstoeko\zugferd\entities\extended\udt\IDType($this->bic)); - + $TradeSettlementPaymentMeansType = new \horstoeko\zugferd\entities\extended\ram\TradeSettlementPaymentMeansType(); $TradeSettlementPaymentMeansType->setTypeCode($this->code)->setInformation($this->information); $TradeSettlementPaymentMeansType->setPayeePartyCreditorFinancialAccount($CreditorFinancialAccountType); diff --git a/app/Services/EDocument/Adapters/UBL/PaymentMeans.php b/app/Services/EDocument/Adapters/UBL/PaymentMeans.php index cd546f25e8..45c10d9702 100644 --- a/app/Services/EDocument/Adapters/UBL/PaymentMeans.php +++ b/app/Services/EDocument/Adapters/UBL/PaymentMeans.php @@ -100,7 +100,7 @@ class PaymentMeans implements PaymentMeansInterface '97' => 'Clearing between partners', 'ZZZ' => 'Mutually defined', ]; - + public function run() { } diff --git a/app/Services/EDocument/Gateway/MutatorInterface.php b/app/Services/EDocument/Gateway/MutatorInterface.php index 65174ce7ff..4d706159f3 100644 --- a/app/Services/EDocument/Gateway/MutatorInterface.php +++ b/app/Services/EDocument/Gateway/MutatorInterface.php @@ -13,7 +13,6 @@ namespace App\Services\EDocument\Gateway; interface MutatorInterface { - public function receiverSpecificLevelMutators(): self; public function senderSpecificLevelMutators(): self; diff --git a/app/Services/EDocument/Gateway/MutatorUtil.php b/app/Services/EDocument/Gateway/MutatorUtil.php index 1438ec82db..87866cc1cf 100644 --- a/app/Services/EDocument/Gateway/MutatorUtil.php +++ b/app/Services/EDocument/Gateway/MutatorUtil.php @@ -34,7 +34,7 @@ class MutatorUtil * setPaymentMeans * * Sets the payment means - if it exists - * + * * @param bool $required * @return self */ @@ -42,9 +42,9 @@ class MutatorUtil { $peppol = $this->mutator->getPeppol(); - if(isset($peppol->PaymentMeans)) { + if (isset($peppol->PaymentMeans)) { return $this; - } elseif($paymentMeans = $this->getSetting('Invoice.PaymentMeans')) { + } elseif ($paymentMeans = $this->getSetting('Invoice.PaymentMeans')) { $peppol->PaymentMeans = is_array($paymentMeans) ? $paymentMeans : [$paymentMeans]; $this->mutator->setPeppol($peppol); return $this; @@ -65,7 +65,7 @@ class MutatorUtil { return PropertyResolver::resolve($this->mutator->getClientSettings(), $property_path); } - + /** * getCompanySetting * @@ -88,11 +88,11 @@ class MutatorUtil public function getSetting(string $property_path): mixed { - if($prop_value = PropertyResolver::resolve($this->mutator->getPeppol(), $property_path)) { + if ($prop_value = PropertyResolver::resolve($this->mutator->getPeppol(), $property_path)) { return $prop_value; - } elseif($prop_value = PropertyResolver::resolve($this->mutator->getClientSettings(), $property_path)) { + } elseif ($prop_value = PropertyResolver::resolve($this->mutator->getClientSettings(), $property_path)) { return $prop_value; - } elseif($prop_value = PropertyResolver::resolve($this->mutator->getCompanySettings(), $property_path)) { + } elseif ($prop_value = PropertyResolver::resolve($this->mutator->getCompanySettings(), $property_path)) { return $prop_value; } return null; @@ -127,14 +127,14 @@ class MutatorUtil $invoice = $this->mutator->getInvoice(); //@phpstan-ignore-next-line - if(isset($peppol->AccountingCustomerParty->CustomerAssignedAccountID)) { + if (isset($peppol->AccountingCustomerParty->CustomerAssignedAccountID)) { return $this; - } elseif($customer_assigned_account_id = $this->getSetting('Invoice.AccountingCustomerParty.CustomerAssignedAccountID')) { + } elseif ($customer_assigned_account_id = $this->getSetting('Invoice.AccountingCustomerParty.CustomerAssignedAccountID')) { $peppol->AccountingCustomerParty->CustomerAssignedAccountID = $customer_assigned_account_id; $this->mutator->setPeppol($peppol); return $this; - } elseif(strlen($invoice->client->id_number ?? '') > 1) { + } elseif (strlen($invoice->client->id_number ?? '') > 1) { $customer_assigned_account_id = new CustomerAssignedAccountID(); $customer_assigned_account_id->value = $invoice->client->id_number; diff --git a/app/Services/EDocument/Gateway/Qvalia/Invoice.php b/app/Services/EDocument/Gateway/Qvalia/Invoice.php index 66973879e2..db13e60942 100644 --- a/app/Services/EDocument/Gateway/Qvalia/Invoice.php +++ b/app/Services/EDocument/Gateway/Qvalia/Invoice.php @@ -13,12 +13,11 @@ namespace App\Services\EDocument\Gateway\Qvalia; class Invoice { - public function __construct(public Qvalia $qvalia) { } - // Methods + // Methods /** * status * @@ -58,7 +57,7 @@ class Invoice $uri = "/account/{$legal_entity_id}/action/invoice/outgoing/status/{$integration_id}"; $r = $this->qvalia->httpClient($uri, (\App\Enum\HttpVerb::GET)->value, []); - + return $r->object(); } @@ -71,7 +70,7 @@ class Invoice */ public function send(string $legal_entity_id, string $document) { - // Set Headers + // Set Headers // Either "application/json" (default) or "application/xml" $headers = [ @@ -87,7 +86,7 @@ class Invoice $uri = "/transaction/{$legal_entity_id}/invoices/outgoing"; $r = $this->qvalia->httpClient($uri, (\App\Enum\HttpVerb::POST)->value, $data, $headers); - + return $r->object(); } diff --git a/app/Services/EDocument/Gateway/Qvalia/Mutator.php b/app/Services/EDocument/Gateway/Qvalia/Mutator.php index 4af130c55a..be47fb68d6 100644 --- a/app/Services/EDocument/Gateway/Qvalia/Mutator.php +++ b/app/Services/EDocument/Gateway/Qvalia/Mutator.php @@ -16,7 +16,6 @@ use App\Services\EDocument\Gateway\MutatorInterface; class Mutator implements MutatorInterface { - private \InvoiceNinja\EInvoice\Models\Peppol\Invoice $p_invoice; private ?\InvoiceNinja\EInvoice\Models\Peppol\Invoice $_client_settings; @@ -26,7 +25,7 @@ class Mutator implements MutatorInterface private $invoice; private MutatorUtil $mutator_util; - + public function __construct(public Qvalia $qvalia) { $this->mutator_util = new MutatorUtil($this); @@ -93,7 +92,7 @@ class Mutator implements MutatorInterface public function senderSpecificLevelMutators(): self { - if(method_exists($this, $this->invoice->company->country()->iso_3166_2)) { + if (method_exists($this, $this->invoice->company->country()->iso_3166_2)) { $this->{$this->invoice->company->country()->iso_3166_2}(); } @@ -111,14 +110,14 @@ class Mutator implements MutatorInterface public function receiverSpecificLevelMutators(): self { - if(method_exists($this, "client_{$this->invoice->company->country()->iso_3166_2}")) { + if (method_exists($this, "client_{$this->invoice->company->country()->iso_3166_2}")) { $this->{"client_{$this->invoice->company->country()->iso_3166_2}"}(); } return $this; } - // Country-specific methods + // Country-specific methods public function DE(): self { return $this; diff --git a/app/Services/EDocument/Gateway/Qvalia/Partner.php b/app/Services/EDocument/Gateway/Qvalia/Partner.php index a2e19aee74..884d47a256 100644 --- a/app/Services/EDocument/Gateway/Qvalia/Partner.php +++ b/app/Services/EDocument/Gateway/Qvalia/Partner.php @@ -13,14 +13,13 @@ namespace App\Services\EDocument\Gateway\Qvalia; class Partner { - private string $partner_number; public function __construct(public Qvalia $qvalia) { - $this->partner_number = config('ninja.qvalia_partner_number'); + $this->partner_number = config('ninja.qvalia_partner_number'); } - + /** * getAccount * @@ -35,7 +34,7 @@ class Partner return $r->object(); } - + /** * getPeppolId * @@ -46,7 +45,7 @@ class Partner public function getPeppolId(string $id) { $uri = "/partner/{$this->partner_number}/peppol/lookup/{$id}"; - + $uri = "/partner/{$this->partner_number}/account"; $r = $this->qvalia->httpClient($uri, (\App\Enum\HttpVerb::GET)->value, []); @@ -54,7 +53,7 @@ class Partner return $r->object(); } - + /** * getAccountId * diff --git a/app/Services/EDocument/Gateway/Qvalia/Qvalia.php b/app/Services/EDocument/Gateway/Qvalia/Qvalia.php index 5d5c88f86c..13b5f2f1a0 100644 --- a/app/Services/EDocument/Gateway/Qvalia/Qvalia.php +++ b/app/Services/EDocument/Gateway/Qvalia/Qvalia.php @@ -20,13 +20,13 @@ use Illuminate\Http\Client\RequestException; use Turbo124\Beacon\Facades\LightLogs; class Qvalia -{ +{ /** @var string $base_url */ private string $base_url = 'https://api.qvalia.com'; - + /** @var string $sandbox_base_url */ private string $sandbox_base_url = 'https://api-qa.qvalia.com'; - + private bool $test_mode = true; /** @var array $peppol_discovery */ @@ -37,7 +37,7 @@ class Qvalia "scheme" => "de:lwid", "identifier" => "DE:VAT" ]; - + /** @var array $dbn_discovery */ private array $dbn_discovery = [ "documentTypes" => ["invoice"], @@ -67,8 +67,9 @@ class Qvalia private function init(): self { - if($this->test_mode) + if ($this->test_mode) { $this->base_url = $this->sandbox_base_url; + } return $this; } @@ -80,39 +81,38 @@ class Qvalia } - /** - * httpClient - * - * @param string $uri - * @param string $verb - * @param array $data - * @param array $headers - * @return \Illuminate\Http\Client\Response - */ + /** + * httpClient + * + * @param string $uri + * @param string $verb + * @param array $data + * @param array $headers + * @return \Illuminate\Http\Client\Response + */ public function httpClient(string $uri, string $verb, array $data, ?array $headers = []) { - try { + try { $r = Http::withToken(config('ninja.qvalia_api_key')) ->withHeaders($this->getHeaders($headers)) ->{$verb}("{$this->base_url}{$uri}", $data)->throw(); - } - catch (ClientException $e) { + } catch (ClientException $e) { // 4xx errors - + nlog("LEI:: {$this->legal_entity_id}"); nlog("Client error: " . $e->getMessage()); nlog("Response body: " . $e->getResponse()->getBody()->getContents()); } catch (ServerException $e) { // 5xx errors - + nlog("LEI:: {$this->legal_entity_id}"); nlog("Server error: " . $e->getMessage()); nlog("Response body: " . $e->getResponse()->getBody()->getContents()); } catch (\Illuminate\Http\Client\RequestException $e) { nlog("LEI:: {$this->legal_entity_id}"); - nlog("Request error: {$e->getCode()}: " . $e->getMessage()); + nlog("Request error: {$e->getCode()}: " . $e->getMessage()); $responseBody = $e->response->body(); nlog("Response body: " . $responseBody); diff --git a/app/Services/EDocument/Gateway/Storecove/Models/AccountingCustomerParty.php b/app/Services/EDocument/Gateway/Storecove/Models/AccountingCustomerParty.php index f87865b66d..ca10b55d5f 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/AccountingCustomerParty.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/AccountingCustomerParty.php @@ -7,53 +7,53 @@ use Symfony\Component\Serializer\Attribute\SerializedPath; class AccountingCustomerParty { - /** @var Party */ - #[SerializedName('cac:Party')] - public $party; - - /** @var PublicIdentifiers[] */ - public ?array $public_identifiers; + /** @var Party */ + #[SerializedName('cac:Party')] + public $party; - /** - * @param PublicIdentifiers[] $public_identifiers - */ - public function __construct(?Party $party, ?array $public_identifiers) - { - $this->party = $party; - $this->public_identifiers = $public_identifiers; - } + /** @var PublicIdentifiers[] */ + public ?array $public_identifiers; - public function getParty(): ?Party - { - return $this->party; - } + /** + * @param PublicIdentifiers[] $public_identifiers + */ + public function __construct(?Party $party, ?array $public_identifiers) + { + $this->party = $party; + $this->public_identifiers = $public_identifiers; + } - /** - * @return PublicIdentifiers[] - */ - public function getPublicIdentifiers(): ?array - { - return $this->public_identifiers; - } + public function getParty(): ?Party + { + return $this->party; + } - public function setParty(?Party $party): self - { - $this->party = $party; - return $this; - } + /** + * @return PublicIdentifiers[] + */ + public function getPublicIdentifiers(): ?array + { + return $this->public_identifiers; + } - /** - * @param PublicIdentifiers[] $public_identifiers - */ - public function setPublicIdentifiers(?array $public_identifiers): self - { - $this->public_identifiers = $public_identifiers; - return $this; - } + public function setParty(?Party $party): self + { + $this->party = $party; + return $this; + } - public function addPublicIdentifiers($public_identifier): self - { - $this->public_identifiers[] = $public_identifier; - return $this; - } + /** + * @param PublicIdentifiers[] $public_identifiers + */ + public function setPublicIdentifiers(?array $public_identifiers): self + { + $this->public_identifiers = $public_identifiers; + return $this; + } + + public function addPublicIdentifiers($public_identifier): self + { + $this->public_identifiers[] = $public_identifier; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/AccountingSupplierParty.php b/app/Services/EDocument/Gateway/Storecove/Models/AccountingSupplierParty.php index 5fa9c48484..5a532d8cc2 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/AccountingSupplierParty.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/AccountingSupplierParty.php @@ -7,54 +7,53 @@ use Symfony\Component\Serializer\Attribute\SerializedPath; class AccountingSupplierParty { - - /** @var Party */ - #[SerializedName('cac:Party')] - public $party; + /** @var Party */ + #[SerializedName('cac:Party')] + public $party; - /** @var PublicIdentifiers[] */ - public ?array $public_identifiers; + /** @var PublicIdentifiers[] */ + public ?array $public_identifiers; - /** - * @param PublicIdentifiers[] $public_identifiers - */ - public function __construct(?Party $party, ?array $public_identifiers) - { - $this->party = $party; - $this->public_identifiers = $public_identifiers; - } + /** + * @param PublicIdentifiers[] $public_identifiers + */ + public function __construct(?Party $party, ?array $public_identifiers) + { + $this->party = $party; + $this->public_identifiers = $public_identifiers; + } - public function getParty(): ?Party - { - return $this->party; - } + public function getParty(): ?Party + { + return $this->party; + } - /** - * @return PublicIdentifiers[] - */ - public function getPublicIdentifiers(): ?array - { - return $this->public_identifiers; - } + /** + * @return PublicIdentifiers[] + */ + public function getPublicIdentifiers(): ?array + { + return $this->public_identifiers; + } - public function setParty(?Party $party): self - { - $this->party = $party; - return $this; - } + public function setParty(?Party $party): self + { + $this->party = $party; + return $this; + } - /** - * @param PublicIdentifiers[] $public_identifiers - */ - public function setPublicIdentifiers(?array $public_identifiers): self - { - $this->public_identifiers = $public_identifiers; - return $this; - } + /** + * @param PublicIdentifiers[] $public_identifiers + */ + public function setPublicIdentifiers(?array $public_identifiers): self + { + $this->public_identifiers = $public_identifiers; + return $this; + } - public function addPublicIdentifiers($public_identifier): self - { - $this->public_identifiers[] = $public_identifier; - return $this; - } + public function addPublicIdentifiers($public_identifier): self + { + $this->public_identifiers[] = $public_identifier; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/AdditionalItemProperties.php b/app/Services/EDocument/Gateway/Storecove/Models/AdditionalItemProperties.php index 3959617a8c..96eed89bd0 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/AdditionalItemProperties.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/AdditionalItemProperties.php @@ -4,34 +4,34 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class AdditionalItemProperties { - public ?string $name; - public ?string $value; + public ?string $name; + public ?string $value; - public function __construct(?string $name, ?string $value) - { - $this->name = $name; - $this->value = $value; - } + public function __construct(?string $name, ?string $value) + { + $this->name = $name; + $this->value = $value; + } - public function getName(): ?string - { - return $this->name; - } + public function getName(): ?string + { + return $this->name; + } - public function getValue(): ?string - { - return $this->value; - } + public function getValue(): ?string + { + return $this->value; + } - public function setName(?string $name): self - { - $this->name = $name; - return $this; - } + public function setName(?string $name): self + { + $this->name = $name; + return $this; + } - public function setValue(?string $value): self - { - $this->value = $value; - return $this; - } + public function setValue(?string $value): self + { + $this->value = $value; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/Address.php b/app/Services/EDocument/Gateway/Storecove/Models/Address.php index a9a82817a3..a6b941c95e 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/Address.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/Address.php @@ -4,6 +4,7 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; use Symfony\Component\Serializer\Attribute\SerializedName; use Symfony\Component\Serializer\Attribute\SerializedPath; + class Address { #[SerializedPath('[cac:Country][cbc:IdentificationCode][#]')] @@ -21,87 +22,87 @@ class Address #[SerializedPath('[cbc:PostalZone]')] public ?string $zip; - public ?string $county; + public ?string $county; - public function __construct( - ?string $country, - ?string $street1, - ?string $street2, - ?string $city, - ?string $zip, - ?string $county - ) { - $this->country = $country; - $this->street1 = $street1; - $this->street2 = $street2; - $this->city = $city; - $this->zip = $zip; - $this->county = $county; - } + public function __construct( + ?string $country, + ?string $street1, + ?string $street2, + ?string $city, + ?string $zip, + ?string $county + ) { + $this->country = $country; + $this->street1 = $street1; + $this->street2 = $street2; + $this->city = $city; + $this->zip = $zip; + $this->county = $county; + } - public function getCountry(): ?string - { - return $this->country; - } + public function getCountry(): ?string + { + return $this->country; + } - public function getStreet1(): ?string - { - return $this->street1; - } + public function getStreet1(): ?string + { + return $this->street1; + } - public function getStreet2(): ?string - { - return $this->street2; - } + public function getStreet2(): ?string + { + return $this->street2; + } - public function getCity(): ?string - { - return $this->city; - } + public function getCity(): ?string + { + return $this->city; + } - public function getZip(): ?string - { - return $this->zip; - } + public function getZip(): ?string + { + return $this->zip; + } - public function getCounty(): ?string - { - return $this->county; - } + public function getCounty(): ?string + { + return $this->county; + } - public function setCountry(?string $country): self - { - $this->country = $country; - return $this; - } + public function setCountry(?string $country): self + { + $this->country = $country; + return $this; + } - public function setStreet1(?string $street1): self - { - $this->street1 = $street1; - return $this; - } + public function setStreet1(?string $street1): self + { + $this->street1 = $street1; + return $this; + } - public function setStreet2(?string $street2): self - { - $this->street2 = $street2; - return $this; - } + public function setStreet2(?string $street2): self + { + $this->street2 = $street2; + return $this; + } - public function setCity(?string $city): self - { - $this->city = $city; - return $this; - } + public function setCity(?string $city): self + { + $this->city = $city; + return $this; + } - public function setZip(?string $zip): self - { - $this->zip = $zip; - return $this; - } + public function setZip(?string $zip): self + { + $this->zip = $zip; + return $this; + } - public function setCounty(?string $county): self - { - $this->county = $county; - return $this; - } + public function setCounty(?string $county): self + { + $this->county = $county; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/AllowanceCharges.php b/app/Services/EDocument/Gateway/Storecove/Models/AllowanceCharges.php index 25984156ab..9ac05dc536 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/AllowanceCharges.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/AllowanceCharges.php @@ -11,12 +11,12 @@ class AllowanceCharges // #[SerializedPath('[cbc:Amount][#]')] public ?float $amount_excluding_vat; - #[Context(['input_format' => 'float'])] + #[Context(['input_format' => 'float'])] #[SerializedPath('[cbc:Amount][#]')] - public ?float $amount_excluding_tax; + public ?float $amount_excluding_tax; #[Context(['input_format' => 'float'])] - #[SerializedPath('[cbc:BaseAmount][#]')] + #[SerializedPath('[cbc:BaseAmount][#]')] public ?float $base_amount_excluding_tax; // #[SerializedPath('[cbc:Amount][#]')] @@ -38,122 +38,122 @@ class AllowanceCharges #[SerializedPath('[cbc:AllowanceChargeReasonCode]')] public ?string $reason_code; - /** - * @param TaxesDutiesFees[] $taxes_duties_fees - */ - public function __construct( - ?float $amount_excluding_vat, - ?float $amount_excluding_tax, - ?float $base_amount_excluding_tax, - ?float $amount_including_tax, - ?float $base_amount_including_tax, - // ?Tax $tax, - ?array $taxes_duties_fees, - ?string $reason, - ?string $reason_code - ) { - $this->amount_excluding_vat = $amount_excluding_vat; - $this->amount_excluding_tax = $amount_excluding_tax; - $this->base_amount_excluding_tax = $base_amount_excluding_tax; - $this->amount_including_tax = $amount_including_tax; - $this->base_amount_including_tax = $base_amount_including_tax; - // $this->tax = $tax; - $this->taxes_duties_fees = $taxes_duties_fees; - $this->reason = $reason; - $this->reason_code = $reason_code; - } + /** + * @param TaxesDutiesFees[] $taxes_duties_fees + */ + public function __construct( + ?float $amount_excluding_vat, + ?float $amount_excluding_tax, + ?float $base_amount_excluding_tax, + ?float $amount_including_tax, + ?float $base_amount_including_tax, + // ?Tax $tax, + ?array $taxes_duties_fees, + ?string $reason, + ?string $reason_code + ) { + $this->amount_excluding_vat = $amount_excluding_vat; + $this->amount_excluding_tax = $amount_excluding_tax; + $this->base_amount_excluding_tax = $base_amount_excluding_tax; + $this->amount_including_tax = $amount_including_tax; + $this->base_amount_including_tax = $base_amount_including_tax; + // $this->tax = $tax; + $this->taxes_duties_fees = $taxes_duties_fees; + $this->reason = $reason; + $this->reason_code = $reason_code; + } - public function getAmountExcludingVat(): ?float - { - return $this->amount_excluding_vat; - } + public function getAmountExcludingVat(): ?float + { + return $this->amount_excluding_vat; + } - public function getAmountExcludingTax(): ?float - { - return $this->amount_excluding_tax; - } + public function getAmountExcludingTax(): ?float + { + return $this->amount_excluding_tax; + } - public function getBaseAmountExcludingTax(): ?float - { - return $this->base_amount_excluding_tax; - } + public function getBaseAmountExcludingTax(): ?float + { + return $this->base_amount_excluding_tax; + } - public function getAmountIncludingTax(): ?float - { - return $this->amount_including_tax; - } + public function getAmountIncludingTax(): ?float + { + return $this->amount_including_tax; + } - public function getBaseAmountIncludingTax(): ?float - { - return $this->base_amount_including_tax; - } + public function getBaseAmountIncludingTax(): ?float + { + return $this->base_amount_including_tax; + } - /** - * @return TaxesDutiesFees[] - */ - public function getTaxesDutiesFees(): ?array - { - return $this->taxes_duties_fees; - } + /** + * @return TaxesDutiesFees[] + */ + public function getTaxesDutiesFees(): ?array + { + return $this->taxes_duties_fees; + } - public function getReason(): ?string - { - return $this->reason; - } + public function getReason(): ?string + { + return $this->reason; + } - public function getReasonCode(): ?string - { - return $this->reason_code; - } + public function getReasonCode(): ?string + { + return $this->reason_code; + } - public function setAmountExcludingVat(?float $amount_excluding_vat): self - { - $this->amount_excluding_vat = $amount_excluding_vat; - return $this; - } + public function setAmountExcludingVat(?float $amount_excluding_vat): self + { + $this->amount_excluding_vat = $amount_excluding_vat; + return $this; + } - public function setAmountExcludingTax(?float $amount_excluding_tax): self - { - $this->amount_excluding_tax = $amount_excluding_tax; - return $this; - } + public function setAmountExcludingTax(?float $amount_excluding_tax): self + { + $this->amount_excluding_tax = $amount_excluding_tax; + return $this; + } - public function setBaseAmountExcludingTax(?float $base_amount_excluding_tax): self - { - $this->base_amount_excluding_tax = $base_amount_excluding_tax; - return $this; - } + public function setBaseAmountExcludingTax(?float $base_amount_excluding_tax): self + { + $this->base_amount_excluding_tax = $base_amount_excluding_tax; + return $this; + } - public function setAmountIncludingTax(?float $amount_including_tax): self - { - $this->amount_including_tax = $amount_including_tax; - return $this; - } + public function setAmountIncludingTax(?float $amount_including_tax): self + { + $this->amount_including_tax = $amount_including_tax; + return $this; + } - public function setBaseAmountIncludingTax(?float $base_amount_including_tax): self - { - $this->base_amount_including_tax = $base_amount_including_tax; - return $this; - } + public function setBaseAmountIncludingTax(?float $base_amount_including_tax): self + { + $this->base_amount_including_tax = $base_amount_including_tax; + return $this; + } - /** - * @param TaxesDutiesFees[] $taxes_duties_fees - */ - public function setTaxesDutiesFees(?array $taxes_duties_fees): self - { - $this->taxes_duties_fees = $taxes_duties_fees; - return $this; - } + /** + * @param TaxesDutiesFees[] $taxes_duties_fees + */ + public function setTaxesDutiesFees(?array $taxes_duties_fees): self + { + $this->taxes_duties_fees = $taxes_duties_fees; + return $this; + } - public function setReason(?string $reason): self - { - $this->reason = $reason; - return $this; - } + public function setReason(?string $reason): self + { + $this->reason = $reason; + return $this; + } - public function setReasonCode(?string $reason_code): self - { - $this->reason_code = $reason_code; - return $this; - } + public function setReasonCode(?string $reason_code): self + { + $this->reason_code = $reason_code; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/Attachments.php b/app/Services/EDocument/Gateway/Storecove/Models/Attachments.php index da897578d8..cb2f575a0f 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/Attachments.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/Attachments.php @@ -4,92 +4,92 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class Attachments { - public ?string $document; - public ?string $mime_type; - public ?string $filename; - public ?string $description; - public ?string $document_id; - public ?bool $primary_image; + public ?string $document; + public ?string $mime_type; + public ?string $filename; + public ?string $description; + public ?string $document_id; + public ?bool $primary_image; - public function __construct( - ?string $document, - ?string $mime_type, - ?string $filename, - ?string $description, - ?string $document_id, - ?bool $primary_image - ) { - $this->document = $document; - $this->mime_type = $mime_type; - $this->filename = $filename; - $this->description = $description; - $this->document_id = $document_id; - $this->primary_image = $primary_image; - } + public function __construct( + ?string $document, + ?string $mime_type, + ?string $filename, + ?string $description, + ?string $document_id, + ?bool $primary_image + ) { + $this->document = $document; + $this->mime_type = $mime_type; + $this->filename = $filename; + $this->description = $description; + $this->document_id = $document_id; + $this->primary_image = $primary_image; + } - public function getDocument(): ?string - { - return $this->document; - } + public function getDocument(): ?string + { + return $this->document; + } - public function getMimeType(): ?string - { - return $this->mime_type; - } + public function getMimeType(): ?string + { + return $this->mime_type; + } - public function getFilename(): ?string - { - return $this->filename; - } + public function getFilename(): ?string + { + return $this->filename; + } - public function getDescription(): ?string - { - return $this->description; - } + public function getDescription(): ?string + { + return $this->description; + } - public function getDocumentId(): ?string - { - return $this->document_id; - } + public function getDocumentId(): ?string + { + return $this->document_id; + } - public function getPrimaryImage(): ?bool - { - return $this->primary_image; - } + public function getPrimaryImage(): ?bool + { + return $this->primary_image; + } - public function setDocument(?string $document): self - { - $this->document = $document; - return $this; - } + public function setDocument(?string $document): self + { + $this->document = $document; + return $this; + } - public function setMimeType(?string $mime_type): self - { - $this->mime_type = $mime_type; - return $this; - } + public function setMimeType(?string $mime_type): self + { + $this->mime_type = $mime_type; + return $this; + } - public function setFilename(?string $filename): self - { - $this->filename = $filename; - return $this; - } + public function setFilename(?string $filename): self + { + $this->filename = $filename; + return $this; + } - public function setDescription(?string $description): self - { - $this->description = $description; - return $this; - } + public function setDescription(?string $description): self + { + $this->description = $description; + return $this; + } - public function setDocumentId(?string $document_id): self - { - $this->document_id = $document_id; - return $this; - } + public function setDocumentId(?string $document_id): self + { + $this->document_id = $document_id; + return $this; + } - public function setPrimaryImage(?bool $primary_image): self - { - $this->primary_image = $primary_image; - return $this; - } + public function setPrimaryImage(?bool $primary_image): self + { + $this->primary_image = $primary_image; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/BuyerCustomerParty.php b/app/Services/EDocument/Gateway/Storecove/Models/BuyerCustomerParty.php index 0c5e1a94a9..bde1c1875e 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/BuyerCustomerParty.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/BuyerCustomerParty.php @@ -4,21 +4,21 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class BuyerCustomerParty { - public ?Party $party; + public ?Party $party; - public function __construct(?Party $party) - { - $this->party = $party; - } + public function __construct(?Party $party) + { + $this->party = $party; + } - public function getParty(): ?Party - { - return $this->party; - } + public function getParty(): ?Party + { + return $this->party; + } - public function setParty(?Party $party): self - { - $this->party = $party; - return $this; - } + public function setParty(?Party $party): self + { + $this->party = $party; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/Contact.php b/app/Services/EDocument/Gateway/Storecove/Models/Contact.php index 5529343dcc..fef2f5bf10 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/Contact.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/Contact.php @@ -7,84 +7,83 @@ use Symfony\Component\Serializer\Attribute\SerializedPath; class Contact { + #[SerializedPath('[cbc:Name]')] + public ?string $first_name; + public ?string $last_name; - #[SerializedPath('[cbc:Name]')] - public ?string $first_name; - public ?string $last_name; + #[SerializedPath('[cbc:ElectronicMail]')] + public ?string $email; - #[SerializedPath('[cbc:ElectronicMail]')] - public ?string $email; + #[SerializedPath('[cbc:Telephone]')] + public ?string $phone; + public ?string $id; - #[SerializedPath('[cbc:Telephone]')] - public ?string $phone; - public ?string $id; + public function __construct( + ?string $first_name, + ?string $last_name, + ?string $email, + ?string $phone, + ?string $id + ) { + $this->first_name = $first_name; + $this->last_name = $last_name; + $this->email = $email; + $this->phone = $phone; + $this->id = $id; + } - public function __construct( - ?string $first_name, - ?string $last_name, - ?string $email, - ?string $phone, - ?string $id - ) { - $this->first_name = $first_name; - $this->last_name = $last_name; - $this->email = $email; - $this->phone = $phone; - $this->id = $id; - } + public function getFirstName(): ?string + { + return $this->first_name; + } - public function getFirstName(): ?string - { - return $this->first_name; - } + public function getLastName(): ?string + { + return $this->last_name; + } - public function getLastName(): ?string - { - return $this->last_name; - } + public function getEmail(): ?string + { + return $this->email; + } - public function getEmail(): ?string - { - return $this->email; - } + public function getPhone(): ?string + { + return $this->phone; + } - public function getPhone(): ?string - { - return $this->phone; - } + public function getId(): ?string + { + return $this->id; + } - public function getId(): ?string - { - return $this->id; - } + public function setFirstName(?string $first_name): self + { + $this->first_name = $first_name; + return $this; + } - public function setFirstName(?string $first_name): self - { - $this->first_name = $first_name; - return $this; - } + public function setLastName(?string $last_name): self + { + $this->last_name = $last_name; + return $this; + } - public function setLastName(?string $last_name): self - { - $this->last_name = $last_name; - return $this; - } + public function setEmail(?string $email): self + { + $this->email = $email; + return $this; + } - public function setEmail(?string $email): self - { - $this->email = $email; - return $this; - } + public function setPhone(?string $phone): self + { + $this->phone = $phone; + return $this; + } - public function setPhone(?string $phone): self - { - $this->phone = $phone; - return $this; - } - - public function setId(?string $id): self - { - $this->id = $id; - return $this; - } + public function setId(?string $id): self + { + $this->id = $id; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/Delivery.php b/app/Services/EDocument/Gateway/Storecove/Models/Delivery.php index f70b68c53f..9d0363cd1f 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/Delivery.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/Delivery.php @@ -4,120 +4,120 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class Delivery { - public ?DeliveryLocation $delivery_location; - public ?string $requested_delivery_period; - public ?string $actual_delivery_date; - public ?float $quantity; - public ?string $delivery_party_name; - public ?DeliveryParty $delivery_party; - public ?Shipment $shipment; - public ?string $shipping_marks; + public ?DeliveryLocation $delivery_location; + public ?string $requested_delivery_period; + public ?string $actual_delivery_date; + public ?float $quantity; + public ?string $delivery_party_name; + public ?DeliveryParty $delivery_party; + public ?Shipment $shipment; + public ?string $shipping_marks; - public function __construct( - ?DeliveryLocation $delivery_location, - ?string $requested_delivery_period, - ?string $actual_delivery_date, - ?float $quantity, - ?string $delivery_party_name, - ?DeliveryParty $delivery_party, - ?Shipment $shipment, - ?string $shipping_marks - ) { - $this->delivery_location = $delivery_location; - $this->requested_delivery_period = $requested_delivery_period; - $this->actual_delivery_date = $actual_delivery_date; - $this->quantity = $quantity; - $this->delivery_party_name = $delivery_party_name; - $this->delivery_party = $delivery_party; - $this->shipment = $shipment; - $this->shipping_marks = $shipping_marks; - } + public function __construct( + ?DeliveryLocation $delivery_location, + ?string $requested_delivery_period, + ?string $actual_delivery_date, + ?float $quantity, + ?string $delivery_party_name, + ?DeliveryParty $delivery_party, + ?Shipment $shipment, + ?string $shipping_marks + ) { + $this->delivery_location = $delivery_location; + $this->requested_delivery_period = $requested_delivery_period; + $this->actual_delivery_date = $actual_delivery_date; + $this->quantity = $quantity; + $this->delivery_party_name = $delivery_party_name; + $this->delivery_party = $delivery_party; + $this->shipment = $shipment; + $this->shipping_marks = $shipping_marks; + } - public function getDeliveryLocation(): ?DeliveryLocation - { - return $this->delivery_location; - } + public function getDeliveryLocation(): ?DeliveryLocation + { + return $this->delivery_location; + } - public function getRequestedDeliveryPeriod(): ?string - { - return $this->requested_delivery_period; - } + public function getRequestedDeliveryPeriod(): ?string + { + return $this->requested_delivery_period; + } - public function getActualDeliveryDate(): ?string - { - return $this->actual_delivery_date; - } + public function getActualDeliveryDate(): ?string + { + return $this->actual_delivery_date; + } - public function getQuantity(): ?float - { - return $this->quantity; - } + public function getQuantity(): ?float + { + return $this->quantity; + } - public function getDeliveryPartyName(): ?string - { - return $this->delivery_party_name; - } + public function getDeliveryPartyName(): ?string + { + return $this->delivery_party_name; + } - public function getDeliveryParty(): ?DeliveryParty - { - return $this->delivery_party; - } + public function getDeliveryParty(): ?DeliveryParty + { + return $this->delivery_party; + } - public function getShipment(): ?Shipment - { - return $this->shipment; - } + public function getShipment(): ?Shipment + { + return $this->shipment; + } - public function getShippingMarks(): ?string - { - return $this->shipping_marks; - } + public function getShippingMarks(): ?string + { + return $this->shipping_marks; + } - public function setDeliveryLocation(?DeliveryLocation $delivery_location): self - { - $this->delivery_location = $delivery_location; - return $this; - } + public function setDeliveryLocation(?DeliveryLocation $delivery_location): self + { + $this->delivery_location = $delivery_location; + return $this; + } - public function setRequestedDeliveryPeriod(?string $requested_delivery_period): self - { - $this->requested_delivery_period = $requested_delivery_period; - return $this; - } + public function setRequestedDeliveryPeriod(?string $requested_delivery_period): self + { + $this->requested_delivery_period = $requested_delivery_period; + return $this; + } - public function setActualDeliveryDate(?string $actual_delivery_date): self - { - $this->actual_delivery_date = $actual_delivery_date; - return $this; - } + public function setActualDeliveryDate(?string $actual_delivery_date): self + { + $this->actual_delivery_date = $actual_delivery_date; + return $this; + } - public function setQuantity(?float $quantity): self - { - $this->quantity = $quantity; - return $this; - } + public function setQuantity(?float $quantity): self + { + $this->quantity = $quantity; + return $this; + } - public function setDeliveryPartyName(?string $delivery_party_name): self - { - $this->delivery_party_name = $delivery_party_name; - return $this; - } + public function setDeliveryPartyName(?string $delivery_party_name): self + { + $this->delivery_party_name = $delivery_party_name; + return $this; + } - public function setDeliveryParty(?DeliveryParty $delivery_party): self - { - $this->delivery_party = $delivery_party; - return $this; - } + public function setDeliveryParty(?DeliveryParty $delivery_party): self + { + $this->delivery_party = $delivery_party; + return $this; + } - public function setShipment(?Shipment $shipment): self - { - $this->shipment = $shipment; - return $this; - } + public function setShipment(?Shipment $shipment): self + { + $this->shipment = $shipment; + return $this; + } - public function setShippingMarks(?string $shipping_marks): self - { - $this->shipping_marks = $shipping_marks; - return $this; - } + public function setShippingMarks(?string $shipping_marks): self + { + $this->shipping_marks = $shipping_marks; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/DeliveryLocation.php b/app/Services/EDocument/Gateway/Storecove/Models/DeliveryLocation.php index 118b2c3f40..213ef10362 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/DeliveryLocation.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/DeliveryLocation.php @@ -4,78 +4,78 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class DeliveryLocation { - public ?string $id; - public ?string $scheme_id; - public ?string $scheme_agency_id; - public ?string $location_name; - public ?Address $address; + public ?string $id; + public ?string $scheme_id; + public ?string $scheme_agency_id; + public ?string $location_name; + public ?Address $address; - public function __construct( - ?string $id, - ?string $scheme_id, - ?string $scheme_agency_id, - ?string $location_name, - ?Address $address - ) { - $this->id = $id; - $this->scheme_id = $scheme_id; - $this->scheme_agency_id = $scheme_agency_id; - $this->location_name = $location_name; - $this->address = $address; - } + public function __construct( + ?string $id, + ?string $scheme_id, + ?string $scheme_agency_id, + ?string $location_name, + ?Address $address + ) { + $this->id = $id; + $this->scheme_id = $scheme_id; + $this->scheme_agency_id = $scheme_agency_id; + $this->location_name = $location_name; + $this->address = $address; + } - public function getId(): ?string - { - return $this->id; - } + public function getId(): ?string + { + return $this->id; + } - public function getSchemeId(): ?string - { - return $this->scheme_id; - } + public function getSchemeId(): ?string + { + return $this->scheme_id; + } - public function getSchemeAgencyId(): ?string - { - return $this->scheme_agency_id; - } + public function getSchemeAgencyId(): ?string + { + return $this->scheme_agency_id; + } - public function getLocationName(): ?string - { - return $this->location_name; - } + public function getLocationName(): ?string + { + return $this->location_name; + } - public function getAddress(): ?Address - { - return $this->address; - } + public function getAddress(): ?Address + { + return $this->address; + } - public function setId(?string $id): self - { - $this->id = $id; - return $this; - } + public function setId(?string $id): self + { + $this->id = $id; + return $this; + } - public function setSchemeId(?string $scheme_id): self - { - $this->scheme_id = $scheme_id; - return $this; - } + public function setSchemeId(?string $scheme_id): self + { + $this->scheme_id = $scheme_id; + return $this; + } - public function setSchemeAgencyId(?string $scheme_agency_id): self - { - $this->scheme_agency_id = $scheme_agency_id; - return $this; - } + public function setSchemeAgencyId(?string $scheme_agency_id): self + { + $this->scheme_agency_id = $scheme_agency_id; + return $this; + } - public function setLocationName(?string $location_name): self - { - $this->location_name = $location_name; - return $this; - } + public function setLocationName(?string $location_name): self + { + $this->location_name = $location_name; + return $this; + } - public function setAddress(?Address $address): self - { - $this->address = $address; - return $this; - } + public function setAddress(?Address $address): self + { + $this->address = $address; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/DeliveryParty.php b/app/Services/EDocument/Gateway/Storecove/Models/DeliveryParty.php index 0ef1657c95..00a103a8c9 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/DeliveryParty.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/DeliveryParty.php @@ -4,44 +4,44 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class DeliveryParty { - public ?Party $party; - /** @var PublicIdentifiers[] */ - public ?array $public_identifiers; + public ?Party $party; + /** @var PublicIdentifiers[] */ + public ?array $public_identifiers; - /** - * @param PublicIdentifiers[] $public_identifiers - */ - public function __construct(?Party $party, ?array $public_identifiers) - { - $this->party = $party; - $this->public_identifiers = $public_identifiers; - } + /** + * @param PublicIdentifiers[] $public_identifiers + */ + public function __construct(?Party $party, ?array $public_identifiers) + { + $this->party = $party; + $this->public_identifiers = $public_identifiers; + } - public function getParty(): ?Party - { - return $this->party; - } + public function getParty(): ?Party + { + return $this->party; + } - /** - * @return PublicIdentifiers[] - */ - public function getPublicIdentifiers(): ?array - { - return $this->public_identifiers; - } + /** + * @return PublicIdentifiers[] + */ + public function getPublicIdentifiers(): ?array + { + return $this->public_identifiers; + } - public function setParty(?Party $party): self - { - $this->party = $party; - return $this; - } + public function setParty(?Party $party): self + { + $this->party = $party; + return $this; + } - /** - * @param PublicIdentifiers[] $public_identifiers - */ - public function setPublicIdentifiers(?array $public_identifiers): self - { - $this->public_identifiers = $public_identifiers; - return $this; - } + /** + * @param PublicIdentifiers[] $public_identifiers + */ + public function setPublicIdentifiers(?array $public_identifiers): self + { + $this->public_identifiers = $public_identifiers; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/DeliveryTerms.php b/app/Services/EDocument/Gateway/Storecove/Models/DeliveryTerms.php index 573dd561d3..533e61fd43 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/DeliveryTerms.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/DeliveryTerms.php @@ -4,50 +4,50 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class DeliveryTerms { - public ?string $incoterms; - public ?string $special_terms; - public ?string $delivery_location_id; + public ?string $incoterms; + public ?string $special_terms; + public ?string $delivery_location_id; - public function __construct( - ?string $incoterms, - ?string $special_terms, - ?string $delivery_location_id - ) { - $this->incoterms = $incoterms; - $this->special_terms = $special_terms; - $this->delivery_location_id = $delivery_location_id; - } + public function __construct( + ?string $incoterms, + ?string $special_terms, + ?string $delivery_location_id + ) { + $this->incoterms = $incoterms; + $this->special_terms = $special_terms; + $this->delivery_location_id = $delivery_location_id; + } - public function getIncoterms(): ?string - { - return $this->incoterms; - } + public function getIncoterms(): ?string + { + return $this->incoterms; + } - public function getSpecialTerms(): ?string - { - return $this->special_terms; - } + public function getSpecialTerms(): ?string + { + return $this->special_terms; + } - public function getDeliveryLocationId(): ?string - { - return $this->delivery_location_id; - } + public function getDeliveryLocationId(): ?string + { + return $this->delivery_location_id; + } - public function setIncoterms(?string $incoterms): self - { - $this->incoterms = $incoterms; - return $this; - } + public function setIncoterms(?string $incoterms): self + { + $this->incoterms = $incoterms; + return $this; + } - public function setSpecialTerms(?string $special_terms): self - { - $this->special_terms = $special_terms; - return $this; - } + public function setSpecialTerms(?string $special_terms): self + { + $this->special_terms = $special_terms; + return $this; + } - public function setDeliveryLocationId(?string $delivery_location_id): self - { - $this->delivery_location_id = $delivery_location_id; - return $this; - } + public function setDeliveryLocationId(?string $delivery_location_id): self + { + $this->delivery_location_id = $delivery_location_id; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/Document.php b/app/Services/EDocument/Gateway/Storecove/Models/Document.php index 00a65e5ec3..6be37e17e3 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/Document.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/Document.php @@ -4,64 +4,64 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class Document { - public ?string $document_type; - public ?string $source; - public ?Invoice $invoice; - public ?Order $order; + public ?string $document_type; + public ?string $source; + public ?Invoice $invoice; + public ?Order $order; - public function __construct( - ?string $document_type, - ?string $source, - ?Invoice $invoice, - ?Order $order - ) { - $this->document_type = $document_type; - $this->source = $source; - $this->invoice = $invoice; - $this->order = $order; - } + public function __construct( + ?string $document_type, + ?string $source, + ?Invoice $invoice, + ?Order $order + ) { + $this->document_type = $document_type; + $this->source = $source; + $this->invoice = $invoice; + $this->order = $order; + } - public function getDocumentType(): ?string - { - return $this->document_type; - } + public function getDocumentType(): ?string + { + return $this->document_type; + } - public function getSource(): ?string - { - return $this->source; - } + public function getSource(): ?string + { + return $this->source; + } - public function getInvoice(): ?Invoice - { - return $this->invoice; - } + public function getInvoice(): ?Invoice + { + return $this->invoice; + } - public function getOrder(): ?Order - { - return $this->order; - } + public function getOrder(): ?Order + { + return $this->order; + } - public function setDocumentType(?string $document_type): self - { - $this->document_type = $document_type; - return $this; - } + public function setDocumentType(?string $document_type): self + { + $this->document_type = $document_type; + return $this; + } - public function setSource(?string $source): self - { - $this->source = $source; - return $this; - } + public function setSource(?string $source): self + { + $this->source = $source; + return $this; + } - public function setInvoice(?Invoice $invoice): self - { - $this->invoice = $invoice; - return $this; - } + public function setInvoice(?Invoice $invoice): self + { + $this->invoice = $invoice; + return $this; + } - public function setOrder(?Order $order): self - { - $this->order = $order; - return $this; - } + public function setOrder(?Order $order): self + { + $this->order = $order; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/Invoice.php b/app/Services/EDocument/Gateway/Storecove/Models/Invoice.php index f4172ca5a7..4860b766a0 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/Invoice.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/Invoice.php @@ -11,903 +11,903 @@ use Symfony\Component\Serializer\Attribute\Context; class Invoice { #[SerializedPath('[cbc:ID][#]')] - public $invoice_number; + public $invoice_number; // /** @var ?\DateTime */ #[SerializedPath('[cbc:IssueDate]')] // #[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])] - public $issue_date; + public $issue_date; #[SerializedPath('[cac:AccountingCustomerParty]')] /** @var ?AccountingCustomerParty */ - public $accounting_customer_party; + public $accounting_customer_party; #[SerializedName('cac:InvoiceLine')] - /** @var InvoiceLines[] */ - public array $invoice_lines; + /** @var InvoiceLines[] */ + public array $invoice_lines; #[SerializedPath('[cbc:AccountingCost]')] - public $accounting_cost; + public $accounting_cost; + + public ?string $accounting_currency_exchange_rate; + public ?string $accounting_currency_taxable_amount; + public ?string $accounting_currency_tax_amount; + public ?string $accounting_currency_tax_amount_currency; - public ?string $accounting_currency_exchange_rate; - public ?string $accounting_currency_taxable_amount; - public ?string $accounting_currency_tax_amount; - public ?string $accounting_currency_tax_amount_currency; - #[SerializedPath('[cac:AccountingSupplierParty]')] /** @var ?AccountingSupplierParty */ - public $accounting_supplier_party; + public $accounting_supplier_party; #[SerializedPath('[cac:AllowanceCharge]')] - /** @var AllowanceCharges[] */ - public ?array $allowance_charges = []; + /** @var AllowanceCharges[] */ + public ?array $allowance_charges = []; //this is an experimental prop // #[SerializedPath('[cac:LegalMonetaryTotal][cbc:TaxInclusiveAmount][#]')] // #[Context(['path_type' => 'tax'])] - public $amount_including_tax; - + public $amount_including_tax; + #[SerializedPath('[cac:LegalMonetaryTotal][cbc:TaxInclusiveAmount][#]')] - public $amount_including_vat; - + public $amount_including_vat; + /** @var Attachments[] */ - public ?array $attachments; - + public ?array $attachments; + public ?bool $consumer_tax_mode; //toggle this to TRUE if we are using a secondary identifier ie. when German company is taxing French company and therefore using the additional Vat identifier - - #[SerializedName('cac:Delivery')] + + #[SerializedName('cac:Delivery')] public ?Delivery $delivery; - //no mapping - public ?DeliveryTerms $delivery_terms; - + //no mapping + public ?DeliveryTerms $delivery_terms; + #[SerializedPath('[cbc:DocumentCurrencyCode][#]')] public $document_currency_code; - + // /** @var ?\DateTime */ #[SerializedPath('[cbc:DueDate]')] // #[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])] public ?string $due_date; - //may need something custom for this + //may need something custom for this public ?string $invoice_period; //no mapping - public ?array $issue_reasons; - + public ?array $issue_reasons; + //no mapping public ?string $issue_time; #[SerializedPath('[cbc:Note]')] - public $note; + public $note; //no mapping - public ?string $payable_rounding_amount; + public ?string $payable_rounding_amount; #[SerializedPath('[cac:PaymentMeans]')] - /** @var PaymentMeansArray[] */ - public array $payment_means_array; + /** @var PaymentMeansArray[] */ + public array $payment_means_array; - #[SerializedPath('[cac:PaymentTerms][0]')] - public ?PaymentTerms $payment_terms; + #[SerializedPath('[cac:PaymentTerms][0]')] + public ?PaymentTerms $payment_terms; // no mapping - public ?string $preferred_invoice_type; - + public ?string $preferred_invoice_type; + #[SerializedPath('[cac:LegalMonetaryTotal][cbc:PrepaidAmount]')] - public ?string $prepaid_amount; + public ?string $prepaid_amount; - //no mapping - // 'price_mode_gross' can only be used for sender countries ES, IT and PT - public ?string $price_mode; + //no mapping + // 'price_mode_gross' can only be used for sender countries ES, IT and PT + public ?string $price_mode; - /** @var References[] */ - public ?array $references; + /** @var References[] */ + public ?array $references; - //AU/NZ and JP. - only available intra country ie AU - AU - public ?bool $self_billing_mode; + //AU/NZ and JP. - only available intra country ie AU - AU + public ?bool $self_billing_mode; - //readonly prop for received documents - public ?string $sub_type; + //readonly prop for received documents + public ?string $sub_type; - //proxy of issue date - public ?string $tax_point_date; + //proxy of issue date + public ?string $tax_point_date; - #[SerializedPath('[cac:TaxTotal][0][cac:TaxSubtotal]')] - /** @var TaxSubtotals[] */ - public $tax_subtotals; + #[SerializedPath('[cac:TaxTotal][0][cac:TaxSubtotal]')] + /** @var TaxSubtotals[] */ + public $tax_subtotals; - //storecove - no mappings - tax_line_percentages - public ?string $tax_system; + //storecove - no mappings - tax_line_percentages + public ?string $tax_system; - //italy only - invoice level - /** @var TaxesDutiesFees[] */ - public ?array $taxes_duties_fees; + //italy only - invoice level + /** @var TaxesDutiesFees[] */ + public ?array $taxes_duties_fees; - //no mapping - public ?string $time_zone; + //no mapping + public ?string $time_zone; - // india only enum (b2b, sezwp, sezwop, expwp, expwop, dexp) - public ?string $transaction_type; + // india only enum (b2b, sezwp, sezwop, expwp, expwop, dexp) + public ?string $transaction_type; - //no mapping - public ?array $ubl_extensions; + //no mapping + public ?array $ubl_extensions; - //no mapping - public ?string $x2y; + //no mapping + public ?string $x2y; - //not found in schema - public ?bool $vat_reverse_charge; - public ?string $tax_exempt_reason; - public ?string $invoice_type; - public ?string $payment_means_iban; - public ?string $payment_means_bic; - public ?string $payment_means_code; - public ?string $payment_means_payment_id; - //not found in schema + //not found in schema + public ?bool $vat_reverse_charge; + public ?string $tax_exempt_reason; + public ?string $invoice_type; + public ?string $payment_means_iban; + public ?string $payment_means_bic; + public ?string $payment_means_code; + public ?string $payment_means_payment_id; + //not found in schema #[SerializedPath('[cbc:BuyerReference]')] - public ?string $buyer_reference; + public ?string $buyer_reference; #[SerializedPath('[cac:OrderReference][cbc:ID][#]')] - public ?string $order_reference; + public ?string $order_reference; #[SerializedPath('[cac:OrderReference][cbc:SalesOrderID][#]')] - public ?string $sales_order_id; + public ?string $sales_order_id; #[SerializedPath('[cac:BillingReference][cac:InvoiceDocumentReference][cbc:ID][#]')] - public ?string $billing_reference; + public ?string $billing_reference; #[SerializedPath('[cac:ContractDocumentReference][cbc:ID][#]')] - public ?string $contract_document_reference; + public ?string $contract_document_reference; #[SerializedPath('[cac:ProjectReference][cbc:ID][#]')] - public ?string $project_reference; - - public function __construct( - ?string $invoice_number, - ?string $issue_date, - ?AccountingCustomerParty $accounting_customer_party, - ?array $invoice_lines, - ?string $accounting_cost, - ?string $accounting_currency_exchange_rate, - ?string $accounting_currency_taxable_amount, - ?string $accounting_currency_tax_amount, - ?string $accounting_currency_tax_amount_currency, - ?AccountingSupplierParty $accounting_supplier_party, - ?array $allowance_charges, - ?float $amount_including_tax, - ?float $amount_including_vat, - ?array $attachments, - ?bool $consumer_tax_mode, - ?Delivery $delivery, - ?DeliveryTerms $delivery_terms, - ?string $document_currency_code, - ?string $due_date, - ?string $invoice_period, - ?array $issue_reasons, - ?string $issue_time, - ?string $note, - ?string $payable_rounding_amount, - ?array $payment_means_array, - ?PaymentTerms $payment_terms, - ?string $preferred_invoice_type, - ?string $prepaid_amount, - ?string $price_mode, - ?array $references, - ?bool $self_billing_mode, - ?string $sub_type, - ?string $tax_point_date, - ?array $tax_subtotals, - ?string $tax_system, - ?array $taxes_duties_fees, - ?string $time_zone, - ?string $transaction_type, - ?array $ubl_extensions, - ?string $x2y, - ?bool $vat_reverse_charge, - ?string $tax_exempt_reason, - ?string $invoice_type, - ?string $buyer_reference, - ?string $order_reference, - ?string $sales_order_id, - ?string $billing_reference, - ?string $contract_document_reference, - ?string $project_reference, - ?string $payment_means_iban, - ?string $payment_means_bic, - ?string $payment_means_code, - ?string $payment_means_payment_id - ) { - $this->invoice_number = $invoice_number; - $this->issue_date = $issue_date; - $this->accounting_customer_party = $accounting_customer_party; - $this->invoice_lines = $invoice_lines; - $this->accounting_cost = $accounting_cost; - $this->accounting_currency_exchange_rate = $accounting_currency_exchange_rate; - $this->accounting_currency_taxable_amount = $accounting_currency_taxable_amount; - $this->accounting_currency_tax_amount = $accounting_currency_tax_amount; - $this->accounting_currency_tax_amount_currency = $accounting_currency_tax_amount_currency; - $this->accounting_supplier_party = $accounting_supplier_party; - $this->allowance_charges = $allowance_charges; - $this->amount_including_tax = $amount_including_tax; - $this->amount_including_vat = $amount_including_vat; - $this->attachments = $attachments; - $this->consumer_tax_mode = $consumer_tax_mode; - $this->delivery = $delivery; - $this->delivery_terms = $delivery_terms; - $this->document_currency_code = $document_currency_code; - $this->due_date = $due_date; - $this->invoice_period = $invoice_period; - $this->issue_reasons = $issue_reasons; - $this->issue_time = $issue_time; - $this->note = $note; - $this->payable_rounding_amount = $payable_rounding_amount; - $this->payment_means_array = $payment_means_array; - $this->payment_terms = $payment_terms; - $this->preferred_invoice_type = $preferred_invoice_type; - $this->prepaid_amount = $prepaid_amount; - $this->price_mode = $price_mode; - $this->references = $references; - $this->self_billing_mode = $self_billing_mode; - $this->sub_type = $sub_type; - $this->tax_point_date = $tax_point_date; - $this->tax_subtotals = $tax_subtotals; - $this->tax_system = $tax_system; - $this->taxes_duties_fees = $taxes_duties_fees; - $this->time_zone = $time_zone; - $this->transaction_type = $transaction_type; - $this->ubl_extensions = $ubl_extensions; - $this->x2y = $x2y; - $this->vat_reverse_charge = $vat_reverse_charge; - $this->tax_exempt_reason = $tax_exempt_reason; - $this->invoice_type = $invoice_type; - $this->buyer_reference = $buyer_reference; - $this->order_reference = $order_reference; - $this->sales_order_id = $sales_order_id; - $this->billing_reference = $billing_reference; - $this->contract_document_reference = $contract_document_reference; - $this->project_reference = $project_reference; - $this->payment_means_iban = $payment_means_iban; - $this->payment_means_bic = $payment_means_bic; - $this->payment_means_code = $payment_means_code; - $this->payment_means_payment_id = $payment_means_payment_id; - } - - public function getInvoiceNumber(): ?string - { - return $this->invoice_number; - } - - public function getIssueDate(): ?string - { - return $this->issue_date; - } - - public function getAccountingCustomerParty(): ?AccountingCustomerParty - { - return $this->accounting_customer_party; - } - - /** - * @return InvoiceLines[] - */ - public function getInvoiceLines(): ?array - { - return $this->invoice_lines; - } - - public function getAccountingCost(): ?string - { - return $this->accounting_cost; - } - - public function getAccountingCurrencyExchangeRate(): ?string - { - return $this->accounting_currency_exchange_rate; - } - - public function getAccountingCurrencyTaxableAmount(): ?string - { - return $this->accounting_currency_taxable_amount; - } - - public function getAccountingCurrencyTaxAmount(): ?string - { - return $this->accounting_currency_tax_amount; - } - - public function getAccountingCurrencyTaxAmountCurrency(): ?string - { - return $this->accounting_currency_tax_amount_currency; - } - - public function getAccountingSupplierParty(): ?AccountingSupplierParty - { - return $this->accounting_supplier_party; - } - - /** - * @return AllowanceCharges[] - */ - public function getAllowanceCharges(): ?array - { - return $this->allowance_charges; - } - - public function getAmountIncludingTax(): ?float - { - return $this->amount_including_tax; - } - - public function getAmountIncludingVat(): ?float - { - return $this->amount_including_vat; - } - - /** - * @return Attachments[] - */ - public function getAttachments(): ?array - { - return $this->attachments; - } - - public function getConsumerTaxMode(): ?bool - { - return $this->consumer_tax_mode; - } - - public function getDelivery(): ?Delivery - { - return $this->delivery; - } - - public function getDeliveryTerms(): ?DeliveryTerms - { - return $this->delivery_terms; - } - - public function getDocumentCurrencyCode(): ?string - { - return $this->document_currency_code; - } - - public function getDueDate() - { - return $this->due_date; - } - - public function getInvoicePeriod(): ?string - { - return $this->invoice_period; - } - - /** - * @return string[] - */ - public function getIssueReasons(): ?array - { - return $this->issue_reasons; - } - - public function getIssueTime(): ?string - { - return $this->issue_time; - } - - public function getNote(): ?string - { - return $this->note; - } - - public function getPayableRoundingAmount(): ?string - { - return $this->payable_rounding_amount; - } - - /** - * @return PaymentMeansArray[] - */ - public function getPaymentMeansArray(): ?array - { - return $this->payment_means_array; - } - - public function getPaymentTerms(): ?PaymentTerms - { - return $this->payment_terms; - } - - public function getPreferredInvoiceType(): ?string - { - return $this->preferred_invoice_type; - } - - public function getPrepaidAmount(): ?string - { - return $this->prepaid_amount; - } - - public function getPriceMode(): ?string - { - return $this->price_mode; - } - - /** - * @return References[] - */ - public function getReferences(): ?array - { - return $this->references; - } - - public function getSelfBillingMode(): ?bool - { - return $this->self_billing_mode; - } - - public function getSubType(): ?string - { - return $this->sub_type; - } - - public function getTaxPointDate(): ?string - { - return $this->tax_point_date; - } - - /** - * @return TaxSubtotals[] - */ - public function getTaxSubtotals(): ?array - { - return $this->tax_subtotals; - } - - public function getTaxSystem(): ?string - { - return $this->tax_system; - } - - /** - * @return TaxesDutiesFees[] - */ - public function getTaxesDutiesFees(): ?array - { - return $this->taxes_duties_fees; - } - - public function getTimeZone(): ?string - { - return $this->time_zone; - } - - public function getTransactionType(): ?string - { - return $this->transaction_type; - } - - /** - * @return string[] - */ - public function getUblExtensions(): ?array - { - return $this->ubl_extensions; - } - - public function getX2y(): ?string - { - return $this->x2y; - } - - public function getVatReverseCharge(): ?bool - { - return $this->vat_reverse_charge; - } - - public function getTaxExemptReason(): ?string - { - return $this->tax_exempt_reason; - } - - public function getInvoiceType(): ?string - { - return $this->invoice_type; - } - - public function getBuyerReference(): ?string - { - return $this->buyer_reference; - } - - public function getOrderReference(): ?string - { - return $this->order_reference; - } - - public function getSalesOrderId(): ?string - { - return $this->sales_order_id; - } - - public function getBillingReference(): ?string - { - return $this->billing_reference; - } - - public function getContractDocumentReference(): ?string - { - return $this->contract_document_reference; - } - - public function getProjectReference(): ?string - { - return $this->project_reference; - } - - public function getPaymentMeansIban(): ?string - { - return $this->payment_means_iban; - } - - public function getPaymentMeansBic(): ?string - { - return $this->payment_means_bic; - } - - public function getPaymentMeansCode(): ?string - { - return $this->payment_means_code; - } - - public function getPaymentMeansPaymentId(): ?string - { - return $this->payment_means_payment_id; - } - - public function setInvoiceNumber(?string $invoice_number): self - { - $this->invoice_number = $invoice_number; - return $this; - } - - public function setIssueDate($issue_date): self - { - $this->issue_date = $issue_date; - return $this; - } - - public function setAccountingCustomerParty(?AccountingCustomerParty $accounting_customer_party): self - { - $this->accounting_customer_party = $accounting_customer_party; - return $this; - } - - /** - * @param InvoiceLines[] $invoice_lines - */ - public function setInvoiceLines(?array $invoice_lines): self - { - $this->invoice_lines = $invoice_lines; - return $this; - } - - public function setAccountingCost(?string $accounting_cost): self - { - $this->accounting_cost = $accounting_cost; - return $this; - } - - public function setAccountingCurrencyExchangeRate(?string $accounting_currency_exchange_rate): self - { - $this->accounting_currency_exchange_rate = $accounting_currency_exchange_rate; - return $this; - } - - public function setAccountingCurrencyTaxableAmount(?string $accounting_currency_taxable_amount): self - { - $this->accounting_currency_taxable_amount = $accounting_currency_taxable_amount; - return $this; - } - - public function setAccountingCurrencyTaxAmount(?string $accounting_currency_tax_amount): self - { - $this->accounting_currency_tax_amount = $accounting_currency_tax_amount; - return $this; - } - - public function setAccountingCurrencyTaxAmountCurrency(?string $accounting_currency_tax_amount_currency): self - { - $this->accounting_currency_tax_amount_currency = $accounting_currency_tax_amount_currency; - return $this; - } - - public function setAccountingSupplierParty(?AccountingSupplierParty $accounting_supplier_party): self - { - $this->accounting_supplier_party = $accounting_supplier_party; - return $this; - } - - /** - * @param AllowanceCharges[] $allowance_charges - */ - public function setAllowanceCharges(?array $allowance_charges): self - { - $this->allowance_charges = $allowance_charges; - return $this; - } - - public function setAmountIncludingTax(?float $amount_including_tax): self - { - $this->amount_including_tax = $amount_including_tax; - return $this; - } - - public function setAmountIncludingVat(?float $amount_including_vat): self - { - $this->amount_including_vat = $amount_including_vat; - return $this; - } - - /** - * @param Attachments[] $attachments - */ - public function setAttachments(?array $attachments): self - { - $this->attachments = $attachments; - return $this; - } - - public function setConsumerTaxMode(?bool $consumer_tax_mode): self - { - $this->consumer_tax_mode = $consumer_tax_mode; - return $this; - } - - public function setDelivery(?Delivery $delivery): self - { - $this->delivery = $delivery; - return $this; - } - - public function setDeliveryTerms(?DeliveryTerms $delivery_terms): self - { - $this->delivery_terms = $delivery_terms; - return $this; - } - - public function setDocumentCurrencyCode(?string $document_currency_code): self - { - $this->document_currency_code = $document_currency_code; - return $this; - } - - public function setDueDate(?string $due_date): self - { - $this->due_date = $due_date; - return $this; - } - - public function setInvoicePeriod(?string $invoice_period): self - { - $this->invoice_period = $invoice_period; - return $this; - } - - /** - * @param string[] $issue_reasons - */ - public function setIssueReasons(?array $issue_reasons): self - { - $this->issue_reasons = $issue_reasons; - return $this; - } - - public function setIssueTime(?string $issue_time): self - { - $this->issue_time = $issue_time; - return $this; - } - - public function setNote(?string $note): self - { - $this->note = $note; - return $this; - } - - public function setPayableRoundingAmount(?string $payable_rounding_amount): self - { - $this->payable_rounding_amount = $payable_rounding_amount; - return $this; - } - - /** - * @param PaymentMeansArray[] $payment_means_array - */ - public function setPaymentMeansArray(?array $payment_means_array): self - { - $this->payment_means_array = $payment_means_array; - return $this; - } - - public function setPaymentTerms(?PaymentTerms $payment_terms): self - { - $this->payment_terms = $payment_terms; - return $this; - } - - public function setPreferredInvoiceType(?string $preferred_invoice_type): self - { - $this->preferred_invoice_type = $preferred_invoice_type; - return $this; - } - - public function setPrepaidAmount(?string $prepaid_amount): self - { - $this->prepaid_amount = $prepaid_amount; - return $this; - } - - public function setPriceMode(?string $price_mode): self - { - $this->price_mode = $price_mode; - return $this; - } - - /** - * @param References[] $references - */ - public function setReferences(?array $references): self - { - $this->references = $references; - return $this; - } - - public function setSelfBillingMode(?bool $self_billing_mode): self - { - $this->self_billing_mode = $self_billing_mode; - return $this; - } - - public function setSubType(?string $sub_type): self - { - $this->sub_type = $sub_type; - return $this; - } - - public function setTaxPointDate(?string $tax_point_date): self - { - $this->tax_point_date = $tax_point_date; - return $this; - } - - /** - * @param TaxSubtotals[] $tax_subtotals - */ - public function setTaxSubtotals(?array $tax_subtotals): self - { - $this->tax_subtotals = $tax_subtotals; - return $this; - } - - public function setTaxSystem(?string $tax_system): self - { - $this->tax_system = $tax_system; - return $this; - } - - /** - * @param TaxesDutiesFees[] $taxes_duties_fees - */ - public function setTaxesDutiesFees(?array $taxes_duties_fees): self - { - $this->taxes_duties_fees = $taxes_duties_fees; - return $this; - } - - public function setTimeZone(?string $time_zone): self - { - $this->time_zone = $time_zone; - return $this; - } - - public function setTransactionType(?string $transaction_type): self - { - $this->transaction_type = $transaction_type; - return $this; - } - - /** - * @param string[] $ubl_extensions - */ - public function setUblExtensions(?array $ubl_extensions): self - { - $this->ubl_extensions = $ubl_extensions; - return $this; - } - - public function setX2y(?string $x2y): self - { - $this->x2y = $x2y; - return $this; - } - - public function setVatReverseCharge(?bool $vat_reverse_charge): self - { - $this->vat_reverse_charge = $vat_reverse_charge; - return $this; - } - - public function setTaxExemptReason(?string $tax_exempt_reason): self - { - $this->tax_exempt_reason = $tax_exempt_reason; - return $this; - } - - public function setInvoiceType(?string $invoice_type): self - { - $this->invoice_type = $invoice_type; - return $this; - } - - public function setBuyerReference(?string $buyer_reference): self - { - $this->buyer_reference = $buyer_reference; - return $this; - } - - public function setOrderReference(?string $order_reference): self - { - $this->order_reference = $order_reference; - return $this; - } - - public function setSalesOrderId(?string $sales_order_id): self - { - $this->sales_order_id = $sales_order_id; - return $this; - } - - public function setBillingReference(?string $billing_reference): self - { - $this->billing_reference = $billing_reference; - return $this; - } - - public function setContractDocumentReference(?string $contract_document_reference): self - { - $this->contract_document_reference = $contract_document_reference; - return $this; - } - - public function setProjectReference(?string $project_reference): self - { - $this->project_reference = $project_reference; - return $this; - } - - public function setPaymentMeansIban(?string $payment_means_iban): self - { - $this->payment_means_iban = $payment_means_iban; - return $this; - } - - public function setPaymentMeansBic(?string $payment_means_bic): self - { - $this->payment_means_bic = $payment_means_bic; - return $this; - } - - public function setPaymentMeansCode(?string $payment_means_code): self - { - $this->payment_means_code = $payment_means_code; - return $this; - } - - public function setPaymentMeansPaymentId(?string $payment_means_payment_id): self - { - $this->payment_means_payment_id = $payment_means_payment_id; - return $this; - } + public ?string $project_reference; + + public function __construct( + ?string $invoice_number, + ?string $issue_date, + ?AccountingCustomerParty $accounting_customer_party, + ?array $invoice_lines, + ?string $accounting_cost, + ?string $accounting_currency_exchange_rate, + ?string $accounting_currency_taxable_amount, + ?string $accounting_currency_tax_amount, + ?string $accounting_currency_tax_amount_currency, + ?AccountingSupplierParty $accounting_supplier_party, + ?array $allowance_charges, + ?float $amount_including_tax, + ?float $amount_including_vat, + ?array $attachments, + ?bool $consumer_tax_mode, + ?Delivery $delivery, + ?DeliveryTerms $delivery_terms, + ?string $document_currency_code, + ?string $due_date, + ?string $invoice_period, + ?array $issue_reasons, + ?string $issue_time, + ?string $note, + ?string $payable_rounding_amount, + ?array $payment_means_array, + ?PaymentTerms $payment_terms, + ?string $preferred_invoice_type, + ?string $prepaid_amount, + ?string $price_mode, + ?array $references, + ?bool $self_billing_mode, + ?string $sub_type, + ?string $tax_point_date, + ?array $tax_subtotals, + ?string $tax_system, + ?array $taxes_duties_fees, + ?string $time_zone, + ?string $transaction_type, + ?array $ubl_extensions, + ?string $x2y, + ?bool $vat_reverse_charge, + ?string $tax_exempt_reason, + ?string $invoice_type, + ?string $buyer_reference, + ?string $order_reference, + ?string $sales_order_id, + ?string $billing_reference, + ?string $contract_document_reference, + ?string $project_reference, + ?string $payment_means_iban, + ?string $payment_means_bic, + ?string $payment_means_code, + ?string $payment_means_payment_id + ) { + $this->invoice_number = $invoice_number; + $this->issue_date = $issue_date; + $this->accounting_customer_party = $accounting_customer_party; + $this->invoice_lines = $invoice_lines; + $this->accounting_cost = $accounting_cost; + $this->accounting_currency_exchange_rate = $accounting_currency_exchange_rate; + $this->accounting_currency_taxable_amount = $accounting_currency_taxable_amount; + $this->accounting_currency_tax_amount = $accounting_currency_tax_amount; + $this->accounting_currency_tax_amount_currency = $accounting_currency_tax_amount_currency; + $this->accounting_supplier_party = $accounting_supplier_party; + $this->allowance_charges = $allowance_charges; + $this->amount_including_tax = $amount_including_tax; + $this->amount_including_vat = $amount_including_vat; + $this->attachments = $attachments; + $this->consumer_tax_mode = $consumer_tax_mode; + $this->delivery = $delivery; + $this->delivery_terms = $delivery_terms; + $this->document_currency_code = $document_currency_code; + $this->due_date = $due_date; + $this->invoice_period = $invoice_period; + $this->issue_reasons = $issue_reasons; + $this->issue_time = $issue_time; + $this->note = $note; + $this->payable_rounding_amount = $payable_rounding_amount; + $this->payment_means_array = $payment_means_array; + $this->payment_terms = $payment_terms; + $this->preferred_invoice_type = $preferred_invoice_type; + $this->prepaid_amount = $prepaid_amount; + $this->price_mode = $price_mode; + $this->references = $references; + $this->self_billing_mode = $self_billing_mode; + $this->sub_type = $sub_type; + $this->tax_point_date = $tax_point_date; + $this->tax_subtotals = $tax_subtotals; + $this->tax_system = $tax_system; + $this->taxes_duties_fees = $taxes_duties_fees; + $this->time_zone = $time_zone; + $this->transaction_type = $transaction_type; + $this->ubl_extensions = $ubl_extensions; + $this->x2y = $x2y; + $this->vat_reverse_charge = $vat_reverse_charge; + $this->tax_exempt_reason = $tax_exempt_reason; + $this->invoice_type = $invoice_type; + $this->buyer_reference = $buyer_reference; + $this->order_reference = $order_reference; + $this->sales_order_id = $sales_order_id; + $this->billing_reference = $billing_reference; + $this->contract_document_reference = $contract_document_reference; + $this->project_reference = $project_reference; + $this->payment_means_iban = $payment_means_iban; + $this->payment_means_bic = $payment_means_bic; + $this->payment_means_code = $payment_means_code; + $this->payment_means_payment_id = $payment_means_payment_id; + } + + public function getInvoiceNumber(): ?string + { + return $this->invoice_number; + } + + public function getIssueDate(): ?string + { + return $this->issue_date; + } + + public function getAccountingCustomerParty(): ?AccountingCustomerParty + { + return $this->accounting_customer_party; + } + + /** + * @return InvoiceLines[] + */ + public function getInvoiceLines(): ?array + { + return $this->invoice_lines; + } + + public function getAccountingCost(): ?string + { + return $this->accounting_cost; + } + + public function getAccountingCurrencyExchangeRate(): ?string + { + return $this->accounting_currency_exchange_rate; + } + + public function getAccountingCurrencyTaxableAmount(): ?string + { + return $this->accounting_currency_taxable_amount; + } + + public function getAccountingCurrencyTaxAmount(): ?string + { + return $this->accounting_currency_tax_amount; + } + + public function getAccountingCurrencyTaxAmountCurrency(): ?string + { + return $this->accounting_currency_tax_amount_currency; + } + + public function getAccountingSupplierParty(): ?AccountingSupplierParty + { + return $this->accounting_supplier_party; + } + + /** + * @return AllowanceCharges[] + */ + public function getAllowanceCharges(): ?array + { + return $this->allowance_charges; + } + + public function getAmountIncludingTax(): ?float + { + return $this->amount_including_tax; + } + + public function getAmountIncludingVat(): ?float + { + return $this->amount_including_vat; + } + + /** + * @return Attachments[] + */ + public function getAttachments(): ?array + { + return $this->attachments; + } + + public function getConsumerTaxMode(): ?bool + { + return $this->consumer_tax_mode; + } + + public function getDelivery(): ?Delivery + { + return $this->delivery; + } + + public function getDeliveryTerms(): ?DeliveryTerms + { + return $this->delivery_terms; + } + + public function getDocumentCurrencyCode(): ?string + { + return $this->document_currency_code; + } + + public function getDueDate() + { + return $this->due_date; + } + + public function getInvoicePeriod(): ?string + { + return $this->invoice_period; + } + + /** + * @return string[] + */ + public function getIssueReasons(): ?array + { + return $this->issue_reasons; + } + + public function getIssueTime(): ?string + { + return $this->issue_time; + } + + public function getNote(): ?string + { + return $this->note; + } + + public function getPayableRoundingAmount(): ?string + { + return $this->payable_rounding_amount; + } + + /** + * @return PaymentMeansArray[] + */ + public function getPaymentMeansArray(): ?array + { + return $this->payment_means_array; + } + + public function getPaymentTerms(): ?PaymentTerms + { + return $this->payment_terms; + } + + public function getPreferredInvoiceType(): ?string + { + return $this->preferred_invoice_type; + } + + public function getPrepaidAmount(): ?string + { + return $this->prepaid_amount; + } + + public function getPriceMode(): ?string + { + return $this->price_mode; + } + + /** + * @return References[] + */ + public function getReferences(): ?array + { + return $this->references; + } + + public function getSelfBillingMode(): ?bool + { + return $this->self_billing_mode; + } + + public function getSubType(): ?string + { + return $this->sub_type; + } + + public function getTaxPointDate(): ?string + { + return $this->tax_point_date; + } + + /** + * @return TaxSubtotals[] + */ + public function getTaxSubtotals(): ?array + { + return $this->tax_subtotals; + } + + public function getTaxSystem(): ?string + { + return $this->tax_system; + } + + /** + * @return TaxesDutiesFees[] + */ + public function getTaxesDutiesFees(): ?array + { + return $this->taxes_duties_fees; + } + + public function getTimeZone(): ?string + { + return $this->time_zone; + } + + public function getTransactionType(): ?string + { + return $this->transaction_type; + } + + /** + * @return string[] + */ + public function getUblExtensions(): ?array + { + return $this->ubl_extensions; + } + + public function getX2y(): ?string + { + return $this->x2y; + } + + public function getVatReverseCharge(): ?bool + { + return $this->vat_reverse_charge; + } + + public function getTaxExemptReason(): ?string + { + return $this->tax_exempt_reason; + } + + public function getInvoiceType(): ?string + { + return $this->invoice_type; + } + + public function getBuyerReference(): ?string + { + return $this->buyer_reference; + } + + public function getOrderReference(): ?string + { + return $this->order_reference; + } + + public function getSalesOrderId(): ?string + { + return $this->sales_order_id; + } + + public function getBillingReference(): ?string + { + return $this->billing_reference; + } + + public function getContractDocumentReference(): ?string + { + return $this->contract_document_reference; + } + + public function getProjectReference(): ?string + { + return $this->project_reference; + } + + public function getPaymentMeansIban(): ?string + { + return $this->payment_means_iban; + } + + public function getPaymentMeansBic(): ?string + { + return $this->payment_means_bic; + } + + public function getPaymentMeansCode(): ?string + { + return $this->payment_means_code; + } + + public function getPaymentMeansPaymentId(): ?string + { + return $this->payment_means_payment_id; + } + + public function setInvoiceNumber(?string $invoice_number): self + { + $this->invoice_number = $invoice_number; + return $this; + } + + public function setIssueDate($issue_date): self + { + $this->issue_date = $issue_date; + return $this; + } + + public function setAccountingCustomerParty(?AccountingCustomerParty $accounting_customer_party): self + { + $this->accounting_customer_party = $accounting_customer_party; + return $this; + } + + /** + * @param InvoiceLines[] $invoice_lines + */ + public function setInvoiceLines(?array $invoice_lines): self + { + $this->invoice_lines = $invoice_lines; + return $this; + } + + public function setAccountingCost(?string $accounting_cost): self + { + $this->accounting_cost = $accounting_cost; + return $this; + } + + public function setAccountingCurrencyExchangeRate(?string $accounting_currency_exchange_rate): self + { + $this->accounting_currency_exchange_rate = $accounting_currency_exchange_rate; + return $this; + } + + public function setAccountingCurrencyTaxableAmount(?string $accounting_currency_taxable_amount): self + { + $this->accounting_currency_taxable_amount = $accounting_currency_taxable_amount; + return $this; + } + + public function setAccountingCurrencyTaxAmount(?string $accounting_currency_tax_amount): self + { + $this->accounting_currency_tax_amount = $accounting_currency_tax_amount; + return $this; + } + + public function setAccountingCurrencyTaxAmountCurrency(?string $accounting_currency_tax_amount_currency): self + { + $this->accounting_currency_tax_amount_currency = $accounting_currency_tax_amount_currency; + return $this; + } + + public function setAccountingSupplierParty(?AccountingSupplierParty $accounting_supplier_party): self + { + $this->accounting_supplier_party = $accounting_supplier_party; + return $this; + } + + /** + * @param AllowanceCharges[] $allowance_charges + */ + public function setAllowanceCharges(?array $allowance_charges): self + { + $this->allowance_charges = $allowance_charges; + return $this; + } + + public function setAmountIncludingTax(?float $amount_including_tax): self + { + $this->amount_including_tax = $amount_including_tax; + return $this; + } + + public function setAmountIncludingVat(?float $amount_including_vat): self + { + $this->amount_including_vat = $amount_including_vat; + return $this; + } + + /** + * @param Attachments[] $attachments + */ + public function setAttachments(?array $attachments): self + { + $this->attachments = $attachments; + return $this; + } + + public function setConsumerTaxMode(?bool $consumer_tax_mode): self + { + $this->consumer_tax_mode = $consumer_tax_mode; + return $this; + } + + public function setDelivery(?Delivery $delivery): self + { + $this->delivery = $delivery; + return $this; + } + + public function setDeliveryTerms(?DeliveryTerms $delivery_terms): self + { + $this->delivery_terms = $delivery_terms; + return $this; + } + + public function setDocumentCurrencyCode(?string $document_currency_code): self + { + $this->document_currency_code = $document_currency_code; + return $this; + } + + public function setDueDate(?string $due_date): self + { + $this->due_date = $due_date; + return $this; + } + + public function setInvoicePeriod(?string $invoice_period): self + { + $this->invoice_period = $invoice_period; + return $this; + } + + /** + * @param string[] $issue_reasons + */ + public function setIssueReasons(?array $issue_reasons): self + { + $this->issue_reasons = $issue_reasons; + return $this; + } + + public function setIssueTime(?string $issue_time): self + { + $this->issue_time = $issue_time; + return $this; + } + + public function setNote(?string $note): self + { + $this->note = $note; + return $this; + } + + public function setPayableRoundingAmount(?string $payable_rounding_amount): self + { + $this->payable_rounding_amount = $payable_rounding_amount; + return $this; + } + + /** + * @param PaymentMeansArray[] $payment_means_array + */ + public function setPaymentMeansArray(?array $payment_means_array): self + { + $this->payment_means_array = $payment_means_array; + return $this; + } + + public function setPaymentTerms(?PaymentTerms $payment_terms): self + { + $this->payment_terms = $payment_terms; + return $this; + } + + public function setPreferredInvoiceType(?string $preferred_invoice_type): self + { + $this->preferred_invoice_type = $preferred_invoice_type; + return $this; + } + + public function setPrepaidAmount(?string $prepaid_amount): self + { + $this->prepaid_amount = $prepaid_amount; + return $this; + } + + public function setPriceMode(?string $price_mode): self + { + $this->price_mode = $price_mode; + return $this; + } + + /** + * @param References[] $references + */ + public function setReferences(?array $references): self + { + $this->references = $references; + return $this; + } + + public function setSelfBillingMode(?bool $self_billing_mode): self + { + $this->self_billing_mode = $self_billing_mode; + return $this; + } + + public function setSubType(?string $sub_type): self + { + $this->sub_type = $sub_type; + return $this; + } + + public function setTaxPointDate(?string $tax_point_date): self + { + $this->tax_point_date = $tax_point_date; + return $this; + } + + /** + * @param TaxSubtotals[] $tax_subtotals + */ + public function setTaxSubtotals(?array $tax_subtotals): self + { + $this->tax_subtotals = $tax_subtotals; + return $this; + } + + public function setTaxSystem(?string $tax_system): self + { + $this->tax_system = $tax_system; + return $this; + } + + /** + * @param TaxesDutiesFees[] $taxes_duties_fees + */ + public function setTaxesDutiesFees(?array $taxes_duties_fees): self + { + $this->taxes_duties_fees = $taxes_duties_fees; + return $this; + } + + public function setTimeZone(?string $time_zone): self + { + $this->time_zone = $time_zone; + return $this; + } + + public function setTransactionType(?string $transaction_type): self + { + $this->transaction_type = $transaction_type; + return $this; + } + + /** + * @param string[] $ubl_extensions + */ + public function setUblExtensions(?array $ubl_extensions): self + { + $this->ubl_extensions = $ubl_extensions; + return $this; + } + + public function setX2y(?string $x2y): self + { + $this->x2y = $x2y; + return $this; + } + + public function setVatReverseCharge(?bool $vat_reverse_charge): self + { + $this->vat_reverse_charge = $vat_reverse_charge; + return $this; + } + + public function setTaxExemptReason(?string $tax_exempt_reason): self + { + $this->tax_exempt_reason = $tax_exempt_reason; + return $this; + } + + public function setInvoiceType(?string $invoice_type): self + { + $this->invoice_type = $invoice_type; + return $this; + } + + public function setBuyerReference(?string $buyer_reference): self + { + $this->buyer_reference = $buyer_reference; + return $this; + } + + public function setOrderReference(?string $order_reference): self + { + $this->order_reference = $order_reference; + return $this; + } + + public function setSalesOrderId(?string $sales_order_id): self + { + $this->sales_order_id = $sales_order_id; + return $this; + } + + public function setBillingReference(?string $billing_reference): self + { + $this->billing_reference = $billing_reference; + return $this; + } + + public function setContractDocumentReference(?string $contract_document_reference): self + { + $this->contract_document_reference = $contract_document_reference; + return $this; + } + + public function setProjectReference(?string $project_reference): self + { + $this->project_reference = $project_reference; + return $this; + } + + public function setPaymentMeansIban(?string $payment_means_iban): self + { + $this->payment_means_iban = $payment_means_iban; + return $this; + } + + public function setPaymentMeansBic(?string $payment_means_bic): self + { + $this->payment_means_bic = $payment_means_bic; + return $this; + } + + public function setPaymentMeansCode(?string $payment_means_code): self + { + $this->payment_means_code = $payment_means_code; + return $this; + } + + public function setPaymentMeansPaymentId(?string $payment_means_payment_id): self + { + $this->payment_means_payment_id = $payment_means_payment_id; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/InvoiceLines.php b/app/Services/EDocument/Gateway/Storecove/Models/InvoiceLines.php index b06e49014c..eda13ceb9a 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/InvoiceLines.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/InvoiceLines.php @@ -5,11 +5,9 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; use Symfony\Component\Serializer\Attribute\SerializedName; use Symfony\Component\Serializer\Attribute\SerializedPath; - class InvoiceLines { - - #[SerializedPath('[cbc:ID][#]')] + #[SerializedPath('[cbc:ID][#]')] public ?string $line_id; #[SerializedPath('[cac:Item][cbc:Description]')] @@ -51,7 +49,7 @@ class InvoiceLines #[SerializedPath('[cac:Item][cac:ClassifiedTaxCategory]')] /** @var TaxesDutiesFees[] */ - public ?array $taxes_duties_fees = []; + public ?array $taxes_duties_fees = []; #[SerializedPath('[cbc:AccountingCost]')] public ?string $accounting_cost; @@ -82,337 +80,337 @@ class InvoiceLines #[SerializedPath('[cbc:Note]')] public ?string $note; - /** - * @param AllowanceCharges[] $allowance_charges - * @param TaxesDutiesFees[] $taxes_duties_fees - * @param References[] $references - * @param AdditionalItemProperties[] $additional_item_properties - */ - public function __construct( - ?string $line_id, - ?string $description, - ?string $name, - ?string $order_line_reference_line_id, - ?string $invoice_period, - ?float $item_price, - ?float $quantity, - ?float $base_quantity, - ?string $quantity_unit_code, - ?array $allowance_charges, - ?float $amount_excluding_vat, - ?float $amount_excluding_tax, - ?float $amount_including_tax, - ?array $taxes_duties_fees, - ?string $accounting_cost, - ?array $references, - ?array $additional_item_properties, - ?string $sellers_item_identification, - ?string $buyers_item_identification, - ?string $standard_item_identification, - ?string $standard_item_identification_scheme_id, - ?string $standard_item_identification_scheme_agency_id, - ?string $note - ) { - $this->line_id = $line_id; - $this->description = $description; - $this->name = $name; - $this->order_line_reference_line_id = $order_line_reference_line_id; - $this->invoice_period = $invoice_period; - $this->item_price = $item_price; - $this->quantity = $quantity; - $this->base_quantity = $base_quantity; - $this->quantity_unit_code = $quantity_unit_code; - $this->allowance_charges = $allowance_charges; - $this->amount_excluding_vat = $amount_excluding_vat; - $this->amount_excluding_tax = $amount_excluding_tax; - $this->amount_including_tax = $amount_including_tax; - $this->taxes_duties_fees = $taxes_duties_fees; - $this->accounting_cost = $accounting_cost; - $this->references = $references; - $this->additional_item_properties = $additional_item_properties; - $this->sellers_item_identification = $sellers_item_identification; - $this->buyers_item_identification = $buyers_item_identification; - $this->standard_item_identification = $standard_item_identification; - $this->standard_item_identification_scheme_id = $standard_item_identification_scheme_id; - $this->standard_item_identification_scheme_agency_id = $standard_item_identification_scheme_agency_id; - $this->note = $note; - } + /** + * @param AllowanceCharges[] $allowance_charges + * @param TaxesDutiesFees[] $taxes_duties_fees + * @param References[] $references + * @param AdditionalItemProperties[] $additional_item_properties + */ + public function __construct( + ?string $line_id, + ?string $description, + ?string $name, + ?string $order_line_reference_line_id, + ?string $invoice_period, + ?float $item_price, + ?float $quantity, + ?float $base_quantity, + ?string $quantity_unit_code, + ?array $allowance_charges, + ?float $amount_excluding_vat, + ?float $amount_excluding_tax, + ?float $amount_including_tax, + ?array $taxes_duties_fees, + ?string $accounting_cost, + ?array $references, + ?array $additional_item_properties, + ?string $sellers_item_identification, + ?string $buyers_item_identification, + ?string $standard_item_identification, + ?string $standard_item_identification_scheme_id, + ?string $standard_item_identification_scheme_agency_id, + ?string $note + ) { + $this->line_id = $line_id; + $this->description = $description; + $this->name = $name; + $this->order_line_reference_line_id = $order_line_reference_line_id; + $this->invoice_period = $invoice_period; + $this->item_price = $item_price; + $this->quantity = $quantity; + $this->base_quantity = $base_quantity; + $this->quantity_unit_code = $quantity_unit_code; + $this->allowance_charges = $allowance_charges; + $this->amount_excluding_vat = $amount_excluding_vat; + $this->amount_excluding_tax = $amount_excluding_tax; + $this->amount_including_tax = $amount_including_tax; + $this->taxes_duties_fees = $taxes_duties_fees; + $this->accounting_cost = $accounting_cost; + $this->references = $references; + $this->additional_item_properties = $additional_item_properties; + $this->sellers_item_identification = $sellers_item_identification; + $this->buyers_item_identification = $buyers_item_identification; + $this->standard_item_identification = $standard_item_identification; + $this->standard_item_identification_scheme_id = $standard_item_identification_scheme_id; + $this->standard_item_identification_scheme_agency_id = $standard_item_identification_scheme_agency_id; + $this->note = $note; + } - public function getLineId(): ?string - { - return $this->line_id; - } + public function getLineId(): ?string + { + return $this->line_id; + } - public function getDescription(): ?string - { - return $this->description; - } + public function getDescription(): ?string + { + return $this->description; + } - public function getName(): ?string - { - return $this->name; - } + public function getName(): ?string + { + return $this->name; + } - public function getOrderLineReferenceLineId(): ?string - { - return $this->order_line_reference_line_id; - } + public function getOrderLineReferenceLineId(): ?string + { + return $this->order_line_reference_line_id; + } - public function getInvoicePeriod(): ?string - { - return $this->invoice_period; - } + public function getInvoicePeriod(): ?string + { + return $this->invoice_period; + } - public function getItemPrice(): ?float - { - return $this->item_price; - } + public function getItemPrice(): ?float + { + return $this->item_price; + } - public function getQuantity(): ?float - { - return $this->quantity; - } + public function getQuantity(): ?float + { + return $this->quantity; + } - public function getBaseQuantity(): ?float - { - return $this->base_quantity; - } + public function getBaseQuantity(): ?float + { + return $this->base_quantity; + } - public function getQuantityUnitCode(): ?string - { - return $this->quantity_unit_code; - } + public function getQuantityUnitCode(): ?string + { + return $this->quantity_unit_code; + } - /** - * @return AllowanceCharges[] - */ - public function getAllowanceCharges(): ?array - { - return $this->allowance_charges; - } + /** + * @return AllowanceCharges[] + */ + public function getAllowanceCharges(): ?array + { + return $this->allowance_charges; + } - public function getAmountExcludingVat(): ?float - { - return $this->amount_excluding_vat; - } + public function getAmountExcludingVat(): ?float + { + return $this->amount_excluding_vat; + } - public function getAmountExcludingTax(): ?float - { - return $this->amount_excluding_tax; - } + public function getAmountExcludingTax(): ?float + { + return $this->amount_excluding_tax; + } - public function getAmountIncludingTax(): ?float - { - return $this->amount_including_tax; - } + public function getAmountIncludingTax(): ?float + { + return $this->amount_including_tax; + } - /** - * @return TaxesDutiesFees[] - */ - public function getTaxesDutiesFees(): ?array - { - return $this->taxes_duties_fees; - } + /** + * @return TaxesDutiesFees[] + */ + public function getTaxesDutiesFees(): ?array + { + return $this->taxes_duties_fees; + } - public function getAccountingCost(): ?string - { - return $this->accounting_cost; - } + public function getAccountingCost(): ?string + { + return $this->accounting_cost; + } - /** - * @return References[] - */ - public function getReferences(): ?array - { - return $this->references; - } + /** + * @return References[] + */ + public function getReferences(): ?array + { + return $this->references; + } - /** - * @return AdditionalItemProperties[] - */ - public function getAdditionalItemProperties(): ?array - { - return $this->additional_item_properties; - } + /** + * @return AdditionalItemProperties[] + */ + public function getAdditionalItemProperties(): ?array + { + return $this->additional_item_properties; + } - public function getSellersItemIdentification(): ?string - { - return $this->sellers_item_identification; - } + public function getSellersItemIdentification(): ?string + { + return $this->sellers_item_identification; + } - public function getBuyersItemIdentification(): ?string - { - return $this->buyers_item_identification; - } + public function getBuyersItemIdentification(): ?string + { + return $this->buyers_item_identification; + } - public function getStandardItemIdentification(): ?string - { - return $this->standard_item_identification; - } + public function getStandardItemIdentification(): ?string + { + return $this->standard_item_identification; + } - public function getStandardItemIdentificationSchemeId(): ?string - { - return $this->standard_item_identification_scheme_id; - } + public function getStandardItemIdentificationSchemeId(): ?string + { + return $this->standard_item_identification_scheme_id; + } - public function getStandardItemIdentificationSchemeAgencyId(): ?string - { - return $this->standard_item_identification_scheme_agency_id; - } + public function getStandardItemIdentificationSchemeAgencyId(): ?string + { + return $this->standard_item_identification_scheme_agency_id; + } - public function getNote(): ?string - { - return $this->note; - } + public function getNote(): ?string + { + return $this->note; + } - public function setLineId(?string $line_id): self - { - $this->line_id = $line_id; - return $this; - } + public function setLineId(?string $line_id): self + { + $this->line_id = $line_id; + return $this; + } - public function setDescription(?string $description): self - { - $this->description = $description; - return $this; - } + public function setDescription(?string $description): self + { + $this->description = $description; + return $this; + } - public function setName(?string $name): self - { - $this->name = $name; - return $this; - } + public function setName(?string $name): self + { + $this->name = $name; + return $this; + } - public function setOrderLineReferenceLineId(?string $order_line_reference_line_id): self - { - $this->order_line_reference_line_id = $order_line_reference_line_id; - return $this; - } + public function setOrderLineReferenceLineId(?string $order_line_reference_line_id): self + { + $this->order_line_reference_line_id = $order_line_reference_line_id; + return $this; + } - public function setInvoicePeriod(?string $invoice_period): self - { - $this->invoice_period = $invoice_period; - return $this; - } + public function setInvoicePeriod(?string $invoice_period): self + { + $this->invoice_period = $invoice_period; + return $this; + } - public function setItemPrice(?float $item_price): self - { - $this->item_price = $item_price; - return $this; - } + public function setItemPrice(?float $item_price): self + { + $this->item_price = $item_price; + return $this; + } - public function setQuantity(?float $quantity): self - { - $this->quantity = $quantity; - return $this; - } + public function setQuantity(?float $quantity): self + { + $this->quantity = $quantity; + return $this; + } - public function setBaseQuantity(?float $base_quantity): self - { - $this->base_quantity = $base_quantity; - return $this; - } + public function setBaseQuantity(?float $base_quantity): self + { + $this->base_quantity = $base_quantity; + return $this; + } - public function setQuantityUnitCode(?string $quantity_unit_code): self - { - $this->quantity_unit_code = $quantity_unit_code; - return $this; - } + public function setQuantityUnitCode(?string $quantity_unit_code): self + { + $this->quantity_unit_code = $quantity_unit_code; + return $this; + } - /** - * @param AllowanceCharges[] $allowance_charges - */ - public function setAllowanceCharges(?array $allowance_charges): self - { - $this->allowance_charges = $allowance_charges; - return $this; - } + /** + * @param AllowanceCharges[] $allowance_charges + */ + public function setAllowanceCharges(?array $allowance_charges): self + { + $this->allowance_charges = $allowance_charges; + return $this; + } - public function setAmountExcludingVat(?float $amount_excluding_vat): self - { - $this->amount_excluding_vat = $amount_excluding_vat; - return $this; - } + public function setAmountExcludingVat(?float $amount_excluding_vat): self + { + $this->amount_excluding_vat = $amount_excluding_vat; + return $this; + } - public function setAmountExcludingTax(?float $amount_excluding_tax): self - { - $this->amount_excluding_tax = $amount_excluding_tax; - return $this; - } + public function setAmountExcludingTax(?float $amount_excluding_tax): self + { + $this->amount_excluding_tax = $amount_excluding_tax; + return $this; + } - public function setAmountIncludingTax(?float $amount_including_tax): self - { - $this->amount_including_tax = $amount_including_tax; - return $this; - } + public function setAmountIncludingTax(?float $amount_including_tax): self + { + $this->amount_including_tax = $amount_including_tax; + return $this; + } - /** - * @param TaxesDutiesFees[] $taxes_duties_fees - */ - public function setTaxesDutiesFees(?array $taxes_duties_fees): self - { - $this->taxes_duties_fees = $taxes_duties_fees; - return $this; - } + /** + * @param TaxesDutiesFees[] $taxes_duties_fees + */ + public function setTaxesDutiesFees(?array $taxes_duties_fees): self + { + $this->taxes_duties_fees = $taxes_duties_fees; + return $this; + } - public function setAccountingCost(?string $accounting_cost): self - { - $this->accounting_cost = $accounting_cost; - return $this; - } + public function setAccountingCost(?string $accounting_cost): self + { + $this->accounting_cost = $accounting_cost; + return $this; + } - /** - * @param References[] $references - */ - public function setReferences(?array $references): self - { - $this->references = $references; - return $this; - } + /** + * @param References[] $references + */ + public function setReferences(?array $references): self + { + $this->references = $references; + return $this; + } - /** - * @param AdditionalItemProperties[] $additional_item_properties - */ - public function setAdditionalItemProperties(?array $additional_item_properties): self - { - $this->additional_item_properties = $additional_item_properties; - return $this; - } + /** + * @param AdditionalItemProperties[] $additional_item_properties + */ + public function setAdditionalItemProperties(?array $additional_item_properties): self + { + $this->additional_item_properties = $additional_item_properties; + return $this; + } - public function setSellersItemIdentification(?string $sellers_item_identification): self - { - $this->sellers_item_identification = $sellers_item_identification; - return $this; - } + public function setSellersItemIdentification(?string $sellers_item_identification): self + { + $this->sellers_item_identification = $sellers_item_identification; + return $this; + } - public function setBuyersItemIdentification(?string $buyers_item_identification): self - { - $this->buyers_item_identification = $buyers_item_identification; - return $this; - } + public function setBuyersItemIdentification(?string $buyers_item_identification): self + { + $this->buyers_item_identification = $buyers_item_identification; + return $this; + } - public function setStandardItemIdentification(?string $standard_item_identification): self - { - $this->standard_item_identification = $standard_item_identification; - return $this; - } + public function setStandardItemIdentification(?string $standard_item_identification): self + { + $this->standard_item_identification = $standard_item_identification; + return $this; + } - public function setStandardItemIdentificationSchemeId(?string $standard_item_identification_scheme_id): self - { - $this->standard_item_identification_scheme_id = $standard_item_identification_scheme_id; - return $this; - } + public function setStandardItemIdentificationSchemeId(?string $standard_item_identification_scheme_id): self + { + $this->standard_item_identification_scheme_id = $standard_item_identification_scheme_id; + return $this; + } - public function setStandardItemIdentificationSchemeAgencyId(?string $standard_item_identification_scheme_agency_id): self - { - $this->standard_item_identification_scheme_agency_id = $standard_item_identification_scheme_agency_id; - return $this; - } + public function setStandardItemIdentificationSchemeAgencyId(?string $standard_item_identification_scheme_agency_id): self + { + $this->standard_item_identification_scheme_agency_id = $standard_item_identification_scheme_agency_id; + return $this; + } - public function setNote(?string $note): self - { - $this->note = $note; - return $this; - } + public function setNote(?string $note): self + { + $this->note = $note; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/Order.php b/app/Services/EDocument/Gateway/Storecove/Models/Order.php index ee1af6690b..efcbf80921 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/Order.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/Order.php @@ -4,322 +4,322 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class Order { - public ?string $document_number; - public ?string $issue_date; - public ?SellerSupplierParty $seller_supplier_party; - /** @var OrderLines[] */ - public ?array $order_lines; - public ?string $amount_including_tax; - public ?string $tax_system; - /** @var References[] */ - public ?array $references; - public ?string $issue_time; - public ?string $time_zone; - public ?string $order_type; - public ?string $note; - public ?string $document_currency_code; - public ?string $accounting_cost; - public ?string $validity_period; - public ?BuyerCustomerParty $buyer_customer_party; - public ?Delivery $delivery; - public ?DeliveryTerms $delivery_terms; - public ?PaymentTerms $payment_terms; - /** @var AllowanceCharges[] */ - public ?array $allowance_charges; - /** @var Attachments[] */ - public ?array $attachments; + public ?string $document_number; + public ?string $issue_date; + public ?SellerSupplierParty $seller_supplier_party; + /** @var OrderLines[] */ + public ?array $order_lines; + public ?string $amount_including_tax; + public ?string $tax_system; + /** @var References[] */ + public ?array $references; + public ?string $issue_time; + public ?string $time_zone; + public ?string $order_type; + public ?string $note; + public ?string $document_currency_code; + public ?string $accounting_cost; + public ?string $validity_period; + public ?BuyerCustomerParty $buyer_customer_party; + public ?Delivery $delivery; + public ?DeliveryTerms $delivery_terms; + public ?PaymentTerms $payment_terms; + /** @var AllowanceCharges[] */ + public ?array $allowance_charges; + /** @var Attachments[] */ + public ?array $attachments; - /** - * @param OrderLines[] $order_lines - * @param References[] $references - * @param AllowanceCharges[] $allowance_charges - * @param Attachments[] $attachments - */ - public function __construct( - ?string $document_number, - ?string $issue_date, - ?SellerSupplierParty $seller_supplier_party, - ?array $order_lines, - ?string $amount_including_tax, - ?string $tax_system, - ?array $references, - ?string $issue_time, - ?string $time_zone, - ?string $order_type, - ?string $note, - ?string $document_currency_code, - ?string $accounting_cost, - ?string $validity_period, - ?BuyerCustomerParty $buyer_customer_party, - ?Delivery $delivery, - ?DeliveryTerms $delivery_terms, - ?PaymentTerms $payment_terms, - ?array $allowance_charges, - ?array $attachments - ) { - $this->document_number = $document_number; - $this->issue_date = $issue_date; - $this->seller_supplier_party = $seller_supplier_party; - $this->order_lines = $order_lines; - $this->amount_including_tax = $amount_including_tax; - $this->tax_system = $tax_system; - $this->references = $references; - $this->issue_time = $issue_time; - $this->time_zone = $time_zone; - $this->order_type = $order_type; - $this->note = $note; - $this->document_currency_code = $document_currency_code; - $this->accounting_cost = $accounting_cost; - $this->validity_period = $validity_period; - $this->buyer_customer_party = $buyer_customer_party; - $this->delivery = $delivery; - $this->delivery_terms = $delivery_terms; - $this->payment_terms = $payment_terms; - $this->allowance_charges = $allowance_charges; - $this->attachments = $attachments; - } + /** + * @param OrderLines[] $order_lines + * @param References[] $references + * @param AllowanceCharges[] $allowance_charges + * @param Attachments[] $attachments + */ + public function __construct( + ?string $document_number, + ?string $issue_date, + ?SellerSupplierParty $seller_supplier_party, + ?array $order_lines, + ?string $amount_including_tax, + ?string $tax_system, + ?array $references, + ?string $issue_time, + ?string $time_zone, + ?string $order_type, + ?string $note, + ?string $document_currency_code, + ?string $accounting_cost, + ?string $validity_period, + ?BuyerCustomerParty $buyer_customer_party, + ?Delivery $delivery, + ?DeliveryTerms $delivery_terms, + ?PaymentTerms $payment_terms, + ?array $allowance_charges, + ?array $attachments + ) { + $this->document_number = $document_number; + $this->issue_date = $issue_date; + $this->seller_supplier_party = $seller_supplier_party; + $this->order_lines = $order_lines; + $this->amount_including_tax = $amount_including_tax; + $this->tax_system = $tax_system; + $this->references = $references; + $this->issue_time = $issue_time; + $this->time_zone = $time_zone; + $this->order_type = $order_type; + $this->note = $note; + $this->document_currency_code = $document_currency_code; + $this->accounting_cost = $accounting_cost; + $this->validity_period = $validity_period; + $this->buyer_customer_party = $buyer_customer_party; + $this->delivery = $delivery; + $this->delivery_terms = $delivery_terms; + $this->payment_terms = $payment_terms; + $this->allowance_charges = $allowance_charges; + $this->attachments = $attachments; + } - public function getDocumentNumber(): ?string - { - return $this->document_number; - } + public function getDocumentNumber(): ?string + { + return $this->document_number; + } - public function getIssueDate(): ?string - { - return $this->issue_date; - } + public function getIssueDate(): ?string + { + return $this->issue_date; + } - public function getSellerSupplierParty(): ?SellerSupplierParty - { - return $this->seller_supplier_party; - } + public function getSellerSupplierParty(): ?SellerSupplierParty + { + return $this->seller_supplier_party; + } - /** - * @return OrderLines[] - */ - public function getOrderLines(): ?array - { - return $this->order_lines; - } + /** + * @return OrderLines[] + */ + public function getOrderLines(): ?array + { + return $this->order_lines; + } - public function getAmountIncludingTax(): ?string - { - return $this->amount_including_tax; - } + public function getAmountIncludingTax(): ?string + { + return $this->amount_including_tax; + } - public function getTaxSystem(): ?string - { - return $this->tax_system; - } + public function getTaxSystem(): ?string + { + return $this->tax_system; + } - /** - * @return References[] - */ - public function getReferences(): ?array - { - return $this->references; - } + /** + * @return References[] + */ + public function getReferences(): ?array + { + return $this->references; + } - public function getIssueTime(): ?string - { - return $this->issue_time; - } + public function getIssueTime(): ?string + { + return $this->issue_time; + } - public function getTimeZone(): ?string - { - return $this->time_zone; - } + public function getTimeZone(): ?string + { + return $this->time_zone; + } - public function getOrderType(): ?string - { - return $this->order_type; - } + public function getOrderType(): ?string + { + return $this->order_type; + } - public function getNote(): ?string - { - return $this->note; - } + public function getNote(): ?string + { + return $this->note; + } - public function getDocumentCurrencyCode(): ?string - { - return $this->document_currency_code; - } + public function getDocumentCurrencyCode(): ?string + { + return $this->document_currency_code; + } - public function getAccountingCost(): ?string - { - return $this->accounting_cost; - } + public function getAccountingCost(): ?string + { + return $this->accounting_cost; + } - public function getValidityPeriod(): ?string - { - return $this->validity_period; - } + public function getValidityPeriod(): ?string + { + return $this->validity_period; + } - public function getBuyerCustomerParty(): ?BuyerCustomerParty - { - return $this->buyer_customer_party; - } + public function getBuyerCustomerParty(): ?BuyerCustomerParty + { + return $this->buyer_customer_party; + } - public function getDelivery(): ?Delivery - { - return $this->delivery; - } + public function getDelivery(): ?Delivery + { + return $this->delivery; + } - public function getDeliveryTerms(): ?DeliveryTerms - { - return $this->delivery_terms; - } + public function getDeliveryTerms(): ?DeliveryTerms + { + return $this->delivery_terms; + } - public function getPaymentTerms(): ?PaymentTerms - { - return $this->payment_terms; - } + public function getPaymentTerms(): ?PaymentTerms + { + return $this->payment_terms; + } - /** - * @return AllowanceCharges[] - */ - public function getAllowanceCharges(): ?array - { - return $this->allowance_charges; - } + /** + * @return AllowanceCharges[] + */ + public function getAllowanceCharges(): ?array + { + return $this->allowance_charges; + } - /** - * @return Attachments[] - */ - public function getAttachments(): ?array - { - return $this->attachments; - } + /** + * @return Attachments[] + */ + public function getAttachments(): ?array + { + return $this->attachments; + } - public function setDocumentNumber(?string $document_number): self - { - $this->document_number = $document_number; - return $this; - } + public function setDocumentNumber(?string $document_number): self + { + $this->document_number = $document_number; + return $this; + } - public function setIssueDate(?string $issue_date): self - { - $this->issue_date = $issue_date; - return $this; - } + public function setIssueDate(?string $issue_date): self + { + $this->issue_date = $issue_date; + return $this; + } - public function setSellerSupplierParty(?SellerSupplierParty $seller_supplier_party): self - { - $this->seller_supplier_party = $seller_supplier_party; - return $this; - } + public function setSellerSupplierParty(?SellerSupplierParty $seller_supplier_party): self + { + $this->seller_supplier_party = $seller_supplier_party; + return $this; + } - /** - * @param OrderLines[] $order_lines - */ - public function setOrderLines(?array $order_lines): self - { - $this->order_lines = $order_lines; - return $this; - } + /** + * @param OrderLines[] $order_lines + */ + public function setOrderLines(?array $order_lines): self + { + $this->order_lines = $order_lines; + return $this; + } - public function setAmountIncludingTax(?string $amount_including_tax): self - { - $this->amount_including_tax = $amount_including_tax; - return $this; - } + public function setAmountIncludingTax(?string $amount_including_tax): self + { + $this->amount_including_tax = $amount_including_tax; + return $this; + } - public function setTaxSystem(?string $tax_system): self - { - $this->tax_system = $tax_system; - return $this; - } + public function setTaxSystem(?string $tax_system): self + { + $this->tax_system = $tax_system; + return $this; + } - /** - * @param References[] $references - */ - public function setReferences(?array $references): self - { - $this->references = $references; - return $this; - } + /** + * @param References[] $references + */ + public function setReferences(?array $references): self + { + $this->references = $references; + return $this; + } - public function setIssueTime(?string $issue_time): self - { - $this->issue_time = $issue_time; - return $this; - } + public function setIssueTime(?string $issue_time): self + { + $this->issue_time = $issue_time; + return $this; + } - public function setTimeZone(?string $time_zone): self - { - $this->time_zone = $time_zone; - return $this; - } + public function setTimeZone(?string $time_zone): self + { + $this->time_zone = $time_zone; + return $this; + } - public function setOrderType(?string $order_type): self - { - $this->order_type = $order_type; - return $this; - } + public function setOrderType(?string $order_type): self + { + $this->order_type = $order_type; + return $this; + } - public function setNote(?string $note): self - { - $this->note = $note; - return $this; - } + public function setNote(?string $note): self + { + $this->note = $note; + return $this; + } - public function setDocumentCurrencyCode(?string $document_currency_code): self - { - $this->document_currency_code = $document_currency_code; - return $this; - } + public function setDocumentCurrencyCode(?string $document_currency_code): self + { + $this->document_currency_code = $document_currency_code; + return $this; + } - public function setAccountingCost(?string $accounting_cost): self - { - $this->accounting_cost = $accounting_cost; - return $this; - } + public function setAccountingCost(?string $accounting_cost): self + { + $this->accounting_cost = $accounting_cost; + return $this; + } - public function setValidityPeriod(?string $validity_period): self - { - $this->validity_period = $validity_period; - return $this; - } + public function setValidityPeriod(?string $validity_period): self + { + $this->validity_period = $validity_period; + return $this; + } - public function setBuyerCustomerParty(?BuyerCustomerParty $buyer_customer_party): self - { - $this->buyer_customer_party = $buyer_customer_party; - return $this; - } + public function setBuyerCustomerParty(?BuyerCustomerParty $buyer_customer_party): self + { + $this->buyer_customer_party = $buyer_customer_party; + return $this; + } - public function setDelivery(?Delivery $delivery): self - { - $this->delivery = $delivery; - return $this; - } + public function setDelivery(?Delivery $delivery): self + { + $this->delivery = $delivery; + return $this; + } - public function setDeliveryTerms(?DeliveryTerms $delivery_terms): self - { - $this->delivery_terms = $delivery_terms; - return $this; - } + public function setDeliveryTerms(?DeliveryTerms $delivery_terms): self + { + $this->delivery_terms = $delivery_terms; + return $this; + } - public function setPaymentTerms(?PaymentTerms $payment_terms): self - { - $this->payment_terms = $payment_terms; - return $this; - } + public function setPaymentTerms(?PaymentTerms $payment_terms): self + { + $this->payment_terms = $payment_terms; + return $this; + } - /** - * @param AllowanceCharges[] $allowance_charges - */ - public function setAllowanceCharges(?array $allowance_charges): self - { - $this->allowance_charges = $allowance_charges; - return $this; - } + /** + * @param AllowanceCharges[] $allowance_charges + */ + public function setAllowanceCharges(?array $allowance_charges): self + { + $this->allowance_charges = $allowance_charges; + return $this; + } - /** - * @param Attachments[] $attachments - */ - public function setAttachments(?array $attachments): self - { - $this->attachments = $attachments; - return $this; - } + /** + * @param Attachments[] $attachments + */ + public function setAttachments(?array $attachments): self + { + $this->attachments = $attachments; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/OrderLines.php b/app/Services/EDocument/Gateway/Storecove/Models/OrderLines.php index 5335a51647..9bec275f6a 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/OrderLines.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/OrderLines.php @@ -4,288 +4,288 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class OrderLines { - public ?string $line_id; - public ?float $quantity; - public ?string $quantity_unit_code; - public ?string $amount_excluding_tax; - public ?float $item_price; - public ?float $base_quantity; - /** @var AllowanceCharges[] */ - public ?array $allowance_charges; - public ?bool $allow_partial_delivery; - public ?string $accounting_cost; - public ?Delivery $delivery; - public ?string $description; - public ?string $name; - /** @var References[] */ - public ?array $references; - /** @var TaxesDutiesFees[] */ - public ?array $taxes_duties_fees; - /** @var AdditionalItemProperties[] */ - public ?array $additional_item_properties; - /** @var string[] */ - public ?array $lot_number_ids; - public ?string $note; + public ?string $line_id; + public ?float $quantity; + public ?string $quantity_unit_code; + public ?string $amount_excluding_tax; + public ?float $item_price; + public ?float $base_quantity; + /** @var AllowanceCharges[] */ + public ?array $allowance_charges; + public ?bool $allow_partial_delivery; + public ?string $accounting_cost; + public ?Delivery $delivery; + public ?string $description; + public ?string $name; + /** @var References[] */ + public ?array $references; + /** @var TaxesDutiesFees[] */ + public ?array $taxes_duties_fees; + /** @var AdditionalItemProperties[] */ + public ?array $additional_item_properties; + /** @var string[] */ + public ?array $lot_number_ids; + public ?string $note; - /** - * @param AllowanceCharges[] $allowance_charges - * @param References[] $references - * @param TaxesDutiesFees[] $taxes_duties_fees - * @param AdditionalItemProperties[] $additional_item_properties - * @param string[] $lot_number_ids - */ - public function __construct( - ?string $line_id, - ?float $quantity, - ?string $quantity_unit_code, - ?string $amount_excluding_tax, - ?float $item_price, - ?float $base_quantity, - ?array $allowance_charges, - ?bool $allow_partial_delivery, - ?string $accounting_cost, - ?Delivery $delivery, - ?string $description, - ?string $name, - ?array $references, - ?array $taxes_duties_fees, - ?array $additional_item_properties, - ?array $lot_number_ids, - ?string $note - ) { - $this->line_id = $line_id; - $this->quantity = $quantity; - $this->quantity_unit_code = $quantity_unit_code; - $this->amount_excluding_tax = $amount_excluding_tax; - $this->item_price = $item_price; - $this->base_quantity = $base_quantity; - $this->allowance_charges = $allowance_charges; - $this->allow_partial_delivery = $allow_partial_delivery; - $this->accounting_cost = $accounting_cost; - $this->delivery = $delivery; - $this->description = $description; - $this->name = $name; - $this->references = $references; - $this->taxes_duties_fees = $taxes_duties_fees; - $this->additional_item_properties = $additional_item_properties; - $this->lot_number_ids = $lot_number_ids; - $this->note = $note; - } + /** + * @param AllowanceCharges[] $allowance_charges + * @param References[] $references + * @param TaxesDutiesFees[] $taxes_duties_fees + * @param AdditionalItemProperties[] $additional_item_properties + * @param string[] $lot_number_ids + */ + public function __construct( + ?string $line_id, + ?float $quantity, + ?string $quantity_unit_code, + ?string $amount_excluding_tax, + ?float $item_price, + ?float $base_quantity, + ?array $allowance_charges, + ?bool $allow_partial_delivery, + ?string $accounting_cost, + ?Delivery $delivery, + ?string $description, + ?string $name, + ?array $references, + ?array $taxes_duties_fees, + ?array $additional_item_properties, + ?array $lot_number_ids, + ?string $note + ) { + $this->line_id = $line_id; + $this->quantity = $quantity; + $this->quantity_unit_code = $quantity_unit_code; + $this->amount_excluding_tax = $amount_excluding_tax; + $this->item_price = $item_price; + $this->base_quantity = $base_quantity; + $this->allowance_charges = $allowance_charges; + $this->allow_partial_delivery = $allow_partial_delivery; + $this->accounting_cost = $accounting_cost; + $this->delivery = $delivery; + $this->description = $description; + $this->name = $name; + $this->references = $references; + $this->taxes_duties_fees = $taxes_duties_fees; + $this->additional_item_properties = $additional_item_properties; + $this->lot_number_ids = $lot_number_ids; + $this->note = $note; + } - public function getLineId(): ?string - { - return $this->line_id; - } + public function getLineId(): ?string + { + return $this->line_id; + } - public function getQuantity(): ?float - { - return $this->quantity; - } + public function getQuantity(): ?float + { + return $this->quantity; + } - public function getQuantityUnitCode(): ?string - { - return $this->quantity_unit_code; - } + public function getQuantityUnitCode(): ?string + { + return $this->quantity_unit_code; + } - public function getAmountExcludingTax(): ?string - { - return $this->amount_excluding_tax; - } + public function getAmountExcludingTax(): ?string + { + return $this->amount_excluding_tax; + } - public function getItemPrice(): ?float - { - return $this->item_price; - } + public function getItemPrice(): ?float + { + return $this->item_price; + } - public function getBaseQuantity(): ?float - { - return $this->base_quantity; - } + public function getBaseQuantity(): ?float + { + return $this->base_quantity; + } - /** - * @return AllowanceCharges[] - */ - public function getAllowanceCharges(): ?array - { - return $this->allowance_charges; - } + /** + * @return AllowanceCharges[] + */ + public function getAllowanceCharges(): ?array + { + return $this->allowance_charges; + } - public function getAllowPartialDelivery(): ?bool - { - return $this->allow_partial_delivery; - } + public function getAllowPartialDelivery(): ?bool + { + return $this->allow_partial_delivery; + } - public function getAccountingCost(): ?string - { - return $this->accounting_cost; - } + public function getAccountingCost(): ?string + { + return $this->accounting_cost; + } - public function getDelivery(): ?Delivery - { - return $this->delivery; - } + public function getDelivery(): ?Delivery + { + return $this->delivery; + } - public function getDescription(): ?string - { - return $this->description; - } + public function getDescription(): ?string + { + return $this->description; + } - public function getName(): ?string - { - return $this->name; - } + public function getName(): ?string + { + return $this->name; + } - /** - * @return References[] - */ - public function getReferences(): ?array - { - return $this->references; - } + /** + * @return References[] + */ + public function getReferences(): ?array + { + return $this->references; + } - /** - * @return TaxesDutiesFees[] - */ - public function getTaxesDutiesFees(): ?array - { - return $this->taxes_duties_fees; - } + /** + * @return TaxesDutiesFees[] + */ + public function getTaxesDutiesFees(): ?array + { + return $this->taxes_duties_fees; + } - /** - * @return AdditionalItemProperties[] - */ - public function getAdditionalItemProperties(): ?array - { - return $this->additional_item_properties; - } + /** + * @return AdditionalItemProperties[] + */ + public function getAdditionalItemProperties(): ?array + { + return $this->additional_item_properties; + } - /** - * @return string[] - */ - public function getLotNumberIds(): ?array - { - return $this->lot_number_ids; - } + /** + * @return string[] + */ + public function getLotNumberIds(): ?array + { + return $this->lot_number_ids; + } - public function getNote(): ?string - { - return $this->note; - } + public function getNote(): ?string + { + return $this->note; + } - public function setLineId(?string $line_id): self - { - $this->line_id = $line_id; - return $this; - } + public function setLineId(?string $line_id): self + { + $this->line_id = $line_id; + return $this; + } - public function setQuantity(?float $quantity): self - { - $this->quantity = $quantity; - return $this; - } + public function setQuantity(?float $quantity): self + { + $this->quantity = $quantity; + return $this; + } - public function setQuantityUnitCode(?string $quantity_unit_code): self - { - $this->quantity_unit_code = $quantity_unit_code; - return $this; - } + public function setQuantityUnitCode(?string $quantity_unit_code): self + { + $this->quantity_unit_code = $quantity_unit_code; + return $this; + } - public function setAmountExcludingTax(?string $amount_excluding_tax): self - { - $this->amount_excluding_tax = $amount_excluding_tax; - return $this; - } + public function setAmountExcludingTax(?string $amount_excluding_tax): self + { + $this->amount_excluding_tax = $amount_excluding_tax; + return $this; + } - public function setItemPrice(?float $item_price): self - { - $this->item_price = $item_price; - return $this; - } + public function setItemPrice(?float $item_price): self + { + $this->item_price = $item_price; + return $this; + } - public function setBaseQuantity(?float $base_quantity): self - { - $this->base_quantity = $base_quantity; - return $this; - } + public function setBaseQuantity(?float $base_quantity): self + { + $this->base_quantity = $base_quantity; + return $this; + } - /** - * @param AllowanceCharges[] $allowance_charges - */ - public function setAllowanceCharges(?array $allowance_charges): self - { - $this->allowance_charges = $allowance_charges; - return $this; - } + /** + * @param AllowanceCharges[] $allowance_charges + */ + public function setAllowanceCharges(?array $allowance_charges): self + { + $this->allowance_charges = $allowance_charges; + return $this; + } - public function setAllowPartialDelivery(?bool $allow_partial_delivery): self - { - $this->allow_partial_delivery = $allow_partial_delivery; - return $this; - } + public function setAllowPartialDelivery(?bool $allow_partial_delivery): self + { + $this->allow_partial_delivery = $allow_partial_delivery; + return $this; + } - public function setAccountingCost(?string $accounting_cost): self - { - $this->accounting_cost = $accounting_cost; - return $this; - } + public function setAccountingCost(?string $accounting_cost): self + { + $this->accounting_cost = $accounting_cost; + return $this; + } - public function setDelivery(?Delivery $delivery): self - { - $this->delivery = $delivery; - return $this; - } + public function setDelivery(?Delivery $delivery): self + { + $this->delivery = $delivery; + return $this; + } - public function setDescription(?string $description): self - { - $this->description = $description; - return $this; - } + public function setDescription(?string $description): self + { + $this->description = $description; + return $this; + } - public function setName(?string $name): self - { - $this->name = $name; - return $this; - } + public function setName(?string $name): self + { + $this->name = $name; + return $this; + } - /** - * @param References[] $references - */ - public function setReferences(?array $references): self - { - $this->references = $references; - return $this; - } + /** + * @param References[] $references + */ + public function setReferences(?array $references): self + { + $this->references = $references; + return $this; + } - /** - * @param TaxesDutiesFees[] $taxes_duties_fees - */ - public function setTaxesDutiesFees(?array $taxes_duties_fees): self - { - $this->taxes_duties_fees = $taxes_duties_fees; - return $this; - } + /** + * @param TaxesDutiesFees[] $taxes_duties_fees + */ + public function setTaxesDutiesFees(?array $taxes_duties_fees): self + { + $this->taxes_duties_fees = $taxes_duties_fees; + return $this; + } - /** - * @param AdditionalItemProperties[] $additional_item_properties - */ - public function setAdditionalItemProperties(?array $additional_item_properties): self - { - $this->additional_item_properties = $additional_item_properties; - return $this; - } + /** + * @param AdditionalItemProperties[] $additional_item_properties + */ + public function setAdditionalItemProperties(?array $additional_item_properties): self + { + $this->additional_item_properties = $additional_item_properties; + return $this; + } - /** - * @param string[] $lot_number_ids - */ - public function setLotNumberIds(?array $lot_number_ids): self - { - $this->lot_number_ids = $lot_number_ids; - return $this; - } + /** + * @param string[] $lot_number_ids + */ + public function setLotNumberIds(?array $lot_number_ids): self + { + $this->lot_number_ids = $lot_number_ids; + return $this; + } - public function setNote(?string $note): self - { - $this->note = $note; - return $this; - } + public function setNote(?string $note): self + { + $this->note = $note; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/OriginAddress.php b/app/Services/EDocument/Gateway/Storecove/Models/OriginAddress.php index 54c3243b25..93da901c6a 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/OriginAddress.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/OriginAddress.php @@ -4,92 +4,92 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class OriginAddress { - public ?string $country; - public ?string $street1; - public ?string $street2; - public ?string $city; - public ?string $zip; - public ?string $county; + public ?string $country; + public ?string $street1; + public ?string $street2; + public ?string $city; + public ?string $zip; + public ?string $county; - public function __construct( - ?string $country, - ?string $street1, - ?string $street2, - ?string $city, - ?string $zip, - ?string $county - ) { - $this->country = $country; - $this->street1 = $street1; - $this->street2 = $street2; - $this->city = $city; - $this->zip = $zip; - $this->county = $county; - } + public function __construct( + ?string $country, + ?string $street1, + ?string $street2, + ?string $city, + ?string $zip, + ?string $county + ) { + $this->country = $country; + $this->street1 = $street1; + $this->street2 = $street2; + $this->city = $city; + $this->zip = $zip; + $this->county = $county; + } - public function getCountry(): ?string - { - return $this->country; - } + public function getCountry(): ?string + { + return $this->country; + } - public function getStreet1(): ?string - { - return $this->street1; - } + public function getStreet1(): ?string + { + return $this->street1; + } - public function getStreet2(): ?string - { - return $this->street2; - } + public function getStreet2(): ?string + { + return $this->street2; + } - public function getCity(): ?string - { - return $this->city; - } + public function getCity(): ?string + { + return $this->city; + } - public function getZip(): ?string - { - return $this->zip; - } + public function getZip(): ?string + { + return $this->zip; + } - public function getCounty(): ?string - { - return $this->county; - } + public function getCounty(): ?string + { + return $this->county; + } - public function setCountry(?string $country): self - { - $this->country = $country; - return $this; - } + public function setCountry(?string $country): self + { + $this->country = $country; + return $this; + } - public function setStreet1(?string $street1): self - { - $this->street1 = $street1; - return $this; - } + public function setStreet1(?string $street1): self + { + $this->street1 = $street1; + return $this; + } - public function setStreet2(?string $street2): self - { - $this->street2 = $street2; - return $this; - } + public function setStreet2(?string $street2): self + { + $this->street2 = $street2; + return $this; + } - public function setCity(?string $city): self - { - $this->city = $city; - return $this; - } + public function setCity(?string $city): self + { + $this->city = $city; + return $this; + } - public function setZip(?string $zip): self - { - $this->zip = $zip; - return $this; - } + public function setZip(?string $zip): self + { + $this->zip = $zip; + return $this; + } - public function setCounty(?string $county): self - { - $this->county = $county; - return $this; - } + public function setCounty(?string $county): self + { + $this->county = $county; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/Party.php b/app/Services/EDocument/Gateway/Storecove/Models/Party.php index a29a7a4135..80e9c3a129 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/Party.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/Party.php @@ -7,86 +7,86 @@ use Symfony\Component\Serializer\Attribute\SerializedPath; class Party { - #[SerializedPath('[cac:PartyName][0][cbc:Name]')] - public $company_name; - - #[SerializedPath('[cac:PartyLegalEntity][0][cbc:RegistrationName]')] - public ?string $registration_name; + #[SerializedPath('[cac:PartyName][0][cbc:Name]')] + public $company_name; - public ?string $classification_code; + #[SerializedPath('[cac:PartyLegalEntity][0][cbc:RegistrationName]')] + public ?string $registration_name; - #[SerializedPath('[cac:PostalAddress]')] - public ?Address $address; - - #[SerializedPath('[cac:Contact]')] - public ?Contact $contact; + public ?string $classification_code; - public function __construct( - ?string $company_name, - ?string $registration_name, - ?string $classification_code, - ?Address $address, - ?Contact $contact - ) { - $this->company_name = $company_name; - $this->registration_name = $registration_name; - $this->classification_code = $classification_code; - $this->address = $address; - $this->contact = $contact; - } + #[SerializedPath('[cac:PostalAddress]')] + public ?Address $address; - public function getCompanyName(): ?string - { - return $this->company_name; - } + #[SerializedPath('[cac:Contact]')] + public ?Contact $contact; - public function getRegistrationName(): ?string - { - return $this->registration_name; - } + public function __construct( + ?string $company_name, + ?string $registration_name, + ?string $classification_code, + ?Address $address, + ?Contact $contact + ) { + $this->company_name = $company_name; + $this->registration_name = $registration_name; + $this->classification_code = $classification_code; + $this->address = $address; + $this->contact = $contact; + } - public function getClassificationCode(): ?string - { - return $this->classification_code; - } + public function getCompanyName(): ?string + { + return $this->company_name; + } - public function getAddress(): ?Address - { - return $this->address; - } + public function getRegistrationName(): ?string + { + return $this->registration_name; + } - public function getContact(): ?Contact - { - return $this->contact; - } + public function getClassificationCode(): ?string + { + return $this->classification_code; + } - public function setCompanyName(?string $company_name): self - { - $this->company_name = $company_name; - return $this; - } + public function getAddress(): ?Address + { + return $this->address; + } - public function setRegistrationName(?string $registration_name): self - { - $this->registration_name = $registration_name; - return $this; - } + public function getContact(): ?Contact + { + return $this->contact; + } - public function setClassificationCode(?string $classification_code): self - { - $this->classification_code = $classification_code; - return $this; - } + public function setCompanyName(?string $company_name): self + { + $this->company_name = $company_name; + return $this; + } - public function setAddress(?Address $address): self - { - $this->address = $address; - return $this; - } + public function setRegistrationName(?string $registration_name): self + { + $this->registration_name = $registration_name; + return $this; + } - public function setContact(?Contact $contact): self - { - $this->contact = $contact; - return $this; - } + public function setClassificationCode(?string $classification_code): self + { + $this->classification_code = $classification_code; + return $this; + } + + public function setAddress(?Address $address): self + { + $this->address = $address; + return $this; + } + + public function setContact(?Contact $contact): self + { + $this->contact = $contact; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/PaymentMeansArray.php b/app/Services/EDocument/Gateway/Storecove/Models/PaymentMeansArray.php index 5c62b2c5ed..efe72c8b3d 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/PaymentMeansArray.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/PaymentMeansArray.php @@ -7,7 +7,7 @@ use Symfony\Component\Serializer\Attribute\SerializedPath; class PaymentMeansArray { - #[SerializedPath('[cbc:PaymentMeansCode][#]')] + #[SerializedPath('[cbc:PaymentMeansCode][#]')] public ?string $code; #[SerializedPath('[cac:PayeeFinancialAccount][cbc:ID][#]')] @@ -31,111 +31,111 @@ class PaymentMeansArray #[SerializedPath('[cbc:PaymentAmount][#]')] public ?string $amount; - public function __construct( - ?string $code, - ?string $account, - ?string $branche_code, - ?string $holder, - ?string $network, - ?string $mandate, - ?string $payment_id, - ?string $amount - ) { - $this->code = $code; - $this->account = $account; - $this->branche_code = $branche_code; - $this->holder = $holder; - $this->network = $network; - $this->mandate = $mandate; - $this->payment_id = $payment_id; - $this->amount = $amount; - } + public function __construct( + ?string $code, + ?string $account, + ?string $branche_code, + ?string $holder, + ?string $network, + ?string $mandate, + ?string $payment_id, + ?string $amount + ) { + $this->code = $code; + $this->account = $account; + $this->branche_code = $branche_code; + $this->holder = $holder; + $this->network = $network; + $this->mandate = $mandate; + $this->payment_id = $payment_id; + $this->amount = $amount; + } - public function getCode(): ?string - { - return $this->code; - } + public function getCode(): ?string + { + return $this->code; + } - public function getAccount(): ?string - { - return $this->account; - } + public function getAccount(): ?string + { + return $this->account; + } - public function getBrancheCode(): ?string - { - return $this->branche_code; - } + public function getBrancheCode(): ?string + { + return $this->branche_code; + } - public function getHolder(): ?string - { - return $this->holder; - } + public function getHolder(): ?string + { + return $this->holder; + } - public function getNetwork(): ?string - { - return $this->network; - } + public function getNetwork(): ?string + { + return $this->network; + } - public function getMandate(): ?string - { - return $this->mandate; - } + public function getMandate(): ?string + { + return $this->mandate; + } - public function getPaymentId(): ?string - { - return $this->payment_id; - } + public function getPaymentId(): ?string + { + return $this->payment_id; + } - public function getAmount(): ?string - { - return $this->amount; - } + public function getAmount(): ?string + { + return $this->amount; + } - public function setCode(?string $code): self - { - $this->code = $code; - return $this; - } + public function setCode(?string $code): self + { + $this->code = $code; + return $this; + } - public function setAccount(?string $account): self - { - $this->account = $account; - return $this; - } + public function setAccount(?string $account): self + { + $this->account = $account; + return $this; + } - public function setBrancheCode(?string $branche_code): self - { - $this->branche_code = $branche_code; - return $this; - } + public function setBrancheCode(?string $branche_code): self + { + $this->branche_code = $branche_code; + return $this; + } - public function setHolder(?string $holder): self - { - $this->holder = $holder; - return $this; - } + public function setHolder(?string $holder): self + { + $this->holder = $holder; + return $this; + } - public function setNetwork(?string $network): self - { - $this->network = $network; - return $this; - } + public function setNetwork(?string $network): self + { + $this->network = $network; + return $this; + } - public function setMandate(?string $mandate): self - { - $this->mandate = $mandate; - return $this; - } + public function setMandate(?string $mandate): self + { + $this->mandate = $mandate; + return $this; + } - public function setPaymentId(?string $payment_id): self - { - $this->payment_id = $payment_id; - return $this; - } + public function setPaymentId(?string $payment_id): self + { + $this->payment_id = $payment_id; + return $this; + } - public function setAmount(?string $amount): self - { - $this->amount = $amount; - return $this; - } + public function setAmount(?string $amount): self + { + $this->amount = $amount; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/PaymentTerms.php b/app/Services/EDocument/Gateway/Storecove/Models/PaymentTerms.php index fda8d785c0..149b33b668 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/PaymentTerms.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/PaymentTerms.php @@ -6,22 +6,22 @@ use Symfony\Component\Serializer\Attribute\SerializedName; class PaymentTerms { - #[SerializedName('cbc:Note')] - public ?string $note; + #[SerializedName('cbc:Note')] + public ?string $note; - public function __construct(?string $note) - { - $this->note = $note; - } + public function __construct(?string $note) + { + $this->note = $note; + } - public function getNote(): ?string - { - return $this->note; - } + public function getNote(): ?string + { + return $this->note; + } - public function setNote(?string $note): self - { - $this->note = $note; - return $this; - } + public function setNote(?string $note): self + { + $this->note = $note; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/PublicIdentifiers.php b/app/Services/EDocument/Gateway/Storecove/Models/PublicIdentifiers.php index 216727cf0d..76d7c929b8 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/PublicIdentifiers.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/PublicIdentifiers.php @@ -4,34 +4,34 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class PublicIdentifiers { - public ?string $scheme; - public ?string $id; + public ?string $scheme; + public ?string $id; - public function __construct(?string $scheme, ?string $id) - { - $this->scheme = $scheme; - $this->id = $id; - } + public function __construct(?string $scheme, ?string $id) + { + $this->scheme = $scheme; + $this->id = $id; + } - public function getScheme(): ?string - { - return $this->scheme; - } + public function getScheme(): ?string + { + return $this->scheme; + } - public function getId(): ?string - { - return $this->id; - } + public function getId(): ?string + { + return $this->id; + } - public function setScheme(?string $scheme): self - { - $this->scheme = $scheme; - return $this; - } + public function setScheme(?string $scheme): self + { + $this->scheme = $scheme; + return $this; + } - public function setId(?string $id): self - { - $this->id = $id; - return $this; - } + public function setId(?string $id): self + { + $this->id = $id; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/References.php b/app/Services/EDocument/Gateway/Storecove/Models/References.php index 1f851a5af2..37b2232901 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/References.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/References.php @@ -4,190 +4,190 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class References { - public ?string $document_type; - public ?string $document_type_code; - public ?string $document_id; - public ?string $document_uuid; - public ?string $document_id_scheme_id; - public ?string $document_id_scheme_agency_id; - public ?string $document_id_scheme_version_id; - public ?string $document_id_list_id; - public ?string $document_id_list_agency_id; - public ?string $document_id_list_version_id; - public ?string $line_id; - public ?string $issue_date; - public ?string $document_description; + public ?string $document_type; + public ?string $document_type_code; + public ?string $document_id; + public ?string $document_uuid; + public ?string $document_id_scheme_id; + public ?string $document_id_scheme_agency_id; + public ?string $document_id_scheme_version_id; + public ?string $document_id_list_id; + public ?string $document_id_list_agency_id; + public ?string $document_id_list_version_id; + public ?string $line_id; + public ?string $issue_date; + public ?string $document_description; - public function __construct( - ?string $document_type, - ?string $document_type_code, - ?string $document_id, - ?string $document_uuid, - ?string $document_id_scheme_id, - ?string $document_id_scheme_agency_id, - ?string $document_id_scheme_version_id, - ?string $document_id_list_id, - ?string $document_id_list_agency_id, - ?string $document_id_list_version_id, - ?string $line_id, - ?string $issue_date, - ?string $document_description - ) { - $this->document_type = $document_type; - $this->document_type_code = $document_type_code; - $this->document_id = $document_id; - $this->document_uuid = $document_uuid; - $this->document_id_scheme_id = $document_id_scheme_id; - $this->document_id_scheme_agency_id = $document_id_scheme_agency_id; - $this->document_id_scheme_version_id = $document_id_scheme_version_id; - $this->document_id_list_id = $document_id_list_id; - $this->document_id_list_agency_id = $document_id_list_agency_id; - $this->document_id_list_version_id = $document_id_list_version_id; - $this->line_id = $line_id; - $this->issue_date = $issue_date; - $this->document_description = $document_description; - } + public function __construct( + ?string $document_type, + ?string $document_type_code, + ?string $document_id, + ?string $document_uuid, + ?string $document_id_scheme_id, + ?string $document_id_scheme_agency_id, + ?string $document_id_scheme_version_id, + ?string $document_id_list_id, + ?string $document_id_list_agency_id, + ?string $document_id_list_version_id, + ?string $line_id, + ?string $issue_date, + ?string $document_description + ) { + $this->document_type = $document_type; + $this->document_type_code = $document_type_code; + $this->document_id = $document_id; + $this->document_uuid = $document_uuid; + $this->document_id_scheme_id = $document_id_scheme_id; + $this->document_id_scheme_agency_id = $document_id_scheme_agency_id; + $this->document_id_scheme_version_id = $document_id_scheme_version_id; + $this->document_id_list_id = $document_id_list_id; + $this->document_id_list_agency_id = $document_id_list_agency_id; + $this->document_id_list_version_id = $document_id_list_version_id; + $this->line_id = $line_id; + $this->issue_date = $issue_date; + $this->document_description = $document_description; + } - public function getDocumentType(): ?string - { - return $this->document_type; - } + public function getDocumentType(): ?string + { + return $this->document_type; + } - public function getDocumentTypeCode(): ?string - { - return $this->document_type_code; - } + public function getDocumentTypeCode(): ?string + { + return $this->document_type_code; + } - public function getDocumentId(): ?string - { - return $this->document_id; - } + public function getDocumentId(): ?string + { + return $this->document_id; + } - public function getDocumentUuid(): ?string - { - return $this->document_uuid; - } + public function getDocumentUuid(): ?string + { + return $this->document_uuid; + } - public function getDocumentIdSchemeId(): ?string - { - return $this->document_id_scheme_id; - } + public function getDocumentIdSchemeId(): ?string + { + return $this->document_id_scheme_id; + } - public function getDocumentIdSchemeAgencyId(): ?string - { - return $this->document_id_scheme_agency_id; - } + public function getDocumentIdSchemeAgencyId(): ?string + { + return $this->document_id_scheme_agency_id; + } - public function getDocumentIdSchemeVersionId(): ?string - { - return $this->document_id_scheme_version_id; - } + public function getDocumentIdSchemeVersionId(): ?string + { + return $this->document_id_scheme_version_id; + } - public function getDocumentIdListId(): ?string - { - return $this->document_id_list_id; - } + public function getDocumentIdListId(): ?string + { + return $this->document_id_list_id; + } - public function getDocumentIdListAgencyId(): ?string - { - return $this->document_id_list_agency_id; - } + public function getDocumentIdListAgencyId(): ?string + { + return $this->document_id_list_agency_id; + } - public function getDocumentIdListVersionId(): ?string - { - return $this->document_id_list_version_id; - } + public function getDocumentIdListVersionId(): ?string + { + return $this->document_id_list_version_id; + } - public function getLineId(): ?string - { - return $this->line_id; - } + public function getLineId(): ?string + { + return $this->line_id; + } - public function getIssueDate(): ?string - { - return $this->issue_date; - } + public function getIssueDate(): ?string + { + return $this->issue_date; + } - public function getDocumentDescription(): ?string - { - return $this->document_description; - } + public function getDocumentDescription(): ?string + { + return $this->document_description; + } - public function setDocumentType(?string $document_type): self - { - $this->document_type = $document_type; - return $this; - } + public function setDocumentType(?string $document_type): self + { + $this->document_type = $document_type; + return $this; + } - public function setDocumentTypeCode(?string $document_type_code): self - { - $this->document_type_code = $document_type_code; - return $this; - } + public function setDocumentTypeCode(?string $document_type_code): self + { + $this->document_type_code = $document_type_code; + return $this; + } - public function setDocumentId(?string $document_id): self - { - $this->document_id = $document_id; - return $this; - } + public function setDocumentId(?string $document_id): self + { + $this->document_id = $document_id; + return $this; + } - public function setDocumentUuid(?string $document_uuid): self - { - $this->document_uuid = $document_uuid; - return $this; - } + public function setDocumentUuid(?string $document_uuid): self + { + $this->document_uuid = $document_uuid; + return $this; + } - public function setDocumentIdSchemeId(?string $document_id_scheme_id): self - { - $this->document_id_scheme_id = $document_id_scheme_id; - return $this; - } + public function setDocumentIdSchemeId(?string $document_id_scheme_id): self + { + $this->document_id_scheme_id = $document_id_scheme_id; + return $this; + } - public function setDocumentIdSchemeAgencyId(?string $document_id_scheme_agency_id): self - { - $this->document_id_scheme_agency_id = $document_id_scheme_agency_id; - return $this; - } + public function setDocumentIdSchemeAgencyId(?string $document_id_scheme_agency_id): self + { + $this->document_id_scheme_agency_id = $document_id_scheme_agency_id; + return $this; + } - public function setDocumentIdSchemeVersionId(?string $document_id_scheme_version_id): self - { - $this->document_id_scheme_version_id = $document_id_scheme_version_id; - return $this; - } + public function setDocumentIdSchemeVersionId(?string $document_id_scheme_version_id): self + { + $this->document_id_scheme_version_id = $document_id_scheme_version_id; + return $this; + } - public function setDocumentIdListId(?string $document_id_list_id): self - { - $this->document_id_list_id = $document_id_list_id; - return $this; - } + public function setDocumentIdListId(?string $document_id_list_id): self + { + $this->document_id_list_id = $document_id_list_id; + return $this; + } - public function setDocumentIdListAgencyId(?string $document_id_list_agency_id): self - { - $this->document_id_list_agency_id = $document_id_list_agency_id; - return $this; - } + public function setDocumentIdListAgencyId(?string $document_id_list_agency_id): self + { + $this->document_id_list_agency_id = $document_id_list_agency_id; + return $this; + } - public function setDocumentIdListVersionId(?string $document_id_list_version_id): self - { - $this->document_id_list_version_id = $document_id_list_version_id; - return $this; - } + public function setDocumentIdListVersionId(?string $document_id_list_version_id): self + { + $this->document_id_list_version_id = $document_id_list_version_id; + return $this; + } - public function setLineId(?string $line_id): self - { - $this->line_id = $line_id; - return $this; - } + public function setLineId(?string $line_id): self + { + $this->line_id = $line_id; + return $this; + } - public function setIssueDate(?string $issue_date): self - { - $this->issue_date = $issue_date; - return $this; - } + public function setIssueDate(?string $issue_date): self + { + $this->issue_date = $issue_date; + return $this; + } - public function setDocumentDescription(?string $document_description): self - { - $this->document_description = $document_description; - return $this; - } + public function setDocumentDescription(?string $document_description): self + { + $this->document_description = $document_description; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/RootObject.php b/app/Services/EDocument/Gateway/Storecove/Models/RootObject.php index 1fdb596285..ecda41a1ff 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/RootObject.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/RootObject.php @@ -4,78 +4,78 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class RootObject { - public ?string $legal_entity_id; - public ?string $direction; - public ?string $guid; - public ?string $original; - public ?Document $document; + public ?string $legal_entity_id; + public ?string $direction; + public ?string $guid; + public ?string $original; + public ?Document $document; - public function __construct( - ?string $legal_entity_id, - ?string $direction, - ?string $guid, - ?string $original, - ?Document $document - ) { - $this->legal_entity_id = $legal_entity_id; - $this->direction = $direction; - $this->guid = $guid; - $this->original = $original; - $this->document = $document; - } + public function __construct( + ?string $legal_entity_id, + ?string $direction, + ?string $guid, + ?string $original, + ?Document $document + ) { + $this->legal_entity_id = $legal_entity_id; + $this->direction = $direction; + $this->guid = $guid; + $this->original = $original; + $this->document = $document; + } - public function getLegalEntityId(): ?string - { - return $this->legal_entity_id; - } + public function getLegalEntityId(): ?string + { + return $this->legal_entity_id; + } - public function getDirection(): ?string - { - return $this->direction; - } + public function getDirection(): ?string + { + return $this->direction; + } - public function getGuid(): ?string - { - return $this->guid; - } + public function getGuid(): ?string + { + return $this->guid; + } - public function getOriginal(): ?string - { - return $this->original; - } + public function getOriginal(): ?string + { + return $this->original; + } - public function getDocument(): ?Document - { - return $this->document; - } + public function getDocument(): ?Document + { + return $this->document; + } - public function setLegalEntityId(?string $legal_entity_id): self - { - $this->legal_entity_id = $legal_entity_id; - return $this; - } + public function setLegalEntityId(?string $legal_entity_id): self + { + $this->legal_entity_id = $legal_entity_id; + return $this; + } - public function setDirection(?string $direction): self - { - $this->direction = $direction; - return $this; - } + public function setDirection(?string $direction): self + { + $this->direction = $direction; + return $this; + } - public function setGuid(?string $guid): self - { - $this->guid = $guid; - return $this; - } + public function setGuid(?string $guid): self + { + $this->guid = $guid; + return $this; + } - public function setOriginal(?string $original): self - { - $this->original = $original; - return $this; - } + public function setOriginal(?string $original): self + { + $this->original = $original; + return $this; + } - public function setDocument(?Document $document): self - { - $this->document = $document; - return $this; - } + public function setDocument(?Document $document): self + { + $this->document = $document; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/SellerSupplierParty.php b/app/Services/EDocument/Gateway/Storecove/Models/SellerSupplierParty.php index 9af0c0d577..ce97d6759c 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/SellerSupplierParty.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/SellerSupplierParty.php @@ -4,44 +4,44 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class SellerSupplierParty { - public ?Party $party; - /** @var PublicIdentifiers[] */ - public ?array $public_identifiers; + public ?Party $party; + /** @var PublicIdentifiers[] */ + public ?array $public_identifiers; - /** - * @param PublicIdentifiers[] $public_identifiers - */ - public function __construct(?Party $party, ?array $public_identifiers) - { - $this->party = $party; - $this->public_identifiers = $public_identifiers; - } + /** + * @param PublicIdentifiers[] $public_identifiers + */ + public function __construct(?Party $party, ?array $public_identifiers) + { + $this->party = $party; + $this->public_identifiers = $public_identifiers; + } - public function getParty(): ?Party - { - return $this->party; - } + public function getParty(): ?Party + { + return $this->party; + } - /** - * @return PublicIdentifiers[] - */ - public function getPublicIdentifiers(): ?array - { - return $this->public_identifiers; - } + /** + * @return PublicIdentifiers[] + */ + public function getPublicIdentifiers(): ?array + { + return $this->public_identifiers; + } - public function setParty(?Party $party): self - { - $this->party = $party; - return $this; - } + public function setParty(?Party $party): self + { + $this->party = $party; + return $this; + } - /** - * @param PublicIdentifiers[] $public_identifiers - */ - public function setPublicIdentifiers(?array $public_identifiers): self - { - $this->public_identifiers = $public_identifiers; - return $this; - } + /** + * @param PublicIdentifiers[] $public_identifiers + */ + public function setPublicIdentifiers(?array $public_identifiers): self + { + $this->public_identifiers = $public_identifiers; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/Shipment.php b/app/Services/EDocument/Gateway/Storecove/Models/Shipment.php index 0bcb9cfce5..a356429d08 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/Shipment.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/Shipment.php @@ -4,60 +4,60 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class Shipment { - public ?string $shipping_marks; - public ?OriginAddress $origin_address; - /** @var AllowanceCharges[] */ - public ?array $allowance_charges; + public ?string $shipping_marks; + public ?OriginAddress $origin_address; + /** @var AllowanceCharges[] */ + public ?array $allowance_charges; - /** - * @param AllowanceCharges[] $allowance_charges - */ - public function __construct( - ?string $shipping_marks, - ?OriginAddress $origin_address, - ?array $allowance_charges - ) { - $this->shipping_marks = $shipping_marks; - $this->origin_address = $origin_address; - $this->allowance_charges = $allowance_charges; - } + /** + * @param AllowanceCharges[] $allowance_charges + */ + public function __construct( + ?string $shipping_marks, + ?OriginAddress $origin_address, + ?array $allowance_charges + ) { + $this->shipping_marks = $shipping_marks; + $this->origin_address = $origin_address; + $this->allowance_charges = $allowance_charges; + } - public function getShippingMarks(): ?string - { - return $this->shipping_marks; - } + public function getShippingMarks(): ?string + { + return $this->shipping_marks; + } - public function getOriginAddress(): ?OriginAddress - { - return $this->origin_address; - } + public function getOriginAddress(): ?OriginAddress + { + return $this->origin_address; + } - /** - * @return AllowanceCharges[] - */ - public function getAllowanceCharges(): ?array - { - return $this->allowance_charges; - } + /** + * @return AllowanceCharges[] + */ + public function getAllowanceCharges(): ?array + { + return $this->allowance_charges; + } - public function setShippingMarks(?string $shipping_marks): self - { - $this->shipping_marks = $shipping_marks; - return $this; - } + public function setShippingMarks(?string $shipping_marks): self + { + $this->shipping_marks = $shipping_marks; + return $this; + } - public function setOriginAddress(?OriginAddress $origin_address): self - { - $this->origin_address = $origin_address; - return $this; - } + public function setOriginAddress(?OriginAddress $origin_address): self + { + $this->origin_address = $origin_address; + return $this; + } - /** - * @param AllowanceCharges[] $allowance_charges - */ - public function setAllowanceCharges(?array $allowance_charges): self - { - $this->allowance_charges = $allowance_charges; - return $this; - } + /** + * @param AllowanceCharges[] $allowance_charges + */ + public function setAllowanceCharges(?array $allowance_charges): self + { + $this->allowance_charges = $allowance_charges; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/Tax.php b/app/Services/EDocument/Gateway/Storecove/Models/Tax.php index 181231c487..cad8072779 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/Tax.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/Tax.php @@ -4,78 +4,78 @@ namespace App\Services\EDocument\Gateway\Storecove\Models; class Tax { - public ?string $country; - public ?float $amount; - public ?float $percentage; - public ?string $category; - public ?string $type; + public ?string $country; + public ?float $amount; + public ?float $percentage; + public ?string $category; + public ?string $type; - public function __construct( - ?string $country, - ?float $amount, - ?float $percentage, - ?string $category, - ?string $type - ) { - $this->country = $country; - $this->amount = $amount; - $this->percentage = $percentage; - $this->category = $category; - $this->type = $type; - } + public function __construct( + ?string $country, + ?float $amount, + ?float $percentage, + ?string $category, + ?string $type + ) { + $this->country = $country; + $this->amount = $amount; + $this->percentage = $percentage; + $this->category = $category; + $this->type = $type; + } - public function getCountry(): ?string - { - return $this->country; - } + public function getCountry(): ?string + { + return $this->country; + } - public function getAmount(): ?float - { - return $this->amount; - } + public function getAmount(): ?float + { + return $this->amount; + } - public function getPercentage(): ?float - { - return $this->percentage; - } + public function getPercentage(): ?float + { + return $this->percentage; + } - public function getCategory(): ?string - { - return $this->category; - } + public function getCategory(): ?string + { + return $this->category; + } - public function getType(): ?string - { - return $this->type; - } + public function getType(): ?string + { + return $this->type; + } - public function setCountry(?string $country): self - { - $this->country = $country; - return $this; - } + public function setCountry(?string $country): self + { + $this->country = $country; + return $this; + } - public function setAmount(?float $amount): self - { - $this->amount = $amount; - return $this; - } + public function setAmount(?float $amount): self + { + $this->amount = $amount; + return $this; + } - public function setPercentage(?float $percentage): self - { - $this->percentage = $percentage; - return $this; - } + public function setPercentage(?float $percentage): self + { + $this->percentage = $percentage; + return $this; + } - public function setCategory(?string $category): self - { - $this->category = $category; - return $this; - } + public function setCategory(?string $category): self + { + $this->category = $category; + return $this; + } - public function setType(?string $type): self - { - $this->type = $type; - return $this; - } + public function setType(?string $type): self + { + $this->type = $type; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/TaxSubtotals.php b/app/Services/EDocument/Gateway/Storecove/Models/TaxSubtotals.php index 00e8d4f971..797cc6b6fa 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/TaxSubtotals.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/TaxSubtotals.php @@ -7,7 +7,6 @@ use Symfony\Component\Serializer\Attribute\SerializedPath; class TaxSubtotals { - #[SerializedPath('[cbc:TaxAmount][#]')] public ?float $tax_amount; @@ -22,93 +21,93 @@ class TaxSubtotals #[SerializedPath('[cac:TaxCategory][cbc:ID][#]')] public ?string $category; - public ?string $type; + public ?string $type; - public function __construct( - ?float $tax_amount, - ?string $country, - ?float $taxable_amount, - ?float $percentage, - ?string $category, - ?string $type - ) { - $this->tax_amount = $tax_amount; - $this->country = $country; - $this->taxable_amount = $taxable_amount; - $this->percentage = $percentage; - $this->category = $category; - $this->type = $type; - } + public function __construct( + ?float $tax_amount, + ?string $country, + ?float $taxable_amount, + ?float $percentage, + ?string $category, + ?string $type + ) { + $this->tax_amount = $tax_amount; + $this->country = $country; + $this->taxable_amount = $taxable_amount; + $this->percentage = $percentage; + $this->category = $category; + $this->type = $type; + } - public function getType(): ?string - { - return $this->type; - } + public function getType(): ?string + { + return $this->type; + } - public function setType(?string $type):self - { - $this->type = $type; + public function setType(?string $type): self + { + $this->type = $type; - return $this; - } + return $this; + } - public function getTaxAmount(): ?float - { - return $this->tax_amount; - } + public function getTaxAmount(): ?float + { + return $this->tax_amount; + } - public function getCountry(): ?string - { - return $this->country; - } + public function getCountry(): ?string + { + return $this->country; + } - public function getTaxableAmount(): ?float - { - return $this->taxable_amount; - } + public function getTaxableAmount(): ?float + { + return $this->taxable_amount; + } - public function getPercentage(): ?float - { - return $this->percentage; - } + public function getPercentage(): ?float + { + return $this->percentage; + } - public function getCategory(): ?string - { - return $this->category; - } + public function getCategory(): ?string + { + return $this->category; + } - public function setTaxAmount(?float $tax_amount): self - { - $this->tax_amount = $tax_amount; - return $this; - } + public function setTaxAmount(?float $tax_amount): self + { + $this->tax_amount = $tax_amount; + return $this; + } - public function setCountry(?string $country): self - { - $this->country = $country; - return $this; - } + public function setCountry(?string $country): self + { + $this->country = $country; + return $this; + } - public function setTaxableAmount(?float $taxable_amount): self - { - $this->taxable_amount = $taxable_amount; - return $this; - } + public function setTaxableAmount(?float $taxable_amount): self + { + $this->taxable_amount = $taxable_amount; + return $this; + } - public function setPercentage(?float $percentage): self - { - $this->percentage = $percentage; - return $this; - } + public function setPercentage(?float $percentage): self + { + $this->percentage = $percentage; + return $this; + } - public function setCategory(?string $category): self - { - $this->category = $category; - return $this; - } + public function setCategory(?string $category): self + { + $this->category = $category; + return $this; + } - public function toArray(): array - { - return (array)$this; - } + public function toArray(): array + { + return (array)$this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Models/TaxesDutiesFees.php b/app/Services/EDocument/Gateway/Storecove/Models/TaxesDutiesFees.php index 9099abcad4..84ea3b2eaa 100644 --- a/app/Services/EDocument/Gateway/Storecove/Models/TaxesDutiesFees.php +++ b/app/Services/EDocument/Gateway/Storecove/Models/TaxesDutiesFees.php @@ -8,85 +8,85 @@ use Symfony\Component\Serializer\Attribute\SerializedPath; class TaxesDutiesFees { - public ?string $country; //need to run postprocessing on this - public ?float $amount; + public ?string $country; //need to run postprocessing on this + public ?float $amount; - #[Context(['input_format' => 'float'])] - #[SerializedName('cbc:Percent')] - public ?float $percentage = 0; + #[Context(['input_format' => 'float'])] + #[SerializedName('cbc:Percent')] + public ?float $percentage = 0; - #[SerializedPath('[cbc:ID][#]')] - public ?string $category; + #[SerializedPath('[cbc:ID][#]')] + public ?string $category; - #[SerializedPath('[cac:TaxScheme][cbc:ID][#]')] - public ?string $type; + #[SerializedPath('[cac:TaxScheme][cbc:ID][#]')] + public ?string $type; - public function __construct( - ?string $country, - ?float $amount, - ?float $percentage, - ?string $category, - ?string $type - ) { - $this->country = $country; - $this->amount = $amount; - $this->percentage = $percentage; - $this->category = $category; - $this->type = $type; - } + public function __construct( + ?string $country, + ?float $amount, + ?float $percentage, + ?string $category, + ?string $type + ) { + $this->country = $country; + $this->amount = $amount; + $this->percentage = $percentage; + $this->category = $category; + $this->type = $type; + } - public function getCountry(): ?string - { - return $this->country; - } + public function getCountry(): ?string + { + return $this->country; + } - public function getAmount(): ?float - { - return $this->amount; - } + public function getAmount(): ?float + { + return $this->amount; + } - public function getPercentage(): ?float - { - return $this->percentage; - } + public function getPercentage(): ?float + { + return $this->percentage; + } - public function getCategory(): ?string - { - return $this->category; - } + public function getCategory(): ?string + { + return $this->category; + } - public function getType(): ?string - { - return $this->type; - } + public function getType(): ?string + { + return $this->type; + } - public function setCountry(?string $country): self - { - $this->country = $country; - return $this; - } + public function setCountry(?string $country): self + { + $this->country = $country; + return $this; + } - public function setAmount(?float $amount): self - { - $this->amount = $amount; - return $this; - } + public function setAmount(?float $amount): self + { + $this->amount = $amount; + return $this; + } - public function setPercentage(?float $percentage): self - { - $this->percentage = $percentage; - return $this; - } + public function setPercentage(?float $percentage): self + { + $this->percentage = $percentage; + return $this; + } - public function setCategory(?string $category): self - { - $this->category = $category; - return $this; - } + public function setCategory(?string $category): self + { + $this->category = $category; + return $this; + } - public function setType(?string $type): self - { - $this->type = $type; - return $this; - } + public function setType(?string $type): self + { + $this->type = $type; + return $this; + } } diff --git a/app/Services/EDocument/Gateway/Storecove/Mutator.php b/app/Services/EDocument/Gateway/Storecove/Mutator.php index f42a30d8ec..153c8c9172 100644 --- a/app/Services/EDocument/Gateway/Storecove/Mutator.php +++ b/app/Services/EDocument/Gateway/Storecove/Mutator.php @@ -18,15 +18,14 @@ use App\Services\EDocument\Gateway\Storecove\StorecoveRouter; class Mutator implements MutatorInterface { - private \InvoiceNinja\EInvoice\Models\Peppol\Invoice $p_invoice; - + private ?\InvoiceNinja\EInvoice\Models\Peppol\Invoice $_client_settings; private ?\InvoiceNinja\EInvoice\Models\Peppol\Invoice $_company_settings; private $invoice; - + private array $storecove_meta = []; private MutatorUtil $mutator_util; @@ -84,7 +83,7 @@ class Mutator implements MutatorInterface /** * setCompanySettings - * + * * @param \InvoiceNinja\EInvoice\Models\Peppol\Invoice $company_settings * @return self */ @@ -93,7 +92,7 @@ class Mutator implements MutatorInterface $this->_company_settings = $company_settings; return $this; } - + /** * getClientSettings * @@ -103,7 +102,7 @@ class Mutator implements MutatorInterface { return $this->_client_settings; } - + /** * getCompanySettings * @@ -113,7 +112,7 @@ class Mutator implements MutatorInterface { return $this->_company_settings; } - + /** * getInvoice * @@ -123,7 +122,7 @@ class Mutator implements MutatorInterface { return $this->invoice; } - + /** * getSetting * @@ -146,7 +145,7 @@ class Mutator implements MutatorInterface public function senderSpecificLevelMutators(): self { - if(method_exists($this, $this->invoice->company->country()->iso_3166_2)) { + if (method_exists($this, $this->invoice->company->country()->iso_3166_2)) { $this->{$this->invoice->company->country()->iso_3166_2}(); } @@ -164,7 +163,7 @@ class Mutator implements MutatorInterface public function receiverSpecificLevelMutators(): self { - if(method_exists($this, "client_{$this->invoice->company->country()->iso_3166_2}")) { + if (method_exists($this, "client_{$this->invoice->company->country()->iso_3166_2}")) { $this->{"client_{$this->invoice->company->country()->iso_3166_2}"}(); } @@ -216,7 +215,7 @@ class Mutator implements MutatorInterface { //special fields for sending to AT:GOV - if($this->invoice->client->classification == 'government') { + if ($this->invoice->client->classification == 'government') { //routing "b" for production "test" for test environment $this->setStorecoveMeta($this->buildRouting(["scheme" => 'AT:GOV', "id" => 'b'])); @@ -248,11 +247,11 @@ class Mutator implements MutatorInterface public function ES(): self { - if(!isset($this->invoice->due_date)) { + if (!isset($this->invoice->due_date)) { $this->p_invoice->DueDate = new \DateTime($this->invoice->date); } - if($this->invoice->client->classification == 'business' && $this->invoice->company->getSetting('classification') == 'business') { + if ($this->invoice->client->classification == 'business' && $this->invoice->company->getSetting('classification') == 'business') { //must have a paymentmeans as credit_transfer $this->mutator_util->setPaymentMeans(true); } @@ -282,7 +281,7 @@ class Mutator implements MutatorInterface return $this; } - + /** * FI * @@ -311,7 +310,7 @@ class Mutator implements MutatorInterface // All invoices have to be routed to SIRET 0009:11000201100044. There is no test environment for sending to public entities. // The SIRET / 0009 identifier of the final recipient is to be included in the invoice.accountingCustomerParty.publicIdentifiers array. - if($this->invoice->client->classification == 'government') { + if ($this->invoice->client->classification == 'government') { //route to SIRET 0009:11000201100044 $this->setStorecoveMeta($this->buildRouting([ ["scheme" => 'FR:SIRET', "id" => '11000201100044'] @@ -324,7 +323,7 @@ class Mutator implements MutatorInterface } - if(strlen($this->invoice->client->id_number ?? '') == 9) { + if (strlen($this->invoice->client->id_number ?? '') == 9) { //SIREN $this->setStorecoveMeta($this->buildRouting([ ["scheme" => 'FR:SIRET', "id" => "{$this->invoice->client->id_number}"] @@ -342,7 +341,7 @@ class Mutator implements MutatorInterface return $this; } - + /** * IT * @@ -353,7 +352,7 @@ class Mutator implements MutatorInterface // IT Sender, IT Receiver, B2B/B2G // Provide the receiver IT:VAT and the receiver IT:CUUO (codice destinatario) - if(in_array($this->invoice->client->classification, ['business','government']) && $this->invoice->company->country()->iso_3166_2 == 'IT') { + if (in_array($this->invoice->client->classification, ['business','government']) && $this->invoice->company->country()->iso_3166_2 == 'IT') { $this->setStorecoveMeta($this->buildRouting([ ["scheme" => 'IT:IVA', "id" => $this->invoice->client->vat_number], @@ -365,7 +364,7 @@ class Mutator implements MutatorInterface // IT Sender, IT Receiver, B2C // Provide the receiver IT:CF and the receiver IT:CUUO (codice destinatario) - if($this->invoice->client->classification == 'individual' && $this->invoice->company->country()->iso_3166_2 == 'IT') { + if ($this->invoice->client->classification == 'individual' && $this->invoice->company->country()->iso_3166_2 == 'IT') { $this->setStorecoveMeta($this->buildRouting([ ["scheme" => 'IT:CF', "id" => $this->invoice->client->vat_number], @@ -379,7 +378,7 @@ class Mutator implements MutatorInterface // IT Sender, non-IT Receiver // Provide the receiver tax identifier and any routing identifier applicable to the receiving country (see Receiver Identifiers). - if($this->invoice->client->country->iso_3166_2 != 'IT' && $this->invoice->company->country()->iso_3166_2 == 'IT') { + if ($this->invoice->client->country->iso_3166_2 != 'IT' && $this->invoice->company->country()->iso_3166_2 == 'IT') { $code = $this->getClientRoutingCode(); @@ -393,7 +392,7 @@ class Mutator implements MutatorInterface return $this; } - + /** * client_IT * @@ -404,7 +403,7 @@ class Mutator implements MutatorInterface // non-IT Sender, IT Receiver, B2C // Provide the receiver IT:CF and an optional email. The invoice will be eReported and sent via email. Note that this cannot be a PEC email address. - if(in_array($this->invoice->client->classification, ['individual']) && $this->invoice->company->country()->iso_3166_2 != 'IT') { + if (in_array($this->invoice->client->classification, ['individual']) && $this->invoice->company->country()->iso_3166_2 != 'IT') { return $this; } @@ -415,7 +414,7 @@ class Mutator implements MutatorInterface return $this; } - + /** * MY * @@ -426,7 +425,7 @@ class Mutator implements MutatorInterface //way too much to digest here, delayed. return $this; } - + /** * NL * @@ -441,7 +440,7 @@ class Mutator implements MutatorInterface return $this; } - + /** * NZ * @@ -452,7 +451,7 @@ class Mutator implements MutatorInterface // New Zealand uses a GLN to identify businesses. In addition, when sending invoices to a New Zealand customer, make sure you include the pseudo identifier NZ:GST as their tax identifier. return $this; } - + /** * PL * @@ -483,7 +482,7 @@ class Mutator implements MutatorInterface return $this; } - + /** * RO * @@ -517,10 +516,10 @@ class Mutator implements MutatorInterface $this->p_invoice->AccountingCustomerParty->Party->PostalAddress->CountrySubentity = $resolved_state; $this->p_invoice->AccountingCustomerParty->Party->PostalAddress->CityName = $resolved_city; - + return $this; } - + /** * SG * @@ -576,11 +575,12 @@ class Mutator implements MutatorInterface { return $this->invoice->client->present()->email(); } - + private function getClientPublicIdentifier(string $code): string { - if($this->invoice->client->classification == 'individual' && strlen($this->invoice->client->id_number ?? '') > 2) + if ($this->invoice->client->classification == 'individual' && strlen($this->invoice->client->id_number ?? '') > 2) { return $this->invoice->client->id_number; + } // elseif($this->invoice->client->classification == 'business') return $this->invoice->client->vat_number; @@ -589,7 +589,7 @@ class Mutator implements MutatorInterface public function setClientRoutingCode(): self { - if($this->invoice->client->classification == 'individual' || (strlen($this->invoice->client->vat_number ?? '') < 2 && strlen($this->invoice->client->id_number ?? '') < 2)){ + if ($this->invoice->client->classification == 'individual' || (strlen($this->invoice->client->vat_number ?? '') < 2 && strlen($this->invoice->client->id_number ?? '') < 2)) { return $this->setEmailRouting($this->getIndividualEmailRoute()); } @@ -599,16 +599,19 @@ class Mutator implements MutatorInterface $code = $this->getClientRoutingCode(); $identifier = false; - if($this->invoice->client->country->iso_3166_2 == 'FR') + if ($this->invoice->client->country->iso_3166_2 == 'FR') { $identifier = $this->invoice->client->id_number; - else + } else { $identifier = $this->invoice->client->vat_number; + } - if($this->invoice->client->country->iso_3166_2 == 'DE' && $this->invoice->client->classification == 'government') + if ($this->invoice->client->country->iso_3166_2 == 'DE' && $this->invoice->client->classification == 'government') { $identifier = $this->invoice->client->routing_id; - - if(!$identifier) + } + + if (!$identifier) { $identifier = $this->getClientPublicIdentifier($code); + } $this->setStorecoveMeta($this->buildRouting([ @@ -646,7 +649,7 @@ class Mutator implements MutatorInterface ] ]; } - + /** * setEmailRouting @@ -658,7 +661,7 @@ class Mutator implements MutatorInterface { $meta = $this->getStorecoveMeta(); - if(isset($meta['routing']['emails'])) { + if (isset($meta['routing']['emails'])) { $emails = $meta['routing']['emails']; array_push($emails, $email); $meta['routing']['emails'] = $emails; @@ -688,7 +691,7 @@ class Mutator implements MutatorInterface return $this; } - + /** * getStorecoveMeta * @@ -700,4 +703,4 @@ class Mutator implements MutatorInterface } -} \ No newline at end of file +} diff --git a/app/Services/EDocument/Gateway/Storecove/Storecove.php b/app/Services/EDocument/Gateway/Storecove/Storecove.php index b092446bd9..c34590c40a 100644 --- a/app/Services/EDocument/Gateway/Storecove/Storecove.php +++ b/app/Services/EDocument/Gateway/Storecove/Storecove.php @@ -29,10 +29,10 @@ enum HttpVerb: string } class Storecove -{ +{ /** @var string $base_url */ private string $base_url = 'https://api.storecove.com/api/v2/'; - + /** @var array $peppol_discovery */ private array $peppol_discovery = [ "documentTypes" => ["invoice"], @@ -41,7 +41,7 @@ class Storecove // "scheme" => "de:lwid", // "identifier" => "DE:VAT", ]; - + /** @var array $dbn_discovery */ private array $dbn_discovery = [ "documentTypes" => ["invoice"], @@ -71,7 +71,7 @@ class Storecove $this->expense = new StorecoveExpense($this); $this->proxy = new StorecoveProxy($this); } - + /** * build * @@ -80,7 +80,7 @@ class Storecove */ public function build($model): self { - // return + // return $this->adapter ->transform($model) ->decorate() @@ -124,7 +124,7 @@ class Storecove }; $uri = "discovery/receives"; - + $r = $this->httpClient($uri, (HttpVerb::POST)->value, $network_data, $this->getHeaders()); return ($r->successful() && $r->json()['code'] == 'OK') ? true : false; @@ -164,12 +164,12 @@ class Storecove */ public function sendJsonDocument(array $payload): string|\Illuminate\Http\Client\Response { - + $uri = "document_submissions"; $r = $this->httpClient($uri, (HttpVerb::POST)->value, $payload, $this->getHeaders()); - if($r->successful()) { + if ($r->successful()) { nlog("sent! GUID = {$r->json()['guid']}"); return $r->json()['guid']; } @@ -180,14 +180,14 @@ class Storecove return $r; } - + /** * Send Raw UBL Document via StoreCove * * @param string $document * @param int $routing_id * @param array $override_payload - * + * * @return string|\Illuminate\Http\Client\Response */ public function sendDocument(string $document, int $routing_id, array $override_payload = []) @@ -219,7 +219,7 @@ class Storecove $r = $this->httpClient($uri, (HttpVerb::POST)->value, $payload, $this->getHeaders()); - if($r->successful()) { + if ($r->successful()) { return $r->json()['guid']; } @@ -229,7 +229,7 @@ class Storecove /** * Get Sending Evidence - * + * * "guid" => "661c079d-0c2b-4b45-8263-678ed81224af", * * @param string $guid @@ -241,8 +241,9 @@ class Storecove $r = $this->httpClient($uri, (HttpVerb::GET)->value, [], $this->getHeaders()); - if($r->successful()) + if ($r->successful()) { return $r->json(); + } return $r; } @@ -259,7 +260,7 @@ class Storecove $add_identifier_response = $this->addIdentifier( legal_entity_id: $legal_entity_response['id'], - identifier: $data['classification'] === 'individual' ? str_replace('/','', $data['id_number']) : str_replace(" ", "", $data['vat_number']), + identifier: $data['classification'] === 'individual' ? str_replace('/', '', $data['id_number']) : str_replace(" ", "", $data['vat_number']), scheme: $scheme, ); @@ -279,21 +280,21 @@ class Storecove /** * CreateLegalEntity * - * Creates a legal entity for a Company. - * + * Creates a legal entity for a Company. + * * Following creation, you will also need to create a Peppol Identifier - * + * * @url https://www.storecove.com/docs/#_openapi_legalentitycreate - * + * * @return mixed */ public function createLegalEntity(array $data, ?Company $company = null) { $uri = 'legal_entities'; - if($company){ + if ($company) { - $data = array_merge([ + $data = array_merge([ 'city' => $company->settings->city, 'country' => $company->country()->iso_3166_2, 'county' => $company->settings->state, @@ -318,7 +319,7 @@ class Storecove $r = $this->httpClient($uri, (HttpVerb::POST)->value, $payload); - if($r->successful()) { + if ($r->successful()) { $data = $r->object(); LightLogs::create(new LegalEntityCreated($data->id, $data->tenant_id))->batch(); return $r->json(); @@ -327,7 +328,7 @@ class Storecove return $r; } - + /** * GetLegalEntity * @@ -341,14 +342,14 @@ class Storecove $r = $this->httpClient($uri, (HttpVerb::GET)->value, []); - if($r->successful()) { + if ($r->successful()) { return $r->json(); } return $r; } - + /** * UpdateLegalEntity * @@ -363,17 +364,17 @@ class Storecove $r = $this->httpClient($uri, (HttpVerb::PATCH)->value, $data); - if($r->successful()) { + if ($r->successful()) { return $r->json(); } return $r; } - + /** * AddIdentifier - * + * * Add a Peppol identifier to the legal entity * * @param int $legal_entity_id @@ -393,16 +394,16 @@ class Storecove $r = $this->httpClient($uri, (HttpVerb::POST)->value, $data); - if($r->successful()) { + if ($r->successful()) { $data = $r->json(); - + return $data; } nlog($r->body()); return $r; } - + /** * addAdditionalTaxIdentifier * @@ -455,7 +456,7 @@ class Storecove { $legal_entity = $this->getLegalEntity($legal_entity_id); - if(isset($legal_entity['additional_tax_identifiers']) && is_array($legal_entity['additional_tax_identifiers'])) { + if (isset($legal_entity['additional_tax_identifiers']) && is_array($legal_entity['additional_tax_identifiers'])) { $identifer = collect($legal_entity['additional_tax_identifiers']) ->filter(fn ($id) => $id['identifier'] == $tax_identifier) ->first(); @@ -480,7 +481,7 @@ class Storecove /** * Delete Legal Entity Identifier - * + * * Remove the entity from the network * * @param int $legal_entity_id @@ -498,7 +499,7 @@ class Storecove return $r; } - + /** * getDocument * @@ -523,13 +524,13 @@ class Storecove } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - + + /** * getHeaders - * + * * Base request headers - * + * * @param array $headers * @return array */ @@ -541,7 +542,7 @@ class Storecove ], $headers); } - + /** * Http Client * @@ -554,26 +555,25 @@ class Storecove private function httpClient(string $uri, string $verb, array $data, ?array $headers = []) { - try { + try { $r = Http::withToken(config('ninja.storecove_api_key')) ->withHeaders($this->getHeaders($headers)) ->{$verb}("{$this->base_url}{$uri}", $data)->throw(); - } - catch (ClientException $e) { + } catch (ClientException $e) { // 4xx errors nlog("LEI:: {$this->legal_entity_id}"); nlog("Client error: " . $e->getMessage()); nlog("Response body: " . $e->getResponse()->getBody()->getContents()); } catch (ServerException $e) { // 5xx errors - + nlog("LEI:: {$this->legal_entity_id}"); nlog("Server error: " . $e->getMessage()); nlog("Response body: " . $e->getResponse()->getBody()->getContents()); } catch (\Illuminate\Http\Client\RequestException $e) { nlog("LEI:: {$this->legal_entity_id}"); - nlog("Request error: {$e->getCode()}: " . $e->getMessage()); + nlog("Request error: {$e->getCode()}: " . $e->getMessage()); $responseBody = $e->response->body(); nlog("Response body: " . $responseBody); diff --git a/app/Services/EDocument/Gateway/Storecove/StorecoveAdapter.php b/app/Services/EDocument/Gateway/Storecove/StorecoveAdapter.php index 2d0a7cce94..ff1ab8dad5 100644 --- a/app/Services/EDocument/Gateway/Storecove/StorecoveAdapter.php +++ b/app/Services/EDocument/Gateway/Storecove/StorecoveAdapter.php @@ -40,15 +40,16 @@ use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter class StorecoveAdapter { - - public function __construct(public Storecove $storecove){} + public function __construct(public Storecove $storecove) + { + } private Invoice $storecove_invoice; private array $errors = []; private bool $valid_document = true; - + private $ninja_invoice; private string $nexus; @@ -57,7 +58,7 @@ class StorecoveAdapter public function validate(): self { - + if ($this->has_error) { return $this; } @@ -74,25 +75,25 @@ class StorecoveAdapter { return $this->errors; } - + /** * addError * * Adds an error to the errors array. - * + * * @param string $error * @return self */ private function addError(string $error): self { $this->errors[] = $error; - + return $this; } - + public function deserialize($storecove_object) { - + $context = [ DateTimeNormalizer::FORMAT_KEY => 'Y-m-d', AbstractObjectNormalizer::SKIP_NULL_VALUES => true, @@ -121,7 +122,7 @@ class StorecoveAdapter $serializer = $this->getSerializer(); /** Currently - due to class structures, the serialization process goes like this: - * + * * e-invoice => Peppol -> XML -> Peppol Decoded -> encode to Peppol -> deserialize to Storecove */ $p = (new Peppol($invoice))->run()->toXml(); @@ -137,8 +138,7 @@ class StorecoveAdapter $this->storecove_invoice = $serializer->deserialize($peppolInvoice, $parent, 'json', $context); $this->buildNexus(); - } - catch(\Throwable $th){ + } catch (\Throwable $th) { $this->addError($th->getMessage()); $this->has_error = true; @@ -155,37 +155,34 @@ class StorecoveAdapter public function decorate(): self { - if($this->has_error) + if ($this->has_error) { return $this; + } //set all taxmap countries - resolve the taxing country $lines = $this->storecove_invoice->getInvoiceLines(); - foreach($lines as &$line) - { - if(isset($line->taxes_duties_fees)) - { - foreach($line->taxes_duties_fees as &$tax) - { + foreach ($lines as &$line) { + if (isset($line->taxes_duties_fees)) { + foreach ($line->taxes_duties_fees as &$tax) { $tax->country = $this->nexus; - $tax->percentage = $tax->percentage ?? 0; - if(property_exists($tax,'category')) + $tax->percentage = $tax->percentage ?? 0; + if (property_exists($tax, 'category')) { $tax->category = $this->tranformTaxCode($tax->category); + } } unset($tax); } - if(isset($line->allowance_charges)) - { - foreach($line->allowance_charges as &$allowance) - { - if($allowance->reason == ctrans('texts.discount')) + if (isset($line->allowance_charges)) { + foreach ($line->allowance_charges as &$allowance) { + if ($allowance->reason == ctrans('texts.discount')) { $allowance->amount_excluding_tax = $allowance->amount_excluding_tax * -1; + } - foreach($allowance->getTaxesDutiesFees() ?? [] as &$tax) - { - + foreach ($allowance->getTaxesDutiesFees() ?? [] as &$tax) { + if (property_exists($tax, 'category')) { $tax->category = $this->tranformTaxCode($tax->category); } @@ -201,13 +198,13 @@ class StorecoveAdapter $tax_subtotals = $this->storecove_invoice->getTaxSubtotals(); - foreach($tax_subtotals as &$tax) - { + foreach ($tax_subtotals as &$tax) { $tax->country = $this->nexus; $tax->percentage = $tax->percentage ?? 0; - if (property_exists($tax, 'category')) + if (property_exists($tax, 'category')) { $tax->category = $this->tranformTaxCode($tax->category); + } } unset($tax); @@ -218,21 +215,18 @@ class StorecoveAdapter //update payment means codes to storecove equivalents $payment_means = $this->storecove_invoice->getPaymentMeansArray(); - foreach($payment_means as &$pm) - { + foreach ($payment_means as &$pm) { $pm->code = $this->transformPaymentMeansCode($pm->code); } - + $this->storecove_invoice->setPaymentMeansArray($payment_means); $allowances = $this->storecove_invoice->getAllowanceCharges() ?? []; - foreach($allowances as &$allowance) - { + foreach ($allowances as &$allowance) { $taxes = $allowance->getTaxesDutiesFees() ?? []; - foreach($taxes as &$tax) - { + foreach ($taxes as &$tax) { $tax->country = $this->nexus; $tax->percentage = $tax->percentage ?? 0; @@ -242,7 +236,7 @@ class StorecoveAdapter } unset($tax); - + if ($allowance->reason == ctrans('texts.discount')) { $allowance->amount_excluding_tax = $allowance->amount_excluding_tax * -1; } @@ -255,12 +249,11 @@ class StorecoveAdapter $this->storecove_invoice->setAllowanceCharges($allowances); $this->storecove_invoice->setTaxSystem('tax_line_percentages'); - + //resolve and set the public identifier for the customer $accounting_customer_party = $this->storecove_invoice->getAccountingCustomerParty(); - if(strlen($this->ninja_invoice->client->vat_number) > 2) - { + if (strlen($this->ninja_invoice->client->vat_number) > 2) { // $id = str_ireplace("fr","", $this->ninja_invoice->client->vat_number); $id = $this->ninja_invoice->client->vat_number; $scheme = $this->storecove->router->setInvoice($this->ninja_invoice)->resolveTaxScheme($this->ninja_invoice->client->country->iso_3166_2, $this->ninja_invoice->client->classification ?? 'individual'); @@ -274,7 +267,7 @@ class StorecoveAdapter private function getSerializer() { - + $phpDocExtractor = new PhpDocExtractor(); $reflectionExtractor = new ReflectionExtractor(); $typeExtractors = [$reflectionExtractor,$phpDocExtractor]; @@ -299,7 +292,7 @@ class StorecoveAdapter return $serializer; } - + /** * Builds the document and appends an errors prop * @@ -308,10 +301,11 @@ class StorecoveAdapter public function getDocument(): mixed { - if($this->has_error) + if ($this->has_error) { return ['errors' => $this->getErrors(), 'document' => false]; - - + } + + $serializer = $this->getSerializer(); $context = [ @@ -333,7 +327,7 @@ class StorecoveAdapter return $data; } - + /** * RemoveEmptyValues * @@ -366,7 +360,7 @@ class StorecoveAdapter $eu_countries = $br->eu_country_codes; if ($client_country_code == $company_country_code) { - //Domestic Sales + //Domestic Sales nlog("domestic sales"); $this->nexus = $company_country_code; } elseif (in_array($company_country_code, $eu_countries) && !in_array($client_country_code, $eu_countries)) { @@ -374,7 +368,7 @@ class StorecoveAdapter nlog("non eu"); $this->nexus = $company_country_code; } elseif (in_array($client_country_code, $eu_countries)) { - + // First, determine if we're over threshold $is_over_threshold = isset($this->ninja_invoice->company->tax_data->regions->EU->has_sales_above_threshold) && $this->ninja_invoice->company->tax_data->regions->EU->has_sales_above_threshold; @@ -384,7 +378,7 @@ class StorecoveAdapter !($this->ninja_invoice->client->has_valid_vat_number ?? false) || $this->ninja_invoice->client->classification == 'individual'; - + // B2C, under threshold, no Company VAT Registerd - must charge origin country VAT if ($is_b2c && !$is_over_threshold && strlen($this->ninja_invoice->company->settings->vat_number) < 2) { nlog("no company vat"); @@ -405,8 +399,8 @@ class StorecoveAdapter // B2C under threshold - origin country VAT $this->nexus = $company_country_code; } - } elseif ($is_over_threshold && !in_array($company_country_code, $eu_countries)){ - $this->nexus = $client_country_code; + } elseif ($is_over_threshold && !in_array($company_country_code, $eu_countries)) { + $this->nexus = $client_country_code; } else { nlog("B2B with valid vat"); // B2B with valid VAT - origin country @@ -415,7 +409,7 @@ class StorecoveAdapter } - if($company_country_code == 'DE' && $client_country_code == 'DE' && $this->ninja_invoice->client->classification == 'government') { + if ($company_country_code == 'DE' && $client_country_code == 'DE' && $this->ninja_invoice->client->classification == 'government') { $this->removeSupplierVatNumber(); } @@ -432,9 +426,9 @@ class StorecoveAdapter return $this; } - private function setupDestinationVAT($client_country_code):self + private function setupDestinationVAT($client_country_code): self { - + $this->storecove_invoice->setConsumerTaxMode(true); $id = $this->ninja_invoice->company->tax_data->regions->EU->subregions->{$client_country_code}->vat_number; $scheme = $this->storecove->router->setInvoice($this->ninja_invoice)->resolveTaxScheme($client_country_code, $this->ninja_invoice->client->classification ?? 'individual'); @@ -443,20 +437,21 @@ class StorecoveAdapter $asp = $this->storecove_invoice->getAccountingSupplierParty(); $asp->addPublicIdentifiers($pi); $this->storecove_invoice->setAccountingSupplierParty($asp); - + return $this; } private function tranformTaxCode(string $code): ?string { - if($code == 'O' && $this->ninja_invoice->client->classification == 'government') + if ($code == 'O' && $this->ninja_invoice->client->classification == 'government') { return 'exempt'; - + } + // elseif($code == 'K' && $this->ninja_invoice->company->getSetting('classification') == 'individual') // return 'reverse_charge'; - return match($code){ + return match($code) { 'S' => 'standard', 'Z' => 'zero_rated', 'E' => 'exempt', @@ -477,14 +472,14 @@ class StorecoveAdapter private function transformPaymentMeansCode(?string $code): string { - return match($code){ + return match($code) { '30' => 'credit_transfer', '58' => 'sepa_credit_transfer', '31' => 'debit_transfer', '49' => 'direct_debit', '59' => 'sepa_direct_debit', '48' => 'card', // Generic card payment - '54' => 'bank_card', + '54' => 'bank_card', '55' => 'credit_card', '57' => 'standing_agreement', '10' => 'cash', @@ -510,5 +505,5 @@ class StorecoveAdapter }; } - -} \ No newline at end of file + +} diff --git a/app/Services/EDocument/Gateway/Storecove/StorecoveProxy.php b/app/Services/EDocument/Gateway/Storecove/StorecoveProxy.php index 35ea65b464..f2c3c85370 100644 --- a/app/Services/EDocument/Gateway/Storecove/StorecoveProxy.php +++ b/app/Services/EDocument/Gateway/Storecove/StorecoveProxy.php @@ -41,8 +41,9 @@ class StorecoveProxy if (Ninja::isHosted()) { $response = $this->storecove->getLegalEntity($legal_entity_id); - if (is_array($response)) //successful response is the array + if (is_array($response)) { //successful response is the array return $response; + } return $this->handleResponseError($response); //otherwise need to handle the http response returned } @@ -129,9 +130,9 @@ class StorecoveProxy ]; if (Ninja::isHosted()) { - + $response = $this->storecove->addAdditionalTaxIdentifier($data['legal_entity_id'], $data['vat_number'], $scheme); - + if (is_array($response)) { return $response; } @@ -163,7 +164,7 @@ class StorecoveProxy * handleResponseError * * Generic error handler that can return an array response - * + * * @param mixed $response * @return array */ @@ -214,8 +215,9 @@ class StorecoveProxy ->withHeaders($this->getHeaders()) ->post($uri, $payload); - if ($response->successful()) + if ($response->successful()) { return $response->json(); + } return $this->handleResponseError($response); } diff --git a/app/Services/EDocument/Gateway/Storecove/StorecoveRouter.php b/app/Services/EDocument/Gateway/Storecove/StorecoveRouter.php index 96e02dbe72..e0f258239d 100644 --- a/app/Services/EDocument/Gateway/Storecove/StorecoveRouter.php +++ b/app/Services/EDocument/Gateway/Storecove/StorecoveRouter.php @@ -12,11 +12,11 @@ namespace App\Services\EDocument\Gateway\Storecove; class StorecoveRouter -{ +{ /** * Provides a country matrix for the correct scheme to send via * [ "iso_3166_2" => [, , , ] - * @var array $routing_rules + * @var array $routing_rules **/ private array $routing_rules = [ "US" => [ @@ -104,10 +104,10 @@ class StorecoveRouter public function __construct() { } - + /** * Return the routing code based on country and entity classification - * + * * @param string $country * @param ?string $classification DE:STNR * @return string @@ -115,16 +115,16 @@ class StorecoveRouter public function resolveRouting(string $country, ?string $classification = 'business'): string { $rules = $this->routing_rules[$country]; - + $code = 'B'; - + match($classification) { "business" => $code = "B", "government" => $code = "G", "individual" => $code = "C", default => $code = "B", }; - + //France determine routing scheme if ($this->invoice && $country == 'FR') { @@ -137,28 +137,28 @@ class StorecoveRouter } } - + //DE we can route via Steurnummer? double check with storecove @blocked - if($country == "DE" && $classification == 'individual'){ + if ($country == "DE" && $classification == 'individual') { return 'DE:STNR'; } - //Single array + //Single array if (is_array($rules) && !is_array($rules[0])) { return $rules[3]; } //Multi Array - iterate - foreach($rules as $rule) { - if(stripos($rule[0], $code) !== false) { + foreach ($rules as $rule) { + if (stripos($rule[0], $code) !== false) { return $rule[3]; } } return $rules[0][3]; } - - public function setInvoice($invoice):self + + public function setInvoice($invoice): self { $this->invoice = $invoice; return $this; @@ -172,7 +172,7 @@ class StorecoveRouter */ public function resolveTaxScheme(string $country, ?string $classification = "business"): string { - + $rules = isset($this->routing_rules[$country]) ? $this->routing_rules[$country] : [false, false, false, false]; $code = "B"; @@ -185,12 +185,12 @@ class StorecoveRouter }; //single array - if(is_array($rules) && !is_array($rules[0])) { + if (is_array($rules) && !is_array($rules[0])) { return $rules[2]; } - foreach($rules as $rule) { - if(stripos($rule[0], $code) !== false) { + foreach ($rules as $rule) { + if (stripos($rule[0], $code) !== false) { return $rule[2]; } } @@ -204,47 +204,46 @@ class StorecoveRouter $country = $parts[0]; $rules = $this->routing_rules[$country]; - + if (is_array($rules) && !is_array($rules[0])) { - + if (stripos($identifier, $rules[2]) !== false) { return 'vat_number'; } elseif (stripos($identifier, $rules[3]) !== false) { return 'id_number'; } - - } - else { - foreach($rules as $country_identifiers) - { - - if(stripos($identifier, $country_identifiers[2]) !== false) + + } else { + foreach ($rules as $country_identifiers) { + + if (stripos($identifier, $country_identifiers[2]) !== false) { return 'vat_number'; - elseif(stripos($identifier, $country_identifiers[3]) !== false) + } elseif (stripos($identifier, $country_identifiers[3]) !== false) { return 'id_number'; + } } } return ''; } - /** - * used as a proxy for - * the schemeID of partyidentification - * property - for Storecove only: - * - * Used in the format key:value - * - * ie. IT:IVA / DE:VAT - * - * Note there are multiple options for the following countries: - * - * US (EIN/SSN) employer identification number / social security number - * IT (CF/IVA) Codice Fiscale (person/company identifier) / company vat number - * - * @var array - * @deprecated - */ + /** + * used as a proxy for + * the schemeID of partyidentification + * property - for Storecove only: + * + * Used in the format key:value + * + * ie. IT:IVA / DE:VAT + * + * Note there are multiple options for the following countries: + * + * US (EIN/SSN) employer identification number / social security number + * IT (CF/IVA) Codice Fiscale (person/company identifier) / company vat number + * + * @var array + * @deprecated + */ private array $schemeIdIdentifiers = [ 'US' => 'EIN', 'US' => 'SSN', @@ -305,4 +304,4 @@ class StorecoveRouter 'SA' => 'TIN', ]; -} \ No newline at end of file +} diff --git a/app/Services/EDocument/Gateway/Transformers/StorecoveExpense.php b/app/Services/EDocument/Gateway/Transformers/StorecoveExpense.php index 8ee5b104b7..bf743876e5 100644 --- a/app/Services/EDocument/Gateway/Transformers/StorecoveExpense.php +++ b/app/Services/EDocument/Gateway/Transformers/StorecoveExpense.php @@ -43,14 +43,15 @@ use App\Services\EDocument\Gateway\Storecove\PeppolToStorecoveNormalizer; use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter; use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter; -class StorecoveExpense +class StorecoveExpense { - - public function __construct(private Storecove $storecove){} + public function __construct(private Storecove $storecove) + { + } public function getStorecoveInvoice($storecove_json) { - + $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); // Create a proper PropertyInfoExtractor @@ -116,26 +117,25 @@ class StorecoveExpense $vendor = Vendor::query() ->where('company_id', $company->id) - ->where(function($query) use ($expense_array) { - // Check VAT number if present - if (strlen($expense_array['vendor']['vat_number']) > 2) { - $query->orWhere('vat_number', $expense_array['vendor']['vat_number']); - } - - // Check ID number if present - if (strlen($expense_array['vendor']['id_number']) > 2) { - $query->orWhere('id_number', $expense_array['vendor']['id_number']); - } - - // If no valid identifiers, force no results - if (strlen($expense_array['vendor']['vat_number']) <= 2 && strlen($expense_array['vendor']['id_number']) <= 2) { - $query->where('id', 0); // Forces no match - } + ->where(function ($query) use ($expense_array) { + // Check VAT number if present + if (strlen($expense_array['vendor']['vat_number']) > 2) { + $query->orWhere('vat_number', $expense_array['vendor']['vat_number']); + } - })->first(); - - if(!$vendor) - { + // Check ID number if present + if (strlen($expense_array['vendor']['id_number']) > 2) { + $query->orWhere('id_number', $expense_array['vendor']['id_number']); + } + + // If no valid identifiers, force no results + if (strlen($expense_array['vendor']['vat_number']) <= 2 && strlen($expense_array['vendor']['id_number']) <= 2) { + $query->where('id', 0); // Forces no match + } + + })->first(); + + if (!$vendor) { $vendor_repo = new VendorRepository(new VendorContactRepository()); $vendor = VendorFactory::create($company->id, $company->owner()->id); $vendor = $vendor_repo->save($expense_array['vendor'], $vendor); @@ -146,9 +146,9 @@ class StorecoveExpense $expense = ExpenseFactory::create($vendor->company_id, $vendor->user_id); $expense->vendor_id = $vendor->id; - + unset($expense_array['vendor']); - + $expense = $expense_repo->save($expense_array, $expense); $fields = new \stdClass(); @@ -301,4 +301,4 @@ class StorecoveExpense return $expense; } -} \ No newline at end of file +} diff --git a/app/Services/EDocument/Imports/MindeeEDocument.php b/app/Services/EDocument/Imports/MindeeEDocument.php index 0a92b403e4..fe851a8605 100644 --- a/app/Services/EDocument/Imports/MindeeEDocument.php +++ b/app/Services/EDocument/Imports/MindeeEDocument.php @@ -48,8 +48,9 @@ class MindeeEDocument extends AbstractService { $api_key = config('services.mindee.api_key'); - if (!$api_key) + if (!$api_key) { throw new Exception('Mindee API key not configured'); + } $this->checkLimits(); @@ -62,8 +63,9 @@ class MindeeEDocument extends AbstractService /** @var \Mindee\Product\Invoice\InvoiceV4Document $prediction */ $prediction = $result->document->inference->prediction; - if ($prediction->documentType->value !== 'INVOICE') + if ($prediction->documentType->value !== 'INVOICE') { throw new Exception('Unsupported document type'); + } $grandTotalAmount = $prediction->totalAmount->value; $documentno = $prediction->invoiceNumber->value; @@ -100,7 +102,7 @@ class MindeeEDocument extends AbstractService ], $expense); // $expense->saveQuietly(); - $expense->uses_inclusive_taxes = True; + $expense->uses_inclusive_taxes = true; $expense->amount = $grandTotalAmount; $counter = 1; @@ -135,8 +137,9 @@ class MindeeEDocument extends AbstractService return $c->iso_3166_2 == $country || $c->iso_3166_3 == $country; }); - if ($country) + if ($country) { $vendor->country_id = $country->id; + } $vendor->save(); @@ -167,14 +170,18 @@ class MindeeEDocument extends AbstractService Cache::add('mindeeTotalMonthlyRequests', 0, now()->endOfMonth()); Cache::add('mindeeAccountDailyRequests' . $this->company->account->id, 0, now()->endOfDay()); Cache::add('mindeeAccountMonthlyRequests' . $this->company->account->id, 0, now()->endOfMonth()); - if (config('services.mindee.daily_limit') != 0 && Cache::get('mindeeTotalDailyRequests') > config('services.mindee.daily_limit')) + if (config('services.mindee.daily_limit') != 0 && Cache::get('mindeeTotalDailyRequests') > config('services.mindee.daily_limit')) { throw new Exception('Mindee daily limit reached'); - if (config('services.mindee.monthly_limit') != 0 && Cache::get('mindeeTotalMonthlyRequests') > config('services.mindee.monthly_limit')) + } + if (config('services.mindee.monthly_limit') != 0 && Cache::get('mindeeTotalMonthlyRequests') > config('services.mindee.monthly_limit')) { throw new Exception('Mindee monthly limit reached'); - if (config('services.mindee.account_daily_limit') != 0 && Cache::get('mindeeAccountDailyRequests' . $this->company->account->id) > config('services.mindee.account_daily_limit')) + } + if (config('services.mindee.account_daily_limit') != 0 && Cache::get('mindeeAccountDailyRequests' . $this->company->account->id) > config('services.mindee.account_daily_limit')) { throw new Exception('Mindee daily limit reached for account: ' . $this->company->account->id); - if (config('services.mindee.account_monthly_limit') != 0 && Cache::get('mindeeAccountMonthlyRequests' . $this->company->account->id) > config('services.mindee.account_monthly_limit')) + } + if (config('services.mindee.account_monthly_limit') != 0 && Cache::get('mindeeAccountMonthlyRequests' . $this->company->account->id) > config('services.mindee.account_monthly_limit')) { throw new Exception('Mindee monthly limit reached for account: ' . $this->company->account->id); + } } private function incrementRequestCounts() @@ -185,4 +192,3 @@ class MindeeEDocument extends AbstractService Cache::increment('mindeeAccountMonthlyRequests' . $this->company->account->id); } } - diff --git a/app/Services/EDocument/Imports/ParseEDocument.php b/app/Services/EDocument/Imports/ParseEDocument.php index 72884aa57b..66fb32693e 100644 --- a/app/Services/EDocument/Imports/ParseEDocument.php +++ b/app/Services/EDocument/Imports/ParseEDocument.php @@ -21,7 +21,6 @@ use App\Services\EDocument\Imports\UblEDocument; class ParseEDocument extends AbstractService { - /** * @throws Exception */ @@ -64,28 +63,28 @@ class ParseEDocument extends AbstractService case ($extension == 'xml' || $mimetype == 'application/xml') && stristr($this->file->get(), "file, $this->company))->run(); - } - catch(\Throwable $e){ + } catch (\Throwable $e) { nlog("UBL Import Exception: " . $e->getMessage()); break; } } // MINDEE OCR - try to parse via mindee external service - if (config('services.mindee.api_key') && !(Ninja::isHosted() && !($account->isPaid() && $account->plan == 'enterprise'))) + if (config('services.mindee.api_key') && !(Ninja::isHosted() && !($account->isPaid() && $account->plan == 'enterprise'))) { switch (true) { case ($extension == 'pdf' || $mimetype == 'application/pdf'): case ($extension == 'heic' || $extension == 'heic' || $extension == 'png' || $extension == 'jpg' || $extension == 'jpeg' || $extension == 'webp' || str_starts_with($mimetype, 'image/')): try { return (new MindeeEDocument($this->file, $this->company))->run(); } catch (Exception $e) { - if (!($e->getMessage() == 'Unsupported document type')) + if (!($e->getMessage() == 'Unsupported document type')) { nlog("Mindee Exception: " . $e->getMessage()); + } } } + } // NO PARSER OR ERROR throw new Exception("File type not supported or issue while parsing", 409); } } - diff --git a/app/Services/EDocument/Imports/Ubl2Pdf.php b/app/Services/EDocument/Imports/Ubl2Pdf.php index e1c46c3936..f9b5ca9ea2 100644 --- a/app/Services/EDocument/Imports/Ubl2Pdf.php +++ b/app/Services/EDocument/Imports/Ubl2Pdf.php @@ -31,7 +31,6 @@ use App\Services\Template\TemplateService; class Ubl2Pdf extends AbstractService { - /** * @throws \Throwable */ @@ -41,7 +40,7 @@ class Ubl2Pdf extends AbstractService public function run() { - + App::forgetInstance('translator'); $t = app('translator'); App::setLocale($this->company->locale()); @@ -63,7 +62,7 @@ class Ubl2Pdf extends AbstractService ]; $ts = new TemplateService(); - + $ts_instance = $ts->setCompany($this->company) ->setData($data) ->setRawTemplate($template) @@ -84,7 +83,7 @@ class Ubl2Pdf extends AbstractService 'details' => ctrans('texts.details'), 'number' => ctrans('texts.number'), 'tax' => ctrans('texts.tax'), - + // 'from' => ctrans('texts.from'), // 'from' => ctrans('texts.from'), // 'from' => ctrans('texts.from'), @@ -102,13 +101,14 @@ class Ubl2Pdf extends AbstractService private function processValues(array $array): array { - foreach($array as $key => $value) - { - if($value === null || $value === '') + foreach ($array as $key => $value) { + if ($value === null || $value === '') { unset($array[$key]); + } - if($value instanceof \DateTime) + if ($value instanceof \DateTime) { $array[$key] = $value->format($this->company->date_format()); + } } return $array; @@ -118,17 +118,17 @@ class Ubl2Pdf extends AbstractService private function clientDetails(): array { return $this->processValues([ - ctrans('texts.name') => data_get($this->invoice, 'AccountingCustomerParty.Party.PartyName.0.Name',''), - ctrans('texts.address1') => data_get($this->invoice, 'AccountingCustomerParty.Party.PostalAddress.StreetName',''), - ctrans('texts.address2') => data_get($this->invoice, 'AccountingCustomerParty.Party.PostalAddress.AdditionalStreetName',''), - ctrans('texts.city') => data_get($this->invoice, 'AccountingCustomerParty.Party.PostalAddress.CityName',''), - ctrans('texts.state') => data_get($this->invoice, 'AccountingSupplierParty.Party.PostalAddress.CountrySubentity',''), - ctrans('texts.postal_code') => data_get($this->invoice, 'AccountingCustomerParty.Party.PostalAddress.PostalZone',''), - ctrans('texts.country_id') => data_get($this->invoice, 'AccountingCustomerParty.Party.PostalAddress.Country.IdentificationCode.value',''), - ctrans('texts.vat_number') => data_get($this->invoice, 'AccountingCustomerParty.Party.PartyTaxScheme.0.CompanyID.value',''), - ctrans('texts.contact_name') => data_get($this->invoice, 'AccountingCustomerParty.Party.Contact.Name',''), - ctrans('texts.phone') => data_get($this->invoice, 'AccountingCustomerParty.Party.Contact.Telephone',''), - ctrans('texts.email') => data_get($this->invoice, 'AccountingCustomerParty.Party.Contact.ElectronicMail',''), + ctrans('texts.name') => data_get($this->invoice, 'AccountingCustomerParty.Party.PartyName.0.Name', ''), + ctrans('texts.address1') => data_get($this->invoice, 'AccountingCustomerParty.Party.PostalAddress.StreetName', ''), + ctrans('texts.address2') => data_get($this->invoice, 'AccountingCustomerParty.Party.PostalAddress.AdditionalStreetName', ''), + ctrans('texts.city') => data_get($this->invoice, 'AccountingCustomerParty.Party.PostalAddress.CityName', ''), + ctrans('texts.state') => data_get($this->invoice, 'AccountingSupplierParty.Party.PostalAddress.CountrySubentity', ''), + ctrans('texts.postal_code') => data_get($this->invoice, 'AccountingCustomerParty.Party.PostalAddress.PostalZone', ''), + ctrans('texts.country_id') => data_get($this->invoice, 'AccountingCustomerParty.Party.PostalAddress.Country.IdentificationCode.value', ''), + ctrans('texts.vat_number') => data_get($this->invoice, 'AccountingCustomerParty.Party.PartyTaxScheme.0.CompanyID.value', ''), + ctrans('texts.contact_name') => data_get($this->invoice, 'AccountingCustomerParty.Party.Contact.Name', ''), + ctrans('texts.phone') => data_get($this->invoice, 'AccountingCustomerParty.Party.Contact.Telephone', ''), + ctrans('texts.email') => data_get($this->invoice, 'AccountingCustomerParty.Party.Contact.ElectronicMail', ''), ]); } @@ -178,7 +178,7 @@ class Ubl2Pdf extends AbstractService ]); $data['line_items'] = $this->invoiceLines(); - + return $data; } @@ -242,8 +242,7 @@ class Ubl2Pdf extends AbstractService $taxes = []; - foreach(data_get($this->invoice, 'TaxTotal.0.TaxSubtotal', []) as $tax_subtotal) - { + foreach (data_get($this->invoice, 'TaxTotal.0.TaxSubtotal', []) as $tax_subtotal) { $taxes[] = [ 'subtotal' => data_get($tax_subtotal, 'TaxAmount.amount', 0), 'tax_name' => data_get($tax_subtotal, 'TaxCategory.TaxScheme.ID.value', ''), @@ -262,23 +261,23 @@ class Ubl2Pdf extends AbstractService ]; } -// private function resolveCountry(?string $iso_country_code): int -// { -// return Country::query() -// ->where('iso_3166_2', $iso_country_code) -// ->orWhere('iso_3166_3', $iso_country_code) -// ->first()?->id ?? (int)$this->company->settings->country_id; -// } + // private function resolveCountry(?string $iso_country_code): int + // { + // return Country::query() + // ->where('iso_3166_2', $iso_country_code) + // ->orWhere('iso_3166_3', $iso_country_code) + // ->first()?->id ?? (int)$this->company->settings->country_id; + // } -// private function resolveCurrencyId(string $currency_code): int -// { - -// /** @var \Illuminate\Support\Collection<\App\Models\Currency> */ -// $currencies = app('currencies'); + // private function resolveCurrencyId(string $currency_code): int + // { -// return $currencies->first(function (Currency $c) use ($currency_code) { -// return $c->code === $currency_code; -// })?->id ?? (int) $this->company->settings->currency_id; -// } + // /** @var \Illuminate\Support\Collection<\App\Models\Currency> */ + // $currencies = app('currencies'); + + // return $currencies->first(function (Currency $c) use ($currency_code) { + // return $c->code === $currency_code; + // })?->id ?? (int) $this->company->settings->currency_id; + // } } diff --git a/app/Services/EDocument/Imports/UblEDocument.php b/app/Services/EDocument/Imports/UblEDocument.php index 65c9ecc344..c85e6845bf 100644 --- a/app/Services/EDocument/Imports/UblEDocument.php +++ b/app/Services/EDocument/Imports/UblEDocument.php @@ -19,7 +19,6 @@ use App\Factory\VendorFactory; use App\Factory\ExpenseFactory; use App\Services\AbstractService; use Illuminate\Http\UploadedFile; - use InvoiceNinja\EInvoice\EInvoice; use App\Utils\Traits\SavesDocuments; use App\Factory\VendorContactFactory; @@ -50,13 +49,13 @@ class UblEDocument extends AbstractService return $this->buildAndSaveExpense($invoice); } - + /** * extractInvoiceUbl * * If the document. - * + * * @param string $xml * @return string */ @@ -64,7 +63,7 @@ class UblEDocument extends AbstractService { $xml = str_replace('', '', $xml); - nlog($xml); + nlog($xml); $dom = new \DOMDocument(); $dom->loadXML($xml); @@ -116,7 +115,7 @@ class UblEDocument extends AbstractService $payment_means[] = data_get($invoice, 'PaymentTerms.0.Note', false); $private_notes = collect($payment_means) - ->reject(function ($means){ + ->reject(function ($means) { return $means === false; })->implode("\n"); @@ -124,15 +123,14 @@ class UblEDocument extends AbstractService $items = []; - foreach($invoice_items as $key => $item) - { + foreach ($invoice_items as $key => $item) { $items[$key]['name'] = data_get($item, 'Item.Name', false); $items[$key]['description'] = data_get($item, 'Item.Description', false); } - $public_notes = collect($items)->reject(function ($item){ + $public_notes = collect($items)->reject(function ($item) { return $item['name'] === false && $item['description'] === false; - })->map(function ($item){ + })->map(function ($item) { return $item['name'] ?? ' ' . ' ## '. $item['description'] ?? ' '; //@phpstan-ignore-line })->implode("\n"); @@ -145,35 +143,34 @@ class UblEDocument extends AbstractService $expense->private_notes = $private_notes; $expense->public_notes = $public_notes; - $tax_level = 1; + $tax_level = 1; - foreach ($tax_sub_totals as $key => $sub_tax) { - $amount = data_get($sub_tax, 'TaxAmount.amount', 0); - $taxable_amount = data_get($sub_tax, 'TaxableAmount.amount', 0); - $tax_rate = data_get($sub_tax, 'TaxCategory.Percent', 0); - $id = data_get($sub_tax, 'TaxCategory.ID.value', ''); - $tax_name = data_get($sub_tax, 'TaxCategory.TaxScheme.ID.value', ''); + foreach ($tax_sub_totals as $key => $sub_tax) { + $amount = data_get($sub_tax, 'TaxAmount.amount', 0); + $taxable_amount = data_get($sub_tax, 'TaxableAmount.amount', 0); + $tax_rate = data_get($sub_tax, 'TaxCategory.Percent', 0); + $id = data_get($sub_tax, 'TaxCategory.ID.value', ''); + $tax_name = data_get($sub_tax, 'TaxCategory.TaxScheme.ID.value', ''); - if (!$this->company->calculate_expense_tax_by_amount && $tax_rate > 0) { + if (!$this->company->calculate_expense_tax_by_amount && $tax_rate > 0) { - $expense->{"tax_rate{$tax_level}"} = $tax_rate; - $expense->{"tax_name{$tax_level}"} = $tax_name; - $expense->calculate_tax_by_amount = false; + $expense->{"tax_rate{$tax_level}"} = $tax_rate; + $expense->{"tax_name{$tax_level}"} = $tax_name; + $expense->calculate_tax_by_amount = false; - } - else { - $expense->calculate_tax_by_amount = true; - $expense->{"tax_amount{$tax_level}"} = $amount; //@phpstan-ignore-line + } else { + $expense->calculate_tax_by_amount = true; + $expense->{"tax_amount{$tax_level}"} = $amount; //@phpstan-ignore-line - } - - $tax_level++; - - if ($tax_level == 4) { - break; - } } + $tax_level++; + + if ($tax_level == 4) { + break; + } + } + $expense->save(); @@ -181,7 +178,7 @@ class UblEDocument extends AbstractService $data = []; $data['documents'][] = $this->file; - + $expense = $repo->save($data, $expense); return $expense; @@ -191,7 +188,7 @@ class UblEDocument extends AbstractService private function resolveCurrencyId(string $currency_code): int { - + /** @var \Illuminate\Support\Collection<\App\Models\Currency> */ $currencies = app('currencies'); @@ -203,7 +200,7 @@ class UblEDocument extends AbstractService private function findOrCreateVendor(\InvoiceNinja\EInvoice\Models\Peppol\Invoice $invoice): Vendor { $asp = $invoice->AccountingSupplierParty; - + $vat_number = $this->resolveVendorVat($invoice); $id_number = $this->resolveVendorIdNumber($invoice); $routing_id = data_get($invoice, 'AccountingSupplierParty.Party.EndpointID.value', false); @@ -211,18 +208,18 @@ class UblEDocument extends AbstractService $vendor = Vendor::query() ->where('company_id', $this->company->id) - ->where(function ($q) use ($vat_number, $routing_id, $id_number, $vendor_name){ + ->where(function ($q) use ($vat_number, $routing_id, $id_number, $vendor_name) { - $q->when($routing_id, function ($q) use ($routing_id){ + $q->when($routing_id, function ($q) use ($routing_id) { $q->where('routing_id', $routing_id); }) - ->when(strlen($vat_number) > 1, function ($q) use ($vat_number){ + ->when(strlen($vat_number) > 1, function ($q) use ($vat_number) { $q->orWhere('vat_number', $vat_number); }) - ->when(strlen($id_number) > 1, function ($q) use ($id_number){ + ->when(strlen($id_number) > 1, function ($q) use ($id_number) { $q->orWhere('id_number', $id_number); }) - ->when(strlen($vendor_name) > 1, function ($q) use ($vendor_name){ + ->when(strlen($vendor_name) > 1, function ($q) use ($vendor_name) { $q->orWhere('name', $vendor_name); }); @@ -233,7 +230,7 @@ class UblEDocument extends AbstractService private function resolveSupplierName(\InvoiceNinja\EInvoice\Models\Peppol\Invoice $invoice): string { - if(data_get($invoice, 'AccountingSupplierParty.Party.PartyName', false)){ + if (data_get($invoice, 'AccountingSupplierParty.Party.PartyName', false)) { $party_name = data_get($invoice, 'AccountingSupplierParty.Party.PartyName', false); return data_get($party_name[0], 'Name', ''); } @@ -242,22 +239,22 @@ class UblEDocument extends AbstractService $ple = data_get($invoice, 'AccountingSupplierParty.Party.PartyName', false); return data_get($ple[0], 'RegistrationName', ''); } - + return ''; } - private function resolveVendorIdNumber(\InvoiceNinja\EInvoice\Models\Peppol\Invoice $invoice):string + private function resolveVendorIdNumber(\InvoiceNinja\EInvoice\Models\Peppol\Invoice $invoice): string { - + $pts = data_get($invoice, 'AccountingSupplierParty.Party.PartyIdentification', false); return $pts ? data_get($pts[0], 'ID.value', '') : ''; } - private function resolveVendorVat(\InvoiceNinja\EInvoice\Models\Peppol\Invoice $invoice):string + private function resolveVendorVat(\InvoiceNinja\EInvoice\Models\Peppol\Invoice $invoice): string { - + $pts = data_get($invoice, 'AccountingSupplierParty.Party.PartyTaxScheme', false); return $pts ? data_get($pts[0], 'CompanyID.value', '') : ''; @@ -268,31 +265,30 @@ class UblEDocument extends AbstractService { $vendor = VendorFactory::create($this->company->id, $this->company->owner()->id); - + $data = [ 'name' => $this->resolveSupplierName($invoice), 'routing_id' => data_get($invoice, 'AccountingSupplierParty.Party.EndpointID.value', ''), 'vat_number' => $this->resolveVendorVat($invoice), 'id_number' => $this->resolveVendorIdNumber($invoice), - 'address1' => data_get($invoice, 'AccountingSupplierParty.Party.PostalAddress.StreetName',''), - 'address2' => data_get($invoice, 'AccountingSupplierParty.Party.PostalAddress.AdditionalStreetName',''), - 'city' => data_get($invoice, 'AccountingSupplierParty.Party.PostalAddress.CityName',''), - 'state' => data_get($invoice, 'AccountingSupplierParty.Party.PostalAddress.CountrySubentity',''), - 'postal_code' => data_get($invoice, 'AccountingSupplierParty.Party.PostalAddress.PostalZone',''), - 'country_id' => $this->resolveCountry(data_get($invoice, 'AccountingSupplierParty.Party.PostalAddress.Country.IdentificationCode.value','')), + 'address1' => data_get($invoice, 'AccountingSupplierParty.Party.PostalAddress.StreetName', ''), + 'address2' => data_get($invoice, 'AccountingSupplierParty.Party.PostalAddress.AdditionalStreetName', ''), + 'city' => data_get($invoice, 'AccountingSupplierParty.Party.PostalAddress.CityName', ''), + 'state' => data_get($invoice, 'AccountingSupplierParty.Party.PostalAddress.CountrySubentity', ''), + 'postal_code' => data_get($invoice, 'AccountingSupplierParty.Party.PostalAddress.PostalZone', ''), + 'country_id' => $this->resolveCountry(data_get($invoice, 'AccountingSupplierParty.Party.PostalAddress.Country.IdentificationCode.value', '')), 'currency_id' => $this->resolveCurrencyId(data_get($invoice, 'DocumentCurrencyCode.value', $this->company->currency()->code)), ]; $vendor->fill($data); $vendor->save(); - + $vendor->service()->applyNumber(); - if(data_get($invoice, 'AccountingSupplierParty.Party.Contact',false)) - { + if (data_get($invoice, 'AccountingSupplierParty.Party.Contact', false)) { $vc = VendorContactFactory::create($this->company->id, $this->company->owner()->id); $vc->vendor_id = $vendor->id; - $vc->first_name = data_get($invoice, 'AccountingSupplierParty.Party.Contact.Name',''); + $vc->first_name = data_get($invoice, 'AccountingSupplierParty.Party.Contact.Name', ''); $vc->phone = data_get($invoice, 'AccountingSupplierParty.Party.Contact.Telephone', ''); $vc->email = data_get($invoice, 'AccountingSupplierParty.Party.Contact.ElectronicMail', ''); $vc->save(); @@ -309,4 +305,4 @@ class UblEDocument extends AbstractService ->orWhere('iso_3166_3', $iso_country_code) ->first()?->id ?? (int)$this->company->settings->country_id; } -} \ No newline at end of file +} diff --git a/app/Services/EDocument/Imports/ZugferdEDocument.php b/app/Services/EDocument/Imports/ZugferdEDocument.php index ea34076eca..b9421a729a 100644 --- a/app/Services/EDocument/Imports/ZugferdEDocument.php +++ b/app/Services/EDocument/Imports/ZugferdEDocument.php @@ -76,8 +76,9 @@ class ZugferdEDocument extends AbstractService $expense->save(); $documents = [$this->file]; - if ($this->file->getExtension() == "xml") + if ($this->file->getExtension() == "xml") { array_push($documents, TempFile::UploadedFileFromRaw($visualizer->renderPdf(), $documentno . "_visualiser.pdf", "application/pdf")); + } $this->saveDocuments($documents, $expense); $expense->save(); @@ -109,16 +110,16 @@ class ZugferdEDocument extends AbstractService $vendor = Vendor::query() ->where("company_id", $this->company->id) - ->where(function ($q) use($taxid, $person_name, $contact_email){ - $q->when(!is_null($taxid), function ($when_query) use($taxid){ - $when_query->orWhere('vat_number', $taxid); - }) + ->where(function ($q) use ($taxid, $person_name, $contact_email) { + $q->when(!is_null($taxid), function ($when_query) use ($taxid) { + $when_query->orWhere('vat_number', $taxid); + }) ->orWhere("name", $person_name) - ->orWhereHas('contacts', function ($qq) use ($contact_email){ - $qq->where("email", $contact_email); + ->orWhereHas('contacts', function ($qq) use ($contact_email) { + $qq->where("email", $contact_email); }); })->first(); - + if ($vendor) { $expense->vendor_id = $vendor->id; } else { @@ -138,8 +139,9 @@ class ZugferdEDocument extends AbstractService /** @var \App\Models\Country $c */ return $c->iso_3166_2 == $country || $c->iso_3166_3 == $country; }); - if ($country) + if ($country) { $vendor->country_id = $country->id; + } $vendor_repo = new VendorRepository(new VendorContactRepository()); $vendor = $vendor_repo->save([], $vendor); @@ -155,8 +157,8 @@ class ZugferdEDocument extends AbstractService } $expense_repo = new ExpenseRepository(); - $expense = $expense_repo->save([],$expense); - + $expense = $expense_repo->save([], $expense); + return $expense; } } diff --git a/app/Services/EDocument/Jobs/SendEDocument.php b/app/Services/EDocument/Jobs/SendEDocument.php index cb630e620b..2721ec4b8b 100644 --- a/app/Services/EDocument/Jobs/SendEDocument.php +++ b/app/Services/EDocument/Jobs/SendEDocument.php @@ -38,7 +38,7 @@ class SendEDocument implements ShouldQueue use SerializesModels; public $tries = 5; - + public $deleteWhenMissingModels = true; public function __construct(private string $entity, private int $id, private string $db) @@ -53,12 +53,12 @@ class SendEDocument implements ShouldQueue public function handle(Storecove $storecove) { MultiDB::setDB($this->db); - + nlog("trying"); $model = $this->entity::find($this->id); - if($model->company->account->is_flagged){ + if ($model->company->account->is_flagged) { nlog("Bad Actor"); return; //Bad Actor present. } @@ -74,7 +74,7 @@ class SendEDocument implements ShouldQueue nlog($result); return $result['errors']; } - + $payload = [ 'legal_entity_id' => $model->company->legal_entity_id, "idempotencyGuid" => \Illuminate\Support\Str::uuid(), @@ -88,31 +88,30 @@ class SendEDocument implements ShouldQueue 'e_invoicing_token' => $model->company->account->e_invoicing_token, ]; - //Self Hosted Sending Code Path - if(Ninja::isSelfHost() && ($model instanceof Invoice) && $model->company->peppolSendingEnabled()) - { - + //Self Hosted Sending Code Path + if (Ninja::isSelfHost() && ($model instanceof Invoice) && $model->company->peppolSendingEnabled()) { + $r = Http::withHeaders($this->getHeaders()) ->post(config('ninja.hosted_ninja_url')."/api/einvoice/submission", $payload); - if($r->successful()) { + if ($r->successful()) { nlog("Model {$model->number} was successfully sent for third party processing via hosted Invoice Ninja"); - + $data = $r->json(); return $this->writeActivity($model, $data['guid']); } - if($r->failed()) { + if ($r->failed()) { nlog("Model {$model->number} failed to be accepted by invoice ninja, error follows:"); nlog($r->getBody()->getContents()); return response()->json(['message' => "Model {$model->number} failed to be accepted by invoice ninja"], 400); } - } - elseif(Ninja::isSelfHost()) + } elseif (Ninja::isSelfHost()) { return; - + } + //Run this check outside of the next loop as it will never send otherwise. if ($model->company->account->e_invoice_quota == 0 && $model->company->legal_entity_id) { $key = "e_invoice_quota_exhausted_{$model->company->account->key}"; @@ -133,11 +132,10 @@ class SendEDocument implements ShouldQueue } return; - } + } //Hosted Sending Code Path. - if(($model instanceof Invoice) && $model->company->peppolSendingEnabled()) - { + if (($model instanceof Invoice) && $model->company->peppolSendingEnabled()) { if ($model->company->account->e_invoice_quota <= config('ninja.e_invoice_quota_warning')) { $key = "e_invoice_quota_low_{$model->company->account->key}"; @@ -161,20 +159,20 @@ class SendEDocument implements ShouldQueue $r = $sc->sendJsonDocument($payload); // Successful send - update quota! - if(is_string($r)){ - + if (is_string($r)) { + $account = $model->company->account; $account->decrement('e_invoice_quota', 1); - $account->refresh(); + $account->refresh(); - if($account->e_invoice_quota == 0 && class_exists(\Modules\Admin\Jobs\Account\SuspendESendReceive::class)){ + if ($account->e_invoice_quota == 0 && class_exists(\Modules\Admin\Jobs\Account\SuspendESendReceive::class)) { \Modules\Admin\Jobs\Account\SuspendESendReceive::dispatch($account->key); } return $this->writeActivity($model, $r); } - - if($r->failed()) { + + if ($r->failed()) { nlog("Model {$model->number} failed to be accepted by invoice ninja, error follows:"); nlog($r->getBody()->getContents()); } @@ -196,17 +194,17 @@ class SendEDocument implements ShouldQueue $activity->save(); - $std = new \stdClass; + $std = new \stdClass(); $std->guid = str_replace('"', '', $guid); $model->backup = $std; $model->saveQuietly(); } - + /** * Self hosted request headers * - * + * **/ private function getHeaders(): array { diff --git a/app/Services/EDocument/Standards/FacturaEInvoice.php b/app/Services/EDocument/Standards/FacturaEInvoice.php index 204eebc518..99dafbf9e3 100644 --- a/app/Services/EDocument/Standards/FacturaEInvoice.php +++ b/app/Services/EDocument/Standards/FacturaEInvoice.php @@ -184,11 +184,11 @@ class FacturaEInvoice extends AbstractService { $facturae_centres = []; - if($this->invoice->client->custom_value1 == 'yes') { + if ($this->invoice->client->custom_value1 == 'yes') { - foreach($this->invoice->client->contacts()->whereNotNull('custom_value1')->whereNull('deleted_at')->cursor() as $contact) { + foreach ($this->invoice->client->contacts()->whereNotNull('custom_value1')->whereNull('deleted_at')->cursor() as $contact) { - if(in_array($contact->custom_value1, array_keys($this->centre_codes))) { + if (in_array($contact->custom_value1, array_keys($this->centre_codes))) { $facturae_centres[] = new FacturaeCentre([ 'role' => $this->centre_codes[$contact->custom_value1], 'code' => $contact->custom_value2, @@ -216,7 +216,7 @@ class FacturaEInvoice extends AbstractService private function setDiscount(): self { - if($this->invoice->discount > 0) { + if ($this->invoice->discount > 0) { $this->fac->addDiscount(ctrans('texts.discount'), $this->calc->getTotalDiscount()); } @@ -232,7 +232,7 @@ class FacturaEInvoice extends AbstractService private function setBillingPeriod(): self { - if(!$this->invoice->custom_value3) { + if (!$this->invoice->custom_value3) { return $this; } @@ -242,7 +242,7 @@ class FacturaEInvoice extends AbstractService ) { $this->fac->setBillingPeriod(\Carbon\Carbon::parse($this->invoice->custom_value3)->format('Y-m-d'), \Carbon\Carbon::parse($this->invoice->custom_value4)->format('Y-m-d')); } - } catch(\Exception $e) { + } catch (\Exception $e) { nlog($e->getMessage()); } @@ -349,7 +349,7 @@ class FacturaEInvoice extends AbstractService $data['method'] = $method; - if($method == FacturaePayment::TYPE_TRANSFER) { + if ($method == FacturaePayment::TYPE_TRANSFER) { $data['iban'] = $payment->custom_value1; $data['bic'] = $payment->custom_value2; } @@ -362,7 +362,7 @@ class FacturaEInvoice extends AbstractService private function buildItems(): self { - foreach($this->invoice->line_items as $item) { + foreach ($this->invoice->line_items as $item) { $this->fac->addItem(new FacturaeItem([ 'name' => $item->product_key, 'description' => $item->notes, @@ -407,7 +407,7 @@ class FacturaEInvoice extends AbstractService } - if(count($data) == 0) { + if (count($data) == 0) { $data[Facturae::TAX_IVA] = 0; } @@ -456,7 +456,7 @@ class FacturaEInvoice extends AbstractService { $company = $this->invoice->company; - if($company->getSetting('classification') == 'individual') { + if ($company->getSetting('classification') == 'individual') { return $this->setIndividualSeller(); } @@ -554,7 +554,7 @@ class FacturaEInvoice extends AbstractService // "ineTownCode" => "280796" // Cód. de municipio del INE ]; - if($this->invoice->client->classification === 'individual') { + if ($this->invoice->client->classification === 'individual') { $buyer_array['name'] = $this->invoice->client->present()->first_name(); $buyer_array['firstSurname'] = $this->invoice->client->present()->last_name(); } @@ -573,7 +573,7 @@ class FacturaEInvoice extends AbstractService $ssl_cert = $this->invoice->company->getInvoiceCert(); $ssl_passphrase = $this->invoice->company->getSslPassPhrase(); - if($ssl_cert) { + if ($ssl_cert) { $this->fac->sign($ssl_cert, null, $ssl_passphrase); } diff --git a/app/Services/EDocument/Standards/FatturaPA.php b/app/Services/EDocument/Standards/FatturaPA.php index 455083033c..fdbbe2417d 100644 --- a/app/Services/EDocument/Standards/FatturaPA.php +++ b/app/Services/EDocument/Standards/FatturaPA.php @@ -253,7 +253,7 @@ $datiTrasporto->setDatiAnagraficiVettore($datiAnagraficiVettore) } //totals - if($this->invoice->tax_rate1 > $tax_rate_level) { + if ($this->invoice->tax_rate1 > $tax_rate_level) { $tax_rate_level = sprintf('%0.2f', $this->invoice->tax_rate1); } diff --git a/app/Services/EDocument/Standards/FatturaPANew.php b/app/Services/EDocument/Standards/FatturaPANew.php index 5988e27b9d..bbce59a637 100644 --- a/app/Services/EDocument/Standards/FatturaPANew.php +++ b/app/Services/EDocument/Standards/FatturaPANew.php @@ -237,7 +237,7 @@ class FatturaPANew extends AbstractService } //totals - if($this->invoice->tax_rate1 > $tax_rate_level) { + if ($this->invoice->tax_rate1 > $tax_rate_level) { $tax_rate_level = sprintf('%0.2f', $this->invoice->tax_rate1); } diff --git a/app/Services/EDocument/Standards/Peppol.php b/app/Services/EDocument/Standards/Peppol.php index 8a3d0cd606..c259221f5f 100644 --- a/app/Services/EDocument/Standards/Peppol.php +++ b/app/Services/EDocument/Standards/Peppol.php @@ -65,8 +65,8 @@ class Peppol extends AbstractService * */ - private ?string $override_vat_number; - + private ?string $override_vat_number; + /** @var array $InvoiceTypeCodes */ private array $InvoiceTypeCodes = [ "380" => "Commercial invoice", @@ -82,7 +82,7 @@ class Peppol extends AbstractService "875" => "Self-billed credit note", "896" => "Debit note related to self-billed invoice" ]; - + /** @var array $tax_codes */ private array $tax_codes = [ 'AE' => [ @@ -126,7 +126,7 @@ class Peppol extends AbstractService 'description' => 'VAT not to be paid to the issuer of the invoice but directly to relevant tax authority. This code is allowed in the EN 16931 for Italy only based on the Italian A-deviation.' ] ]; - + private Company $company; private InvoiceSum | InvoiceSumInclusive $calc; @@ -145,7 +145,7 @@ class Peppol extends AbstractService private string $customizationID = 'urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0'; - private string $profileID = 'urn:fdc:peppol.eu:2017:poacc:billing:01:1.0'; + private string $profileID = 'urn:fdc:peppol.eu:2017:poacc:billing:01:1.0'; private array $tax_map = []; @@ -162,10 +162,10 @@ class Peppol extends AbstractService $this->company = $invoice->company; $this->calc = $this->invoice->calc(); $this->e = new EInvoice(); - $this->gateway = new $this->api_network; + $this->gateway = new $this->api_network(); $this->setSettings()->setInvoice(); } - + /** * Entry point for building document * @@ -189,11 +189,13 @@ class Peppol extends AbstractService $this->p_invoice->ID = $this->invoice->number; $this->p_invoice->IssueDate = new \DateTime($this->invoice->date); - if($this->invoice->due_date) + if ($this->invoice->due_date) { $this->p_invoice->DueDate = new \DateTime($this->invoice->due_date); + } - if(strlen($this->invoice->public_notes ?? '') > 0) + if (strlen($this->invoice->public_notes ?? '') > 0) { $this->p_invoice->Note = strip_tags($this->invoice->public_notes); + } $this->p_invoice->DocumentCurrencyCode = $this->invoice->client->currency()->code; @@ -203,7 +205,7 @@ class Peppol extends AbstractService $ip->EndDate = new \DateTime($this->invoice->due_date); $this->p_invoice->InvoicePeriod = [$ip]; } - + if ($this->invoice->project_id) { $pr = new \InvoiceNinja\EInvoice\Models\Peppol\ProjectReferenceType\ProjectReference(); $id = new \InvoiceNinja\EInvoice\Models\Peppol\IdentifierType\ID(); @@ -231,7 +233,7 @@ class Peppol extends AbstractService ->receiverSpecificLevelMutators() ->getPeppol(); - }catch(\Throwable $th) { + } catch (\Throwable $th) { nlog("Unable to create Peppol Invoice" . $th->getMessage()); $this->errors[] = $th->getMessage(); } @@ -239,7 +241,7 @@ class Peppol extends AbstractService return $this; } - + /** * Transforms a stdClass Invoice * to Peppol\Invoice::class @@ -247,7 +249,7 @@ class Peppol extends AbstractService * @param mixed $invoice * @return self */ - public function decode(mixed $invoice):self + public function decode(mixed $invoice): self { $this->p_invoice = $this->e->decode('Peppol', json_encode($invoice), 'json'); @@ -262,7 +264,7 @@ class Peppol extends AbstractService private function setInvoice(): self { /** Handle Existing Document */ - if($this->invoice->e_invoice && isset($this->invoice->e_invoice->Invoice)) { + if ($this->invoice->e_invoice && isset($this->invoice->e_invoice->Invoice)) { $this->decode($this->invoice->e_invoice->Invoice); @@ -273,7 +275,7 @@ class Peppol extends AbstractService ->setClientSettings($this->_client_settings) ->setCompanySettings($this->_company_settings); - return $this; + return $this; } @@ -306,7 +308,7 @@ class Peppol extends AbstractService return $this; } - + /** * getInvoice * @@ -316,12 +318,12 @@ class Peppol extends AbstractService { return $this->p_invoice; } - + /** * toXml * * Builds a full Peppol XML document including tags - * + * * @return string */ public function toXml(): string @@ -335,20 +337,20 @@ class Peppol extends AbstractService xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2">'; $suffix = ''; - + $xml = str_ireplace(['\n',''], ['', $prefix], $xml); $xml .= $suffix; return $xml; - + } - + /** * toJson * * Returns the peppol invoice in json format - * + * * @return string */ public function toJson(): string @@ -359,36 +361,36 @@ class Peppol extends AbstractService return $json; } - + /** * toObject * * returns the Peppol document in object format. - * + * * @return mixed */ public function toObject(): mixed { - $invoice = new \stdClass; + $invoice = new \stdClass(); $invoice->Invoice = json_decode($this->toJson()); return $invoice; } - + /** * toArray * * Returns the peppol document in Array format - * + * * @return array */ public function toArray(): array { return ['Invoice' => json_decode($this->toJson(), true)]; } - - + + /** * setOrderReference * @@ -398,7 +400,7 @@ class Peppol extends AbstractService private function setOrderReference(): self { - + if (strlen($this->invoice->po_number ?? '') > 1) { $this->p_invoice->BuyerReference = $this->invoice->po_number ?? ''; @@ -415,16 +417,16 @@ class Peppol extends AbstractService return $this; } - + /** * getAllowanceCharges * * Allowance charges are discounts / fees that are * applied to line or invoice level items - * + * * ChargeIndicator flags whether the item is a discount 'false' * this prop is ONLY set for discounts. Fees are inferred. - * + * * @return array */ private function getAllowanceCharges(): array @@ -432,7 +434,7 @@ class Peppol extends AbstractService $allowances = []; //Invoice Level discount - if($this->invoice->discount > 0){ + if ($this->invoice->discount > 0) { // Add Allowance Charge to Price $allowanceCharge = new \InvoiceNinja\EInvoice\Models\Peppol\AllowanceChargeType\AllowanceCharge(); @@ -443,7 +445,7 @@ class Peppol extends AbstractService // Add percentage if available if ($this->invoice->discount > 0 && !$this->invoice->is_amount_discount) { - + $allowanceCharge->BaseAmount = new \InvoiceNinja\EInvoice\Models\Peppol\AmountType\BaseAmount(); $allowanceCharge->BaseAmount->currencyID = $this->invoice->client->currency()->code; $allowanceCharge->BaseAmount->amount = number_format($this->calc->getSubtotalWithSurcharges(), 2, '.', ''); @@ -464,7 +466,7 @@ class Peppol extends AbstractService } //Invoice level surcharges (@todo React - need to turn back on surcharge taxes and use the first tax....) - if($this->invoice->custom_surcharge1 > 0){ + if ($this->invoice->custom_surcharge1 > 0) { // Add Allowance Charge to Price $allowanceCharge = new \InvoiceNinja\EInvoice\Models\Peppol\AllowanceChargeType\AllowanceCharge(); @@ -493,8 +495,8 @@ class Peppol extends AbstractService $allowanceCharge->BaseAmount = new \InvoiceNinja\EInvoice\Models\Peppol\AmountType\BaseAmount(); $allowanceCharge->BaseAmount->currencyID = $this->invoice->client->currency()->code; $allowanceCharge->BaseAmount->amount = (string) $this->calc->getSubtotalWithSurcharges(); - - + + $this->calculateTaxMap($this->invoice->custom_surcharge2); $allowanceCharge->TaxCategory = $this->globalTaxCategories; @@ -513,7 +515,7 @@ class Peppol extends AbstractService $allowanceCharge->BaseAmount = new \InvoiceNinja\EInvoice\Models\Peppol\AmountType\BaseAmount(); $allowanceCharge->BaseAmount->currencyID = $this->invoice->client->currency()->code; $allowanceCharge->BaseAmount->amount = (string) $this->calc->getSubtotalWithSurcharges(); - + $this->calculateTaxMap($this->invoice->custom_surcharge3); $allowanceCharge->TaxCategory = $this->globalTaxCategories; @@ -579,24 +581,24 @@ class Peppol extends AbstractService $am = new \InvoiceNinja\EInvoice\Models\Peppol\AmountType\AllowanceTotalAmount(); $am->currencyID = $this->invoice->client->currency()->code; - $am->amount = number_format($this->calc->getTotalDiscount(), 2, '.',''); + $am->amount = number_format($this->calc->getTotalDiscount(), 2, '.', ''); $lmt->AllowanceTotalAmount = $am; return $lmt; } - + /** * getTaxType * * Calculates the PEPPOL code for the tax type - * + * * @param string $tax_id * @return string */ private function getTaxType(string $tax_id = ''): string { $tax_type = null; - + switch ($tax_id) { case Product::PRODUCT_TYPE_SERVICE: case Product::PRODUCT_TYPE_DIGITAL: @@ -613,13 +615,14 @@ class Peppol extends AbstractService break; case Product::PRODUCT_TYPE_REVERSE_TAX: $tax_type = 'AE'; + // no break case Product::PRODUCT_INTRA_COMMUNITY: $tax_type = 'K'; break; } $eu_states = ["AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "EL", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "ES-CE", "ES-ML", "ES-CN", "SE", "IS", "LI", "NO", "CH"]; - + if (empty($tax_type)) { if ((in_array($this->company->country()->iso_3166_2, $eu_states) && in_array($this->invoice->client->country->iso_3166_2, $eu_states)) && $this->invoice->company->country()->iso_3166_2 != $this->invoice->client->country->iso_3166_2) { $tax_type = 'K'; // EEA Exempt @@ -630,8 +633,8 @@ class Peppol extends AbstractService } } - if(in_array($this->invoice->client->country->iso_3166_2, ["ES-CE", "ES-ML", "ES-CN"]) && $tax_type == 'S') { - + if (in_array($this->invoice->client->country->iso_3166_2, ["ES-CE", "ES-ML", "ES-CN"]) && $tax_type == 'S') { + if ($this->invoice->client->country->iso_3166_2 == "ES-CN") { $tax_type = 'L'; //Canary Islands general indirect tax } elseif (in_array($this->invoice->client->country->iso_3166_2, ["ES-CE", "ES-ML"])) { @@ -642,19 +645,19 @@ class Peppol extends AbstractService return $tax_type; } - + private function resolveTaxExemptReason($item, $ctc = null): mixed { - + $eu_states = ["AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "EL", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "ES-CE", "ES-ML", "ES-CN", "SE", "IS", "LI", "NO", "CH"]; - if($item->tax_id == '9') { + if ($item->tax_id == '9') { $tax_type = 'AE'; // EEA Exempt $reason_code = 'vatex-eu-ae'; $reason = 'Reverse charge'; - } elseif ((in_array($this->company->country()->iso_3166_2, $eu_states) && - in_array($this->invoice->client->country->iso_3166_2, $eu_states)) && + } elseif ((in_array($this->company->country()->iso_3166_2, $eu_states) && + in_array($this->invoice->client->country->iso_3166_2, $eu_states)) && $this->invoice->company->country()->iso_3166_2 != $this->invoice->client->country->iso_3166_2) { $tax_type = 'K'; // EEA Exempt $reason_code = 'vatex-eu-ic'; @@ -665,7 +668,7 @@ class Peppol extends AbstractService $reason_code = 'vatex-eu-g'; $reason = 'Export outside the EU'; } else { - $tax_type = 'O'; + $tax_type = 'O'; $reason_code = "vatex-eu-o"; $reason = 'Services outside scope of tax'; } @@ -673,13 +676,14 @@ class Peppol extends AbstractService $this->tax_category_id = $tax_type; //no vat, build a single tax category for tax exemption - + $taxCategory = new \InvoiceNinja\EInvoice\Models\Peppol\TaxCategoryType\TaxCategory(); $taxCategory->ID = new \InvoiceNinja\EInvoice\Models\Peppol\IdentifierType\ID(); $taxCategory->ID->value = $tax_type; - if($this->tax_category_id != 'O') + if ($this->tax_category_id != 'O') { $taxCategory->Percent = '0'; + } $taxScheme = new \InvoiceNinja\EInvoice\Models\Peppol\TaxSchemeType\TaxScheme(); $taxScheme->ID = new \InvoiceNinja\EInvoice\Models\Peppol\IdentifierType\ID(); @@ -692,18 +696,20 @@ class Peppol extends AbstractService $this->globalTaxCategories = [$taxCategory]; - if($this->tax_category_id == 'O' && isset($this->p_invoice->AccountingSupplierParty->Party->PartyTaxScheme)) + if ($this->tax_category_id == 'O' && isset($this->p_invoice->AccountingSupplierParty->Party->PartyTaxScheme)) { unset($this->p_invoice->AccountingSupplierParty->Party->PartyTaxScheme); - + } + if ($this->tax_category_id == 'O' && isset($this->p_invoice->AccountingCustomerParty->Party->PartyTaxScheme)) { unset($this->p_invoice->AccountingCustomerParty->Party->PartyTaxScheme); } - if($ctc) { + if ($ctc) { $ctc->ID->value = $tax_type; - if($this->tax_category_id != 'O') + if ($this->tax_category_id != 'O') { $ctc->Percent = '0'; + } // $terc = new \InvoiceNinja\EInvoice\Models\Peppol\CodeType\TaxExemptionReasonCode(); // $terc->value = $reason_code; // $ctc->TaxExemptionReasonCode = $terc; @@ -717,19 +723,19 @@ class Peppol extends AbstractService } - /** - * getInvoiceLines - * - * Compiles the invoice line items of the document - * - * @return array - */ + /** + * getInvoiceLines + * + * Compiles the invoice line items of the document + * + * @return array + */ private function getInvoiceLines(): array { $lines = []; - foreach($this->invoice->line_items as $key => $item) { - + foreach ($this->invoice->line_items as $key => $item) { + // $item->line_total = round($item->line_total,2); // $item->gross_line_total = round($item->gross_line_total, 2); @@ -737,13 +743,14 @@ class Peppol extends AbstractService $_item->Name = $item->product_key; $_item->Description = $item->notes; - + $ctc = new ClassifiedTaxCategory(); $ctc->ID = new ID(); $ctc->ID->value = $this->getTaxType($item->tax_id); - if($item->tax_rate1 > 0) + if ($item->tax_rate1 > 0) { $ctc->Percent = (string)$item->tax_rate1; + } $ts = new TaxScheme(); $id = new ID(); @@ -751,23 +758,23 @@ class Peppol extends AbstractService $ts->ID = $id; $ctc->TaxScheme = $ts; - if(floatval($item->tax_rate1) === 0.0) - { + if (floatval($item->tax_rate1) === 0.0) { $ctc = $this->resolveTaxExemptReason($item, $ctc); - if($this->tax_category_id == 'O') + if ($this->tax_category_id == 'O') { unset($ctc->Percent); - + } + } $_item->ClassifiedTaxCategory[] = $ctc; - + if ($item->tax_rate2 > 0) { $ctc = new ClassifiedTaxCategory(); $ctc->ID = new ID(); $ctc->ID->value = $this->getTaxType($item->tax_id); $ctc->Percent = (string)$item->tax_rate2; - + $ts = new TaxScheme(); $id = new ID(); $id->value = $this->standardizeTaxSchemeId($item->tax_name2); @@ -793,9 +800,9 @@ class Peppol extends AbstractService } $line = new InvoiceLine(); - + $id = new ID(); - $id->value = (string) ($key+1); + $id->value = (string) ($key + 1); $line->ID = $id; $iq = new \InvoiceNinja\EInvoice\Models\Peppol\QuantityType\InvoicedQuantity(); @@ -814,7 +821,7 @@ class Peppol extends AbstractService // Handle Price and Discounts if ($item->discount > 0) { - + // Base Price (before discount) $basePrice = new Price(); $basePriceAmount = new PriceAmount(); @@ -827,7 +834,7 @@ class Peppol extends AbstractService $allowanceCharge->ChargeIndicator = 'false'; // false = discount $allowanceCharge->Amount = new \InvoiceNinja\EInvoice\Models\Peppol\AmountType\Amount(); $allowanceCharge->Amount->currencyID = $this->invoice->client->currency()->code; - $allowanceCharge->Amount->amount = number_format($this->calculateTotalItemDiscountAmount($item),2, '.', ''); + $allowanceCharge->Amount->amount = number_format($this->calculateTotalItemDiscountAmount($item), 2, '.', ''); $this->allowance_total += $this->calculateTotalItemDiscountAmount($item); @@ -836,13 +843,13 @@ class Peppol extends AbstractService $allowanceCharge->BaseAmount = new \InvoiceNinja\EInvoice\Models\Peppol\AmountType\BaseAmount(); $allowanceCharge->BaseAmount->currencyID = $this->invoice->client->currency()->code; - $allowanceCharge->BaseAmount->amount = (string)round(($item->cost * $item->quantity),2); + $allowanceCharge->BaseAmount->amount = (string)round(($item->cost * $item->quantity), 2); $mfn = new \InvoiceNinja\EInvoice\Models\Peppol\NumericType\MultiplierFactorNumeric(); - $mfn->value = (string) round($item->discount,2); + $mfn->value = (string) round($item->discount, 2); $allowanceCharge->MultiplierFactorNumeric = $mfn; // Convert percentage to decimal } - + // } // Required reason $allowanceCharge->AllowanceChargeReason = ctrans('texts.discount'); @@ -866,9 +873,9 @@ class Peppol extends AbstractService return $lines; } - private function calculateTotalItemDiscountAmount($item):float + private function calculateTotalItemDiscountAmount($item): float { - + if ($item->is_amount_discount) { return $item->discount; } @@ -881,21 +888,20 @@ class Peppol extends AbstractService * calculateTaxMap * * Generates a standard tax_map entry for a given $amount - * + * * Iterates through all of the globalTaxCategories found in the document - * + * * @param float $amount * @return self */ private function calculateTaxMap($amount): self { - foreach($this->globalTaxCategories as $tc) - { + foreach ($this->globalTaxCategories as $tc) { $this->tax_map[] = [ 'taxableAmount' => $amount, - 'taxAmount' => $amount * ($tc->Percent/100), + 'taxAmount' => $amount * ($tc->Percent / 100), 'percentage' => $tc->Percent, ]; @@ -903,13 +909,13 @@ class Peppol extends AbstractService return $this; } - + /** * getAllUsedTaxes * * Build a full tax category property based on all * of the item taxes that have been applied to the invoice. - * + * * @return self */ private function getAllUsedTaxes(): self @@ -928,8 +934,8 @@ class Peppol extends AbstractService }) ->unique(fn ($tax) => $tax['percentage'] . '_' . $tax['name']) ->values() - ->each(function ($tax){ - + ->each(function ($tax) { + $taxCategory = new \InvoiceNinja\EInvoice\Models\Peppol\TaxCategoryType\TaxCategory(); $taxCategory->ID = new \InvoiceNinja\EInvoice\Models\Peppol\IdentifierType\ID(); $taxCategory->ID->value = $tax['scheme']; @@ -940,14 +946,14 @@ class Peppol extends AbstractService $taxCategory->TaxScheme = $taxScheme; $this->globalTaxCategories[] = $taxCategory; - + }); - + return $this; } - - + + /** * getAccountingSupplierParty * @@ -968,8 +974,8 @@ class Peppol extends AbstractService $pi = new PartyIdentification(); $vatID = new ID(); $vatID->schemeID = $this->resolveScheme(); - $vatID->value = $this->override_vat_number ?? $this->company->settings->vat_number; //todo if we are cross border - switch to the supplier local vat number - + $vatID->value = $this->override_vat_number ?? $this->company->settings->vat_number; //todo if we are cross border - switch to the supplier local vat number + $pi->ID = $vatID; $party->PartyIdentification[] = $pi; $pts = new \InvoiceNinja\EInvoice\Models\Peppol\PartyTaxSchemeType\PartyTaxScheme(); @@ -997,9 +1003,10 @@ class Peppol extends AbstractService $address = new Address(); $address->CityName = $this->invoice->company->settings->city; $address->StreetName = $this->invoice->company->settings->address1; - - if(strlen($this->invoice->company->settings->address2 ?? '') > 1) + + if (strlen($this->invoice->company->settings->address2 ?? '') > 1) { $address->AdditionalStreetName = $this->invoice->company->settings->address2; + } $address->PostalZone = $this->invoice->company->settings->postal_code; // $address->CountrySubentity = $this->invoice->company->settings->state; @@ -1009,10 +1016,10 @@ class Peppol extends AbstractService $ic = new IdentificationCode(); $ic->value = substr($this->invoice->company->country()->iso_3166_2, 0, 2); $country->IdentificationCode = $ic; - + $address->Country = $country; $party->PostalAddress = $address; - + $contact = new Contact(); $contact->ElectronicMail = $this->gateway->mutator->getSetting('Invoice.AccountingSupplierParty.Party.Contact') ?? $this->invoice->company->owner()->present()->email(); $contact->Telephone = $this->gateway->mutator->getSetting('Invoice.AccountingSupplierParty.Party.Telephone') ?? $this->invoice->company->getSetting('phone'); @@ -1023,12 +1030,12 @@ class Peppol extends AbstractService $ple = new \InvoiceNinja\EInvoice\Models\Peppol\PartyLegalEntity(); $ple->RegistrationName = $this->invoice->company->present()->name(); $party->PartyLegalEntity[] = $ple; - + $asp->Party = $party; return $asp; } - + /** * getAccountingCustomerParty * @@ -1041,7 +1048,7 @@ class Peppol extends AbstractService $party = new Party(); - if(strlen($this->invoice->client->vat_number ?? '') > 1) { + if (strlen($this->invoice->client->vat_number ?? '') > 1) { $pi = new PartyIdentification(); @@ -1072,8 +1079,7 @@ class Peppol extends AbstractService $party_name->Name = $this->invoice->client->present()->name(); //@todo if we have an exact GLN/routing number we should update this, otherwise Storecove will proxy and update on transit - if(strlen($this->invoice->client->routing_id ?? '') > 1) - { + if (strlen($this->invoice->client->routing_id ?? '') > 1) { $id = new \InvoiceNinja\EInvoice\Models\Peppol\IdentifierType\EndpointID(); $id->value = $this->invoice->client->routing_id; $id->schemeID = $this->resolveScheme(true); @@ -1086,8 +1092,9 @@ class Peppol extends AbstractService $address->CityName = $this->invoice->client->city; $address->StreetName = $this->invoice->client->address1; - if(strlen($this->invoice->client->address2 ?? '') > 1) + if (strlen($this->invoice->client->address2 ?? '') > 1) { $address->AdditionalStreetName = $this->invoice->client->address2; + } $address->PostalZone = $this->invoice->client->postal_code; // $address->CountrySubentity = $this->invoice->client->state; @@ -1096,7 +1103,7 @@ class Peppol extends AbstractService $ic = new IdentificationCode(); $ic->value = substr($this->invoice->client->country->iso_3166_2, 0, 2); - + $country->IdentificationCode = $ic; $address->Country = $country; @@ -1105,8 +1112,9 @@ class Peppol extends AbstractService $contact = new Contact(); $contact->ElectronicMail = $this->invoice->client->present()->email(); - if(strlen($this->invoice->client->phone ?? '') > 2) + if (strlen($this->invoice->client->phone ?? '') > 2) { $contact->Telephone = $this->invoice->client->phone; + } $party->Contact = $contact; @@ -1118,7 +1126,7 @@ class Peppol extends AbstractService return $acp; } - + private function getDelivery(): array { $delivery = new \InvoiceNinja\EInvoice\Models\Peppol\DeliveryType\Delivery(); @@ -1180,7 +1188,7 @@ class Peppol extends AbstractService $total -= $this->invoice->discount; } else { $total *= (100 - $this->invoice->discount) / 100; - + } } @@ -1200,11 +1208,11 @@ class Peppol extends AbstractService $total += $this->invoice->custom_surcharge4; } - return round($total,2); + return round($total, 2); } ///////////////// Helper Methods ///////////////////////// - + /** * setInvoiceDefaults @@ -1216,16 +1224,14 @@ class Peppol extends AbstractService { // Stub new invoice with company settings. - if($this->_company_settings) - { - foreach(get_object_vars($this->_company_settings) as $prop => $value){ + if ($this->_company_settings) { + foreach (get_object_vars($this->_company_settings) as $prop => $value) { $this->p_invoice->{$prop} = $value; } } // Overwrite with any client level settings - if($this->_client_settings) - { + if ($this->_client_settings) { foreach (get_object_vars($this->_client_settings) as $prop => $value) { $this->p_invoice->{$prop} = $value; } @@ -1249,9 +1255,9 @@ class Peppol extends AbstractService ]; //only scans for top level props - foreach($settings as $prop => $visibility) { + foreach ($settings as $prop => $visibility) { - if($prop_value = $this->gateway->mutator->getSetting($prop)) { + if ($prop_value = $this->gateway->mutator->getSetting($prop)) { $this->p_invoice->{$prop} = $prop_value; } @@ -1262,13 +1268,12 @@ class Peppol extends AbstractService public function setTaxBreakdown(): self { - + $tax_total = new TaxTotal(); $taxes = $this->calc->getTaxMap(); - if(count($taxes) < 1) - { - + if (count($taxes) < 1) { + $tax_amount = new TaxAmount(); $tax_amount->currencyID = $this->invoice->client->currency()->code; $tax_amount->amount = (string)0; @@ -1279,7 +1284,7 @@ class Peppol extends AbstractService // Required: TaxableAmount (BT-116) $taxable_amount = new TaxableAmount(); $taxable_amount->currencyID = $this->invoice->client->currency()->code; - $taxable_amount->amount = (string)round($this->invoice->amount,2); + $taxable_amount->amount = (string)round($this->invoice->amount, 2); $tax_subtotal->TaxableAmount = $taxable_amount; @@ -1316,8 +1321,7 @@ class Peppol extends AbstractService } - foreach($taxes as $key => $grouped_tax) - { + foreach ($taxes as $key => $grouped_tax) { // Required: TaxAmount (BT-110) $tax_amount = new TaxAmount(); $tax_amount->currencyID = $this->invoice->client->currency()->code; @@ -1331,17 +1335,18 @@ class Peppol extends AbstractService $taxable_amount = new TaxableAmount(); $taxable_amount->currencyID = $this->invoice->client->currency()->code; - if(floatval($grouped_tax['total']) === 0.0) + if (floatval($grouped_tax['total']) === 0.0) { $taxable_amount->amount = (string)round($this->invoice->amount, 2); - else - $taxable_amount->amount = (string)round($grouped_tax['base_amount'],2); + } else { + $taxable_amount->amount = (string)round($grouped_tax['base_amount'], 2); + } $tax_subtotal->TaxableAmount = $taxable_amount; // Required: TaxAmount (BT-117) $subtotal_tax_amount = new TaxAmount(); $subtotal_tax_amount->currencyID = $this->invoice->client->currency()->code; - $subtotal_tax_amount->amount = (string)round($grouped_tax['total'],2); + $subtotal_tax_amount->amount = (string)round($grouped_tax['total'], 2); $tax_subtotal->TaxAmount = $subtotal_tax_amount; @@ -1355,8 +1360,9 @@ class Peppol extends AbstractService $tax_category->ID = $category_id; // Required: TaxCategory Rate (BT-119) - if($grouped_tax['tax_rate'] > 0) + if ($grouped_tax['tax_rate'] > 0) { $tax_category->Percent = (string)$grouped_tax['tax_rate']; + } // Required: TaxScheme (BG-23) $tax_scheme = new TaxScheme(); @@ -1377,36 +1383,35 @@ class Peppol extends AbstractService public function getJurisdiction() { - + //calculate nexus $country_code = $this->company->country()->iso_3166_2; $br = new \App\DataMapper\Tax\BaseRule(); $eu_countries = $br->eu_country_codes; - if($this->invoice->client->country->iso_3166_2 == $this->company->country()->iso_3166_2){ + if ($this->invoice->client->country->iso_3166_2 == $this->company->country()->iso_3166_2) { //Domestic Sales $country_code = $this->company->country()->iso_3166_2; - } - elseif(in_array($country_code, $eu_countries) && !in_array($this->invoice->client->country->iso_3166_2, $eu_countries)){ + } elseif (in_array($country_code, $eu_countries) && !in_array($this->invoice->client->country->iso_3166_2, $eu_countries)) { //EU => FOREIGN sale - } - elseif(in_array($this->invoice->client->country->iso_3166_2, $eu_countries)){ - // EU Sale - if((isset($this->company->tax_data->regions->EU->has_sales_above_threshold) && $this->company->tax_data->regions->EU->has_sales_above_threshold) || !$this->invoice->client->has_valid_vat_number){ //over threshold - tax in buyer country - + } elseif (in_array($this->invoice->client->country->iso_3166_2, $eu_countries)) { + // EU Sale + if ((isset($this->company->tax_data->regions->EU->has_sales_above_threshold) && $this->company->tax_data->regions->EU->has_sales_above_threshold) || !$this->invoice->client->has_valid_vat_number) { //over threshold - tax in buyer country + $country_code = $this->invoice->client->country->iso_3166_2; - if(isset($this->ninja_invoice->company->tax_data->regions->EU->subregions->{$country_code}->vat_number)) + if (isset($this->ninja_invoice->company->tax_data->regions->EU->subregions->{$country_code}->vat_number)) { $this->override_vat_number = $this->ninja_invoice->company->tax_data->regions->EU->subregions->{$country_code}->vat_number; + } } } - + $jurisdiction = new \InvoiceNinja\EInvoice\Models\Peppol\AddressType\JurisdictionRegionAddress(); $country = new Country(); $ic = new IdentificationCode(); $ic->value = $country_code; $country->IdentificationCode = $ic; - $jurisdiction->Country = $country; + $jurisdiction->Country = $country; $addressTypeCode = new \InvoiceNinja\EInvoice\Models\Peppol\CodeType\AddressTypeCode(); $addressTypeCode->value = 'JURISDICTION'; // or the appropriate code from PEPPOL spec $jurisdiction->AddressTypeCode = $addressTypeCode; @@ -1416,32 +1421,32 @@ class Peppol extends AbstractService } - private function standardizeTaxSchemeId(string $tax_name): string + private function standardizeTaxSchemeId(string $tax_name): string { - + $br = new BaseRule(); $eu_countries = $br->eu_country_codes; // If company is in EU, standardize to VAT // if (in_array($this->company->country()->iso_3166_2, $eu_countries)) { - return "VAT"; + return "VAT"; // } // For non-EU countries, return original or handle specifically // return $this->standardizeTaxSchemeId($tax_name); } - + /** * ResolveScheme * * If we need to explicitly set the schemeID, we will need to resolve * the exact one based on the type the user has, ie. GLN DUNS, validation * is performed here, so lots can go wrong if bad data is used. - * + * * @param bool $is_client * @return string */ - private function resolveScheme(bool $is_client=false): string + private function resolveScheme(bool $is_client = false): string { $vat_number = $is_client ? $this->invoice->client->vat_number : $this->company->settings->vat_number; diff --git a/app/Services/EDocument/Standards/Peppol/BaseCountry.php b/app/Services/EDocument/Standards/Peppol/BaseCountry.php index e53db73956..6255c7af6f 100644 --- a/app/Services/EDocument/Standards/Peppol/BaseCountry.php +++ b/app/Services/EDocument/Standards/Peppol/BaseCountry.php @@ -20,4 +20,4 @@ class BaseCountry { } -} \ No newline at end of file +} diff --git a/app/Services/EDocument/Standards/Peppol/RO.php b/app/Services/EDocument/Standards/Peppol/RO.php index ea90b32251..6402e889cd 100644 --- a/app/Services/EDocument/Standards/Peppol/RO.php +++ b/app/Services/EDocument/Standards/Peppol/RO.php @@ -126,7 +126,7 @@ class RO extends BaseCountry $state_code = strlen($state_code ?? '') > 1 ? $state_code : $this->invoice->client->state; //codes are configured by default - if(isset($this->countrySubEntity[$state_code])) { + if (isset($this->countrySubEntity[$state_code])) { return $state_code; } @@ -143,7 +143,7 @@ class RO extends BaseCountry { $client_sector_code = $client_city ?? $this->invoice->client->city; - if(in_array($this->getStateCode($this->invoice->client->state), ['BUCHAREST', 'RO-B'])) { + if (in_array($this->getStateCode($this->invoice->client->state), ['BUCHAREST', 'RO-B'])) { return in_array(strtoupper($this->invoice->client->city), array_keys($this->sectorList)) ? strtoupper($this->invoice->client->city) : 'SECTOR1'; } diff --git a/app/Services/EDocument/Standards/Validation/Peppol/EntityLevel.php b/app/Services/EDocument/Standards/Validation/Peppol/EntityLevel.php index 14d2218109..751b327e33 100644 --- a/app/Services/EDocument/Standards/Validation/Peppol/EntityLevel.php +++ b/app/Services/EDocument/Standards/Validation/Peppol/EntityLevel.php @@ -130,8 +130,8 @@ class EntityLevel $this->errors['client'] = $this->testClientState($invoice->client); $this->errors['company'] = $this->testCompanyState($invoice->client); // uses client level settings which is what we want - if(count($this->errors['client']) > 0){ - + if (count($this->errors['client']) > 0) { + $this->errors['passes'] = false; return $this->errors; @@ -141,35 +141,32 @@ class EntityLevel $xml = false; - try{ + try { $xml = $p->run()->toXml(); - if(count($p->getErrors()) >= 1){ + if (count($p->getErrors()) >= 1) { - foreach($p->getErrors() as $error) - { + foreach ($p->getErrors() as $error) { $this->errors['invoice'][] = $error; } } - } - catch(PeppolValidationException $e) { + } catch (PeppolValidationException $e) { $this->errors['invoice'] = ['field' => $e->getInvalidField(), 'label' => $e->getInvalidField()]; - } - catch(\Throwable $th){ + } catch (\Throwable $th) { } - if($xml){ + if ($xml) { // Second pass through the XSLT validator $xslt = new XsltDocumentValidator($xml); $errors = $xslt->validate()->getErrors(); - if(isset($errors['stylesheet']) && count($errors['stylesheet']) > 0){ + if (isset($errors['stylesheet']) && count($errors['stylesheet']) > 0) { $this->errors['invoice'] = array_merge($this->errors['invoice'], $errors['stylesheet']); } - - if(isset($errors['general']) && count($errors['general']) > 0) { + + if (isset($errors['general']) && count($errors['general']) > 0) { $this->errors['invoice'] = array_merge($this->errors['invoice'], $errors['general']); } @@ -190,14 +187,15 @@ class EntityLevel $errors = []; - foreach($this->client_fields as $field) - { + foreach ($this->client_fields as $field) { - if($this->validString($client->{$field})) + if ($this->validString($client->{$field})) { continue; + } - if($field == 'country_id' && $client->country_id >=1) + if ($field == 'country_id' && $client->country_id >= 1) { continue; + } $errors[] = ['field' => $field, 'label' => ctrans("texts.{$field}")]; @@ -214,32 +212,28 @@ class EntityLevel private function testCompanyState(mixed $entity): array { - + $client = false; $vendor = false; $settings_object = false; - $company =false; + $company = false; - if($entity instanceof Client){ + if ($entity instanceof Client) { $client = $entity; $company = $entity->company; $settings_object = $client; - } - elseif($entity instanceof Company){ + } elseif ($entity instanceof Company) { $company = $entity; - $settings_object = $company; - } - elseif($entity instanceof Vendor){ - $vendor = $entity; + $settings_object = $company; + } elseif ($entity instanceof Vendor) { + $vendor = $entity; $company = $entity->company; $settings_object = $company; - } - elseif($entity instanceof Invoice || $entity instanceof Credit || $entity instanceof Quote){ + } elseif ($entity instanceof Invoice || $entity instanceof Credit || $entity instanceof Quote) { $client = $entity->client; $company = $entity->company; $settings_object = $entity->client; - } - elseif($entity instanceof PurchaseOrder){ + } elseif ($entity instanceof PurchaseOrder) { $vendor = $entity->vendor; $company = $entity->company; $settings_object = $company; @@ -247,26 +241,25 @@ class EntityLevel $errors = []; - foreach($this->company_settings_fields as $field) - { + foreach ($this->company_settings_fields as $field) { - if($this->validString($settings_object->getSetting($field))) + if ($this->validString($settings_object->getSetting($field))) { continue; - + } + $errors[] = ['field' => $field, 'label' => ctrans("texts.{$field}")]; } //test legal entity id present - if(!is_int($company->legal_entity_id)) + if (!is_int($company->legal_entity_id)) { $errors[] = ['field' => "You have not registered a legal entity id as yet."]; + } //If not an individual, you MUST have a VAT number - if($company->getSetting('classification') != 'individual' && !$this->validString($company->getSetting('vat_number'))) - { + if ($company->getSetting('classification') != 'individual' && !$this->validString($company->getSetting('vat_number'))) { $errors[] = ['field' => 'vat_number', 'label' => ctrans("texts.vat_number")]; - } - elseif ($company->getSetting('classification') == 'individual' && !$this->validString($company->getSetting('id_number'))) { + } elseif ($company->getSetting('classification') == 'individual' && !$this->validString($company->getSetting('id_number'))) { $errors[] = ['field' => 'id_number', 'label' => ctrans("texts.id_number")]; } @@ -304,4 +297,4 @@ class EntityLevel return iconv_strlen($string) >= 1; } -} \ No newline at end of file +} diff --git a/app/Services/EDocument/Standards/Validation/XsltDocumentValidator.php b/app/Services/EDocument/Standards/Validation/XsltDocumentValidator.php index 1811d32cff..a8b146c756 100644 --- a/app/Services/EDocument/Standards/Validation/XsltDocumentValidator.php +++ b/app/Services/EDocument/Standards/Validation/XsltDocumentValidator.php @@ -49,37 +49,36 @@ class XsltDocumentValidator private function validateSchema(): self { - try{ + try { $processor = new \Saxon\SaxonProcessor(); $xslt = $processor->newXslt30Processor(); - foreach($this->stylesheets as $stylesheet) - { + foreach ($this->stylesheets as $stylesheet) { $xdmNode = $processor->parseXmlFromString($this->xml_document); - + /** @var \Saxon\XsltExecutable $xsltExecutable */ $xsltExecutable = $xslt->compileFromFile(app_path($stylesheet)); //@phpstan-ignore-line $result = $xsltExecutable->transformToValue($xdmNode); - if($result->size() == 0) + if ($result->size() == 0) { continue; + } - for ($x=0; $x<$result->size(); $x++) - { + for ($x = 0; $x < $result->size(); $x++) { $a = $result->itemAt($x); - if(strlen($a->getStringValue() ?? '') > 1) + if (strlen($a->getStringValue() ?? '') > 1) { $this->errors['stylesheet'][] = $a->getStringValue(); + } } } - - } - catch(\Throwable $th){ + + } catch (\Throwable $th) { $this->errors['general'][] = $th->getMessage(); - } + } return $this; @@ -87,7 +86,7 @@ class XsltDocumentValidator private function validateXsd(): self { - + libxml_use_internal_errors(true); $xml = new \DOMDocument(); @@ -114,7 +113,7 @@ class XsltDocumentValidator public function setStyleSheets(array $stylesheets): self { $this->stylesheets = $stylesheets; - + return $this; } @@ -140,7 +139,7 @@ class XsltDocumentValidator // Load XML document $xml_doc = $processor->parseXmlFromString($xml); - + // Compile and apply stylesheet $stylesheet = $xslt->compileFromFile(app_path($this->peppol_stylesheet)); //@phpstan-ignore-line diff --git a/app/Services/EDocument/Standards/ZugferdEDokument.php b/app/Services/EDocument/Standards/ZugferdEDokument.php index 3107e4a5eb..a3f79ff1bf 100644 --- a/app/Services/EDocument/Standards/ZugferdEDokument.php +++ b/app/Services/EDocument/Standards/ZugferdEDokument.php @@ -65,7 +65,7 @@ class ZugferdEDokument extends AbstractService $this->xdocument = ZugferdDocumentBuilder::CreateNew($profile); - $user_or_company_phone = strlen($this->document->user->present()->phone()) > 3 ? $this->document->user->present()->phone() : $company->present()->phone; + $user_or_company_phone = strlen($this->document->user->present()->phone()) > 3 ? $this->document->user->present()->phone() : $company->present()->phone; $this->xdocument ->setDocumentSupplyChainEvent(date_create($this->document->date ?? now()->format('Y-m-d'))) @@ -125,7 +125,7 @@ class ZugferdEDokument extends AbstractService $custom_value1 = $company->settings->custom_value1; //BR-DE-23 - If „Payment means type code“ (BT-81) contains a code for credit transfer (30, 58), „CREDIT TRANSFER“ (BG-17) shall be provided. //Payment Means - Switcher - if(isset($custom_value1) && !empty($custom_value1) && ($custom_value1 == '30'|| $custom_value1=='58')) { + if (isset($custom_value1) && !empty($custom_value1) && ($custom_value1 == '30' || $custom_value1 == '58')) { $this->xdocument->addDocumentPaymentMean(typecode: $company->settings->custom_value1, payeeIban: $company->settings->custom_value2, payeeAccountName: $company->settings->custom_value4, payeeBic: $company->settings->custom_value3); } else { $this->xdocument->addDocumentPaymentMean('68', ctrans("texts.xinvoice_online_payment")); @@ -176,7 +176,7 @@ class ZugferdEDokument extends AbstractService } $this->xdocument->setDocumentPositionLineSummation($item->line_total); - if (isset($company->tax_data->regions->EU->has_sales_above_threshold) && !$company->tax_data->regions->EU->has_sales_above_threshold){ + if (isset($company->tax_data->regions->EU->has_sales_above_threshold) && !$company->tax_data->regions->EU->has_sales_above_threshold) { // According to european law, each line item can only have one tax rate if (!(empty($item->tax_name1) && empty($item->tax_name2) && empty($item->tax_name3))) { $taxtype = $this->getTaxType($item->tax_id ?? 2); @@ -223,39 +223,41 @@ class ZugferdEDokument extends AbstractService $this->addtoTaxMap($taxtype, $item->line_total, 0); // nlog("Can't add correct tax position"); } - }} else { - $taxtype = ZugferdDutyTaxFeeCategories::EXEMPT_FROM_TAX; - $this->xdocument->addDocumentPositionTax($taxtype, 'VAT', 0, 0, ctrans('texts.vat_not_registered'), "VATNOTREG"); - $this->addtoTaxMap($taxtype, $item->line_total, 0); } + } else { + $taxtype = ZugferdDutyTaxFeeCategories::EXEMPT_FROM_TAX; + $this->xdocument->addDocumentPositionTax($taxtype, 'VAT', 0, 0, ctrans('texts.vat_not_registered'), "VATNOTREG"); + $this->addtoTaxMap($taxtype, $item->line_total, 0); } + } if ($this->document->is_amount_discount) { $document_discount = abs($this->document->discount); } else { $document_discount = $this->document->amount * $this->document->discount / 100; } - if (isset($company->tax_data->regions->EU->has_sales_above_threshold) && !$company->tax_data->regions->EU->has_sales_above_threshold){ - $this->xdocument->setDocumentSummation($this->document->amount, $this->document->balance, $invoicing_data->getSubTotal(), $invoicing_data->getTotalSurcharges(), $document_discount, $invoicing_data->getSubTotal() - $document_discount, $invoicing_data->getItemTotalTaxes(), 0.0, $this->document->amount - $this->document->balance); - foreach ($this->tax_map as $item) { - if ($document_discount > 0) { - if ($item["net_amount"] >= $document_discount) { - $item["net_amount"] -= $document_discount; - $this->xdocument->addDocumentAllowanceCharge($document_discount, false, $item["tax_type"], "VAT", $item["tax_rate"] * 100); - } else { - $document_discount -= $item["net_amount"]; - $this->xdocument->addDocumentAllowanceCharge($item["net_amount"], false, $item["tax_type"], "VAT", $item["tax_rate"] * 100); - $item["net_amount"] = 0; + if (isset($company->tax_data->regions->EU->has_sales_above_threshold) && !$company->tax_data->regions->EU->has_sales_above_threshold) { + $this->xdocument->setDocumentSummation($this->document->amount, $this->document->balance, $invoicing_data->getSubTotal(), $invoicing_data->getTotalSurcharges(), $document_discount, $invoicing_data->getSubTotal() - $document_discount, $invoicing_data->getItemTotalTaxes(), 0.0, $this->document->amount - $this->document->balance); + foreach ($this->tax_map as $item) { + if ($document_discount > 0) { + if ($item["net_amount"] >= $document_discount) { + $item["net_amount"] -= $document_discount; + $this->xdocument->addDocumentAllowanceCharge($document_discount, false, $item["tax_type"], "VAT", $item["tax_rate"] * 100); + } else { + $document_discount -= $item["net_amount"]; + $this->xdocument->addDocumentAllowanceCharge($item["net_amount"], false, $item["tax_type"], "VAT", $item["tax_rate"] * 100); + $item["net_amount"] = 0; + } + } + if ($item["tax_type"] == ZugferdDutyTaxFeeCategories::VAT_EXEMPT_FOR_EEA_INTRACOMMUNITY_SUPPLY_OF_GOODS_AND_SERVICES) { + $this->xdocument->addDocumentTax($item["tax_type"], "VAT", $item["net_amount"], $item["tax_rate"] * $item["net_amount"], $item["tax_rate"] * 100, ctrans('texts.intracommunity_tax_info')); + } else { + $this->xdocument->addDocumentTax($item["tax_type"], "VAT", $item["net_amount"], $item["tax_rate"] * $item["net_amount"], $item["tax_rate"] * 100); } - } - if ($item["tax_type"] == ZugferdDutyTaxFeeCategories::VAT_EXEMPT_FOR_EEA_INTRACOMMUNITY_SUPPLY_OF_GOODS_AND_SERVICES) { - $this->xdocument->addDocumentTax($item["tax_type"], "VAT", $item["net_amount"], $item["tax_rate"] * $item["net_amount"], $item["tax_rate"] * 100, ctrans('texts.intracommunity_tax_info')); - } else { - $this->xdocument->addDocumentTax($item["tax_type"], "VAT", $item["net_amount"], $item["tax_rate"] * $item["net_amount"], $item["tax_rate"] * 100); - } - }} else { + } + } else { $this->xdocument->addDocumentTax(ZugferdDutyTaxFeeCategories::EXEMPT_FROM_TAX, "VAT", 0, 0, 0, ctrans('texts.vat_not_registered'), "VATNOTREG"); } diff --git a/app/Services/Email/Email.php b/app/Services/Email/Email.php index 94142d97e6..90f3f90c5e 100644 --- a/app/Services/Email/Email.php +++ b/app/Services/Email/Email.php @@ -251,7 +251,7 @@ class Email implements ShouldQueue private function incrementEmailCounter(): void { - if(in_array($this->email_object->settings->email_sending_method, ['default','mailgun','postmark'])) { + if (in_array($this->email_object->settings->email_sending_method, ['default','mailgun','postmark'])) { Cache::increment("email_quota".$this->company->account->key); } } @@ -292,10 +292,10 @@ class Email implements ShouldQueue LightLogs::create(new EmailSuccess($this->company->company_key, $this->mailable->subject)) ->send(); - } catch(\Symfony\Component\Mailer\Exception\TransportException $e){ + } catch (\Symfony\Component\Mailer\Exception\TransportException $e) { nlog("Mailer failed with a Transport Exception {$e->getMessage()}"); - - if(Ninja::isHosted() && $this->mailer == 'smtp'){ + + if (Ninja::isHosted() && $this->mailer == 'smtp') { $settings = $this->email_object->settings; $settings->email_sending_method = 'default'; $this->company->settings = $settings; @@ -318,7 +318,7 @@ class Email implements ShouldQueue $this->cleanUpMailers(); $this->logMailError($e->getMessage(), $this->company->clients()->first()); return; - } catch(\Google\Service\Exception $e) { + } catch (\Google\Service\Exception $e) { if ($e->getCode() == '429') { @@ -346,7 +346,7 @@ class Email implements ShouldQueue return; } - if(stripos($e->getMessage(), 'Dsn') !== false) { + if (stripos($e->getMessage(), 'Dsn') !== false) { nlog("Incorrectly configured mail server - setting to default mail driver."); $this->email_object->settings->email_sending_method = 'default'; @@ -533,7 +533,7 @@ class Email implements ShouldQueue { /** Force free/trials onto specific mail driver */ - if($this->email_object->settings->email_sending_method == 'default' && $this->company->account->isNewHostedAccount()) { + if ($this->email_object->settings->email_sending_method == 'default' && $this->company->account->isNewHostedAccount()) { $this->mailer = 'mailgun'; $this->setHostedMailgunMailer(); return $this; @@ -629,7 +629,7 @@ class Email implements ShouldQueue $smtp_local_domain = strlen($company->smtp_local_domain ?? '') > 2 ? $company->smtp_local_domain : null; $smtp_verify_peer = $company->smtp_verify_peer ?? true; - if(strlen($smtp_host) <= 1 || + if (strlen($smtp_host) <= 1 || strlen($smtp_username) <= 1 || strlen($smtp_password) <= 1 ) { @@ -953,7 +953,7 @@ class Email implements ShouldQueue 'refresh_token' => $user->oauth_user_refresh_token ], ])->getBody()->getContents()); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Problem getting new Microsoft token for User: {$user->email}"); } diff --git a/app/Services/Email/EmailDefaults.php b/app/Services/Email/EmailDefaults.php index d9e25b0996..8ba11e1e41 100644 --- a/app/Services/Email/EmailDefaults.php +++ b/app/Services/Email/EmailDefaults.php @@ -214,15 +214,15 @@ class EmailDefaults $reply_to_email = $this->email->company->owner()->email; $reply_to_name = $this->email->company->owner()->present()->name(); - if(str_contains($this->email->email_object->settings->reply_to_email, "@")) { + if (str_contains($this->email->email_object->settings->reply_to_email, "@")) { $reply_to_email = $this->email->email_object->settings->reply_to_email; - } elseif(isset($this->email->email_object->invitation->user)) { + } elseif (isset($this->email->email_object->invitation->user)) { $reply_to_email = $this->email->email_object->invitation->user->email; } - if(strlen($this->email->email_object->settings->reply_to_name) > 3) { + if (strlen($this->email->email_object->settings->reply_to_name) > 3) { $reply_to_name = $this->email->email_object->settings->reply_to_name; - } elseif(isset($this->email->email_object->invitation->user)) { + } elseif (isset($this->email->email_object->invitation->user)) { $reply_to_name = $this->email->email_object->invitation->user->present()->name(); } @@ -310,7 +310,7 @@ class EmailDefaults if ($this->email->email_object->settings->pdf_email_attachment) { $pdf = ((new CreateRawPdf($this->email->email_object->invitation))->handle()); - if($this->email->email_object->settings->embed_documents && ($this->email->email_object->entity->documents()->where('is_public', true)->count() > 0 || $this->email->email_object->entity->company->documents()->where('is_public', true)->count() > 0)) { + if ($this->email->email_object->settings->embed_documents && ($this->email->email_object->entity->documents()->where('is_public', true)->count() > 0 || $this->email->email_object->entity->company->documents()->where('is_public', true)->count() > 0)) { $pdf = $this->email->email_object->entity->documentMerge($pdf); } @@ -327,17 +327,16 @@ class EmailDefaults } /** E-Invoice xml file */ if ($this->email->email_object->settings->enable_e_invoice && $this->email->email_object->settings->enable_e_invoice) { - + $xml_string = false; - try{ + try { $xml_string = $this->email->email_object->entity->service()->getEDocument(); - } - catch(\Throwable $th){ + } catch (\Throwable $th) { nlog("could not generate e invoice for:: ".$this->email->email_object->entity->id); } - if($xml_string) { + if ($xml_string) { $this->email->email_object->attachments = array_merge($this->email->email_object->attachments, [['file' => base64_encode($xml_string), 'name' => explode(".", $this->email->email_object->entity->getFileName('xml'))[0]."-e_invoice.xml"]]); } diff --git a/app/Services/InboundMail/InboundMail.php b/app/Services/InboundMail/InboundMail.php index 2430df047e..845d11d899 100644 --- a/app/Services/InboundMail/InboundMail.php +++ b/app/Services/InboundMail/InboundMail.php @@ -26,7 +26,7 @@ class InboundMail public ?string $subject = null; public ?string $body = null; - + public ?UploadedFile $body_document = null; public string $text_body; diff --git a/app/Services/InboundMail/InboundMailEngine.php b/app/Services/InboundMail/InboundMailEngine.php index b420a851f2..4fdad7dd26 100644 --- a/app/Services/InboundMail/InboundMailEngine.php +++ b/app/Services/InboundMail/InboundMailEngine.php @@ -30,12 +30,14 @@ use Illuminate\Queue\SerializesModels; class InboundMailEngine { - use SerializesModels, MakesHash; - use GeneratesCounter, SavesDocuments; + use SerializesModels; + use MakesHash; + use GeneratesCounter; + use SavesDocuments; private array $globalBlacklist; - private array $globalWhitelist; + private array $globalWhitelist; public function __construct(private Company $company) { @@ -49,8 +51,9 @@ class InboundMailEngine */ public function handleExpenseMailbox(InboundMail $email) { - if ($this->isInvalidOrBlocked($email->from, $email->to)) + if ($this->isInvalidOrBlocked($email->from, $email->to)) { return; + } // check if company plan matches requirements @@ -144,8 +147,9 @@ class InboundMailEngine //@todo - refactor public function saveMeta(string $from, string $to, bool $isUnknownRecipent = false) { - if(Ninja::isHosted()) + if (Ninja::isHosted()) { return; + } Cache::add('inboundMailCountSender:' . $from, 0, now()->addHours(12)); Cache::increment('inboundMailCountSender:' . $from); @@ -195,8 +199,9 @@ class InboundMailEngine $expense = (new ParseEDocument($document, $this->company))->run(); // check if expense was already matched within this job and skip if true - if (array_search($expense->id, $parsed_expense_ids)) + if (array_search($expense->id, $parsed_expense_ids)) { continue; + } array_push($parsed_expense_ids, $expense->id); @@ -212,36 +217,44 @@ class InboundMailEngine } // populate missing data with data from email - if (!$expense) + if (!$expense) { $expense = ExpenseFactory::create($this->company->id, $this->company->owner()->id); + } $is_imported_by_parser = array_search($expense->id, $parsed_expense_ids); - if ($is_imported_by_parser) + if ($is_imported_by_parser) { $expense->public_notes = $expense->public_notes . $email->subject; + } - if ($is_imported_by_parser) + if ($is_imported_by_parser) { $expense->private_notes = $expense->private_notes . $email->text_body; + } - if (!$expense->date) + if (!$expense->date) { $expense->date = $email->date; + } - if (!$expense->vendor_id && $expense_vendor) + if (!$expense->vendor_id && $expense_vendor) { $expense->vendor_id = $expense_vendor->id; + } - if ($is_imported_by_parser) + if ($is_imported_by_parser) { $expense->saveQuietly(); - else + } else { $expense->save(); + } // save document only, when not imported by parser $documents = []; - if (!$is_imported_by_parser) + if (!$is_imported_by_parser) { array_push($documents, $document); + } // email document - if ($email->body_document !== null) + if ($email->body_document !== null) { array_push($documents, $email->body_document); + } $this->saveDocuments($documents, $expense); @@ -252,8 +265,9 @@ class InboundMailEngine private function processHtmlBodyToDocument(InboundMail $email) { - if (!is_null($email->body)) + if (!is_null($email->body)) { $email->body_document = TempFile::UploadedFileFromRaw($email->body, "E-Mail.html", "text/html"); + } } private function validateExpenseSender(InboundMail $email) @@ -263,31 +277,39 @@ class InboundMailEngine // whitelists $whitelist = explode(",", $this->company->inbound_mailbox_whitelist); - if (is_array($whitelist) && in_array($email->from, $whitelist)) + if (is_array($whitelist) && in_array($email->from, $whitelist)) { return true; - if (is_array($whitelist) && in_array($domain, $whitelist)) + } + if (is_array($whitelist) && in_array($domain, $whitelist)) { return true; + } $blacklist = explode(",", $this->company->inbound_mailbox_blacklist); - if (is_array($blacklist) && in_array($email->from, $blacklist)) + if (is_array($blacklist) && in_array($email->from, $blacklist)) { return false; - if (is_array($blacklist) && in_array($domain, $blacklist)) + } + if (is_array($blacklist) && in_array($domain, $blacklist)) { return false; + } // allow unknown - if ($this->company->inbound_mailbox_allow_unknown) + if ($this->company->inbound_mailbox_allow_unknown) { return true; + } // own users - if ($this->company->inbound_mailbox_allow_company_users && $this->company->users()->where("email", $email->from)->exists()) + if ($this->company->inbound_mailbox_allow_company_users && $this->company->users()->where("email", $email->from)->exists()) { return true; + } // from vendors - if ($this->company->inbound_mailbox_allow_vendors && VendorContact::where("company_id", $this->company->id)->where("email", $email->from)->exists()) + if ($this->company->inbound_mailbox_allow_vendors && VendorContact::where("company_id", $this->company->id)->where("email", $email->from)->exists()) { return true; + } // from clients - if ($this->company->inbound_mailbox_allow_clients && ClientContact::where("company_id", $this->company->id)->where("email", $email->from)->exists()) + if ($this->company->inbound_mailbox_allow_clients && ClientContact::where("company_id", $this->company->id)->where("email", $email->from)->exists()) { return true; + } // denie return false; diff --git a/app/Services/Invoice/ApplyNumber.php b/app/Services/Invoice/ApplyNumber.php index ce238029ba..a7df2ddc17 100644 --- a/app/Services/Invoice/ApplyNumber.php +++ b/app/Services/Invoice/ApplyNumber.php @@ -74,7 +74,7 @@ class ApplyNumber extends AbstractService $this->invoice->saveQuietly(); $this->completed = false; - } catch(QueryException $e) { + } catch (QueryException $e) { $x++; if ($x > 50) { diff --git a/app/Services/Invoice/ApplyPaymentAmount.php b/app/Services/Invoice/ApplyPaymentAmount.php index 11241b09a0..ccbb5710c3 100644 --- a/app/Services/Invoice/ApplyPaymentAmount.php +++ b/app/Services/Invoice/ApplyPaymentAmount.php @@ -81,7 +81,7 @@ class ApplyPaymentAmount extends AbstractService $invoice_service->checkReminderStatus(); } - if($this->invoice->balance == 0) { + if ($this->invoice->balance == 0) { $this->invoice->next_send_date = null; } diff --git a/app/Services/Invoice/AutoBillInvoice.php b/app/Services/Invoice/AutoBillInvoice.php index 8612bed1a7..3c48082784 100644 --- a/app/Services/Invoice/AutoBillInvoice.php +++ b/app/Services/Invoice/AutoBillInvoice.php @@ -75,7 +75,7 @@ class AutoBillInvoice extends AbstractService $this->applyCreditPayment(); } - if($this->client->getSetting('use_unapplied_payment') != 'off') { + if ($this->client->getSetting('use_unapplied_payment') != 'off') { $this->applyUnappliedPayment(); } @@ -156,7 +156,7 @@ class AutoBillInvoice extends AbstractService ]); nlog("Payment hash created => {$payment_hash->id}"); - + $payment = false; try { $payment = $gateway_token->gateway @@ -180,9 +180,8 @@ class AutoBillInvoice extends AbstractService 'auto_bill_tries' => 0 ]); - } - else { - + } else { + \App\Models\Invoice::where('id', $this->invoice->id)->update([ 'auto_bill_tries' => $this->invoice->auto_bill_tries ]); @@ -276,7 +275,7 @@ class AutoBillInvoice extends AbstractService event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars())); //if we have paid the invoice in full using credits, then we need to fire the event - if($this->invoice->balance == 0) { + if ($this->invoice->balance == 0) { event(new InvoiceWasPaid($this->invoice, $payment, $payment->company, Ninja::eventVars())); } @@ -363,7 +362,7 @@ class AutoBillInvoice extends AbstractService } } - if((int)$this->invoice->balance == 0) { + if ((int)$this->invoice->balance == 0) { event(new InvoiceWasPaid($this->invoice, $payment, $payment->company, Ninja::eventVars())); return $this; } diff --git a/app/Services/Invoice/GenerateDeliveryNote.php b/app/Services/Invoice/GenerateDeliveryNote.php index 171cf89e78..769b3ff1ba 100644 --- a/app/Services/Invoice/GenerateDeliveryNote.php +++ b/app/Services/Invoice/GenerateDeliveryNote.php @@ -46,7 +46,7 @@ class GenerateDeliveryNote $delivery_note_design_id = $this->invoice->client->getSetting('delivery_note_design_id'); $design = Design::withTrashed()->find($this->decodePrimaryKey($delivery_note_design_id)); - if($design && $design->is_template) { + if ($design && $design->is_template) { $ts = new TemplateService($design); diff --git a/app/Services/Invoice/InvoiceService.php b/app/Services/Invoice/InvoiceService.php index a012dba324..2d695e030e 100644 --- a/app/Services/Invoice/InvoiceService.php +++ b/app/Services/Invoice/InvoiceService.php @@ -109,7 +109,7 @@ class InvoiceService /** * Apply a payment amount to an invoice. - * + * * *** does not create a paymentable **** * @param Payment $payment The Payment * @param float $payment_amount The Payment amount @@ -315,11 +315,11 @@ class InvoiceService public function checkReminderStatus(): self { - if($this->invoice->partial == 0) { + if ($this->invoice->partial == 0) { $this->invoice->partial_due_date = null; } - if($this->invoice->partial == 0 && $this->invoice->balance > 0) { + if ($this->invoice->partial == 0 && $this->invoice->balance > 0) { $this->invoice->reminder1_sent = null; $this->invoice->reminder2_sent = null; $this->invoice->reminder3_sent = null; @@ -449,7 +449,7 @@ class InvoiceService $items = collect((array)$this->invoice->line_items) ->filter(function ($item) { return $item->type_id != '3'; - })->toArray(); + })->toArray(); $this->invoice->line_items = array_values($items); @@ -631,7 +631,7 @@ class InvoiceService $sub_id = $this->decodePrimaryKey($subscription_id); - if(Subscription::withTrashed()->where('id', $sub_id)->where('company_id', $this->invoice->company_id)->exists()) { + if (Subscription::withTrashed()->where('id', $sub_id)->where('company_id', $this->invoice->company_id)->exists()) { $this->invoice->subscription_id = $sub_id; } diff --git a/app/Services/Invoice/MarkInvoiceDeleted.php b/app/Services/Invoice/MarkInvoiceDeleted.php index 6614fba2e9..e34790321a 100644 --- a/app/Services/Invoice/MarkInvoiceDeleted.php +++ b/app/Services/Invoice/MarkInvoiceDeleted.php @@ -61,12 +61,12 @@ class MarkInvoiceDeleted extends AbstractService private function adjustPaidToDateAndBalance() { - + $this->invoice ->client ->service() ->updateBalanceAndPaidToDate($this->balance_adjustment * -1, $this->adjustment_amount * -1) - ->save(); + ->save(); return $this; } @@ -186,7 +186,7 @@ class MarkInvoiceDeleted extends AbstractService private function triggeredActions(): self { - if($this->invoice->quote) { + if ($this->invoice->quote) { $this->invoice->quote->invoice_id = null; $this->invoice->quote->status_id = Quote::STATUS_SENT; $this->invoice->pushQuietly(); diff --git a/app/Services/Invoice/TriggeredActions.php b/app/Services/Invoice/TriggeredActions.php index 08e60708c6..a47d277c96 100644 --- a/app/Services/Invoice/TriggeredActions.php +++ b/app/Services/Invoice/TriggeredActions.php @@ -35,7 +35,7 @@ class TriggeredActions extends AbstractService if ($this->request->has('auto_bill') && $this->request->input('auto_bill') == 'true') { try { $this->invoice->service()->autoBill(); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: TriggeredActions::" . $e->getMessage()); } //update notification sends automatically for this. } diff --git a/app/Services/Ledger/LedgerService.php b/app/Services/Ledger/LedgerService.php index c2d60c3964..565650b8ff 100644 --- a/app/Services/Ledger/LedgerService.php +++ b/app/Services/Ledger/LedgerService.php @@ -44,7 +44,7 @@ class LedgerService public function updateInvoiceBalance($adjustment, $notes = '') { - if($adjustment == 0) { + if ($adjustment == 0) { return $this; } diff --git a/app/Services/Payment/DeletePayment.php b/app/Services/Payment/DeletePayment.php index 938853c00a..3a63110f20 100644 --- a/app/Services/Payment/DeletePayment.php +++ b/app/Services/Payment/DeletePayment.php @@ -94,11 +94,11 @@ class DeletePayment nlog("net deletable amount - refunded = {$net_deletable}"); - if($paymentable_invoice->status_id == Invoice::STATUS_CANCELLED){ - + if ($paymentable_invoice->status_id == Invoice::STATUS_CANCELLED) { + $is_trashed = false; - if($paymentable_invoice->trashed()){ + if ($paymentable_invoice->trashed()) { $is_trashed = true; $paymentable_invoice->restore(); } @@ -106,19 +106,18 @@ class DeletePayment $paymentable_invoice->service() ->updatePaidToDate($net_deletable * -1) ->save(); - + $this->payment ->client ->service() ->updatePaidToDate($net_deletable * -1) ->save(); - if($is_trashed){ + if ($is_trashed) { $paymentable_invoice->delete(); } - } - elseif (! $paymentable_invoice->is_deleted) { + } elseif (! $paymentable_invoice->is_deleted) { $paymentable_invoice->restore(); $paymentable_invoice->service() @@ -139,7 +138,7 @@ class DeletePayment if ($paymentable_invoice->balance == $paymentable_invoice->amount) { $paymentable_invoice->service()->setStatus(Invoice::STATUS_SENT)->save(); - } elseif($paymentable_invoice->balance == 0) { + } elseif ($paymentable_invoice->balance == 0) { $paymentable_invoice->service()->setStatus(Invoice::STATUS_PAID)->save(); } else { $paymentable_invoice->service()->setStatus(Invoice::STATUS_PARTIAL)->save(); @@ -159,7 +158,7 @@ class DeletePayment if ($this->update_client_paid_to_date) { $reduced_paid_to_date = $this->payment->amount < 0 ? $this->payment->amount * -1 : min(0, ($this->payment->amount - $this->payment->refunded - $this->_paid_to_date_deleted) * -1); - + // $reduced_paid_to_date = min(0, ($this->payment->amount - $this->payment->refunded - $this->_paid_to_date_deleted) * -1); $this->payment diff --git a/app/Services/Payment/RefundPayment.php b/app/Services/Payment/RefundPayment.php index bb1bc65fcb..a5bf14e66c 100644 --- a/app/Services/Payment/RefundPayment.php +++ b/app/Services/Payment/RefundPayment.php @@ -62,7 +62,7 @@ class RefundPayment private function finalize(): self { - if($this->refund_failed) { + if ($this->refund_failed) { throw new PaymentRefundFailed($this->refund_failed_message); } @@ -94,11 +94,11 @@ class RefundPayment if ($this->payment->company_gateway) { $response = $this->payment->company_gateway->driver($this->payment->client)->refund($this->payment, $net_refund); - if($response['amount'] ?? false) { + if ($response['amount'] ?? false) { $net_refund = $response['amount']; } - if($response['voided'] ?? false) { + if ($response['voided'] ?? false) { //When a transaction is voided - all invoices attached to the payment need to be reversed, this //block prevents the edge case where a partial refund was attempted. $this->refund_data['invoices'] = $this->payment->invoices->map(function ($invoice) { diff --git a/app/Services/Payment/SendEmail.php b/app/Services/Payment/SendEmail.php index 35937e6e94..7c413e8b55 100644 --- a/app/Services/Payment/SendEmail.php +++ b/app/Services/Payment/SendEmail.php @@ -31,7 +31,7 @@ class SendEmail if (!$this->contact) { - if($invoice = $this->payment->invoices->first() ?? false) { + if ($invoice = $this->payment->invoices->first() ?? false) { $invitation = $invoice @@ -41,7 +41,7 @@ class SendEmail }) ->first(); - if($invitation) { + if ($invitation) { $this->contact = $invitation->contact; } else { $this->contact = $this->payment->client->contacts()->orderBy('send_email', 'desc')->orderBy('is_primary', 'desc')->first(); diff --git a/app/Services/Payment/UpdateInvoicePayment.php b/app/Services/Payment/UpdateInvoicePayment.php index a3a6ace964..a13444729e 100644 --- a/app/Services/Payment/UpdateInvoicePayment.php +++ b/app/Services/Payment/UpdateInvoicePayment.php @@ -95,15 +95,15 @@ class UpdateInvoicePayment if (property_exists($this->payment_hash->data, 'pre_payment') && $this->payment_hash->data->pre_payment == "1") { $invoice->payments()->each(function ($p) { $p->pivot->forceDelete(); - $p->invoices()->each(function ($i){ + $p->invoices()->each(function ($i) { $i->pivot->forceDelete(); }); }); - + $invoice ->ledger() - ->updateInvoiceBalance($paid_amount*-1, "Prepayment Balance Adjustment"); + ->updateInvoiceBalance($paid_amount * -1, "Prepayment Balance Adjustment"); $invoice->is_deleted = true; $invoice->deleted_at = now(); diff --git a/app/Services/Pdf/PdfBuilder.php b/app/Services/Pdf/PdfBuilder.php index 6e9c174d80..f1fd3e54ac 100644 --- a/app/Services/Pdf/PdfBuilder.php +++ b/app/Services/Pdf/PdfBuilder.php @@ -133,7 +133,7 @@ class PdfBuilder } - foreach($contents as $key => $content) { + foreach ($contents as $key => $content) { $content->parentNode->replaceChild($replacements[$key], $content); } @@ -367,15 +367,15 @@ class PdfBuilder $this->payment_amount_total += $payment->pivot->amount; - if($payment->pivot->refunded > 0){ + if ($payment->pivot->refunded > 0) { $refund_date = $payment->date; - if($payment->refund_meta && is_array($payment->refund_meta)){ + if ($payment->refund_meta && is_array($payment->refund_meta)) { + + $refund_array = collect($payment->refund_meta)->first(function ($meta) use ($invoice) { + foreach ($meta['invoices'] as $refunded_invoice) { - $refund_array = collect($payment->refund_meta)->first(function ($meta) use($invoice){ - foreach($meta['invoices'] as $refunded_invoice){ - if ($refunded_invoice['invoice_id'] == $invoice->id) { return true; } @@ -431,9 +431,9 @@ class PdfBuilder ]; } - public function statementUnappliedPaymentTableTotals():array + public function statementUnappliedPaymentTableTotals(): array { - + if (is_null($this->service->options['unapplied']) || !$this->service->options['unapplied']->first()) { return []; } @@ -486,10 +486,10 @@ class PdfBuilder $tbody[] = $element; - $this->unapplied_total += round($unapplied_payment->amount - $unapplied_payment->applied,2); + $this->unapplied_total += round($unapplied_payment->amount - $unapplied_payment->applied, 2); } - + return [ ['element' => 'thead', 'elements' => $this->buildTableHeader('statement_unapplied')], ['element' => 'tbody', 'elements' => $tbody], diff --git a/app/Services/Pdf/PdfConfiguration.php b/app/Services/Pdf/PdfConfiguration.php index ac6c7a43e7..86e7c9a810 100644 --- a/app/Services/Pdf/PdfConfiguration.php +++ b/app/Services/Pdf/PdfConfiguration.php @@ -406,7 +406,7 @@ class PdfConfiguration } //04-04-2023 if currency = JPY override precision to 0 - if($this->currency->code == 'JPY') { + if ($this->currency->code == 'JPY') { $precision = 0; } diff --git a/app/Services/Pdf/PdfMock.php b/app/Services/Pdf/PdfMock.php index 1bfc5f87f7..7d223becb6 100644 --- a/app/Services/Pdf/PdfMock.php +++ b/app/Services/Pdf/PdfMock.php @@ -68,7 +68,7 @@ class PdfMock $pdf_config->setCountry(Country::find($this->settings->country_id ?: 840)); $pdf_config->currency_entity = $this->mock->client ?? $this->mock->vendor; - if(isset($this->request['design_id']) && $design = Design::withTrashed()->find($this->request['design_id'])) { + if (isset($this->request['design_id']) && $design = Design::withTrashed()->find($this->request['design_id'])) { $pdf_config->design = $design; $pdf_config->entity_design_id = $design->hashed_id; } else { @@ -77,7 +77,7 @@ class PdfMock $pdf_service->config = $pdf_config; - if(isset($this->request['design'])) { + if (isset($this->request['design'])) { $pdf_designer = (new PdfDesigner($pdf_service))->buildFromPartials($this->request['design']); } else { $pdf_designer = (new PdfDesigner($pdf_service))->build(); diff --git a/app/Services/Pdf/PdfService.php b/app/Services/Pdf/PdfService.php index 85d115e8a4..8124f7ccd7 100644 --- a/app/Services/Pdf/PdfService.php +++ b/app/Services/Pdf/PdfService.php @@ -97,7 +97,7 @@ class PdfService $pdf = $numbered_pdf; } - if($this->config->entity_string == "invoice" && $this->config->settings->enable_e_invoice) { + if ($this->config->entity_string == "invoice" && $this->config->settings->enable_e_invoice) { $pdf = $this->checkEInvoice($pdf); } @@ -180,7 +180,7 @@ class PdfService */ private function checkEInvoice(string $pdf): string { - if(!$this->config->entity instanceof Invoice) { + if (!$this->config->entity instanceof Invoice) { return $pdf; } diff --git a/app/Services/PdfMaker/Design.php b/app/Services/PdfMaker/Design.php index dfff058d61..1f62dd50e1 100644 --- a/app/Services/PdfMaker/Design.php +++ b/app/Services/PdfMaker/Design.php @@ -383,7 +383,7 @@ class Design extends BaseDesign return !in_array($m, ['$invoice.balance_due', '$invoice.total', '$invoice.amount']); }); } - + foreach ($variables as $variable) { $_variable = explode('.', $variable)[1]; $_customs = ['custom1', 'custom2', 'custom3', 'custom4']; @@ -403,7 +403,7 @@ class Design extends BaseDesign ]]; } } - + return $elements; } @@ -528,7 +528,7 @@ class Design extends BaseDesign public function statementInvoiceTableTotals(): array { - + if ($this->type !== self::STATEMENT) { return []; } @@ -574,23 +574,23 @@ class Design extends BaseDesign $tbody[] = $element; $this->payment_amount_total += $payment->pivot->amount; - + if ($payment->pivot->refunded > 0) { $refund_date = $payment->date; - if($payment->refund_meta && is_array($payment->refund_meta)){ + if ($payment->refund_meta && is_array($payment->refund_meta)) { + + $refund_array = collect($payment->refund_meta)->first(function ($meta) use ($invoice) { + foreach ($meta['invoices'] as $refunded_invoice) { - $refund_array = collect($payment->refund_meta)->first(function ($meta) use($invoice){ - foreach($meta['invoices'] as $refunded_invoice){ - if ($refunded_invoice['invoice_id'] == $invoice->id) { return true; } } }); - + $refund_date = $refund_array['date']; } @@ -605,8 +605,8 @@ class Design extends BaseDesign $this->payment_amount_total -= $payment->pivot->refunded; } - - } + + } } @@ -687,9 +687,9 @@ class Design extends BaseDesign ]; } - public function statementUnappliedPaymentTableTotals():array + public function statementUnappliedPaymentTableTotals(): array { - + if (is_null($this->unapplied_payments) || !$this->unapplied_payments->first() || $this->type !== self::STATEMENT) { return []; } @@ -713,7 +713,7 @@ class Design extends BaseDesign */ public function statementUnappliedPaymentTable(): array { - + if (is_null($this->unapplied_payments) && $this->type !== self::STATEMENT) { return []; } @@ -727,8 +727,8 @@ class Design extends BaseDesign //24-03-2022 show payments per invoice foreach ($this->unapplied_payments as $unapplied_payment) { if ($unapplied_payment->is_deleted) { - continue; - } + continue; + } $element = ['element' => 'tr', 'elements' => []]; $element['elements'][] = ['element' => 'td', 'content' => $unapplied_payment->number]; diff --git a/app/Services/PdfMaker/Designs/Utilities/DesignHelpers.php b/app/Services/PdfMaker/Designs/Utilities/DesignHelpers.php index 3683b1aef2..fc76681a4f 100644 --- a/app/Services/PdfMaker/Designs/Utilities/DesignHelpers.php +++ b/app/Services/PdfMaker/Designs/Utilities/DesignHelpers.php @@ -54,7 +54,7 @@ trait DesignHelpers $this->payments = $this->context['payments']; } - if(isset($this->context['unapplied'])){ + if (isset($this->context['unapplied'])) { $this->unapplied_payments = $this->context['unapplied']; } diff --git a/app/Services/PdfMaker/PdfMaker.php b/app/Services/PdfMaker/PdfMaker.php index c251c3a1da..269fb1aedc 100644 --- a/app/Services/PdfMaker/PdfMaker.php +++ b/app/Services/PdfMaker/PdfMaker.php @@ -65,29 +65,29 @@ class PdfMaker $this->updateElementProperties($this->data['template']); } - if(isset($this->options)) { + if (isset($this->options)) { $replacements = []; $contents = $this->document->getElementsByTagName('ninja'); $ts = new TemplateService(); - if(isset($this->options['client'])) { + if (isset($this->options['client'])) { $client = $this->options['client']; try { $ts->setCompany($client->company); $ts->addGlobal(['currency_code' => $client->company->currency()->code]); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog($e->getMessage()); } } - if(isset($this->options['vendor'])) { + if (isset($this->options['vendor'])) { $vendor = $this->options['vendor']; try { $ts->setCompany($vendor->company); $ts->addGlobal(['currency_code' => $vendor->company->currency()->code]); - } catch(\Exception $e) { + } catch (\Exception $e) { nlog($e->getMessage()); } } @@ -108,7 +108,7 @@ class PdfMaker } - foreach($contents as $key => $content) { + foreach ($contents as $key => $content) { $content->parentNode->replaceChild($replacements[$key], $content); } diff --git a/app/Services/PurchaseOrder/CreateInvitations.php b/app/Services/PurchaseOrder/CreateInvitations.php index d10e1f0cc0..74457fb834 100644 --- a/app/Services/PurchaseOrder/CreateInvitations.php +++ b/app/Services/PurchaseOrder/CreateInvitations.php @@ -42,7 +42,7 @@ class CreateInvitations extends AbstractService public function run() { - if(!$this->purchase_order->vendor) { + if (!$this->purchase_order->vendor) { return $this->purchase_order; } diff --git a/app/Services/PurchaseOrder/PurchaseOrderExpense.php b/app/Services/PurchaseOrder/PurchaseOrderExpense.php index 80a43bc07f..edef897e48 100644 --- a/app/Services/PurchaseOrder/PurchaseOrderExpense.php +++ b/app/Services/PurchaseOrder/PurchaseOrderExpense.php @@ -57,10 +57,10 @@ class PurchaseOrderExpense $expense->number = empty($expense->number) ? $this->getNextExpenseNumber($expense) : $expense->number; - if($this->purchase_order->project_id) { + if ($this->purchase_order->project_id) { $expense->project_id = $this->purchase_order->project_id; $expense->client_id = $this->purchase_order->project->client_id; - } elseif($this->purchase_order->client_id) { + } elseif ($this->purchase_order->client_id) { $expense->client_id = $this->purchase_order->client_id; } diff --git a/app/Services/Quickbooks/Jobs/QuickbooksImport.php b/app/Services/Quickbooks/Jobs/QuickbooksImport.php index 140bbbb370..7c4b8870bb 100644 --- a/app/Services/Quickbooks/Jobs/QuickbooksImport.php +++ b/app/Services/Quickbooks/Jobs/QuickbooksImport.php @@ -77,14 +77,14 @@ class QuickbooksImport implements ShouldQueue public function handle() { MultiDB::setDb($this->db); - + $this->company = Company::query()->find($this->company_id); $this->qbs = new QuickbooksService($this->company); $this->settings = $this->company->quickbooks->settings; - - foreach($this->entities as $key => $entity) { - - if(!$this->qbs->syncable($key, \App\Enum\SyncDirection::PULL)) { + + foreach ($this->entities as $key => $entity) { + + if (!$this->qbs->syncable($key, \App\Enum\SyncDirection::PULL)) { nlog('skipping ' . $key); continue; } @@ -96,7 +96,7 @@ class QuickbooksImport implements ShouldQueue } } - + /** * Processes the sync for a given entity * @@ -104,29 +104,29 @@ class QuickbooksImport implements ShouldQueue * @param mixed $records * @return void */ - private function processEntitySync(string $entity, $records): void + private function processEntitySync(string $entity, $records): void { - match($entity){ + match($entity) { 'client' => $this->qbs->client->syncToNinja($records), 'product' => $this->qbs->product->syncToNinja($records), - 'invoice' => $this->qbs->invoice->syncToNinja($records), - 'sales' => $this->qbs->invoice->syncToNinja($records), - // 'vendor' => $this->syncQbToNinjaVendors($records), - // 'quote' => $this->syncInvoices($records), - // 'expense' => $this->syncQbToNinjaExpenses($records), - // 'purchase_order' => $this->syncInvoices($records), - // 'payment' => $this->syncPayment($records), + 'invoice' => $this->qbs->invoice->syncToNinja($records), + 'sales' => $this->qbs->invoice->syncToNinja($records), + // 'vendor' => $this->syncQbToNinjaVendors($records), + // 'quote' => $this->syncInvoices($records), + // 'expense' => $this->syncQbToNinjaExpenses($records), + // 'purchase_order' => $this->syncInvoices($records), + // 'payment' => $this->syncPayment($records), default => false, }; } // private function syncQbToNinjaInvoices($records): void // { - + // } - + // private function syncQbToNinjaVendors(array $records): void // { @@ -151,7 +151,7 @@ class QuickbooksImport implements ShouldQueue // $contact->send_email = true; // $contact->is_primary = true; // $contact->fill($ninja_data[1]); - // $contact->saveQuietly(); + // $contact->saveQuietly(); // } // elseif($this->qbs->syncable('vendor', \App\Enum\SyncDirection::PULL)){ // $contact->fill($ninja_data[1]); @@ -189,14 +189,14 @@ class QuickbooksImport implements ShouldQueue // ->withTrashed() // ->where('company_id', $this->company->id) // ->where('number', $expense['number']); - + // if($search->count() == 0) { // return ExpenseFactory::create($this->company->id, $this->company->owner()->id); // } // elseif($search->count() == 1) { // return $this->qbs->syncable('expense', \App\Enum\SyncDirection::PULL) ? $search->first() : null; // } - + // return null; // } @@ -218,7 +218,7 @@ class QuickbooksImport implements ShouldQueue // }); // }); - + // if($search->count() == 0) { // //new client // return VendorFactory::create($this->company->id, $this->company->owner()->id); @@ -227,7 +227,7 @@ class QuickbooksImport implements ShouldQueue // return $this->qbs->syncable('vendor', \App\Enum\SyncDirection::PULL) ? $search->first() : null; // } - + // return null; // } diff --git a/app/Services/Quickbooks/Models/QbClient.php b/app/Services/Quickbooks/Models/QbClient.php index 9ea3f6d90b..1c2226d455 100644 --- a/app/Services/Quickbooks/Models/QbClient.php +++ b/app/Services/Quickbooks/Models/QbClient.php @@ -39,13 +39,13 @@ class QbClient implements SyncInterface $ninja_data = $transformer->qbToNinja($record); - if($ninja_data[0]['terms']){ + if ($ninja_data[0]['terms']) { $days = $this->service->findEntityById('Term', $ninja_data[0]['terms']); nlog($days); - if($days){ + if ($days) { $ninja_data[0]['settings']->payment_terms = (string)$days->DueDays; } @@ -60,16 +60,14 @@ class QbClient implements SyncInterface $contact = $client->contacts()->where('email', $ninja_data[1]['email'])->first(); - if(!$contact) - { + if (!$contact) { $contact = ClientContactFactory::create($this->service->company->id, $this->service->company->owner()->id); $contact->client_id = $client->id; $contact->send_email = true; $contact->is_primary = true; $contact->fill($ninja_data[1]); $contact->saveQuietly(); - } - elseif($this->service->syncable('client', \App\Enum\SyncDirection::PULL)){ + } elseif ($this->service->syncable('client', \App\Enum\SyncDirection::PULL)) { $contact->fill($ninja_data[1]); $contact->saveQuietly(); } @@ -98,7 +96,7 @@ class QbClient implements SyncInterface if ($search->count() == 0) { $client = ClientFactory::create($this->service->company->id, $this->service->company->owner()->id); - + $sync = new ClientSync(); $sync->qb_id = $key; $client->sync = $sync; diff --git a/app/Services/Quickbooks/Models/QbInvoice.php b/app/Services/Quickbooks/Models/QbInvoice.php index 52253fccc4..1bec3b3b54 100644 --- a/app/Services/Quickbooks/Models/QbInvoice.php +++ b/app/Services/Quickbooks/Models/QbInvoice.php @@ -26,7 +26,7 @@ class QbInvoice implements SyncInterface protected InvoiceTransformer $invoice_transformer; protected InvoiceRepository $invoice_repository; - + public function __construct(public QuickbooksService $service) { $this->invoice_transformer = new InvoiceTransformer($this->service->company); @@ -40,10 +40,10 @@ class QbInvoice implements SyncInterface public function syncToNinja(array $records): void { - + foreach ($records as $record) { - $this->syncNinjaInvoice($record); + $this->syncNinjaInvoice($record); } @@ -59,14 +59,12 @@ class QbInvoice implements SyncInterface $current_ninja_invoice_balance = $invoice->balance; $qb_invoice_balance = $ninja_invoice_data['balance']; - if(floatval($current_ninja_invoice_balance) == floatval($qb_invoice_balance)) - { + if (floatval($current_ninja_invoice_balance) == floatval($qb_invoice_balance)) { nlog('Invoice balance is the same, skipping update of line items'); unset($ninja_invoice_data['line_items']); $invoice->fill($ninja_invoice_data); $invoice->saveQuietly(); - } - else{ + } else { nlog('Invoice balance is different, updating line items'); $this->invoice_repository->save($ninja_invoice_data, $invoice); } @@ -79,7 +77,7 @@ class QbInvoice implements SyncInterface ->where('company_id', $this->service->company->id) ->where('sync->qb_id', $id); - if($search->count() == 0) { + if ($search->count() == 0) { $invoice = InvoiceFactory::create($this->service->company->id, $this->service->company->owner()->id); $invoice->client_id = (int)$client_id; @@ -88,7 +86,7 @@ class QbInvoice implements SyncInterface $invoice->sync = $sync; return $invoice; - } elseif($search->count() == 1) { + } elseif ($search->count() == 1) { return $this->service->syncable('invoice', \App\Enum\SyncDirection::PULL) ? $search->first() : null; } @@ -103,35 +101,31 @@ class QbInvoice implements SyncInterface nlog($qb_record); - if($this->service->syncable('invoice', \App\Enum\SyncDirection::PULL)) - { + if ($this->service->syncable('invoice', \App\Enum\SyncDirection::PULL)) { $invoice = $this->findInvoice($id); nlog("Comparing QB last updated: " . $last_updated); nlog("Comparing Ninja last updated: " . $invoice->updated_at); - if(data_get($qb_record, 'TxnStatus') === 'Voided') - { + if (data_get($qb_record, 'TxnStatus') === 'Voided') { $this->delete($id); return; } - if(!$invoice->id){ + if (!$invoice->id) { $this->syncNinjaInvoice($qb_record); - } - elseif(Carbon::parse($last_updated)->gt(Carbon::parse($invoice->updated_at)) || $qb_record->SyncToken == '0') - { + } elseif (Carbon::parse($last_updated)->gt(Carbon::parse($invoice->updated_at)) || $qb_record->SyncToken == '0') { $ninja_invoice_data = $this->invoice_transformer->qbToNinja($qb_record); nlog($ninja_invoice_data); - + $this->invoice_repository->save($ninja_invoice_data, $invoice); } } } - + /** * syncNinjaInvoice * @@ -144,7 +138,7 @@ class QbInvoice implements SyncInterface $ninja_invoice_data = $this->invoice_transformer->qbToNinja($record); nlog($ninja_invoice_data); - + $payment_ids = $ninja_invoice_data['payment_ids'] ?? []; $client_id = $ninja_invoice_data['client_id'] ?? null; @@ -211,8 +205,7 @@ class QbInvoice implements SyncInterface { $qb_record = $this->find($id); - if($this->service->syncable('invoice', \App\Enum\SyncDirection::PULL) && $invoice = $this->findInvoice($id)) - { + if ($this->service->syncable('invoice', \App\Enum\SyncDirection::PULL) && $invoice = $this->findInvoice($id)) { $invoice->sync = null; $invoice->saveQuietly(); $this->invoice_repository->delete($invoice); diff --git a/app/Services/Quickbooks/Models/QbProduct.php b/app/Services/Quickbooks/Models/QbProduct.php index 0857185462..2ae27144aa 100644 --- a/app/Services/Quickbooks/Models/QbProduct.php +++ b/app/Services/Quickbooks/Models/QbProduct.php @@ -19,14 +19,13 @@ use App\Interfaces\SyncInterface; use App\Services\Quickbooks\QuickbooksService; use App\Services\Quickbooks\Transformers\ProductTransformer; - class QbProduct implements SyncInterface { protected ProductTransformer $product_transformer; public function __construct(public QuickbooksService $service) { - + $this->product_transformer = new ProductTransformer($service->company); } @@ -38,7 +37,7 @@ class QbProduct implements SyncInterface public function syncToNinja(array $records): void { - + foreach ($records as $record) { $ninja_data = $this->product_transformer->qbToNinja($record); @@ -61,18 +60,18 @@ class QbProduct implements SyncInterface ->withTrashed() ->where('company_id', $this->service->company->id) ->where('sync->qb_id', $key); - - if($search->count() == 0) { - + + if ($search->count() == 0) { + $product = ProductFactory::create($this->service->company->id, $this->service->company->owner()->id); $sync = new ProductSync(); $sync->qb_id = $key; $product->sync = $sync; - + return $product; - } elseif($search->count() == 1) { + } elseif ($search->count() == 1) { return $this->service->syncable('product', \App\Enum\SyncDirection::PULL) ? $search->first() : null; } @@ -84,13 +83,11 @@ class QbProduct implements SyncInterface { $qb_record = $this->find($id); - if($this->service->syncable('product', \App\Enum\SyncDirection::PULL) && $ninja_record = $this->findProduct($id)) - { + if ($this->service->syncable('product', \App\Enum\SyncDirection::PULL) && $ninja_record = $this->findProduct($id)) { - if(Carbon::parse($last_updated) > Carbon::parse($ninja_record->updated_at)) - { + if (Carbon::parse($last_updated) > Carbon::parse($ninja_record->updated_at)) { $ninja_data = $this->product_transformer->qbToNinja($qb_record); - + $ninja_record->fill($ninja_data); $ninja_record->save(); @@ -99,4 +96,4 @@ class QbProduct implements SyncInterface } } -} \ No newline at end of file +} diff --git a/app/Services/Quickbooks/QuickbooksService.php b/app/Services/Quickbooks/QuickbooksService.php index 9b3c897e23..bc66fbc6e7 100644 --- a/app/Services/Quickbooks/QuickbooksService.php +++ b/app/Services/Quickbooks/QuickbooksService.php @@ -61,11 +61,11 @@ class QuickbooksService 'auth_mode' => 'oauth2', 'scope' => "com.intuit.quickbooks.accounting", 'RedirectURI' => $this->testMode ? 'https://grok.romulus.com.au/quickbooks/authorized' : 'https://invoicing.co/quickbooks/authorized', - 'baseUrl' => $this->testMode ? CoreConstants::SANDBOX_DEVELOPMENT : CoreConstants::QBO_BASEURL, + 'baseUrl' => $this->testMode ? CoreConstants::SANDBOX_DEVELOPMENT : CoreConstants::QBO_BASEURL, ]; $merged = array_merge($config, $this->ninjaAccessToken()); - + $this->sdk = DataService::Configure($merged); // $this->sdk->setLogLocation(storage_path("logs/quickbooks.log")); @@ -77,13 +77,13 @@ class QuickbooksService $this->checkToken(); $this->invoice = new QbInvoice($this); - + $this->product = new QbProduct($this); $this->client = new QbClient($this); $this->settings = $this->company->quickbooks->settings; - + $this->checkDefaultAccounts(); return $this; @@ -94,7 +94,7 @@ class QuickbooksService $accountQuery = "SELECT * FROM Account WHERE AccountType IN ('Income', 'Cost of Goods Sold')"; - if(strlen($this->settings->default_income_account) == 0 || strlen($this->settings->default_expense_account) == 0){ + if (strlen($this->settings->default_income_account) == 0 || strlen($this->settings->default_expense_account) == 0) { nlog("Checking default accounts for company {$this->company->company_key}"); $accounts = $this->sdk->Query($accountQuery); @@ -103,7 +103,7 @@ class QuickbooksService $find_income_account = true; $find_expense_account = true; - + foreach ($accounts as $account) { if ($account->AccountType->value == 'Income' && $find_income_account) { $this->settings->default_income_account = $account->Id->value; @@ -119,7 +119,7 @@ class QuickbooksService $this->company->quickbooks->settings = $this->settings; $this->company->save(); } - + return $this; } @@ -127,10 +127,11 @@ class QuickbooksService private function checkToken(): self { - if($this->company->quickbooks->accessTokenExpiresAt == 0 || $this->company->quickbooks->accessTokenExpiresAt > time()) + if ($this->company->quickbooks->accessTokenExpiresAt == 0 || $this->company->quickbooks->accessTokenExpiresAt > time()) { return $this; + } - if($this->company->quickbooks->accessTokenExpiresAt && $this->company->quickbooks->accessTokenExpiresAt < time() && $this->try_refresh){ + if ($this->company->quickbooks->accessTokenExpiresAt && $this->company->quickbooks->accessTokenExpiresAt < time() && $this->try_refresh) { $this->sdk()->refreshToken($this->company->quickbooks->refresh_token); $this->company = $this->company->fresh(); $this->try_refresh = false; @@ -157,9 +158,9 @@ class QuickbooksService { return new SdkWrapper($this->sdk, $this->company); } - + /** - * + * * * @return void */ @@ -177,7 +178,7 @@ class QuickbooksService { return $this->sdk->Query($query); } - + /** * Flag to determine if a sync is allowed in either direction * diff --git a/app/Services/Quickbooks/SdkWrapper.php b/app/Services/Quickbooks/SdkWrapper.php index 2fb7e688ac..230a809259 100644 --- a/app/Services/Quickbooks/SdkWrapper.php +++ b/app/Services/Quickbooks/SdkWrapper.php @@ -32,7 +32,7 @@ class SdkWrapper private function init(): self { - + $this->setNinjaAccessToken($this->company->quickbooks); return $this; @@ -53,7 +53,7 @@ class SdkWrapper { return $this->accessToken()->getRefreshToken(); } - + public function company() { return $this->sdk->getCompanyInfo(); @@ -79,7 +79,7 @@ class SdkWrapper return $this->accessToken(); } - + /** * Set Stored NinjaAccessToken * @@ -104,13 +104,13 @@ class SdkWrapper $this->setAccessToken($token); - if($token_object->accessTokenExpiresAt != 0 && $token_object->accessTokenExpiresAt < time()){ + if ($token_object->accessTokenExpiresAt != 0 && $token_object->accessTokenExpiresAt < time()) { $this->refreshToken($token_object->refresh_token); } - + return $this; } - + public function refreshToken(string $refresh_token): self { @@ -169,14 +169,14 @@ class SdkWrapper } public function fetchById(string $entity, $id) - { + { return $this->sdk->FindById($entity, $id); } public function fetchRecords(string $entity, int $max = 100000): array { - if(!in_array($entity, $this->entities)) { + if (!in_array($entity, $this->entities)) { return []; } @@ -193,7 +193,7 @@ class SdkWrapper $limit = min(self::MAXRESULTS, $total - $start); $recordsChunk = $this->queryData("select * from $entity", $start, $limit); - if(empty($recordsChunk)) { + if (empty($recordsChunk)) { break; } @@ -201,7 +201,7 @@ class SdkWrapper $start += $limit; } while ($start < $total); - if(empty($records)) { + if (empty($records)) { throw new \Exception("No records retrieved!"); } diff --git a/app/Services/Quickbooks/Transformers/BaseTransformer.php b/app/Services/Quickbooks/Transformers/BaseTransformer.php index bc5639438f..1d559b2a3c 100644 --- a/app/Services/Quickbooks/Transformers/BaseTransformer.php +++ b/app/Services/Quickbooks/Transformers/BaseTransformer.php @@ -21,7 +21,6 @@ use App\Models\Company; */ class BaseTransformer { - public function __construct(public Company $company) { } @@ -29,25 +28,25 @@ class BaseTransformer public function resolveCountry(string $iso_3_code): string { /** @var \App\Models\Country $country */ - $country = app('countries')->first(function ($c) use ($iso_3_code){ - + $country = app('countries')->first(function ($c) use ($iso_3_code) { + /** @var \App\Models\Country $c */ return $c->iso_3166_3 == $iso_3_code || $c->name == $iso_3_code; }); - + return $country ? (string) $country->id : $this->company->settings->country_id; } public function resolveCurrency(string $currency_code): string { - + /** @var \App\Models\Currency $currency */ - $currency = app('currencies')->first(function($c) use ($currency_code){ - + $currency = app('currencies')->first(function ($c) use ($currency_code) { + /** @var \App\Models\Currency $c */ return $c->code == $currency_code; }); - + return $currency ? (string) $currency->id : $this->company->settings->currency_id; } @@ -80,7 +79,7 @@ class BaseTransformer ->where('company_id', $this->company->id) ->where('number', $customer_reference_id) ->first(); - + return $vendor ? $vendor->id : null; } } diff --git a/app/Services/Quickbooks/Transformers/ClientTransformer.php b/app/Services/Quickbooks/Transformers/ClientTransformer.php index 6a320cb70f..a6b2faa805 100644 --- a/app/Services/Quickbooks/Transformers/ClientTransformer.php +++ b/app/Services/Quickbooks/Transformers/ClientTransformer.php @@ -19,7 +19,6 @@ use App\DataMapper\ClientSettings; */ class ClientTransformer extends BaseTransformer { - public function qbToNinja(mixed $qb_data) { return $this->transform($qb_data); @@ -42,7 +41,7 @@ class ClientTransformer extends BaseTransformer $client = [ 'id' => data_get($data, 'Id.value', null), - 'name' => data_get($data,'CompanyName', ''), + 'name' => data_get($data, 'CompanyName', ''), 'address1' => data_get($data, 'BillAddr.Line1', ''), 'address2' => data_get($data, 'BillAddr.Line2', ''), 'city' => data_get($data, 'BillAddr.City', ''), @@ -62,13 +61,13 @@ class ClientTransformer extends BaseTransformer 'is_tax_exempt' => !data_get($data, 'Taxable', false), 'private_notes' => data_get($data, 'Notes', ''), ]; - - $settings = ClientSettings::defaults(); - $settings->currency_id = (string) $this->resolveCurrency(data_get($data, 'CurrencyRef.value')); - $client['settings'] = $settings; + $settings = ClientSettings::defaults(); + $settings->currency_id = (string) $this->resolveCurrency(data_get($data, 'CurrencyRef.value')); - $new_client_merge = []; + $client['settings'] = $settings; + + $new_client_merge = []; return [$client, $contact, $new_client_merge]; } diff --git a/app/Services/Quickbooks/Transformers/ExpenseTransformer.php b/app/Services/Quickbooks/Transformers/ExpenseTransformer.php index 89035e6321..5448cfaa75 100644 --- a/app/Services/Quickbooks/Transformers/ExpenseTransformer.php +++ b/app/Services/Quickbooks/Transformers/ExpenseTransformer.php @@ -35,7 +35,7 @@ class ExpenseTransformer extends BaseTransformer $expense = [ 'amount' => data_get($data, 'TotalAmt'), - 'date' => Carbon::parse(data_get($data, 'TxnDate',''))->format('Y-m-d'), + 'date' => Carbon::parse(data_get($data, 'TxnDate', ''))->format('Y-m-d'), 'currency_id' => $this->resolveCurrency(data_get($data, 'CurrencyRef.value', '')), 'private_notes' => data_get($data, 'PrivateNote', null), 'public_notes' => null, @@ -45,7 +45,7 @@ class ExpenseTransformer extends BaseTransformer 'invoice_documents' => false, 'uses_inclusive_taxes' => false, 'calculate_tax_by_amount' => false, - 'category_id' => $this->getCategoryId(data_get($data, 'AccountRef.name','')), + 'category_id' => $this->getCategoryId(data_get($data, 'AccountRef.name', '')), ]; @@ -65,10 +65,10 @@ class ExpenseTransformer extends BaseTransformer $related = data_get($entity, 'EntityRef.type'); $entity_id = data_get($entity, 'EntityRef.value'); - switch($related) { + switch ($related) { case 'Vendor': return ['vendor_id' => $this->getVendorId($entity_id)]; - case 'Client': + case 'Client': return ['client_id' => $this->getClientId($entity_id)]; default: return []; @@ -77,16 +77,17 @@ class ExpenseTransformer extends BaseTransformer } private function getCategoryId($name): ?int - { + { - if(strlen($name) == 0) + if (strlen($name) == 0) { return null; + } $category = ExpenseCategory::where('company_id', $this->company->id) ->where('name', $name) ->first(); - if(!$category){ + if (!$category) { $category = ExpenseCategoryFactory::create($this->company->id, $this->company->owner()->id); $category->name = $name; $category->save(); diff --git a/app/Services/Quickbooks/Transformers/InvoiceTransformer.php b/app/Services/Quickbooks/Transformers/InvoiceTransformer.php index b48492e663..2e9bedde40 100644 --- a/app/Services/Quickbooks/Transformers/InvoiceTransformer.php +++ b/app/Services/Quickbooks/Transformers/InvoiceTransformer.php @@ -23,7 +23,6 @@ use App\DataMapper\InvoiceItem; */ class InvoiceTransformer extends BaseTransformer { - public function qbToNinja(mixed $qb_data) { return $this->transform($qb_data); @@ -60,18 +59,15 @@ class InvoiceTransformer extends BaseTransformer private function checkIfDiscountAfterTax($qb_data) { - if($qb_data->ApplyTaxAfterDiscount == 'true'){ + if ($qb_data->ApplyTaxAfterDiscount == 'true') { return 0; } - foreach(data_get($qb_data, 'Line', []) as $line) - { + foreach (data_get($qb_data, 'Line', []) as $line) { - if(data_get($line, 'DetailType.value') == 'DiscountLineDetail') - { + if (data_get($line, 'DetailType.value') == 'DiscountLineDetail') { - if(!isset($this->company->custom_fields->surcharge1)) - { + if (!isset($this->company->custom_fields->surcharge1)) { $this->company->custom_fields->surcharge1 = ctrans('texts.discount'); $this->company->save(); } @@ -86,7 +82,7 @@ class InvoiceTransformer extends BaseTransformer private function calculateTotalTax($qb_data) { $taxLines = data_get($qb_data, 'TxnTaxDetail.TaxLine', []); - + if (!is_array($taxLines)) { $taxLines = [$taxLines]; } @@ -108,19 +104,17 @@ class InvoiceTransformer extends BaseTransformer $qb_payments = data_get($qb_data, 'LinkedTxn', false); - if(!$qb_payments) { + if (!$qb_payments) { return []; } - if(!is_array($qb_payments) && data_get($qb_payments, 'TxnType', false) == 'Payment'){ + if (!is_array($qb_payments) && data_get($qb_payments, 'TxnType', false) == 'Payment') { return [data_get($qb_payments, 'TxnId.value', false)]; } - - foreach($qb_payments as $payment) - { - if(data_get($payment, 'TxnType', false) == 'Payment') - { + + foreach ($qb_payments as $payment) { + if (data_get($payment, 'TxnType', false) == 'Payment') { $payments[] = data_get($payment, 'TxnId.value', false); } } @@ -133,18 +127,16 @@ class InvoiceTransformer extends BaseTransformer { $items = []; - foreach($qb_items as $qb_item) - { + foreach ($qb_items as $qb_item) { - if(data_get($qb_item, 'DetailType.value') == 'SalesItemLineDetail') - { - $item = new InvoiceItem; + if (data_get($qb_item, 'DetailType.value') == 'SalesItemLineDetail') { + $item = new InvoiceItem(); $item->product_key = data_get($qb_item, 'SalesItemLineDetail.ItemRef.name', ''); - $item->notes = data_get($qb_item,'Description', ''); - $item->quantity = (float)data_get($qb_item,'SalesItemLineDetail.Qty', 0); + $item->notes = data_get($qb_item, 'Description', ''); + $item->quantity = (float)data_get($qb_item, 'SalesItemLineDetail.Qty', 0); $item->cost = (float)data_get($qb_item, 'SalesItemLineDetail.UnitPrice', 0); - $item->discount = (float)data_get($item,'DiscountRate', data_get($qb_item,'DiscountAmount', 0)); - $item->is_amount_discount = data_get($qb_item,'DiscountAmount', 0) > 0 ? true : false; + $item->discount = (float)data_get($item, 'DiscountRate', data_get($qb_item, 'DiscountAmount', 0)); + $item->is_amount_discount = data_get($qb_item, 'DiscountAmount', 0) > 0 ? true : false; $item->type_id = stripos(data_get($qb_item, 'ItemAccountRef.name') ?? '', 'Service') !== false ? '2' : '1'; $item->tax_id = data_get($qb_item, 'TaxCodeRef.value', '') == 'NON' ? Product::PRODUCT_TYPE_EXEMPT : $item->type_id; $item->tax_rate1 = (float)data_get($qb_item, 'TxnTaxDetail.TaxLine.TaxLineDetail.TaxPercent', 0); @@ -152,8 +144,7 @@ class InvoiceTransformer extends BaseTransformer $items[] = (object)$item; } - if(data_get($qb_item, 'DetailType.value') == 'DiscountLineDetail' && $include_discount == 'true') - { + if (data_get($qb_item, 'DetailType.value') == 'DiscountLineDetail' && $include_discount == 'true') { $item = new InvoiceItem(); $item->product_key = ctrans('texts.discount'); diff --git a/app/Services/Quickbooks/Transformers/PaymentTransformer.php b/app/Services/Quickbooks/Transformers/PaymentTransformer.php index c29094c253..08ae6007ad 100644 --- a/app/Services/Quickbooks/Transformers/PaymentTransformer.php +++ b/app/Services/Quickbooks/Transformers/PaymentTransformer.php @@ -22,7 +22,6 @@ use App\Models\Credit; */ class PaymentTransformer extends BaseTransformer { - public function qbToNinja(mixed $qb_data) { return $this->transform($qb_data); @@ -36,23 +35,22 @@ class PaymentTransformer extends BaseTransformer { return [ - 'date' => data_get($qb_data, 'TxnDate', now()->format('Y-m-d')), - 'amount' => floatval(data_get($qb_data, 'TotalAmt', 0)), - 'applied' => data_get($qb_data, 'TotalAmt', 0) - data_get($qb_data, 'UnappliedAmt', 0), + 'date' => data_get($qb_data, 'TxnDate', now()->format('Y-m-d')), + 'amount' => floatval(data_get($qb_data, 'TotalAmt', 0)), + 'applied' => data_get($qb_data, 'TotalAmt', 0) - data_get($qb_data, 'UnappliedAmt', 0), 'number' => data_get($qb_data, 'DocNumber', null), 'private_notes' => data_get($qb_data, 'PrivateNote', null), 'currency_id' => (string) $this->resolveCurrency(data_get($qb_data, 'CurrencyRef.value')), - 'client_id' => $this->getClientId(data_get($qb_data, 'CustomerRef.value', null)), + 'client_id' => $this->getClientId(data_get($qb_data, 'CustomerRef.value', null)), ]; } - + public function buildPayment($qb_data): ?Payment { $ninja_payment_data = $this->transform($qb_data); - if($ninja_payment_data['client_id']) - { - $payment = PaymentFactory::create($this->company->id, $this->company->owner()->id,$ninja_payment_data['client_id']); + if ($ninja_payment_data['client_id']) { + $payment = PaymentFactory::create($this->company->id, $this->company->owner()->id, $ninja_payment_data['client_id']); $payment->amount = $ninja_payment_data['amount']; $payment->applied = $ninja_payment_data['applied']; $payment->status_id = 4; @@ -61,14 +59,14 @@ class PaymentTransformer extends BaseTransformer $payment->client->service()->updatePaidToDate($payment->amount); - if($payment->amount == 0) { + if ($payment->amount == 0) { //this is a credit memo, create a stub credit for this. $payment = $this->createCredit($payment, $qb_data); $payment->type_id = \App\Models\PaymentType::CREDIT; $payment->save(); } - + return $payment; } @@ -79,17 +77,18 @@ class PaymentTransformer extends BaseTransformer { $credit_line = null; - foreach($qb_data->Line as $item) { - - if(data_get($item, 'LinkedTxn.TxnType', null) == 'CreditMemo') { + foreach ($qb_data->Line as $item) { + + if (data_get($item, 'LinkedTxn.TxnType', null) == 'CreditMemo') { $credit_line = $item; break; } - + } - - if(!$credit_line) + + if (!$credit_line) { return $payment; + } $credit = \App\Factory\CreditFactory::create($this->company->id, $this->company->owner()->id); $credit->client_id = $payment->client_id; @@ -123,10 +122,10 @@ class PaymentTransformer extends BaseTransformer { $invoices = []; $invoice = $this->getString($data, 'Line.LinkedTxn.TxnType'); - if(is_null($invoice) || $invoice !== 'Invoice') { + if (is_null($invoice) || $invoice !== 'Invoice') { return $invoices; } - if(is_null(($invoice_id = $this->getInvoiceId($this->getString($data, 'Line.LinkedTxn.TxnId.value'))))) { + if (is_null(($invoice_id = $this->getInvoiceId($this->getString($data, 'Line.LinkedTxn.TxnId.value'))))) { return $invoices; } diff --git a/app/Services/Quickbooks/Transformers/ProductTransformer.php b/app/Services/Quickbooks/Transformers/ProductTransformer.php index 8a93d607fe..17ba1b84d7 100644 --- a/app/Services/Quickbooks/Transformers/ProductTransformer.php +++ b/app/Services/Quickbooks/Transformers/ProductTransformer.php @@ -17,7 +17,6 @@ namespace App\Services\Quickbooks\Transformers; */ class ProductTransformer extends BaseTransformer { - public function qbToNinja(mixed $qb_data) { return $this->transform($qb_data); @@ -30,10 +29,10 @@ class ProductTransformer extends BaseTransformer public function transform(mixed $data): array { - + return [ 'id' => data_get($data, 'Id.value', null), - 'product_key' => data_get($data, 'Name', data_get($data, 'FullyQualifiedName','')), + 'product_key' => data_get($data, 'Name', data_get($data, 'FullyQualifiedName', '')), 'notes' => data_get($data, 'Description', ''), 'cost' => data_get($data, 'PurchaseCost', 0), 'price' => data_get($data, 'UnitPrice', 0), diff --git a/app/Services/Quickbooks/Transformers/VendorTransformer.php b/app/Services/Quickbooks/Transformers/VendorTransformer.php index 5cf9a25eb5..d2303cfea8 100644 --- a/app/Services/Quickbooks/Transformers/VendorTransformer.php +++ b/app/Services/Quickbooks/Transformers/VendorTransformer.php @@ -28,7 +28,7 @@ class VendorTransformer extends BaseTransformer public function transform(mixed $data): array { - + nlog($data); $contact = [ 'first_name' => data_get($data, 'GivenName'), @@ -45,13 +45,13 @@ class VendorTransformer extends BaseTransformer 'city' => data_get($data, 'BillAddr.City'), 'state' => data_get($data, 'BillAddr.CountrySubDivisionCode'), 'postal_code' => data_get($data, 'BillAddr.PostalCode'), - 'country_id' => $this->resolveCountry(data_get($data, 'BillAddr.CountryCode', data_get($data, 'BillAddr.Country',''))), + 'country_id' => $this->resolveCountry(data_get($data, 'BillAddr.CountryCode', data_get($data, 'BillAddr.Country', ''))), 'website' => data_get($data, 'WebAddr.URI'), 'vat_number' => data_get($data, 'TaxIdentifier'), - 'currency_id' => $this->resolveCurrency(data_get($data, 'CurrencyRef.value','')), + 'currency_id' => $this->resolveCurrency(data_get($data, 'CurrencyRef.value', '')), ]; - + $new_vendor_merge = [ 'vendor_hash' => data_get($data, 'V4IDPseudonym', \Illuminate\Support\Str::random(32)), ]; diff --git a/app/Services/Quote/ConvertQuote.php b/app/Services/Quote/ConvertQuote.php index ec822245d8..1c7afb4f51 100644 --- a/app/Services/Quote/ConvertQuote.php +++ b/app/Services/Quote/ConvertQuote.php @@ -75,7 +75,7 @@ class ConvertQuote $quote->status_id = Quote::STATUS_CONVERTED; $quote->save(); - if($quote->documents()->count() > 0) { + if ($quote->documents()->count() > 0) { CopyDocs::dispatch($quote->documents()->pluck('id'), $invoice, $invoice->company->db); } diff --git a/app/Services/Quote/MarkSent.php b/app/Services/Quote/MarkSent.php index 0dc3c08479..ad3eaa7450 100644 --- a/app/Services/Quote/MarkSent.php +++ b/app/Services/Quote/MarkSent.php @@ -46,7 +46,7 @@ class MarkSent event(new QuoteWasMarkedSent($this->quote, $this->quote->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); - if($first_event) { + if ($first_event) { event('eloquent.updated: App\Models\Quote', $this->quote); $this->quote->sendEvent(Webhook::EVENT_SENT_QUOTE, "client"); diff --git a/app/Services/Quote/SendEmail.php b/app/Services/Quote/SendEmail.php index fe3c3ef79b..5dd0aad3dc 100644 --- a/app/Services/Quote/SendEmail.php +++ b/app/Services/Quote/SendEmail.php @@ -20,7 +20,6 @@ use App\Services\Email\EmailObject; class SendEmail { - public function __construct(public Quote $quote, public ?string $reminder_template = null, protected ?ClientContact $contact = null) { } @@ -41,7 +40,7 @@ class SendEmail $this->quote->invitations->each(function ($invitation) { if (! $invitation->contact->trashed() && $invitation->contact->email) { - + //@refactor 2024-11-10 $mo = new EmailObject(); $mo->entity_id = $invitation->quote_id; diff --git a/app/Services/Quote/TriggeredActions.php b/app/Services/Quote/TriggeredActions.php index 8e4fb21f19..fb48ec204f 100644 --- a/app/Services/Quote/TriggeredActions.php +++ b/app/Services/Quote/TriggeredActions.php @@ -84,9 +84,9 @@ class TriggeredActions extends AbstractService // $reminder_template = 'email_template_quote'; // $quote_template = 'email_template_reminder1 $reminder_template = "email_template_{$reminder_template}"; - + $this->quote->invitations->load('contact.client.country', 'quote.client.country', 'quote.company')->each(function ($invitation) use ($reminder_template) { - + $mo = new EmailObject(); $mo->entity_id = $invitation->quote_id; $mo->template = $reminder_template; //full template name in use diff --git a/app/Services/Recurring/RecurringService.php b/app/Services/Recurring/RecurringService.php index 83d15fd130..a70d8dff8d 100644 --- a/app/Services/Recurring/RecurringService.php +++ b/app/Services/Recurring/RecurringService.php @@ -170,7 +170,7 @@ class RecurringService $sub_id = $this->decodePrimaryKey($subscription_id); - if(Subscription::withTrashed()->where('id', $sub_id)->where('company_id', $this->recurring_entity->company_id)->exists()) { + if (Subscription::withTrashed()->where('id', $sub_id)->where('company_id', $this->recurring_entity->company_id)->exists()) { $this->recurring_entity->subscription_id = $sub_id; } diff --git a/app/Services/Report/ARDetailReport.php b/app/Services/Report/ARDetailReport.php index 75697daae1..433ba0df9c 100644 --- a/app/Services/Report/ARDetailReport.php +++ b/app/Services/Report/ARDetailReport.php @@ -28,7 +28,7 @@ use App\Services\Template\TemplateService; class ARDetailReport extends BaseExport { use MakesDates; - + public Writer $csv; public string $date_key = 'created_at'; @@ -121,7 +121,7 @@ class ARDetailReport extends BaseExport 'invoices' => $this->invoices, 'company_logo' => $this->company->present()->logo(), 'company_name' => $this->company->present()->name(), - 'created_on' => $this->translateDate(now()->format('Y-m-d'),$this->company->date_format(), $this->company->locale()), + 'created_on' => $this->translateDate(now()->format('Y-m-d'), $this->company->date_format(), $this->company->locale()), 'created_by' => $user_name, ]; diff --git a/app/Services/Report/ARSummaryReport.php b/app/Services/Report/ARSummaryReport.php index 615f8f35ae..8a2b14c645 100644 --- a/app/Services/Report/ARSummaryReport.php +++ b/app/Services/Report/ARSummaryReport.php @@ -115,7 +115,7 @@ class ARSummaryReport extends BaseExport 'clients' => $this->clients, 'company_logo' => $this->company->present()->logo(), 'company_name' => $this->company->present()->name(), - 'created_on' => $this->translateDate(now()->format('Y-m-d'),$this->company->date_format(), $this->company->locale()), + 'created_on' => $this->translateDate(now()->format('Y-m-d'), $this->company->date_format(), $this->company->locale()), 'created_by' => $user_name, ]; diff --git a/app/Services/Report/ClientBalanceReport.php b/app/Services/Report/ClientBalanceReport.php index 82b161b3f3..d7adf3fa99 100644 --- a/app/Services/Report/ClientBalanceReport.php +++ b/app/Services/Report/ClientBalanceReport.php @@ -100,7 +100,7 @@ class ClientBalanceReport extends BaseExport { $headers = []; - foreach($this->report_keys as $key) { + foreach ($this->report_keys as $key) { $headers[] = ctrans("texts.{$key}"); } diff --git a/app/Services/Report/ProfitLoss.php b/app/Services/Report/ProfitLoss.php index 15d6df0c03..95260308f5 100644 --- a/app/Services/Report/ProfitLoss.php +++ b/app/Services/Report/ProfitLoss.php @@ -295,7 +295,7 @@ class ProfitLoss if ($pivot->paymentable_type == 'invoices') { $invoice = Invoice::query()->withTrashed()->find($pivot->paymentable_id); - if(!$invoice) { + if (!$invoice) { continue; } @@ -310,7 +310,7 @@ class ProfitLoss } - if(!$invoice) { + if (!$invoice) { continue; } @@ -416,7 +416,7 @@ class ProfitLoss $csv->insertOne(['--------------------']); $csv->insertOne([ctrans('texts.expenses')]); $csv->insertOne(['--------------------']); - foreach($this->expenses as $expense) { + foreach ($this->expenses as $expense) { $csv->insertOne([$expense->currency, ($expense->total - $expense->foreign_tax_amount), $expense->foreign_tax_amount]); } diff --git a/app/Services/Report/TaxSummaryReport.php b/app/Services/Report/TaxSummaryReport.php index 8796a99362..788e15ec34 100644 --- a/app/Services/Report/TaxSummaryReport.php +++ b/app/Services/Report/TaxSummaryReport.php @@ -86,7 +86,7 @@ class TaxSummaryReport extends BaseExport $this->csv->insertOne([ctrans('texts.tax_summary')]); $this->csv->insertOne([ctrans('texts.created_on'),' ',$this->translateDate(now()->format('Y-m-d'), $this->company->date_format(), $this->company->locale())]); - if($this->input['date_range'] != 'all') { + if ($this->input['date_range'] != 'all') { $this->csv->insertOne([ctrans('texts.date_range'),' ',$this->translateDate($this->start_date, $this->company->date_format(), $this->company->locale()),' - ',$this->translateDate($this->end_date, $this->company->date_format(), $this->company->locale())]); } @@ -99,18 +99,18 @@ class TaxSummaryReport extends BaseExport $accrual_invoice_map = []; $cash_invoice_map = []; - foreach($query->cursor() as $invoice) { + foreach ($query->cursor() as $invoice) { $calc = $invoice->calc(); //Combine the line taxes with invoice taxes here to get a total tax amount $taxes = array_merge($calc->getTaxMap()->merge($calc->getTotalTaxMap())->toArray()); //filter into two arrays for accrual + cash - foreach($taxes as $tax) { + foreach ($taxes as $tax) { $key = $tax['name']; $tax_prorata = 0; - if(!isset($accrual_map[$key])) { + if (!isset($accrual_map[$key])) { $accrual_map[$key]['tax_amount'] = 0; } @@ -125,25 +125,25 @@ class TaxSummaryReport extends BaseExport //cash $key = $tax['name']; - if(!isset($cash_map[$key])) { + if (!isset($cash_map[$key])) { $cash_map[$key]['tax_amount'] = 0; } - if(in_array($invoice->status_id, [Invoice::STATUS_PARTIAL,Invoice::STATUS_PAID])) { + if (in_array($invoice->status_id, [Invoice::STATUS_PARTIAL,Invoice::STATUS_PAID])) { try { - if($invoice->status_id == Invoice::STATUS_PAID) { + if ($invoice->status_id == Invoice::STATUS_PAID) { $tax_prorata = $tax['total']; $cash_map[$key]['tax_amount'] += $tax['total']; } else { - + $paid_amount = $invoice->amount - $invoice->balance; $payment_ratio = $invoice->amount > 0 ? $paid_amount / $invoice->amount : 0; - $tax_prorata = round($payment_ratio * ($tax['total'] ?? 0),2); + $tax_prorata = round($payment_ratio * ($tax['total'] ?? 0), 2); $cash_map[$key]['tax_amount'] += $tax_prorata; } - + $cash_invoice_map[] = [ 'number' => ctrans('texts.invoice') . " " . $invoice->number, 'date' => $this->translateDate($invoice->date, $this->company->date_format(), $this->company->locale()), @@ -152,7 +152,7 @@ class TaxSummaryReport extends BaseExport ]; - } catch(\DivisionByZeroError $e) { + } catch (\DivisionByZeroError $e) { $cash_map[$key]['tax_amount'] += 0; } } @@ -164,23 +164,23 @@ class TaxSummaryReport extends BaseExport $this->csv->insertOne($this->buildHeader()); $this->csv->insertOne([ctrans('texts.cash_vs_accrual')]); - foreach($accrual_map as $key => $value) { + foreach ($accrual_map as $key => $value) { $this->csv->insertOne([$key, Number::formatMoney($value['tax_amount'], $this->company), Number::formatValue($value['tax_amount'], $this->company->currency())]); } - $this->csv->insertOne([]); + $this->csv->insertOne([]); $this->csv->insertOne([ctrans('texts.cash_accounting')]); $this->csv->insertOne($this->buildHeader()); - foreach($cash_map as $key => $value) { + foreach ($cash_map as $key => $value) { $this->csv->insertOne([$key, Number::formatMoney($value['tax_amount'], $this->company), Number::formatValue($value['tax_amount'], $this->company->currency())]); } - + $this->csv->insertOne([]); $this->csv->insertOne([]); $this->csv->insertOne([ctrans('texts.cash_vs_accrual'), ctrans('texts.date'), ctrans('texts.amount'), ctrans('texts.amount')]); - foreach($accrual_invoice_map as $map){ + foreach ($accrual_invoice_map as $map) { $this->csv->insertOne($map); } @@ -188,7 +188,7 @@ class TaxSummaryReport extends BaseExport $this->csv->insertOne([]); $this->csv->insertOne([ctrans('texts.cash_accounting'), ctrans('texts.date'), ctrans('texts.amount'), ctrans('texts.amount')]); - foreach($cash_invoice_map as $map){ + foreach ($cash_invoice_map as $map) { $this->csv->insertOne($map); } diff --git a/app/Services/Scheduler/EmailRecord.php b/app/Services/Scheduler/EmailRecord.php index 1b80a17d35..0a6c5edaf1 100644 --- a/app/Services/Scheduler/EmailRecord.php +++ b/app/Services/Scheduler/EmailRecord.php @@ -29,7 +29,7 @@ class EmailRecord $entity = $class::find($this->decodePrimaryKey($this->scheduler->parameters['entity_id'])); - if($entity) { + if ($entity) { $entity->service()->markSent()->sendEmail(); } diff --git a/app/Services/Scheduler/EmailReport.php b/app/Services/Scheduler/EmailReport.php index c328e4719d..ecb7aea974 100644 --- a/app/Services/Scheduler/EmailReport.php +++ b/app/Services/Scheduler/EmailReport.php @@ -105,7 +105,7 @@ class EmailReport default => $export = false, }; - if(!$export) { + if (!$export) { $this->cancelSchedule(); return; } @@ -125,7 +125,7 @@ class EmailReport $nmo->settings = $this->scheduler->company->settings; $nmo->to_user = $this->scheduler->user->withoutRelations(); - + try { (new NinjaMailerJob($nmo))->handle(); } catch (\Throwable $th) { diff --git a/app/Services/Subscription/ChangePlanInvoice.php b/app/Services/Subscription/ChangePlanInvoice.php index 8782576359..41b562d242 100644 --- a/app/Services/Subscription/ChangePlanInvoice.php +++ b/app/Services/Subscription/ChangePlanInvoice.php @@ -46,13 +46,13 @@ class ChangePlanInvoice extends AbstractService $invoice = $this->generateInvoice($refund); - if($refund >= $new_charge) { + if ($refund >= $new_charge) { $invoice = $invoice->markPaid()->save(); //generate new recurring invoice at this point as we know the user has succeeded with their upgrade. } - if($refund > $new_charge) { + if ($refund > $new_charge) { return $this->generateCredit($refund - $new_charge); } diff --git a/app/Services/Subscription/PaymentLinkService.php b/app/Services/Subscription/PaymentLinkService.php index 1c66db998f..323eca8eae 100644 --- a/app/Services/Subscription/PaymentLinkService.php +++ b/app/Services/Subscription/PaymentLinkService.php @@ -166,7 +166,7 @@ class PaymentLinkService // Redirects from here work just fine. Livewire will respect it. $client_contact = ClientContact::find($this->decodePrimaryKey($data['contact_id'])); - if(is_string($data['client_id'])) { + if (is_string($data['client_id'])) { $data['client_id'] = $this->decodePrimaryKey($data['client_id']); } diff --git a/app/Services/Subscription/SubscriptionCalculator.php b/app/Services/Subscription/SubscriptionCalculator.php index 22b427172f..d9f2349b70 100644 --- a/app/Services/Subscription/SubscriptionCalculator.php +++ b/app/Services/Subscription/SubscriptionCalculator.php @@ -49,7 +49,7 @@ class SubscriptionCalculator $invoice->number = "####" . ctrans('texts.subscription') . "_" . now()->format('Y-m-d') . "_" . rand(0, 100000); $invoice->line_items = $this->buildItems($context); - if(isset($context['valid_coupon']) && $context['valid_coupon']) { + if (isset($context['valid_coupon']) && $context['valid_coupon']) { $invoice->discount = $this->subscription->promo_discount; $invoice->is_amount_discount = $this->subscription->is_amount_discount; } @@ -75,9 +75,9 @@ class SubscriptionCalculator $items = []; - foreach($recurring as $item) { + foreach ($recurring as $item) { - if($item['quantity'] < 1) { + if ($item['quantity'] < 1) { continue; } @@ -91,9 +91,9 @@ class SubscriptionCalculator } - foreach($one_time as $item) { + foreach ($one_time as $item) { - if($item['quantity'] < 1) { + if ($item['quantity'] < 1) { continue; } diff --git a/app/Services/Subscription/SubscriptionService.php b/app/Services/Subscription/SubscriptionService.php index dc1376cc6b..73ab44360f 100644 --- a/app/Services/Subscription/SubscriptionService.php +++ b/app/Services/Subscription/SubscriptionService.php @@ -253,7 +253,7 @@ class SubscriptionService // Redirects from here work just fine. Livewire will respect it. $client_contact = ClientContact::find($this->decodePrimaryKey($data['contact_id'])); - if(is_string($data['client_id'])) { + if (is_string($data['client_id'])) { $data['client_id'] = $this->decodePrimaryKey($data['client_id']); } @@ -987,7 +987,7 @@ class SubscriptionService ->fillDefaults() ->save(); - if($invoice->fresh()->balance == 0) { + if ($invoice->fresh()->balance == 0) { $invoice->service()->markPaid()->save(); } diff --git a/app/Services/Subscription/SubscriptionStatus.php b/app/Services/Subscription/SubscriptionStatus.php index baa974be54..2471ba7f30 100644 --- a/app/Services/Subscription/SubscriptionStatus.php +++ b/app/Services/Subscription/SubscriptionStatus.php @@ -95,7 +95,7 @@ class SubscriptionStatus extends AbstractService ->orderBy('id', 'desc') ->first(); - if(!$primary_invoice) { + if (!$primary_invoice) { return 0; } @@ -143,7 +143,7 @@ class SubscriptionStatus extends AbstractService private function checkTrial(): self { - if(!$this->subscription->trial_enabled) { + if (!$this->subscription->trial_enabled) { return $this->setIsTrial(false); } @@ -156,7 +156,7 @@ class SubscriptionStatus extends AbstractService ->orderBy('id', 'asc') ->doesntExist(); - if($primary_invoice && Carbon::parse($this->recurring_invoice->next_send_date_client)->gte(now()->startOfDay()->addSeconds($this->recurring_invoice->client->timezone_offset()))) { + if ($primary_invoice && Carbon::parse($this->recurring_invoice->next_send_date_client)->gte(now()->startOfDay()->addSeconds($this->recurring_invoice->client->timezone_offset()))) { return $this->setIsTrial(true); } @@ -174,7 +174,7 @@ class SubscriptionStatus extends AbstractService */ private function checkRefundable(): self { - if(!$this->recurring_invoice->subscription->refund_period || (int)$this->recurring_invoice->subscription->refund_period == 0) {//@phpstan-ignore-line + if (!$this->recurring_invoice->subscription->refund_period || (int)$this->recurring_invoice->subscription->refund_period == 0) {//@phpstan-ignore-line return $this->setRefundable(false); } @@ -185,7 +185,7 @@ class SubscriptionStatus extends AbstractService ->orderBy('id', 'desc') ->first(); - if($primary_invoice && + if ($primary_invoice && $primary_invoice->status_id == Invoice::STATUS_PAID && Carbon::parse($primary_invoice->date)->addSeconds($this->recurring_invoice->subscription->refund_period)->lte(now()->startOfDay()->addSeconds($primary_invoice->client->timezone_offset())) ) { diff --git a/app/Services/Subscription/UpgradePrice.php b/app/Services/Subscription/UpgradePrice.php index 6ea98e3faf..a9d6835f76 100644 --- a/app/Services/Subscription/UpgradePrice.php +++ b/app/Services/Subscription/UpgradePrice.php @@ -38,7 +38,7 @@ class UpgradePrice extends AbstractService ->subscription ->status($this->recurring_invoice); - if($this->status->is_in_good_standing) { + if ($this->status->is_in_good_standing) { $this->calculateUpgrade(); } else { $this->upgrade_price = $this->subscription->price; @@ -84,7 +84,7 @@ class UpgradePrice extends AbstractService $use_credit_setting = $this->recurring_invoice->client->getSetting('use_credits_payment'); - if($use_credit_setting) { + if ($use_credit_setting) { $outstanding_credits = Credit::query() ->where('client_id', $this->recurring_invoice->client_id) diff --git a/app/Services/Subscription/ZeroCostProduct.php b/app/Services/Subscription/ZeroCostProduct.php index aed5420540..6cfe3f9358 100644 --- a/app/Services/Subscription/ZeroCostProduct.php +++ b/app/Services/Subscription/ZeroCostProduct.php @@ -79,7 +79,7 @@ class ZeroCostProduct extends AbstractService 'redirect_url' => "/client/recurring_invoices/{$recurring_invoice->hashed_id}", ]; - if(isset($this->data['campaign'])) { + if (isset($this->data['campaign'])) { $context['campaign'] = $this->data['campaign']; } diff --git a/app/Services/Tax/Providers/TaxProvider.php b/app/Services/Tax/Providers/TaxProvider.php index 3786f7ddca..f2c45d6fd0 100644 --- a/app/Services/Tax/Providers/TaxProvider.php +++ b/app/Services/Tax/Providers/TaxProvider.php @@ -93,13 +93,13 @@ class TaxProvider $tax_data = $tax_provider->run(); - if($tax_data) { + if ($tax_data) { $this->company->origin_tax_data = $tax_data; $this->company->saveQuietly(); $this->updated_client = true; } - } catch(\Exception $e) { + } catch (\Exception $e) { nlog("Exception:: TaxProvider::" . $e->getMessage()); nlog("Could not updated company tax data: " . $e->getMessage()); } @@ -145,7 +145,7 @@ class TaxProvider // nlog($tax_data); - if($tax_data) { + if ($tax_data) { $this->client->tax_data = $tax_data; $this->client->saveQuietly(); $this->updated_client = true; @@ -163,7 +163,7 @@ class TaxProvider private function taxShippingAddress(): bool { - if($this->client->shipping_country_id == "840" && strlen($this->client->shipping_postal_code) > 3) { + if ($this->client->shipping_country_id == "840" && strlen($this->client->shipping_postal_code) > 3) { return true; } @@ -250,7 +250,7 @@ class TaxProvider */ private function configureZipTax(): self { - if(!config('services.tax.zip_tax.key')) { + if (!config('services.tax.zip_tax.key')) { throw new \Exception("ZipTax API key not set in .env file"); } diff --git a/app/Services/Tax/Providers/ZipTax.php b/app/Services/Tax/Providers/ZipTax.php index d967f62ee2..a50f0f9c71 100644 --- a/app/Services/Tax/Providers/ZipTax.php +++ b/app/Services/Tax/Providers/ZipTax.php @@ -30,14 +30,14 @@ class ZipTax implements TaxProviderInterface $response = $this->callApi(['key' => $this->api_key, 'address' => $string_address]); - if($response->successful()) { + if ($response->successful()) { return $this->parseResponse($response->json()); } - if(isset($this->address['postal_code'])) { + if (isset($this->address['postal_code'])) { $response = $this->callApi(['key' => $this->api_key, 'address' => $this->address['postal_code']]); - if($response->successful()) { + if ($response->successful()) { return $this->parseResponse($response->json()); } @@ -68,11 +68,11 @@ class ZipTax implements TaxProviderInterface private function parseResponse($response) { - if(isset($response['rCode']) && $response['rCode'] == 100 && isset($response['results']['0'])) { + if (isset($response['rCode']) && $response['rCode'] == 100 && isset($response['results']['0'])) { return $response['results']['0']; } - if(isset($response['rCode']) && class_exists(\Modules\Admin\Events\TaxProviderException::class)) { + if (isset($response['rCode']) && class_exists(\Modules\Admin\Events\TaxProviderException::class)) { event(new \Modules\Admin\Events\TaxProviderException($response['rCode'])); } diff --git a/app/Services/Tax/TaxService.php b/app/Services/Tax/TaxService.php index 807e1ffad3..2fd424e41a 100644 --- a/app/Services/Tax/TaxService.php +++ b/app/Services/Tax/TaxService.php @@ -21,7 +21,7 @@ class TaxService public function validateVat(): self { - if(!extension_loaded('soap')) { + if (!extension_loaded('soap')) { nlog("Install the PHP SOAP extension if you wish to check VAT Numbers. See https://www.php.net/manual/en/soap.installation.php for more information on installing the PHP"); return $this; } @@ -32,15 +32,15 @@ class TaxService nlog($vat_check); - if($vat_check->isValid()) { + if ($vat_check->isValid()) { $this->client->has_valid_vat_number = true; - if(!$this->client->name && strlen($vat_check->getName()) > 2) { + if (!$this->client->name && strlen($vat_check->getName()) > 2) { $this->client->name = $vat_check->getName(); } - if(empty($this->client->private_notes) && strlen($vat_check->getAddress()) > 2) { + if (empty($this->client->private_notes) && strlen($vat_check->getAddress()) > 2) { $this->client->private_notes = $vat_check->getAddress(); } diff --git a/app/Services/Template/TemplateAction.php b/app/Services/Template/TemplateAction.php index d9904faf26..509a177657 100644 --- a/app/Services/Template/TemplateAction.php +++ b/app/Services/Template/TemplateAction.php @@ -114,7 +114,7 @@ class TemplateAction implements ShouldQueue $first_entity = $result->first(); /** Lets be clever and sniff out Statements */ - if($first_entity instanceof Client && stripos(json_encode($template->design), '##statement##') !== false) { + if ($first_entity instanceof Client && stripos(json_encode($template->design), '##statement##') !== false) { $options = [ 'show_payments_table' => true, @@ -126,17 +126,17 @@ class TemplateAction implements ShouldQueue $pdfs = []; - foreach($result as $client) { + foreach ($result as $client) { $pdfs[] = $client->service()->statement($options); } - if(count($pdfs) == 1) { + if (count($pdfs) == 1) { $pdf = $pdfs[0]; } else { $pdf = (new PdfMerge($pdfs))->run(); } - if($this->send_email) { + if ($this->send_email) { $this->sendEmail($pdf, $template); return; } else { @@ -147,15 +147,15 @@ class TemplateAction implements ShouldQueue } - if($first_entity instanceof Client) { + if ($first_entity instanceof Client) { $currency_code = $first_entity->currency()->code; - } elseif($first_entity->client) { + } elseif ($first_entity->client) { $currency_code = $first_entity->client->currency()->code; } else { $currency_code = $this->company->currency()->code; } - if($result->count() <= 1) { + if ($result->count() <= 1) { $data[$key] = collect($result); } else { $data[$key] = $result; @@ -167,7 +167,7 @@ class TemplateAction implements ShouldQueue ->addGlobal(['currency_code' => $currency_code]) ->build($data); - if($this->send_email) { + if ($this->send_email) { $pdf = $ts->getPdf(); $this->sendEmail($pdf, $template); } else { diff --git a/app/Services/Template/TemplateService.php b/app/Services/Template/TemplateService.php index 8732d6c75d..3aad8caf5b 100644 --- a/app/Services/Template/TemplateService.php +++ b/app/Services/Template/TemplateService.php @@ -45,7 +45,7 @@ class TemplateService use MakesDates; use PdfMaker; use MakesHash; - + private \DomDocument $document; public \Twig\Environment $twig; @@ -105,7 +105,7 @@ class TemplateService $function = new \Twig\TwigFunction('img', \Closure::fromCallable(function (string $image_src, string $image_style = '') { $html = ''; - + return new \Twig\Markup($html, 'UTF-8'); })); @@ -131,7 +131,7 @@ class TemplateService $allowedProperties = ['type_id']; // $allowedMethods = ['img','t']; $allowedMethods = [ - 'Illuminate\Support\Collection' => ['__toString'], + 'Illuminate\Support\Collection' => ['__toString'], ]; $policy = new \Twig\Sandbox\SecurityPolicy($allowedTags, $allowedFilters, $allowedMethods, $allowedProperties, $allowedFunctions); @@ -176,7 +176,7 @@ class TemplateService public function setGlobals(): self { - foreach($this->global_vars as $key => $value) { + foreach ($this->global_vars as $key => $value) { $this->twig->addGlobal($key, $value); } @@ -195,11 +195,11 @@ class TemplateService private function getSettings(): object { - if($this->settings) { + if ($this->settings) { return $this->settings; } - if($this->client) { + if ($this->client) { return $this->client->getMergedSettings(); } @@ -308,19 +308,19 @@ class TemplateService try { $template = $this->twig->createTemplate(html_entity_decode($template)); - } catch(SyntaxError $e) { + } catch (SyntaxError $e) { nlog($e->getMessage()); throw ($e); - } catch(RuntimeError $e) { + } catch (RuntimeError $e) { nlog("runtime = " . $e->getMessage()); throw ($e); - } catch(LoaderError $e) { + } catch (LoaderError $e) { nlog("loader = " . $e->getMessage()); throw ($e); - } catch(SecurityError $e) { + } catch (SecurityError $e) { nlog("security = " . $e->getMessage()); throw ($e); - } catch(Error $e) { + } catch (Error $e) { nlog("error = " . $e->getMessage()); throw ($e); } @@ -337,7 +337,7 @@ class TemplateService } - foreach($contents as $key => $content) { + foreach ($contents as $key => $content) { $content->parentNode->replaceChild($replacements[$key], $content); } @@ -370,15 +370,15 @@ class TemplateService $html = $this->getHtml(); - foreach($this->variables as $key => $variable) { - if(isset($variable['labels']) && isset($variable['values'])) { + foreach ($this->variables as $key => $variable) { + if (isset($variable['labels']) && isset($variable['values'])) { $html = strtr($html, $variable['labels']); $html = strtr($html, $variable['values']); } } @$this->document->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); - + $this->save(); return $this; @@ -403,7 +403,7 @@ class TemplateService */ public function compose(): self { - if(!$this->template) { + if (!$this->template) { return $this; } @@ -419,9 +419,9 @@ class TemplateService } - public function setRawTemplate(string $template):self + public function setRawTemplate(string $template): self { - + @$this->document->loadHTML(mb_convert_encoding($template, 'HTML-ENTITIES', 'UTF-8')); return $this; @@ -461,7 +461,7 @@ class TemplateService $processed = []; - if(in_array($key, ['tasks', 'projects', 'aging', 'unapplied']) || !$value->first()) { + if (in_array($key, ['tasks', 'projects', 'aging', 'unapplied']) || !$value->first()) { return $processed; } @@ -496,7 +496,7 @@ class TemplateService */ private function preProcessDataBlocks($data): array { - + return collect($data)->map(function ($value, $key) { $processed = []; @@ -535,7 +535,7 @@ class TemplateService $payments = []; $this->entity = $invoice; - if($invoice->payments ?? false) { + if ($invoice->payments ?? false) { $payments = $invoice->payments->map(function ($payment) { return $this->transformPayment($payment); })->toArray(); @@ -623,7 +623,7 @@ class TemplateService $item->cost = Number::formatMoney($item->cost_raw, $client_or_vendor); - if($item->is_amount_discount) { + if ($item->is_amount_discount) { $item->discount = Number::formatMoney($item->discount_raw, $client_or_vendor); } @@ -632,7 +632,7 @@ class TemplateService $item->tax_amount = Number::formatMoney($item->tax_amount_raw, $client_or_vendor); $item->product_cost = Number::formatMoney($item->product_cost_raw, $client_or_vendor); $item->task = strlen($item->task_id ?? '') > 1 ? $this->processInvoiceTask($item->task_id) : []; - + return (array)$item; })->toArray(); @@ -737,7 +737,7 @@ class TemplateService private function getPaymentRefundActivity(Payment $payment): array { - if(!is_array($payment->refund_meta)) { + if (!is_array($payment->refund_meta)) { return []; } @@ -750,7 +750,7 @@ class TemplateService $map = []; - foreach($refund['invoices'] as $refunded_invoice) { + foreach ($refund['invoices'] as $refunded_invoice) { $invoice = Invoice::withTrashed()->find($refunded_invoice['invoice_id']); $amount = Number::formatMoney($refunded_invoice['amount'], $payment->client); $notes = ctrans('texts.status_partially_refunded_amount', ['amount' => $amount]); @@ -845,7 +845,7 @@ class TemplateService $this->entity = $credit; - if($credit->payments ?? false) { + if ($credit->payments ?? false) { $payments = $credit->payments->map(function ($payment) { return $this->transformPayment($payment); })->toArray(); @@ -958,7 +958,7 @@ class TemplateService $task = Task::where('company_id', $this->company->id) ->where('id', $this->decodePrimaryKey($task_id)) ->first(); - + return $task ? [ 'number' => (string) $task->number ?: '', 'description' => (string) $task->description ?: '', @@ -1028,7 +1028,7 @@ class TemplateService */ public function processProjects($projects): array { - + return collect($projects)->map(function ($project) { @@ -1049,7 +1049,7 @@ class TemplateService private function transformProject(Project $project, bool $nested = false): array { - + return [ 'name' => $project->name ?: '', 'number' => $project->number ?: '', @@ -1298,7 +1298,7 @@ class TemplateService */ private function shippingDetails(bool $include_labels = false): self { - if(!$this->entity->client) { + if (!$this->entity->client) { return $this; } @@ -1365,19 +1365,19 @@ class TemplateService private function resolveEntity(): string { switch ($this->entity) { - case ($this->entity instanceof Invoice): - return 'invoice'; - case ($this->entity instanceof Quote): - return 'quote'; - case ($this->entity instanceof Credit): - return 'credit'; - case ($this->entity instanceof RecurringInvoice): - return 'invoice'; - case ($this->entity instanceof PurchaseOrder): - return 'purchase_order'; - + case ($this->entity instanceof Invoice): + return 'invoice'; + case ($this->entity instanceof Quote): + return 'quote'; + case ($this->entity instanceof Credit): + return 'credit'; + case ($this->entity instanceof RecurringInvoice): + return 'invoice'; + case ($this->entity instanceof PurchaseOrder): + return 'purchase_order'; + default: - return 'invoice'; + return 'invoice'; } } diff --git a/app/Services/Vendor/Merge.php b/app/Services/Vendor/Merge.php index 6a82f8e98a..5f99a26f73 100644 --- a/app/Services/Vendor/Merge.php +++ b/app/Services/Vendor/Merge.php @@ -31,7 +31,7 @@ class Merge extends AbstractService public function run() { - + $this->mergable_vendor->activities()->update(['vendor_id' => $this->vendor->id]); $this->mergable_vendor->contacts()->update(['vendor_id' => $this->vendor->id]); $this->mergable_vendor->credits()->update(['vendor_id' => $this->vendor->id]); @@ -58,5 +58,5 @@ class Merge extends AbstractService return $this->vendor; } - + } diff --git a/app/Services/Vendor/VendorService.php b/app/Services/Vendor/VendorService.php index ccb83dd013..d92ecba8b0 100644 --- a/app/Services/Vendor/VendorService.php +++ b/app/Services/Vendor/VendorService.php @@ -29,7 +29,7 @@ class VendorService { $x = 1; - if(isset($this->vendor->number)) { + if (isset($this->vendor->number)) { return $this; } diff --git a/app/Transformers/CompanyTransformer.php b/app/Transformers/CompanyTransformer.php index 4dd3cf7b2d..c1128d5525 100644 --- a/app/Transformers/CompanyTransformer.php +++ b/app/Transformers/CompanyTransformer.php @@ -203,7 +203,7 @@ class CompanyTransformer extends EntityTransformer 'has_e_invoice_certificate_passphrase' => $company->e_invoice_certificate_passphrase ? true : false, 'invoice_task_project_header' => (bool) $company->invoice_task_project_header, 'invoice_task_item_description' => (bool) $company->invoice_task_item_description, - 'origin_tax_data' => $company->origin_tax_data ?: new \stdClass, + 'origin_tax_data' => $company->origin_tax_data ?: new \stdClass(), 'expense_mailbox' => (string) $company->expense_mailbox, 'expense_mailbox_active' => (bool) $company->expense_mailbox_active, 'inbound_mailbox_allow_company_users' => (bool) $company->inbound_mailbox_allow_company_users, diff --git a/app/Transformers/UserTransformer.php b/app/Transformers/UserTransformer.php index 23b72d0853..4901e8ae3c 100644 --- a/app/Transformers/UserTransformer.php +++ b/app/Transformers/UserTransformer.php @@ -118,7 +118,7 @@ class UserTransformer extends EntityTransformer $cu = $user->company_users()->where('company_id', $user->company_id)->first(); - if(!$cu) { + if (!$cu) { return null; } diff --git a/app/Utils/Helpers.php b/app/Utils/Helpers.php index 57c764144c..c64944a2d7 100644 --- a/app/Utils/Helpers.php +++ b/app/Utils/Helpers.php @@ -59,7 +59,7 @@ class Helpers $custom_field = ''; $quote_or_credit_field = false; - if($custom_fields && stripos($field, 'quote') !== false && property_exists($custom_fields, $field)) { + if ($custom_fields && stripos($field, 'quote') !== false && property_exists($custom_fields, $field)) { $custom_field = $custom_fields->{$field}; $custom_field_parts = explode('|', $custom_field); @@ -69,7 +69,7 @@ class Helpers $quote_or_credit_field = true; - } elseif($custom_fields && stripos($field, 'credit') !== false && property_exists($custom_fields, $field)) { + } elseif ($custom_fields && stripos($field, 'credit') !== false && property_exists($custom_fields, $field)) { $custom_field = $custom_fields->{$field}; $custom_field_parts = explode('|', $custom_field); @@ -79,9 +79,9 @@ class Helpers $quote_or_credit_field = true; - } elseif($custom_fields && stripos($field, 'credit') !== false) { + } elseif ($custom_fields && stripos($field, 'credit') !== false) { $field = str_replace("credit", "invoice", $field); - } elseif($custom_fields && stripos($field, 'quote') !== false) { + } elseif ($custom_fields && stripos($field, 'quote') !== false) { $field = str_replace("quote", "invoice", $field); } diff --git a/app/Utils/HostedPDF/NinjaPdf.php b/app/Utils/HostedPDF/NinjaPdf.php index cc62daa89b..daa941cc70 100644 --- a/app/Utils/HostedPDF/NinjaPdf.php +++ b/app/Utils/HostedPDF/NinjaPdf.php @@ -29,8 +29,8 @@ class NinjaPdf RequestOptions::JSON => ['html' => $html], ]); - + return $response->getBody()->getContents(); } -} \ No newline at end of file +} diff --git a/app/Utils/HtmlEngine.php b/app/Utils/HtmlEngine.php index 8fd6ecf0de..6c4bca2d2e 100644 --- a/app/Utils/HtmlEngine.php +++ b/app/Utils/HtmlEngine.php @@ -229,8 +229,9 @@ class HtmlEngine $data['$status_logo'] = ['value' => '
' . ctrans('texts.paid') .'
', 'label' => '']; - if($this->entity->status_id == 5) + if ($this->entity->status_id == 5) { $data['$status_logo'] = ['value' => '
' . ctrans('texts.cancelled') .'
', 'label' => '']; + } $data['$show_paid_stamp'] = ['value' => in_array($this->entity->status_id, [4,5]) && $this->settings->show_paid_stamp ? 'flex' : 'none', 'label' => '']; @@ -239,7 +240,7 @@ class HtmlEngine if (strlen($this->company->getSetting('qr_iban')) > 5) { try { $data['$swiss_qr'] = ['value' => (new SwissQrGenerator($this->entity, $this->company))->run(), 'label' => '']; - } catch(\Exception $e) { + } catch (\Exception $e) { $data['$swiss_qr'] = ['value' => '', 'label' => '']; } } @@ -573,7 +574,7 @@ class HtmlEngine $data['$spc_qr_code'] = ['value' => $this->company->present()->getSpcQrCode($this->client->currency()->code, $this->entity->number, $this->entity->balance, $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'company1', $this->settings->custom_value1, $this->client)), 'label' => '']; - if(Ninja::isHosted()) { + if (Ninja::isHosted()) { $logo = $this->company->present()->logo($this->settings); } else { $logo = $this->company->present()->logo_base64($this->settings); @@ -644,7 +645,7 @@ class HtmlEngine $data['$task.task4'] = ['value' => '', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'task4')]; - if($this->entity->vendor) { + if ($this->entity->vendor) { $data['$vendor_name'] = ['value' => $this->entity->vendor->present()->name() ?: ' ', 'label' => ctrans('texts.vendor_name')]; $data['$vendor.name'] = &$data['$vendor_name']; @@ -758,8 +759,7 @@ class HtmlEngine $payment = $this->entity->net_payments()->first(); - if($payment) - { + if ($payment) { $data['$payment.custom1'] = ['value' => $payment->custom_value1, 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'payment1')]; $data['$payment.custom2'] = ['value' => $payment->custom_value2, 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'payment2')]; $data['$payment.custom3'] = ['value' => $payment->custom_value3, 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'payment3')]; @@ -786,7 +786,7 @@ class HtmlEngine private function getPaymentMeta(\App\Models\Payment $payment) { - if(!is_array($payment->refund_meta)) { + if (!is_array($payment->refund_meta)) { return ''; } @@ -799,13 +799,14 @@ class HtmlEngine $map = []; - foreach($refund['invoices'] as $refunded_invoice) { + foreach ($refund['invoices'] as $refunded_invoice) { $invoice = \App\Models\Invoice::withTrashed()->find($refunded_invoice['invoice_id']); $amount = Number::formatMoney($refunded_invoice['amount'], $payment->client); $notes = ctrans('texts.status_partially_refunded_amount', ['amount' => $amount]); - if($invoice) + if ($invoice) { array_push($map, "{$date} {$entity} #{$invoice->number} {$notes}\n"); + } } @@ -827,15 +828,15 @@ class HtmlEngine $tax_label .= ctrans('texts.reverse_tax_info') . "
"; } - if((int)$this->client->country_id !== (int)$this->company->settings->country_id) { + if ((int)$this->client->country_id !== (int)$this->company->settings->country_id) { $tax_label .= ctrans('texts.intracommunity_tax_info') . "
"; - if($this->entity_calc->getTotalTaxes() > 0) { + if ($this->entity_calc->getTotalTaxes() > 0) { $tax_label = ''; } } - if (isset($this->entity->company->tax_data->regions->EU->has_sales_above_threshold) && !$this->entity->company->tax_data->regions->EU->has_sales_above_threshold){ + if (isset($this->entity->company->tax_data->regions->EU->has_sales_above_threshold) && !$this->entity->company->tax_data->regions->EU->has_sales_above_threshold) { $tax_label .= ctrans('text.small_company_info') ."
"; } @@ -844,7 +845,7 @@ class HtmlEngine private function getBalance() { - if($this->entity->status_id == 1) { + if ($this->entity->status_id == 1) { return $this->entity->amount; } diff --git a/app/Utils/Number.php b/app/Utils/Number.php index 84394be04e..650bc64cad 100644 --- a/app/Utils/Number.php +++ b/app/Utils/Number.php @@ -89,7 +89,7 @@ class Number public static function parseFloat($value) { - if(!$value) { + if (!$value) { return 0; } @@ -99,17 +99,17 @@ class Number $decimal = strpos($value, '.'); $comma = strpos($value, ','); - if($comma === false) { //no comma must be a decimal number already + if ($comma === false) { //no comma must be a decimal number already return (float) $value; } - if(!$decimal && substr($value, -3, 1) != ",") { + if (!$decimal && substr($value, -3, 1) != ",") { $value = $value.".00"; } $decimal = strpos($value, '.'); - if($decimal < $comma) { //decimal before a comma = euro + if ($decimal < $comma) { //decimal before a comma = euro $value = str_replace(['.',','], ['','.'], $value); return (float) $value; } @@ -132,13 +132,13 @@ class Number public static function parseFloatXX($value) { - if(!$value) { + if (!$value) { return 0; } $multiplier = false; - if(substr($value, 0, 1) == '-') { + if (substr($value, 0, 1) == '-') { $multiplier = -1; } @@ -152,7 +152,7 @@ class Number $s = str_replace('.', '', substr($s, 0, -3)).substr($s, -3); - if($multiplier) { + if ($multiplier) { $s = floatval($s) * -1; } @@ -164,7 +164,7 @@ class Number public static function parseFloat2($value) { - if(!$value) { + if (!$value) { return 0; } @@ -175,11 +175,11 @@ class Number $comma = strpos($value, ','); //check the 3rd last character - if(!in_array(substr($value, -3, 1), [".", ","])) { + if (!in_array(substr($value, -3, 1), [".", ","])) { - if($comma && (substr($value, -3, 1) != ".")) { + if ($comma && (substr($value, -3, 1) != ".")) { $value .= ".00"; - } elseif($decimal && (substr($value, -3, 1) != ",")) { + } elseif ($decimal && (substr($value, -3, 1) != ",")) { $value .= ",00"; } @@ -188,11 +188,11 @@ class Number $decimal = strpos($value, '.'); $comma = strpos($value, ','); - if($comma === false) { //no comma must be a decimal number already + if ($comma === false) { //no comma must be a decimal number already return (float) $value; } - if($decimal < $comma) { //decimal before a comma = euro + if ($decimal < $comma) { //decimal before a comma = euro $value = str_replace(['.',','], ['','.'], $value); return (float) $value; } @@ -335,7 +335,7 @@ class Number } //04-04-2023 if currency = JPY override precision to 0 - if($currency->code == 'JPY') { + if ($currency->code == 'JPY') { $precision = 0; } diff --git a/app/Utils/SystemHealth.php b/app/Utils/SystemHealth.php index 429503c4f8..6aeef36458 100644 --- a/app/Utils/SystemHealth.php +++ b/app/Utils/SystemHealth.php @@ -104,7 +104,7 @@ class SystemHealth $cs = DB::table('clients') ->select('settings->currency_id as id') ->get(); - } catch(\Exception $e) { + } catch (\Exception $e) { return true; //fresh installs, there may be no DB connection, nor migrations could have run yet. } diff --git a/app/Utils/TemplateEngine.php b/app/Utils/TemplateEngine.php index c8b32db3d9..aba863a1a2 100644 --- a/app/Utils/TemplateEngine.php +++ b/app/Utils/TemplateEngine.php @@ -441,13 +441,13 @@ class TemplateEngine $client->load('company'); } - }catch(\Throwable $th){ + } catch (\Throwable $th) { nlog("Throwable:: transaction:: TemplateEngine MockEntity"); - + DB::connection(config('database.default'))->rollBack(); } - + } private function tearDown() diff --git a/app/Utils/Traits/CleanLineItems.php b/app/Utils/Traits/CleanLineItems.php index 04c084e46e..c123fc0d8c 100644 --- a/app/Utils/Traits/CleanLineItems.php +++ b/app/Utils/Traits/CleanLineItems.php @@ -78,9 +78,9 @@ trait CleanLineItems if (! array_key_exists('tax_id', $item)) { $item['tax_id'] = '1'; - } elseif(array_key_exists('tax_id', $item) && $item['tax_id'] == '') { + } elseif (array_key_exists('tax_id', $item) && $item['tax_id'] == '') { - if($item['type_id'] == '2') { + if ($item['type_id'] == '2') { $item['tax_id'] = '2'; } else { $item['tax_id'] = '1'; @@ -88,22 +88,22 @@ trait CleanLineItems } - if(isset($item['notes'])) { + if (isset($item['notes'])) { $item['notes'] = str_replace(["translations); } - foreach(['translations','pdf_variables'] as $key) { + foreach (['translations','pdf_variables'] as $key) { if (property_exists($settings, $key)) { unset($settings->{$key}); } @@ -115,8 +115,7 @@ trait ClientGroupSettingsSaver continue; } - /*Separate loop if it is a _id field which is an integer cast as a string*/ - elseif (substr($key, -3) == '_id' || + /*Separate loop if it is a _id field which is an integer cast as a string*/ elseif (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter' || ($key == 'payment_terms' && property_exists($settings, 'payment_terms') && strlen($settings->{$key}) >= 1) || ($key == 'valid_until' && property_exists($settings, 'valid_until') && strlen($settings->{$key}) >= 1)) { diff --git a/app/Utils/Traits/CompanySettingsSaver.php b/app/Utils/Traits/CompanySettingsSaver.php index 1b3c304071..ca8eeb9617 100644 --- a/app/Utils/Traits/CompanySettingsSaver.php +++ b/app/Utils/Traits/CompanySettingsSaver.php @@ -86,16 +86,16 @@ trait CompanySettingsSaver $entity->settings = $company_settings; - if($entity?->calculate_taxes && $company_settings->country_id == "840" && array_key_exists('settings', $entity->getDirty()) && !$entity?->account->isFreeHostedClient()) { + if ($entity?->calculate_taxes && $company_settings->country_id == "840" && array_key_exists('settings', $entity->getDirty()) && !$entity?->account->isFreeHostedClient()) { $old_settings = $entity->getOriginal()['settings']; /** Monitor changes of the Postal code */ - if($old_settings->postal_code != $company_settings->postal_code) { + if ($old_settings->postal_code != $company_settings->postal_code) { CompanyTaxRate::dispatch($entity); } - } elseif($entity?->calculate_taxes && $company_settings->country_id == "840" && array_key_exists('calculate_taxes', $entity->getDirty()) && $entity->getOriginal('calculate_taxes') == 0 && !$entity?->account->isFreeHostedClient()) { + } elseif ($entity?->calculate_taxes && $company_settings->country_id == "840" && array_key_exists('calculate_taxes', $entity->getDirty()) && $entity->getOriginal('calculate_taxes') == 0 && !$entity?->account->isFreeHostedClient()) { CompanyTaxRate::dispatch($entity); } @@ -132,11 +132,10 @@ trait CompanySettingsSaver continue; } - /*Separate loop if it is a _id field which is an integer cast as a string*/ - elseif (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter') { + /*Separate loop if it is a _id field which is an integer cast as a string*/ elseif (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter') { $value = 'integer'; - if(in_array($key, $this->string_ids)) { + if (in_array($key, $this->string_ids)) { // if ($key == 'besr_id') { $value = 'string'; } @@ -205,7 +204,7 @@ trait CompanySettingsSaver if (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter') { $value = 'integer'; - if(in_array($key, $this->string_ids)) { + if (in_array($key, $this->string_ids)) { $value = 'string'; } diff --git a/app/Utils/Traits/MakesDates.php b/app/Utils/Traits/MakesDates.php index a35dc2abd4..96299f2093 100644 --- a/app/Utils/Traits/MakesDates.php +++ b/app/Utils/Traits/MakesDates.php @@ -123,24 +123,24 @@ trait MakesDates public function calculateStartAndEndDates(array $data, ?Company $company = null): array { //override for financial years - if($data['date_range'] == 'this_year') { + if ($data['date_range'] == 'this_year') { $first_month_of_year = $company ? $company?->first_month_of_year : 1; $fin_year_start = now()->createFromDate(now()->year, $first_month_of_year, 1); - if(now()->lt($fin_year_start)) { + if (now()->lt($fin_year_start)) { $fin_year_start->subYearNoOverflow(); } } //override for financial years - if($data['date_range'] == 'last_year') { + if ($data['date_range'] == 'last_year') { $first_month_of_year = $company ? $company?->first_month_of_year : 1; $fin_year_start = now()->createFromDate(now()->year, $first_month_of_year, 1); $fin_year_start->subYearNoOverflow(); - if(now()->subYear()->lt($fin_year_start)) { + if (now()->subYear()->lt($fin_year_start)) { $fin_year_start->subYearNoOverflow(); } @@ -165,14 +165,14 @@ trait MakesDates { //override for financial years - if($data['date_range'] == 'this_year') { + if ($data['date_range'] == 'this_year') { $first_month_of_year = $company ? $company?->first_month_of_year : 1; $fin_year_start = now()->createFromDate(now()->year, $first_month_of_year, 1); $fin_year_start->subYearNoOverflow(); - if(now()->subYear()->lt($fin_year_start)) { + if (now()->subYear()->lt($fin_year_start)) { $fin_year_start->subYearNoOverflow(); } diff --git a/app/Utils/Traits/MakesHash.php b/app/Utils/Traits/MakesHash.php index d04060375f..1107076cec 100644 --- a/app/Utils/Traits/MakesHash.php +++ b/app/Utils/Traits/MakesHash.php @@ -70,9 +70,9 @@ trait MakesHash $decoded_array = $hashids->decode($value); - if(isset($decoded_array[0]) ?? false) { + if (isset($decoded_array[0]) ?? false) { return $decoded_array[0]; - } elseif($return_string_failure) { + } elseif ($return_string_failure) { return "Invalid Primary Key"; } else { throw new \Exception('Invalid Primary Key'); diff --git a/app/Utils/Traits/MakesReminders.php b/app/Utils/Traits/MakesReminders.php index e02892ec3a..9cc16a13dc 100644 --- a/app/Utils/Traits/MakesReminders.php +++ b/app/Utils/Traits/MakesReminders.php @@ -84,7 +84,7 @@ trait MakesReminders { $interval = $this->addTimeInterval($last_sent_date, $endless_reminder_frequency_id); - if(is_null($interval)) { + if (is_null($interval)) { return false; } diff --git a/app/Utils/Traits/Pdf/PDF.php b/app/Utils/Traits/Pdf/PDF.php index 9a5a84ba56..cc80b242b2 100644 --- a/app/Utils/Traits/Pdf/PDF.php +++ b/app/Utils/Traits/Pdf/PDF.php @@ -29,7 +29,7 @@ class PDF extends FPDI try { $trans = mb_convert_encoding($trans, 'ISO-8859-1', 'UTF-8'); - } catch(\Exception $e) { + } catch (\Exception $e) { } $this->Cell(0, 5, $trans, 0, 0, $this->text_alignment); diff --git a/app/Utils/Traits/SettingsSaver.php b/app/Utils/Traits/SettingsSaver.php index 417dc1cce5..9a89a217f6 100644 --- a/app/Utils/Traits/SettingsSaver.php +++ b/app/Utils/Traits/SettingsSaver.php @@ -59,11 +59,10 @@ trait SettingsSaver continue; } - /*Separate loop if it is a _id field which is an integer cast as a string*/ - elseif (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter' || ($key == 'payment_terms' && property_exists($settings, $key) && strlen($settings->{$key}) >= 1) || ($key == 'valid_until' && property_exists($settings, $key) && strlen($settings->{$key}) >= 1)) { + /*Separate loop if it is a _id field which is an integer cast as a string*/ elseif (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter' || ($key == 'payment_terms' && property_exists($settings, $key) && strlen($settings->{$key}) >= 1) || ($key == 'valid_until' && property_exists($settings, $key) && strlen($settings->{$key}) >= 1)) { $value = 'integer'; - if(in_array($key, $this->string_ids)) { + if (in_array($key, $this->string_ids)) { // if ($key == 'gmail_sending_user_id' || $key == 'besr_id') { $value = 'string'; } diff --git a/app/Utils/Traits/SubscriptionHooker.php b/app/Utils/Traits/SubscriptionHooker.php index e005fe9cec..fb0f771391 100644 --- a/app/Utils/Traits/SubscriptionHooker.php +++ b/app/Utils/Traits/SubscriptionHooker.php @@ -48,7 +48,7 @@ trait SubscriptionHooker RequestOptions::JSON => ['body' => $body], RequestOptions::ALLOW_REDIRECTS => false, ]); - if($response_body = json_decode($response->getBody(), true)) { + if ($response_body = json_decode($response->getBody(), true)) { return array_merge($body, $response_body); }