From 4a368bfaaf86b3a68b9ad637b9c53cba347bec06 Mon Sep 17 00:00:00 2001 From: Gabriel Cataldo Date: Tue, 5 Dec 2023 09:20:37 -0300 Subject: [PATCH] Finish unit test --- _example/account/main.go | 28 +- _example/anticipation/main.go | 6 +- _example/charge/main.go | 146 ++------- _example/credit_bureau/main.go | 10 +- _example/customer/main.go | 12 +- _example/fiscal_info/main.go | 28 +- _example/installment/main.go | 2 +- _example/invoice/main.go | 2 +- _example/mobile_phone/main.go | 2 +- _example/negativity/main.go | 4 +- _example/notification/main.go | 32 +- _example/payment_link/main.go | 18 +- _example/subaccount/main.go | 4 +- _example/subscription/main.go | 13 +- _example/transfer/main.go | 10 +- _example/webhook/main.go | 4 +- asaas/account.go | 6 +- asaas/account_test.go | 80 ++--- asaas/anticipation_test.go | 42 ++- asaas/assert.go | 84 ++--- asaas/bill_payment.go | 4 +- asaas/bill_payment_test.go | 40 ++- asaas/charge.go | 13 +- asaas/charge_test.go | 119 +++---- asaas/credit_bureau_test.go | 10 +- asaas/credit_card_test.go | 8 +- asaas/customer.go | 2 +- asaas/customer_test.go | 23 +- asaas/date.go | 22 +- asaas/datetime.go | 43 ++- asaas/enum.go | 461 --------------------------- asaas/file.go | 26 +- asaas/fiscal_info.go | 8 +- asaas/fiscal_info_test.go | 12 +- asaas/installment.go | 30 +- asaas/installment_test.go | 41 +-- asaas/invoice.go | 2 +- asaas/invoice_test.go | 26 +- asaas/main_test.go | 449 ++++++++------------------ asaas/mobile_phone_test.go | 32 +- asaas/negativity_test.go | 40 +-- asaas/notification_test.go | 13 +- asaas/payment_link.go | 4 +- asaas/payment_link_test.go | 40 +-- asaas/pix_test.go | 36 +-- asaas/request.go | 42 +-- asaas/response.go | 22 +- asaas/split.go | 5 + asaas/subaccount.go | 8 +- asaas/subaccount_test.go | 71 ++--- asaas/subscription_test.go | 57 ++-- asaas/transfer_test.go | 13 +- asaas/validator.go | 154 --------- asaas/webhook.go | 4 +- asaas/webhook_test.go | 12 +- internal/resource/brazil-states.json | 110 ------- internal/util/util.go | 79 +---- 57 files changed, 662 insertions(+), 1952 deletions(-) delete mode 100644 asaas/validator.go delete mode 100644 internal/resource/brazil-states.json diff --git a/_example/account/main.go b/_example/account/main.go index a72fb8f..350ca41 100644 --- a/_example/account/main.go +++ b/_example/account/main.go @@ -29,19 +29,19 @@ func getAccountBalance() { func updateAccount() { resp, err := accountAsaas.Update(context.TODO(), asaas.UpdateAccountRequest{ - PersonType: asaas.PersonTypePhysical, - CpfCnpj: "29376892000101", + PersonType: "", + CpfCnpj: "", BirthDate: asaas.Date{}, - CompanyType: asaas.CompanyTypeLimited, - Email: "xxxxxx@gmail.com", - Phone: "", - MobilePhone: "", - Site: "", - PostalCode: "69620-970", - Address: "Praça São Cristovão, s/n", - AddressNumber: "10", - Complement: "", - Province: "Centro", + CompanyType: nil, + Email: "", + Phone: nil, + MobilePhone: nil, + Site: nil, + PostalCode: "", + Address: nil, + AddressNumber: nil, + Complement: nil, + Province: nil, }) if err != nil { fmt.Println("error:", err) @@ -54,8 +54,8 @@ func updateAccount() { func getAccountStatement() { resp, err := accountAsaas.GetAccountStatement(context.TODO(), asaas.GetAccountStatementRequest{ - StartDate: nil, - FinishDate: nil, + StartDate: asaas.Date{}, + FinishDate: asaas.Date{}, Offset: 0, Limit: 10, Order: asaas.OrderDesc, diff --git a/_example/anticipation/main.go b/_example/anticipation/main.go index dd27910..a4e522d 100644 --- a/_example/anticipation/main.go +++ b/_example/anticipation/main.go @@ -19,7 +19,7 @@ func main() { func simulateAnticipation() { resp, err := anticipationAsaas.Simulate(context.TODO(), asaas.AnticipationSimulateRequest{ - Payment: "pay_jxqnfvp1qt8qpf5s", + Payment: "", Installment: "", }) if err != nil { @@ -33,7 +33,7 @@ func simulateAnticipation() { func requestAnticipation() { resp, err := anticipationAsaas.Request(context.TODO(), asaas.AnticipationRequest{ - Payment: "pay_jxqnfvp1qt8qpf5s", + Payment: "", Installment: "", Documents: nil, }) @@ -47,7 +47,7 @@ func requestAnticipation() { } func getAnticipationById() { - resp, err := anticipationAsaas.GetById(context.TODO(), "5be2e7dd-f573-49f2-b693-bce455d6e0aa") + resp, err := anticipationAsaas.GetById(context.TODO(), "") if err != nil { fmt.Println("error:", err) } else if resp.IsSuccess() { diff --git a/_example/charge/main.go b/_example/charge/main.go index 51e5ce0..91da484 100644 --- a/_example/charge/main.go +++ b/_example/charge/main.go @@ -5,134 +5,26 @@ import ( "fmt" "github.com/GabrielHCataldo/go-asaas/asaas" "os" - "time" ) var chargeAsaas asaas.Charge func main() { chargeAsaas = asaas.NewCharge(asaas.EnvSandbox, os.Getenv("ASAAS_ACCESS_TOKEN")) - createChargePix() - createChargeBill() - createChargeUndefined() - createChargeCreditCard() + createCharge() updateChargeById() getChargeById() getAllCustomers() deleteChargeById() } -func createChargePix() { +func createCharge() { resp, err := chargeAsaas.Create(context.TODO(), asaas.CreateChargeRequest{ - Customer: "cus_000005799255", - BillingType: asaas.BillingTypePix, - Value: 10, - DueDate: asaas.NewDate(2023, 12, 2, time.Local), - Description: "Example pix charge", - ExternalReference: "", - Discount: nil, - Interest: nil, - Fine: nil, - PostalService: false, - Split: nil, - Callback: nil, - CreditCard: nil, - CreditCardHolderInfo: nil, - CreditCardToken: "", - InstallmentCount: 0, - InstallmentValue: 0, - }) - if err != nil { - fmt.Println("error:", err) - } else if resp.IsSuccess() { - fmt.Println("success:", resp) - } else { - fmt.Println("failure:", resp.Errors) - } -} - -func createChargeBill() { - resp, err := chargeAsaas.Create(context.TODO(), asaas.CreateChargeRequest{ - Customer: "cus_000005799255", - BillingType: asaas.BillingTypeBankSlip, - Value: 10, - DueDate: asaas.NewDate(2023, 12, 2, time.Local), - Description: "Example bill charge", - ExternalReference: "", - Discount: nil, - Interest: nil, - Fine: nil, - PostalService: false, - Split: nil, - Callback: nil, - CreditCard: nil, - CreditCardHolderInfo: nil, - CreditCardToken: "", - InstallmentCount: 0, - InstallmentValue: 0, - }) - if err != nil { - fmt.Println("error:", err) - } else if resp.IsSuccess() { - fmt.Println("success:", resp) - } else { - fmt.Println("failure:", resp.Errors) - } -} - -func createChargeCreditCard() { - resp, err := chargeAsaas.Create(context.TODO(), asaas.CreateChargeRequest{ - Customer: "cus_000005799255", - BillingType: asaas.BillingTypeCreditCard, - Value: 10, - DueDate: asaas.NewDate(2023, 12, 1, time.Local), - Description: "Example bill charge", - ExternalReference: "", - Discount: nil, - Interest: nil, - Fine: nil, - PostalService: false, - Split: nil, - Callback: nil, - CreditCard: &asaas.CreditCardRequest{ - HolderName: "unit test go", - Number: "4000000000000010", - ExpiryMonth: "05", - ExpiryYear: "2035", - Ccv: "123", - }, - CreditCardHolderInfo: &asaas.CreditCardHolderInfoRequest{ - Name: "Example go", - CpfCnpj: "29376892000101", - Email: "example@gmail.com", - Phone: "4738010919", - MobilePhone: "47998781877", - PostalCode: "89223-005", - AddressNumber: "10", - AddressComplement: "", - }, - CreditCardToken: "", - InstallmentCount: 2, - InstallmentValue: 5, - AuthorizeOnly: false, - RemoteIp: "", - }) - if err != nil { - fmt.Println("error:", err) - } else if resp.IsSuccess() { - fmt.Println("success:", resp) - } else { - fmt.Println("failure:", resp.Errors) - } -} - -func createChargeUndefined() { - resp, err := chargeAsaas.Create(context.TODO(), asaas.CreateChargeRequest{ - Customer: "cus_000005799255", - BillingType: asaas.BillingTypeUndefined, - Value: 10, - DueDate: asaas.NewDate(2023, 12, 2, time.Local), - Description: "Example bill charge", + Customer: "", + BillingType: "", + Value: 0, + DueDate: asaas.Date{}, + Description: "", ExternalReference: "", Discount: nil, Interest: nil, @@ -145,6 +37,8 @@ func createChargeUndefined() { CreditCardToken: "", InstallmentCount: 0, InstallmentValue: 0, + AuthorizeOnly: false, + RemoteIp: "", }) if err != nil { fmt.Println("error:", err) @@ -156,21 +50,21 @@ func createChargeUndefined() { } func updateChargeById() { - resp, err := chargeAsaas.UpdateById(context.TODO(), "pay_jxqnfvp1qt8qpf5s", asaas.UpdateChargeRequest{ + resp, err := chargeAsaas.UpdateById(context.TODO(), "", asaas.UpdateChargeRequest{ Customer: "", - BillingType: asaas.BillingTypeBankSlip, - Value: 5, + BillingType: "", + Value: 0, DueDate: asaas.Date{}, - Description: asaas.Pointer("updated"), - ExternalReference: asaas.Pointer(""), + Description: nil, + ExternalReference: nil, Discount: nil, Interest: nil, Fine: nil, - PostalService: asaas.Pointer(false), + PostalService: nil, Split: nil, Callback: nil, - InstallmentCount: 2, - InstallmentValue: 2.5, + InstallmentCount: 0, + InstallmentValue: 0, }) if err != nil { fmt.Println("error:", err) @@ -182,7 +76,7 @@ func updateChargeById() { } func deleteChargeById() { - deleteResponse, err := chargeAsaas.DeleteById(context.TODO(), "pay_484rmiebm04419ey") + deleteResponse, err := chargeAsaas.DeleteById(context.TODO(), "") if err != nil { fmt.Println("error:", err) } else if deleteResponse.IsSuccess() { @@ -193,7 +87,7 @@ func deleteChargeById() { } func getChargeById() { - resp, err := chargeAsaas.GetById(context.TODO(), "pay_jxqnfvp1qt8qpf5s") + resp, err := chargeAsaas.GetById(context.TODO(), "") if err != nil { fmt.Println("error:", err) } else if resp.IsSuccess() { @@ -229,7 +123,7 @@ func getAllCustomers() { DueDateLe: asaas.Date{}, User: "", Offset: 0, - Limit: 10, + Limit: 0, }) if err != nil { fmt.Println("error:", err) diff --git a/_example/credit_bureau/main.go b/_example/credit_bureau/main.go index 3eaf7fd..fccad5f 100644 --- a/_example/credit_bureau/main.go +++ b/_example/credit_bureau/main.go @@ -18,9 +18,9 @@ func main() { func getCreditBureauReport() { resp, err := creditBureauAsaas.GetReport(context.TODO(), asaas.GetReportRequest{ - Customer: "cus_000005791749", + Customer: "", CpfCnpj: "", - State: "SP", + State: "", }) if err != nil { fmt.Println("error:", err) @@ -46,10 +46,10 @@ func getCreditBureauReportById() { func getAllCreditBureauReports() { resp, err := creditBureauAsaas.GetAllReports(context.TODO(), asaas.GetAllReportsRequest{ - StartDate: nil, - EndDate: nil, + StartDate: asaas.Date{}, + EndDate: asaas.Date{}, Offset: 0, - Limit: 10, + Limit: 0, }) if err != nil { fmt.Println("error:", err) diff --git a/_example/customer/main.go b/_example/customer/main.go index 09a8e3e..46286aa 100644 --- a/_example/customer/main.go +++ b/_example/customer/main.go @@ -20,8 +20,8 @@ func main() { func createCustomer() { resp, err := customerAsaas.Create(context.TODO(), asaas.CreateCustomerRequest{ - Name: "Go Asaas Test", - CpfCnpj: "85185238003", + Name: "", + CpfCnpj: "", Email: "", Phone: "", MobilePhone: "", @@ -49,7 +49,7 @@ func createCustomer() { } func updateCustomerById() { - resp, err := customerAsaas.UpdateById(context.TODO(), "cus_000005799255", asaas.UpdateCustomerRequest{ + resp, err := customerAsaas.UpdateById(context.TODO(), "", asaas.UpdateCustomerRequest{ Name: "", CpfCnpj: nil, Email: nil, @@ -79,7 +79,7 @@ func updateCustomerById() { } func deleteCustomerById() { - deleteResponse, err := customerAsaas.DeleteById(context.TODO(), "cus_000005791749") + deleteResponse, err := customerAsaas.DeleteById(context.TODO(), "") if err != nil { fmt.Println("error:", err) } else if deleteResponse.IsSuccess() { @@ -90,7 +90,7 @@ func deleteCustomerById() { } func getCustomerById() { - resp, err := customerAsaas.GetById(context.TODO(), "cus_000005799255") + resp, err := customerAsaas.GetById(context.TODO(), "") if err != nil { fmt.Println("error:", err) } else if resp.IsSuccess() { @@ -110,7 +110,7 @@ func getAllCustomers() { GroupName: "", ExternalReference: "", Offset: 0, - Limit: 10, + Limit: 0, }) if err != nil { fmt.Println("error:", err) diff --git a/_example/fiscal_info/main.go b/_example/fiscal_info/main.go index d57c61b..dd7267f 100644 --- a/_example/fiscal_info/main.go +++ b/_example/fiscal_info/main.go @@ -19,20 +19,20 @@ func main() { func saveFiscalInfo() { resp, err := fiscalInfoAsaas.Save(context.TODO(), asaas.SaveFiscalInfoRequest{ Email: "", - MunicipalInscription: "", - SimplesNacional: false, - CulturalProjectsPromoter: false, - Cnae: "", - SpecialTaxRegime: "", - ServiceListItem: "", - RpsSerie: "", - RpsNumber: 0, - LoteNumber: 0, - Username: "", - Password: "", - AccessToken: "", + MunicipalInscription: nil, + SimplesNacional: nil, + CulturalProjectsPromoter: nil, + Cnae: nil, + SpecialTaxRegime: nil, + ServiceListItem: nil, + RpsSerie: nil, + RpsNumber: nil, + LoteNumber: nil, + Username: nil, + Password: nil, + AccessToken: nil, CertificateFile: nil, - CertificatePassword: "", + CertificatePassword: nil, }) if err != nil { fmt.Println("error:", err) @@ -60,7 +60,7 @@ func getAllFiscalInfoServices() { resp, err := fiscalInfoAsaas.GetAllServices(context.TODO(), asaas.GetAllServicesRequest{ Description: "", Offset: 0, - Limit: 10, + Limit: 0, }) if err != nil { fmt.Println("error:", err) diff --git a/_example/installment/main.go b/_example/installment/main.go index a0764a7..a852053 100644 --- a/_example/installment/main.go +++ b/_example/installment/main.go @@ -59,7 +59,7 @@ func getInstallmentById() { func getAllInstallments() { resp, err := installmentAsaas.GetAll(context.TODO(), asaas.PageableDefaultRequest{ Offset: 0, - Limit: 10, + Limit: 0, }) if err != nil { fmt.Println("error:", err) diff --git a/_example/invoice/main.go b/_example/invoice/main.go index ea402bf..8f85d50 100644 --- a/_example/invoice/main.go +++ b/_example/invoice/main.go @@ -93,7 +93,7 @@ func getAllInvoices() { ExternalReference: "", Status: "", Offset: 0, - Limit: 10, + Limit: 0, }) if err != nil { fmt.Println("error:", err) diff --git a/_example/mobile_phone/main.go b/_example/mobile_phone/main.go index 9cca596..420e9ed 100644 --- a/_example/mobile_phone/main.go +++ b/_example/mobile_phone/main.go @@ -60,7 +60,7 @@ func getMobilePhoneProviderByPhoneNumber() { func getAllMobilePhoneRecharges() { resp, err := mobilePhoneAsaas.GetAllRecharges(context.TODO(), asaas.PageableDefaultRequest{ Offset: 0, - Limit: 10, + Limit: 0, }) if err != nil { fmt.Println("error:", err) diff --git a/_example/negativity/main.go b/_example/negativity/main.go index 4807d00..2c5926b 100644 --- a/_example/negativity/main.go +++ b/_example/negativity/main.go @@ -58,7 +58,7 @@ func cancelNegativityById() { func getNegativityHistoryById() { resp, err := negativityAsaas.GetHistoryById(context.TODO(), "", asaas.PageableDefaultRequest{ Offset: 0, - Limit: 10, + Limit: 0, }) if err != nil { fmt.Println("error:", err) @@ -74,7 +74,7 @@ func getNegativityHistoryById() { func getChargesAvailableForDunning() { resp, err := negativityAsaas.GetChargesAvailableForDunning(context.TODO(), asaas.PageableDefaultRequest{ Offset: 0, - Limit: 10, + Limit: 0, }) if err != nil { fmt.Println("error:", err) diff --git a/_example/notification/main.go b/_example/notification/main.go index d4f5627..f6cceda 100644 --- a/_example/notification/main.go +++ b/_example/notification/main.go @@ -18,14 +18,14 @@ func main() { func updateNotificationById() { resp, err := negativityAsaas.UpdateById(context.TODO(), "", asaas.UpdateNotificationRequest{ - Enabled: false, - EmailEnabledForProvider: false, - SmsEnabledForProvider: false, - EmailEnabledForCustomer: false, - SmsEnabledForCustomer: false, - PhoneCallEnabledForCustomer: false, - WhatsappEnabledForCustomer: false, - ScheduleOffset: 0, + Enabled: nil, + EmailEnabledForProvider: nil, + SmsEnabledForProvider: nil, + EmailEnabledForCustomer: nil, + SmsEnabledForCustomer: nil, + PhoneCallEnabledForCustomer: nil, + WhatsappEnabledForCustomer: nil, + ScheduleOffset: nil, }) if err != nil { fmt.Println("error:", err) @@ -44,14 +44,14 @@ func updateNotificationManyByCustomer() { Notifications: []asaas.UpdateManyNotificationRequest{ { Id: "", - Enabled: false, - EmailEnabledForProvider: false, - SmsEnabledForProvider: false, - EmailEnabledForCustomer: false, - SmsEnabledForCustomer: false, - PhoneCallEnabledForCustomer: false, - WhatsappEnabledForCustomer: false, - ScheduleOffset: 0, + Enabled: nil, + EmailEnabledForProvider: nil, + SmsEnabledForProvider: nil, + EmailEnabledForCustomer: nil, + SmsEnabledForCustomer: nil, + PhoneCallEnabledForCustomer: nil, + WhatsappEnabledForCustomer: nil, + ScheduleOffset: nil, }, }, }) diff --git a/_example/payment_link/main.go b/_example/payment_link/main.go index 7ecce35..4519fba 100644 --- a/_example/payment_link/main.go +++ b/_example/payment_link/main.go @@ -24,7 +24,7 @@ func createPaymentLink() { Description: "", BillingType: "", ChargeType: "", - EndDate: nil, + EndDate: asaas.Date{}, Value: 0, DueDateLimitDays: 0, SubscriptionCycle: "", @@ -44,15 +44,15 @@ func createPaymentLink() { func updatePaymentLinkById() { resp, err := paymentLinkAsaas.UpdateById(context.TODO(), "", asaas.UpdatePaymentLinkRequest{ Name: "", - Description: "", + Description: nil, BillingType: "", ChargeType: "", - EndDate: nil, - Value: 0, + EndDate: asaas.Date{}, + Value: nil, DueDateLimitDays: 0, - SubscriptionCycle: "", + SubscriptionCycle: nil, MaxInstallmentCount: 0, - NotificationEnabled: false, + NotificationEnabled: nil, Callback: nil, }) if err != nil { @@ -95,10 +95,10 @@ func getPaymentLinkById() { func getAllPaymentLink() { resp, err := paymentLinkAsaas.GetAll(context.TODO(), asaas.GetAllPaymentLinksRequest{ Name: "", - Active: false, - IncludeDeleted: false, + Active: nil, + IncludeDeleted: nil, Offset: 0, - Limit: 10, + Limit: 0, }) if err != nil { fmt.Println("error:", err) diff --git a/_example/subaccount/main.go b/_example/subaccount/main.go index b711b7d..d4934f2 100644 --- a/_example/subaccount/main.go +++ b/_example/subaccount/main.go @@ -22,7 +22,7 @@ func createSubaccount() { Email: "", LoginEmail: "", CpfCnpj: "", - BirthDate: nil, + BirthDate: asaas.Date{}, CompanyType: "", Phone: "", MobilePhone: "", @@ -63,7 +63,7 @@ func getAllSubaccount() { Name: "", WalletId: "", Offset: 0, - Limit: 10, + Limit: 0, }) if err != nil { fmt.Println("error:", err) diff --git a/_example/subscription/main.go b/_example/subscription/main.go index 3e450df..93d0515 100644 --- a/_example/subscription/main.go +++ b/_example/subscription/main.go @@ -32,7 +32,7 @@ func createSubscription() { CreditCard: nil, CreditCardHolderInfo: nil, CreditCardToken: "", - EndDate: nil, + EndDate: asaas.Date{}, MaxPayments: 0, ExternalReference: "", Split: nil, @@ -52,16 +52,13 @@ func updateSubscriptionById() { BillingType: "", Value: 0, Status: "", - NextDueDate: nil, + NextDueDate: asaas.Date{}, Discount: nil, Interest: nil, Fine: nil, Cycle: "", - Description: "", - CreditCard: nil, - CreditCardHolderInfo: nil, - CreditCardToken: "", - EndDate: nil, + Description: nil, + EndDate: asaas.Date{}, UpdatePendingPayments: false, ExternalReference: "", }) @@ -114,7 +111,7 @@ func getAllSubscription() { Order: "", Sort: "", Offset: 0, - Limit: 10, + Limit: 0, }) if err != nil { fmt.Println("error:", err) diff --git a/_example/transfer/main.go b/_example/transfer/main.go index 6445184..e90bea9 100644 --- a/_example/transfer/main.go +++ b/_example/transfer/main.go @@ -26,7 +26,7 @@ func transferToBank() { PixAddressKey: "", PixAddressKeyType: "", Description: "", - ScheduleDate: nil, + ScheduleDate: asaas.Date{}, }) if err != nil { fmt.Println("error:", err) @@ -79,10 +79,10 @@ func getTransferById() { func getAllTransfer() { resp, err := transferAsaas.GetAll(context.TODO(), asaas.GetAllTransfersRequest{ - DateCreatedGe: nil, - DateCreatedLe: nil, - TransferDateGe: nil, - TransferDateLe: nil, + DateCreatedGe: asaas.Date{}, + DateCreatedLe: asaas.Date{}, + TransferDateGe: asaas.Date{}, + TransferDateLe: asaas.Date{}, Type: "", }) if err != nil { diff --git a/_example/webhook/main.go b/_example/webhook/main.go index 313e1ae..0fe5ed6 100644 --- a/_example/webhook/main.go +++ b/_example/webhook/main.go @@ -20,8 +20,8 @@ func saveWebhookSetting() { Url: "", Email: "", ApiVersion: "", - Enabled: false, - Interrupted: false, + Enabled: nil, + Interrupted: nil, AuthToken: "", }) if err != nil { diff --git a/asaas/account.go b/asaas/account.go index 3bcc190..8f7536a 100644 --- a/asaas/account.go +++ b/asaas/account.go @@ -29,7 +29,7 @@ type UpdateAccountRequest struct { // Tipo da empresa (somente quando Pessoa Jurídica) CompanyType *CompanyType `json:"companyType,omitempty"` // Email da conta - Email *string `json:"email,omitempty"` + Email string `json:"email,omitempty"` // Telefone Phone *string `json:"phone,omitempty"` // Telefone celular @@ -210,7 +210,7 @@ type AccountCreditCardFeesResponse struct { DiscountOneInstallmentPercentage float64 `json:"discountOneInstallmentPercentage"` DiscountUpToSixInstallmentsPercentage float64 `json:"discountUpToSixInstallmentsPercentage"` DiscountUpToTwelveInstallmentsPercentage float64 `json:"discountUpToTwelveInstallmentsPercentage"` - DiscountExpiration float64 `json:"discountExpiration"` + DiscountExpiration Date `json:"discountExpiration"` } type AccountDebitCardFeesResponse struct { @@ -918,7 +918,7 @@ func (a account) GetAccountStatement(ctx context.Context, filter GetAccountState func (a account) GetPaymentStatistic(ctx context.Context, filter GetPaymentStatisticRequest) ( *PaymentStatisticResponse, error) { req := NewRequest[PaymentStatisticResponse](ctx, a.env, a.accessToken) - return req.make(http.MethodGet, "/v3/payment/statistics", filter) + return req.make(http.MethodGet, "/v3/finance/payment/statistics", filter) } func (a account) GetInvoiceCustomization(ctx context.Context) (*InvoiceCustomizationResponse, error) { diff --git a/asaas/account_test.go b/asaas/account_test.go index 480e4ee..4f48170 100644 --- a/asaas/account_test.go +++ b/asaas/account_test.go @@ -9,142 +9,130 @@ import ( func TestAccountSaveInvoiceCustomization(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) - f, err := os.Open(getEnvValue(EnvImageName)) - assertFatalErrorNonnull(t, err) + f, _ := os.Open(getEnvValue(EnvImageName)) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAccount := NewAccount(EnvSandbox, accessToken) - resp, errAsaas := nAccount.SaveInvoiceCustomization(ctx, SaveInvoiceCustomizationRequest{ + resp, err := nAccount.SaveInvoiceCustomization(ctx, SaveInvoiceCustomizationRequest{ LogoBackgroundColor: "#FFFFFF", InfoBackgroundColor: "#FF0000", FontColor: "#000000", Enabled: false, LogoFile: f, }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } func TestAccountUpdate(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAccount := NewAccount(EnvSandbox, accessToken) - resp, errAsaas := nAccount.Update(ctx, UpdateAccountRequest{ - PersonType: PersonTypeJuridical, - CpfCnpj: "", - BirthDate: Date{}, + resp, err := nAccount.Update(ctx, UpdateAccountRequest{ + PersonType: PersonTypePhysical, + CpfCnpj: "02104996643", + BirthDate: NewDate(1999, 6, 2, time.Local), CompanyType: nil, - Email: nil, + Email: "gabrielcataldo20@gmail.com", Phone: nil, MobilePhone: nil, Site: Pointer("https://sitetest.com.br"), - PostalCode: "", + PostalCode: "69159-970", Address: nil, AddressNumber: nil, Complement: nil, Province: nil, }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } func TestAccountDeleteWhiteLabelSubaccount(t *testing.T) { + initSubaccountDocumentSent() accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) - initSubaccountDocument() ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAccount := NewAccount(EnvSandbox, accessToken) - resp, errAsaas := nAccount.DeleteWhiteLabelSubaccount(ctx, DeleteWhiteLabelSubaccountRequest{ + resp, err := nAccount.DeleteWhiteLabelSubaccount(ctx, DeleteWhiteLabelSubaccountRequest{ RemoveReason: "unit test", }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseFailure(t, resp, err) } func TestAccountGet(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAccount := NewAccount(EnvSandbox, accessToken) - resp, errAsaas := nAccount.Get(ctx) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nAccount.Get(ctx) + assertResponseSuccess(t, resp, err) } func TestAccountGetRegistrationStatus(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAccount := NewAccount(EnvSandbox, accessToken) - resp, errAsaas := nAccount.GetRegistrationStatus(ctx) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nAccount.GetRegistrationStatus(ctx) + assertResponseSuccess(t, resp, err) } func TestAccountGetBankInfo(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAccount := NewAccount(EnvSandbox, accessToken) - resp, errAsaas := nAccount.GetBankInfo(ctx) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nAccount.GetBankInfo(ctx) + assertResponseSuccess(t, resp, err) } func TestAccountGetFees(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAccount := NewAccount(EnvSandbox, accessToken) - resp, errAsaas := nAccount.GetFees(ctx) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nAccount.GetFees(ctx) + assertResponseSuccess(t, resp, err) } func TestAccountGetWallets(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAccount := NewAccount(EnvSandbox, accessToken) - resp, errAsaas := nAccount.GetWallets(ctx) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nAccount.GetWallets(ctx) + assertResponseSuccess(t, resp, err) } func TestAccountGetBalance(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAccount := NewAccount(EnvSandbox, accessToken) - resp, errAsaas := nAccount.GetBalance(ctx) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nAccount.GetBalance(ctx) + assertResponseSuccess(t, resp, err) } func TestAccountGetAccountStatement(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAccount := NewAccount(EnvSandbox, accessToken) - resp, errAsaas := nAccount.GetAccountStatement(ctx, GetAccountStatementRequest{ + resp, err := nAccount.GetAccountStatement(ctx, GetAccountStatementRequest{ StartDate: Date{}, FinishDate: Date{}, Offset: 0, Limit: 10, Order: "", }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } func TestAccountGetPaymentStatistic(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAccount := NewAccount(EnvSandbox, accessToken) - resp, errAsaas := nAccount.GetPaymentStatistic(ctx, GetPaymentStatisticRequest{ + resp, err := nAccount.GetPaymentStatistic(ctx, GetPaymentStatisticRequest{ Customer: "", BillingType: "", Status: "", @@ -157,25 +145,23 @@ func TestAccountGetPaymentStatistic(t *testing.T) { EstimatedCreditDateLe: Date{}, ExternalReference: "", }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } func TestAccountGetSplitStatistic(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAccount := NewAccount(EnvSandbox, accessToken) - resp, errAsaas := nAccount.GetSplitStatistic(ctx) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nAccount.GetSplitStatistic(ctx) + assertResponseSuccess(t, resp, err) } func TestAccountGetInvoiceCustomization(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAccount := NewAccount(EnvSandbox, accessToken) - resp, errAsaas := nAccount.GetInvoiceCustomization(ctx) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nAccount.GetInvoiceCustomization(ctx) + assertResponseSuccess(t, resp, err) } diff --git a/asaas/anticipation_test.go b/asaas/anticipation_test.go index c1d0217..96159fb 100644 --- a/asaas/anticipation_test.go +++ b/asaas/anticipation_test.go @@ -2,89 +2,83 @@ package asaas import ( "context" + "os" "testing" "time" ) func TestAnticipationSimulate(t *testing.T) { + initCreditCardCharge(false) accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) - initCreditCardCharge(true, false) chargeId := getEnvValue(EnvCreditCardChargeId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAnticipation := NewAnticipation(EnvSandbox, accessToken) - resp, errAsaas := nAnticipation.Simulate(ctx, AnticipationSimulateRequest{ + resp, err := nAnticipation.Simulate(ctx, AnticipationSimulateRequest{ Payment: chargeId, Installment: "", }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } func TestAnticipationRequest(t *testing.T) { + initCreditCardCharge(false) accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) - initCreditCardCharge(true, false) chargeId := getEnvValue(EnvCreditCardChargeId) - assertFatalStringBlank(t, chargeId) + f, _ := os.Open(getEnvValue(EnvFileName)) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAnticipation := NewAnticipation(EnvSandbox, accessToken) - resp, errAsaas := nAnticipation.Request(ctx, AnticipationRequest{ + resp, err := nAnticipation.Request(ctx, AnticipationRequest{ Payment: chargeId, Installment: "", - Documents: nil, + Documents: []*os.File{f}, }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } func TestAnticipationAgreementSign(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAnticipation := NewAnticipation(EnvSandbox, accessToken) - resp, errAsaas := nAnticipation.AgreementSign(ctx, AgreementSignRequest{ + resp, err := nAnticipation.AgreementSign(ctx, AgreementSignRequest{ Agreed: true, }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } func TestAnticipationGetById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initAnticipation() + accessToken := getEnvValue(EnvAccessToken) anticipationId := getEnvValue(EnvAnticipationId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAnticipation := NewAnticipation(EnvSandbox, accessToken) - resp, errAsaas := nAnticipation.GetById(ctx, anticipationId) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nAnticipation.GetById(ctx, anticipationId) + assertResponseSuccess(t, resp, err) } func TestAnticipationGetLimits(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAnticipation := NewAnticipation(EnvSandbox, accessToken) - resp, errAsaas := nAnticipation.GetLimits(ctx) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nAnticipation.GetLimits(ctx) + assertResponseSuccess(t, resp, err) } func TestAnticipationGetAll(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nAnticipation := NewAnticipation(EnvSandbox, accessToken) - resp, errAsaas := nAnticipation.GetAll(ctx, GetAllAnticipationsRequest{ + resp, err := nAnticipation.GetAll(ctx, GetAllAnticipationsRequest{ Payment: "", Installment: "", Status: "", Offset: 0, Limit: 10, }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } diff --git a/asaas/assert.go b/asaas/assert.go index be060d0..03779ff 100644 --- a/asaas/assert.go +++ b/asaas/assert.go @@ -2,83 +2,51 @@ package asaas import ( "encoding/json" - "github.com/GabrielHCataldo/go-asaas/internal/util" - "reflect" "testing" ) -func assertFatalErrorNonnull(t *testing.T, err error) { - if err != nil { - logErrorSkipCaller(4, err) - t.Fatal() - } -} - -func assertFatalStringBlank(t *testing.T, v string) { - if util.IsBlank(&v) { - logErrorSkipCaller(4, "value is blank") - t.Fatal() - } -} - func assertResponseSuccess(t *testing.T, resp any, err error) { - r := reflect.ValueOf(resp) - iResp, ok := resp.(response) if err != nil { - logErrorSkipCaller(4, "unexpect: error is not nil:", err) + logDebugSkipCaller(4, "failure: err is not nil:", err) t.Fail() - } else if r.IsNil() || !ok { - logErrorSkipCaller(4, "unexpect: resp is nil or not response interface implemented") - t.Fail() - } else { - vJson, _ := json.Marshal(resp) - if iResp.IsSuccess() && !iResp.IsNoContent() && !iResp.IsFailure() { - logDebugSkipCaller(4, "success: resp is success:", string(vJson)) - } else { - logErrorSkipCaller(4, "unexpect: resp is failure:", string(vJson)) - t.Fail() - } + return } + iResp, ok := resp.(response) + vJson, _ := json.Marshal(resp) + if ok && iResp != nil && iResp.IsSuccess() && !iResp.IsNoContent() && !iResp.IsFailure() { + logDebugSkipCaller(4, "success: resp is success:", string(vJson)) + return + } + logDebugSkipCaller(4, "failure: resp is not success:", string(vJson)) + t.Fail() } func assertResponseFailure(t *testing.T, resp any, err error) { - r := reflect.ValueOf(resp) - iResp, ok := resp.(response) if err != nil { - logErrorSkipCaller(4, "unexpect: error is not nil:", err) - t.Fail() - } else if r.IsNil() || !ok { - logErrorSkipCaller(4, "unexpect: resp is nil or not response interface implemented") - t.Fail() - } else { - vJson, _ := json.Marshal(resp) - if iResp.IsSuccess() || !iResp.IsFailure() || iResp.IsNoContent() { - logErrorSkipCaller(4, "unexpect: resp is success: ", string(vJson)) - t.Fail() - } else { - logDebugSkipCaller(4, "success: resp is failure:", string(vJson)) - } + logDebugSkipCaller(4, "failure: err is not nil:", err) + return + } + iResp, ok := resp.(response) + vJson, _ := json.Marshal(resp) + if ok && iResp != nil && iResp.IsFailure() { + logDebugSkipCaller(4, "success: resp is failure:", string(vJson)) + return } + logDebugSkipCaller(4, "failure: resp is not failure:", string(vJson)) + t.Fail() } func assertResponseNoContent(t *testing.T, resp any, err error) { - r := reflect.ValueOf(resp) - iResp, ok := resp.(response) if err != nil { - vJson, _ := json.Marshal(err) - logErrorSkipCaller(4, "unexpect: error is not nil:", string(vJson)) - t.Fail() - return - } else if r.IsNil() || !ok { - logErrorSkipCaller(4, "unexpect: resp is nil or not response interface implemented") - t.Fail() + logDebugSkipCaller(4, "failure: err is not nil:", err) return } + iResp, ok := resp.(response) vJson, _ := json.Marshal(resp) - if iResp.IsNoContent() && !iResp.IsSuccess() && !iResp.IsFailure() { + if ok && iResp != nil && iResp.IsNoContent() && !iResp.IsSuccess() && !iResp.IsFailure() { logDebugSkipCaller(4, "success: resp is no content", string(vJson)) - } else { - logErrorSkipCaller(4, "unexpect: resp has content ", string(vJson)) - t.Fail() + return } + logDebugSkipCaller(4, "failure: resp is not no content:", string(vJson)) + t.Fail() } diff --git a/asaas/bill_payment.go b/asaas/bill_payment.go index 7a89ab4..b3cfa49 100644 --- a/asaas/bill_payment.go +++ b/asaas/bill_payment.go @@ -352,10 +352,10 @@ func (b billPayment) CancelById(ctx context.Context, billPaymentId string) (*Bil func (b billPayment) GetById(ctx context.Context, billPaymentId string) (*BillPaymentResponse, error) { req := NewRequest[BillPaymentResponse](ctx, b.env, b.accessToken) - return req.make(http.MethodPost, fmt.Sprintf("/v3/bill/%s", billPaymentId), nil) + return req.make(http.MethodGet, fmt.Sprintf("/v3/bill/%s", billPaymentId), nil) } func (b billPayment) GetAll(ctx context.Context, filter PageableDefaultRequest) (*Pageable[BillPaymentResponse], error) { req := NewRequest[Pageable[BillPaymentResponse]](ctx, b.env, b.accessToken) - return req.make(http.MethodPost, "/v3/bill", filter) + return req.make(http.MethodGet, "/v3/bill", filter) } diff --git a/asaas/bill_payment_test.go b/asaas/bill_payment_test.go index 71cd26e..93baf81 100644 --- a/asaas/bill_payment_test.go +++ b/asaas/bill_payment_test.go @@ -7,29 +7,27 @@ import ( ) func TestBillPaymentSimulate(t *testing.T) { + initBankSlipCharge(false) accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) identificationField := getEnvValue(EnvChargeIdentificationField) - assertFatalStringBlank(t, identificationField) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nBillPayment := NewBillPayment(EnvSandbox, accessToken) - resp, errAsaas := nBillPayment.Simulate(ctx, BillPaymentSimulateRequest{ + resp, err := nBillPayment.Simulate(ctx, BillPaymentSimulateRequest{ IdentificationField: identificationField, BarCode: "", }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } func TestBillPaymentCreate(t *testing.T) { + initBankSlipCharge(false) accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) identificationField := getEnvValue(EnvChargeIdentificationField) - assertFatalStringBlank(t, identificationField) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nBillPayment := NewBillPayment(EnvSandbox, accessToken) - resp, errAsaas := nBillPayment.Create(ctx, CreateBillPaymentRequest{ + resp, err := nBillPayment.Create(ctx, CreateBillPaymentRequest{ IdentificationField: identificationField, ScheduleDate: Date{}, Description: "unit test", @@ -39,42 +37,40 @@ func TestBillPaymentCreate(t *testing.T) { Value: 0, DueDate: Date{}, }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } func TestBillPaymentCancelById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initBillPayment() + accessToken := getEnvValue(EnvAccessToken) billPaymentId := getEnvValue(EnvBillPaymentId) - assertFatalStringBlank(t, billPaymentId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nBillPayment := NewBillPayment(EnvSandbox, accessToken) - resp, errAsaas := nBillPayment.CancelById(ctx, billPaymentId) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nBillPayment.CancelById(ctx, billPaymentId) + assertResponseSuccess(t, resp, err) } func TestBillPaymentGetById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initBillPayment() + accessToken := getEnvValue(EnvAccessToken) billPaymentId := getEnvValue(EnvBillPaymentId) - assertFatalStringBlank(t, billPaymentId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nBillPayment := NewBillPayment(EnvSandbox, accessToken) - resp, errAsaas := nBillPayment.GetById(ctx, billPaymentId) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nBillPayment.GetById(ctx, billPaymentId) + assertResponseSuccess(t, resp, err) } func TestBillPaymentGetAll(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initBillPayment() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nBillPayment := NewBillPayment(EnvSandbox, accessToken) - resp, errAsaas := nBillPayment.GetAll(ctx, PageableDefaultRequest{}) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nBillPayment.GetAll(ctx, PageableDefaultRequest{ + Offset: 0, + Limit: 10, + }) + assertResponseSuccess(t, resp, err) } diff --git a/asaas/charge.go b/asaas/charge.go index f19a392..1f7538c 100644 --- a/asaas/charge.go +++ b/asaas/charge.go @@ -48,6 +48,15 @@ type CreateChargeRequest struct { RemoteIp string `json:"remoteIp,omitempty"` } +type PayWithCreditCardRequest struct { + // Informações do cartão de crédito (REQUIRED se CreditCardToken não for informado) + CreditCard *CreditCardRequest `json:"creditCard,omitempty"` + // Informações do titular do cartão de crédito (REQUIRED se CreditCardToken não for informado) + CreditCardHolderInfo *CreditCardHolderInfoRequest `json:"creditCardHolderInfo,omitempty"` + // Token do cartão de crédito para uso da funcionalidade de tokenização de cartão de crédito. Caso informado, os campos acima não são obrigatórios. + CreditCardToken string `json:"creditCardToken,omitempty"` +} + type UpdateChargeRequest struct { // Identificador único do cliente no Asaas Customer string `json:"customer,omitempty"` @@ -370,7 +379,7 @@ type Charge interface { // # DOCS // // Pagar uma cobrança com cartão de crédito: https://docs.asaas.com/reference/pagar-uma-cobranca-com-cartao-de-credito - PayWithCreditCard(ctx context.Context, chargeId string, body CreditCardRequest) (*ChargeResponse, error) + PayWithCreditCard(ctx context.Context, chargeId string, body PayWithCreditCardRequest) (*ChargeResponse, error) // UpdateById (Atualizar cobrança existente) // // Somente é possível atualizar cobranças aguardando pagamento ou vencidas. Uma vez criada, não é possível alterar @@ -1284,7 +1293,7 @@ func (c charge) Create(ctx context.Context, body CreateChargeRequest) (*ChargeRe return req.make(http.MethodPost, "/v3/payments", body) } -func (c charge) PayWithCreditCard(ctx context.Context, chargeId string, body CreditCardRequest) (*ChargeResponse, +func (c charge) PayWithCreditCard(ctx context.Context, chargeId string, body PayWithCreditCardRequest) (*ChargeResponse, error) { req := NewRequest[ChargeResponse](ctx, c.env, c.accessToken) return req.make(http.MethodPost, fmt.Sprintf(`/v3/payments/%s/payWithCreditCard`, chargeId), body) diff --git a/asaas/charge_test.go b/asaas/charge_test.go index 8981e42..dcd9bdd 100644 --- a/asaas/charge_test.go +++ b/asaas/charge_test.go @@ -7,12 +7,10 @@ import ( "time" ) -func TestChangeCreate(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) +func TestChargeCreate(t *testing.T) { initCustomer() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - assertFatalStringBlank(t, customerId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -40,31 +38,39 @@ func TestChangeCreate(t *testing.T) { assertResponseSuccess(t, resp, err) } -func TestChangePayWithCreditCard(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) +func TestChargePayWithCreditCard(t *testing.T) { initUndefinedCharge() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) - resp, err := nCharge.PayWithCreditCard(ctx, chargeId, CreditCardRequest{ - HolderName: "unit test go", - Number: "4000000000000010", - ExpiryMonth: "12", - ExpiryYear: "2036", - Ccv: "123", + resp, err := nCharge.PayWithCreditCard(ctx, chargeId, PayWithCreditCardRequest{ + CreditCard: &CreditCardRequest{ + HolderName: "unit test go", + Number: "4000000000000010", + ExpiryMonth: "05", + ExpiryYear: "2035", + Ccv: "318", + }, + CreditCardHolderInfo: &CreditCardHolderInfoRequest{ + Name: "Unit Test Go", + CpfCnpj: "24971563792", + Email: "unittest@gmail.com", + Phone: "4738010919", + MobilePhone: "47998781877", + PostalCode: "89223-005", + AddressNumber: "277", + }, + CreditCardToken: "", }) assertResponseSuccess(t, resp, err) } -func TestChangeUpdateById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) +func TestChargeUpdateById(t *testing.T) { initUndefinedCharge() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -78,12 +84,10 @@ func TestChangeUpdateById(t *testing.T) { assertResponseSuccess(t, resp, err) } -func TestChangeDeleteById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) +func TestChargeDeleteById(t *testing.T) { initUndefinedCharge() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -91,12 +95,10 @@ func TestChangeDeleteById(t *testing.T) { assertResponseSuccess(t, resp, err) } -func TestChangeRestoreById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) +func TestChargeRestoreById(t *testing.T) { initChargeDeleted() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvChargeDeletedId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -104,12 +106,10 @@ func TestChangeRestoreById(t *testing.T) { assertResponseSuccess(t, resp, err) } -func TestChangeRefundById(t *testing.T) { +func TestChargeRefundById(t *testing.T) { + initCreditCardCharge(false) accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) - initCreditCardCharge(true, false) chargeId := getEnvValue(EnvCreditCardChargeId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -120,16 +120,14 @@ func TestChangeRefundById(t *testing.T) { assertResponseSuccess(t, resp, err) } -func TestChangeReceiveInCashById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) +func TestChargeReceiveInCashById(t *testing.T) { initUndefinedCharge() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) - now := time.Now() + now := DateNow() resp, err := nCharge.ReceiveInCashById(ctx, chargeId, ChargeReceiveInCashRequest{ PaymentDate: NewDate(now.Year(), now.Month(), now.Day(), now.Location()), Value: 100, @@ -138,12 +136,10 @@ func TestChangeReceiveInCashById(t *testing.T) { assertResponseSuccess(t, resp, err) } -func TestChangeUndoReceivedInCashById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) +func TestChargeUndoReceivedInCashById(t *testing.T) { initChargeReceivedInCash() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvChargeReceivedInCashId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -152,13 +148,10 @@ func TestChangeUndoReceivedInCashById(t *testing.T) { } func TestChargeUploadDocumentById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initUndefinedCharge() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - assertFatalStringBlank(t, chargeId) - f, err := os.Open(getEnvValue(EnvFileName)) - assertFatalErrorNonnull(t, err) + f, _ := os.Open(getEnvValue(EnvFileName)) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -171,13 +164,10 @@ func TestChargeUploadDocumentById(t *testing.T) { } func TestChargeUpdateDocumentDefinitionsById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initChargeDocumentId() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - assertFatalStringBlank(t, chargeId) docId := getEnvValue(EnvChargeDocumentId) - assertFatalStringBlank(t, docId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -189,13 +179,10 @@ func TestChargeUpdateDocumentDefinitionsById(t *testing.T) { } func TestChargeDeleteDocumentById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initChargeDocumentId() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - assertFatalStringBlank(t, chargeId) docId := getEnvValue(EnvChargeDocumentId) - assertFatalStringBlank(t, docId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -204,11 +191,9 @@ func TestChargeDeleteDocumentById(t *testing.T) { } func TestChargeGetById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initUndefinedCharge() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -218,7 +203,6 @@ func TestChargeGetById(t *testing.T) { func TestChargeGetCreationLimit(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -227,11 +211,9 @@ func TestChargeGetCreationLimit(t *testing.T) { } func TestChargeGetStatusById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initUndefinedCharge() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -240,11 +222,9 @@ func TestChargeGetStatusById(t *testing.T) { } func TestChargeGetIdentificationFieldById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initBankSlipCharge(false) + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvBankSlipChargeId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -253,11 +233,9 @@ func TestChargeGetIdentificationFieldById(t *testing.T) { } func TestChargeGetPixQrCodeById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPixCharge() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvPixChargeId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -266,11 +244,9 @@ func TestChargeGetPixQrCodeById(t *testing.T) { } func TestChargeGetDocumentById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initChargeDocumentId() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - assertFatalStringBlank(t, chargeId) docId := getEnvValue(EnvChargeDocumentId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() @@ -280,9 +256,8 @@ func TestChargeGetDocumentById(t *testing.T) { } func TestChargeGetAll(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initChargeDocumentId() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -315,11 +290,9 @@ func TestChargeGetAll(t *testing.T) { } func TestChargeGetAllDocumentsById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initChargeDocumentId() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) diff --git a/asaas/credit_bureau_test.go b/asaas/credit_bureau_test.go index cc8bf37..2b64a40 100644 --- a/asaas/credit_bureau_test.go +++ b/asaas/credit_bureau_test.go @@ -7,11 +7,9 @@ import ( ) func TestCreditBureauGetReport(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initCustomer() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - assertFatalStringBlank(t, customerId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCreditBureau := NewCreditBureau(EnvSandbox, accessToken) @@ -24,9 +22,8 @@ func TestCreditBureauGetReport(t *testing.T) { } func TestCreditBureauGetReportById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initCreditBureauReport() + accessToken := getEnvValue(EnvAccessToken) reportId := getEnvValue(EnvCreditBureauReportId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() @@ -36,9 +33,8 @@ func TestCreditBureauGetReportById(t *testing.T) { } func TestCreditBureauGetAllReports(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initCreditBureauReport() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCreditBureau := NewCreditBureau(EnvSandbox, accessToken) diff --git a/asaas/credit_card_test.go b/asaas/credit_card_test.go index 3a79ffa..94372aa 100644 --- a/asaas/credit_card_test.go +++ b/asaas/credit_card_test.go @@ -7,15 +7,13 @@ import ( ) func TestCreditCardTokenize(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initCustomer() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - assertFatalStringBlank(t, customerId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCreditCard := NewCreditCard(EnvSandbox, accessToken) - resp, errAsaas := nCreditCard.Tokenize(ctx, CreditCardTokenizeRequest{ + resp, err := nCreditCard.Tokenize(ctx, CreditCardTokenizeRequest{ Customer: customerId, CreditCard: CreditCardRequest{ HolderName: "unit test go", @@ -35,5 +33,5 @@ func TestCreditCardTokenize(t *testing.T) { AddressComplement: "", }, }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } diff --git a/asaas/customer.go b/asaas/customer.go index bd93119..61f7dd2 100644 --- a/asaas/customer.go +++ b/asaas/customer.go @@ -468,7 +468,7 @@ func (c customer) DeleteById(ctx context.Context, customerId string) (*DeleteRes func (c customer) RestoreById(ctx context.Context, customerId string) (*CustomerResponse, error) { req := NewRequest[CustomerResponse](ctx, c.env, c.accessToken) - return req.make(http.MethodPost, fmt.Sprintf("/v3/customers/%s", customerId), nil) + return req.make(http.MethodPost, fmt.Sprintf("/v3/customers/%s/restore", customerId), nil) } func (c customer) GetById(ctx context.Context, customerId string) (*CustomerResponse, error) { diff --git a/asaas/customer_test.go b/asaas/customer_test.go index 2431914..8b8b512 100644 --- a/asaas/customer_test.go +++ b/asaas/customer_test.go @@ -9,7 +9,6 @@ import ( func TestCustomerCreate(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCustomer := NewCustomer(EnvSandbox, accessToken) @@ -37,11 +36,9 @@ func TestCustomerCreate(t *testing.T) { } func TestCustomerUpdateById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initCustomer() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - assertFatalStringBlank(t, customerId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCustomer := NewCustomer(EnvSandbox, accessToken) @@ -69,11 +66,9 @@ func TestCustomerUpdateById(t *testing.T) { } func TestCustomerDeleteById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initCustomer() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - assertFatalStringBlank(t, customerId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCustomer := NewCustomer(EnvSandbox, accessToken) @@ -82,11 +77,9 @@ func TestCustomerDeleteById(t *testing.T) { } func TestCustomerRestoreById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initCustomerDeleted() - customerId := getEnvValue(EnvChargeDeletedId) - assertFatalStringBlank(t, customerId) + accessToken := getEnvValue(EnvAccessToken) + customerId := getEnvValue(EnvCustomerId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCustomer := NewCustomer(EnvSandbox, accessToken) @@ -95,10 +88,9 @@ func TestCustomerRestoreById(t *testing.T) { } func TestCustomerGetById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initCustomer() - customerId := getEnvValue(EnvChargeDeletedId) + accessToken := getEnvValue(EnvAccessToken) + customerId := getEnvValue(EnvCustomerId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCustomer := NewCustomer(EnvSandbox, accessToken) @@ -107,9 +99,8 @@ func TestCustomerGetById(t *testing.T) { } func TestCustomerGetAll(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initCustomer() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCustomer := NewCustomer(EnvSandbox, accessToken) diff --git a/asaas/date.go b/asaas/date.go index e580451..ae0ff49 100644 --- a/asaas/date.go +++ b/asaas/date.go @@ -30,21 +30,21 @@ func (d Date) MarshalJSON() ([]byte, error) { } func (d Date) Format() string { - t := time.Time(d) + t := d.Time() if t.IsZero() { return "null" } - return time.Time(d).Format(dLayout) -} - -func (d Date) Time() time.Time { - return time.Time(d) + return d.Time().Format(dLayout) } func NewDate(year int, month time.Month, day int, loc *time.Location) Date { return Date(time.Date(year, month, day, 23, 59, 0, 0, loc)) } +func DateNow() Date { + return Date(time.Now()) +} + func (d Date) Year() int { year, _, _, _ := d.date() return year @@ -61,14 +61,18 @@ func (d Date) Day() int { } func (d Date) Location() *time.Location { - return time.Time(d).Location() + return d.Time().Location() } func (d Date) IsZero() bool { - return time.Time(d).IsZero() + return d.Time().IsZero() +} + +func (d Date) Time() time.Time { + return time.Time(d) } func (d Date) date() (year int, month time.Month, day int, yDay int) { - t := time.Time(d) + t := d.Time() return t.Year(), t.Month(), t.Day(), t.YearDay() } diff --git a/asaas/datetime.go b/asaas/datetime.go index 9929ce1..6b1a6d6 100644 --- a/asaas/datetime.go +++ b/asaas/datetime.go @@ -2,7 +2,6 @@ package asaas import ( "fmt" - "strings" "time" ) @@ -10,29 +9,19 @@ type Datetime time.Time var dtLayout = "2006-01-02 15:04:05" -func (d *Datetime) UnmarshalJSON(b []byte) error { - s := strings.Trim(string(b), `"`) - if s == "null" || s == `""` { - return nil - } - t, err := time.Parse(dtLayout, s) - *d = Datetime(t) - return err -} - func (d Datetime) MarshalJSON() ([]byte, error) { - if time.Time(d).IsZero() { + if d.Time().IsZero() { return []byte(fmt.Sprintf(``)), nil } return []byte(fmt.Sprintf(`"%s"`, d.Format())), nil } func (d Datetime) Format() string { - t := time.Time(d) + t := d.Time() if t.IsZero() { return "null" } - return time.Time(d).Format(dtLayout) + return d.Time().Format(dtLayout) } func (d Datetime) Time() time.Time { @@ -48,6 +37,10 @@ func NewDatetimePointer(year int, month time.Month, day, hour, min, sec, nSec in return v } +func DatetimeNow() Datetime { + return Datetime(time.Now()) +} + func (d Datetime) Year() int { year, _, _, _ := d.date() return year @@ -63,15 +56,31 @@ func (d Datetime) Day() int { return day } +func (d Datetime) Hour() int { + return d.Time().Hour() +} + +func (d Datetime) Minute() int { + return d.Time().Minute() +} + +func (d Datetime) Second() int { + return d.Time().Second() +} + +func (d Datetime) Nanosecond() int { + return d.Time().Nanosecond() +} + func (d Datetime) Location() *time.Location { - return time.Time(d).Location() + return d.Time().Location() } func (d Datetime) IsZero() bool { - return time.Time(d).IsZero() + return d.Time().IsZero() } func (d Datetime) date() (year int, month time.Month, day int, yDay int) { - t := time.Time(d) + t := d.Time() return t.Year(), t.Month(), t.Day(), t.YearDay() } diff --git a/asaas/enum.go b/asaas/enum.go index 309fcc7..70a079c 100644 --- a/asaas/enum.go +++ b/asaas/enum.go @@ -1,9 +1,5 @@ package asaas -type BaseEnum interface { - IsEnumValid() bool -} - type BillingType string type ChargeStatus string type ChargeType string @@ -488,413 +484,6 @@ const ( NotificationEventPaymentUpdated NotificationEvent = "PAYMENT_UPDATED" ) -func (c ChargeType) IsEnumValid() bool { - switch c { - case ChargeTypeDetached, ChargeTypeRecurrent, ChargeTypeInstallment: - return true - } - return false -} - -func (s SubaccountDocumentType) IsEnumValid() bool { - switch s { - case SubaccountDocumentTypeIdentification, SubaccountDocumentTypeSocialContract, SubaccountDocumentTypeEntrepreneurRequirement, - SubaccountDocumentTypeMinutesOfElection, SubaccountDocumentTypeCustom: - return true - } - return false -} - -func (s SubaccountDocumentStatus) IsEnumValid() bool { - switch s { - case SubaccountDocumentStatusPending, SubaccountDocumentStatusNotSent, SubaccountDocumentStatusApproved, - SubaccountDocumentStatusRejected: - return true - } - return false -} - -func (t WebhookType) IsEnumValid() bool { - switch t { - case WebhookTypePayment, WebhookTypeInvoice, WebhookTypeTransfer, WebhookTypeReceivableAnticipation, - WebhookTypeMobilePhoneRecharge, WebhookTypeBill, WebhookTypeMobileAccountStatus: - return true - } - return false -} - -func (c CompanyType) IsEnumValid() bool { - switch c { - case CompanyTypeMei, CompanyTypeLimited, CompanyTypeIndividual, CompanyTypeAssociation: - return true - } - return false -} - -func (a AccountStatus) IsEnumValid() bool { - switch a { - case AccountStatusPending, AccountStatusAwaitingActionAuthorization, AccountStatusApproved, AccountStatusDenied: - return true - } - return false -} - -func (m MobilePhoneRechargeStatus) IsEnumValid() bool { - switch m { - case MobilePhoneRechargeStatusPending, MobilePhoneRechargeStatusWaitingCriticalAction, - MobilePhoneRechargeStatusConfirmed, MobilePhoneRechargeStatusCancelled: - return true - } - return false -} - -func (f BillPaymentStatus) IsEnumValid() bool { - switch f { - case BillPaymentStatusPending, BillPaymentStatusBankProcessing, BillPaymentStatusBankPaid, BillPaymentStatusFailed, - BillPaymentStatusCancelled: - return true - } - return false -} - -func (f FileMimeType) IsEnumValid() bool { - switch f { - case FileMimeTypePdf, FileMimeTypeText, FileMimeTypeAvif, FileMimeTypeCss, FileMimeTypeGif, FileMimeTypeHtml, - FileMimeTypeJpeg, FileMimeTypeJs, FileMimeTypeJson, FileMimeTypePng, FileMimeTypeSvg, FileMimeTypeWasm, - FileMimeTypeWebp, FileMimeTypeXml: - return true - } - return false -} - -func (a NegativityStatus) IsEnumValid() bool { - switch a { - case NegativityStatusAwaitingApproval, NegativityStatusAwaitingCancellation, NegativityStatusCancelled, - NegativityStatusDenied, NegativityStatusPaid, NegativityStatusPending, NegativityStatusProcessed, - NegativityStatusPartiallyPaid: - return true - } - return false -} - -func (a NegativityType) IsEnumValid() bool { - switch a { - case NegativityTypeCreditBureau: - return true - } - return false -} - -func (a AnticipationStatus) IsEnumValid() bool { - switch a { - case AnticipationStatusCredited, AnticipationStatusCancelled, AnticipationStatusDenied, AnticipationStatusDebited, - AnticipationStatusOverdue, AnticipationStatusScheduled, AnticipationStatusPending: - return true - } - return false -} - -func (t TransferType) IsEnumValid() bool { - switch t { - case TransferTypeBankAccount, TransferTypeAsaasAccount: - return true - } - return false -} - -func (b BankAccountType) IsEnumValid() bool { - switch b { - case BankAccountTypeChecking, BankAccountTypeSavings: - return true - } - return false -} - -func (t TransferOperationType) IsEnumValid() bool { - switch t { - case TransferOperationTypePix, TransferOperationTypeTed, TransferOperationTypeInternal: - return true - } - return false -} - -func (t TransferStatus) IsEnumValid() bool { - switch t { - case TransferStatusPending, TransferStatusDone, TransferStatusCancelled, TransferStatusFailed, - TransferStatusBankProcessing: - return true - } - return false -} - -func (p PersonType) IsEnumValid() bool { - switch p { - case PersonTypePhysical, PersonTypeJuridical: - return true - } - return false -} - -func (b AccountType) IsEnumValid() bool { - switch b { - case AccountTypeSalaryAccount, AccountTypeTypePaymentAccount, AccountTypeInvestimentAccount, AccountTypeCheckingAccount: - return true - } - return false -} - -func (p PixTransactionFinality) IsEnumValid() bool { - switch p { - case PixTransactionFinalityChange, PixTransactionFinalityWithdrawal: - return true - } - return false -} - -func (p PixTransactionStatus) IsEnumValid() bool { - switch p { - case PixTransactionStatusAwaitingRequest, PixTransactionStatusDone, PixTransactionStatusRequested, PixTransactionStatusScheduled, - PixTransactionStatusRefused, PixTransactionStatusError, PixTransactionStatusCancelled: - return true - } - return false -} - -func (p PixTransactionOriginType) IsEnumValid() bool { - switch p { - case PixTransactionOriginManual, PixTransactionOriginAddressKey, PixTransactionOriginStaticQrcode, - PixTransactionOriginDynamicQrcode, PixTransactionOriginExternalDebit: - return true - } - return false -} - -func (p PixTransactionType) IsEnumValid() bool { - switch p { - case PixTransactionTypeCredit, PixTransactionTypeCreditRefund, PixTransactionTypeDebit, - PixTransactionTypeDebitRefund, PixTransactionTypeDebitRefundCancellation: - return true - } - return false -} - -func (p PixQrCodeType) IsEnumValid() bool { - switch p { - case PixQrCodeTypeStatic, PixQrCodeTypeDynamic: - return true - } - return false -} - -func (q QrCodeFormat) IsEnumValid() bool { - switch q { - case QrCodeFormatAll, QrCodeFormatImage, QrCodeFormatPayload: - return true - } - return false -} - -func (p PixKeyStatus) IsEnumValid() bool { - switch p { - case PixKeyStatusAwaitingActive, PixKeyStatusAwaitingActivation, PixKeyStatusAwaitingDeleted, PixKeyStatusAwaitingAccountDeletion, - PixKeyStatusAwaitingDeletion, PixKeyStatusAwaitingError: - return true - } - return false -} - -func (p PixKeyType) IsEnumValid() bool { - switch p { - case PixKeyTypeCnpj, PixKeyTypeCpf, PixKeyTypeEmail, PixKeyTypePhone, PixKeyTypeEvp: - return true - } - return false -} - -func (i InvoiceDaysBeforeDueDate) IsEnumValid() bool { - switch i { - case InvoiceDaysBeforeDuedateFive, InvoiceDaysBeforeDuedateTen, InvoiceDaysBeforeDuedateFifteen, - InvoiceDaysBeforeDuedateThirty, InvoiceDaysBeforeDuedateSixty: - return true - } - return false -} - -func (i InvoiceStatus) IsEnumValid() bool { - switch i { - case InvoiceStatusAuthorized, InvoiceStatusCanceled, InvoiceStatusCancellationDenied, InvoiceStatusProcessingCancellation, - InvoiceStatusError, InvoiceStatusScheduled, InvoiceStatusSynchronized: - return true - } - return false -} - -func (i EffectiveDatePeriod) IsEnumValid() bool { - switch i { - case EffectiveDatePeriodOnPaymentConfirmation, EffectiveDatePeriodOnPaymentDueDate, - EffectiveDatePeriodBeforePaymentDueDate, EffectiveDatePeriodOnDueDateMonth, - EffectiveDatePeriodOnNextMonth: - return true - } - return false -} - -func (s SortPaymentBookField) IsEnumValid() bool { - switch s { - case SortPaymentBookDueDate: - return true - } - return false -} - -func (s SortSubscriptionField) IsEnumValid() bool { - switch s { - case SortSubscriptionFieldDateCreated: - return true - } - return false -} - -func (s SubscriptionStatus) IsEnumValid() bool { - switch s { - case SubscriptionStatusActive, SubscriptionStatusInactive, SubscriptionStatusExpired: - return true - } - return false -} - -func (o Order) IsEnumValid() bool { - switch o { - case OrderDesc, OrderAsc: - return true - } - return false -} - -func (s SubscriptionCycle) IsEnumValid() bool { - switch s { - case SubscriptionCycleWeekly, SubscriptionCycleBiweekly, SubscriptionCycleMonthly, SubscriptionCycleBimonthly, SubscriptionCycleQuarterly, SubscriptionCycleSemiannually, SubscriptionCycleYearly: - return true - } - return false -} - -func (n NotificationEvent) IsEnumValid() bool { - switch n { - case NotificationEventPaymentCreated, NotificationEventPaymentDuedateWarning, NotificationEventPaymentReceived, NotificationEventSendLinhaDigitavel, NotificationEventPaymentOverdue, - NotificationEventPaymentUpdated: - return true - } - return false -} - -func (c ChargebackReason) IsEnumValid() bool { - switch c { - case ChargebackReason1, ChargebackReason2, ChargebackReason3, ChargebackReason4, ChargebackReason5, - ChargebackReason6, ChargebackReason7, ChargebackReason8, ChargebackReason9, ChargebackReason10, - ChargebackReason11, ChargebackReason12, ChargebackReason13, ChargebackReason14, ChargebackReason15, - ChargebackReason16, ChargebackReason17, ChargebackReason18, ChargebackReason19, - ChargebackReason20, ChargebackReason21, ChargebackReason22, - ChargebackReason23, ChargebackReason24, ChargebackReason25, ChargebackReason26, - ChargebackReason27, ChargebackReason28, ChargebackReason29, ChargebackReason30, - ChargebackReason31, ChargebackReason32: - return true - } - return false -} - -func (c BillingType) IsEnumValid() bool { - switch c { - case BillingTypeBankSlip, BillingTypeCreditCard, BillingTypeUndefined, BillingTypeDebitCard, BillingTypeTransfer, BillingTypeDeposit, BillingTypePix: - return true - } - return false -} - -func (c ChargeStatus) IsEnumValid() bool { - switch c { - case ChargeStatusPending, ChargeStatusReceived, ChargeStatusConfirmed, ChargeStatusOverdue, ChargeStatusRefunded, ChargeStatusReceivedInCash, - ChargeStatusRefundRequested, ChargeStatusRefundInProgress, ChargeStatusChargebackRequested, ChargeStatusChargebackDispute, - ChargeStatusAwaitingChargebackReversal, ChargeStatusDunningRequested, ChargeStatusDunningReceived, - ChargeStatusAwaitingRiskAnalysis: - return true - } - return false -} - -func (c ChargebackStatus) IsEnumValid() bool { - switch c { - case ChargebackStatusRequested, ChargebackStatusInDispute, ChargebackStatusLost, ChargebackStatusReversed, ChargebackStatusDone: - return true - } - return false -} - -func (d DiscountType) IsEnumValid() bool { - switch d { - case DiscountTypeFixed, DiscountTypePercentage: - return true - } - return false -} - -func (a Env) IsEnumValid() bool { - switch a { - case EnvSandbox, EnvProduction: - return true - } - return false -} - -func (f FineType) IsEnumValid() bool { - switch f { - case FineTypeFixed, FineTypePercentage: - return true - } - return false -} - -func (i InterestType) IsEnumValid() bool { - switch i { - case InterestTypeFixed, InterestTypePercentage: - return true - } - return false -} - -func (r RefundStatus) IsEnumValid() bool { - switch r { - case RefundStatusPending, RefundStatusCancelled, RefundStatusDone: - return true - } - return false -} - -func (s SplitRefusalReason) IsEnumValid() bool { - switch s { - case SplitRefusalReason1: - return true - } - return false -} - -func (s SplitStatus) IsEnumValid() bool { - switch s { - case SplitStatusPending, SplitStatusAwaitingCredit, SplitStatusCancelled, SplitStatusDone, SplitStatusRefused: - return true - } - return false -} - -func (t DocumentType) IsEnumValid() bool { - switch t { - case DocumentTypeInvoice, DocumentTypeContract, DocumentTypeDocument, DocumentTypeSpreadsheet, DocumentTypeProgram, - DocumentTypeOther: - return true - } - return false -} - func (c ChargebackReason) String() string { switch c { case ChargebackReason1: @@ -1027,53 +616,3 @@ func (t WebhookType) PathUrl() string { } return "/" } - -func (f FinanceTransType) IsEnumValid() bool { - switch f { - case FinanceTransTypeAsaasCardRecharge, FinanceTransTypeAsaasCardRechargeReversal, - FinanceTransTypeAsaasCardTransaction, FinanceTransTypeAsaasCardCashback, FinanceTransTypeAsaasCardTransactionFee, - FinanceTransTypeAsaasCardTransactionFeeRefund, FinanceTransTypeAsaasCardTransactionPartialRefundCancellation, - FinanceTransTypeAsaasCardTransactionRefund, FinanceTransTypeAsaasCardTransactionRefundCancellation, - FinanceTransTypeAsaasMoneyPaymentAnticipationFeeRefund, FinanceTransTypeAsaasMoneyPaymentCompromisedBalance, - FinanceTransTypeAsaasMoneyPaymentCompromisedBalanceRefund, FinanceTransTypeAsaasMoneyPaymentFinancingFee, - FinanceTransTypeAsaasMoneyPaymentFinancingFeeRefund, FinanceTransTypeAsaasMoneyTransactionCashback, - FinanceTransTypeAsaasMoneyTransactionCashbackRefund, FinanceTransTypeAsaasMoneyTransactionChargeback, - FinanceTransTypeAsaasMoneyTransactionChargebackReversal, FinanceTransTypeBillPayment, - FinanceTransTypeBillPaymentCancelled, FinanceTransTypeBillPaymentRefunded, FinanceTransTypeBillPaymentFee, - FinanceTransTypeBillPaymentFeeCancelled, FinanceTransTypeChargeback, FinanceTransTypeChargebackReversal, - FinanceTransTypeChargedFeeRefund, FinanceTransTypeContractualEffectSettlement, - FinanceTransTypeContractualEffectSettlementReversal, FinanceTransTypeCredit, FinanceTransTypeCreditBureauReport, - FinanceTransTypeCustomerCommissionSettlementCredit, FinanceTransTypeCustomerCommissionSettlementDebit, - FinanceTransTypeDebit, FinanceTransTypeDebitReversal, FinanceTransTypeDebtRecoveryNegotiationFinancialCharges, - FinanceTransTypeFreePaymentUse, FinanceTransTypeInternalTransferCredit, FinanceTransTypeInternalTransferDebit, - FinanceTransTypeInternalTransferReversal, FinanceTransTypeInvoiceFee, FinanceTransTypePartialPayment, - FinanceTransTypePaymentDunningCancellationFee, FinanceTransTypePaymentDunningReceivedFee, - FinanceTransTypePaymentDunningReceivedInCashFee, FinanceTransTypePaymentDunningRequestFee, - FinanceTransTypePaymentFee, FinanceTransTypePaymentFeeReversal, FinanceTransTypePaymentMessagingNotificationFee, - FinanceTransTypePaymentReceived, FinanceTransTypePaymentCustodyBlock, FinanceTransTypePaymentCustodyBlockReversal, - FinanceTransTypePaymentRefundCancelled, FinanceTransTypePaymentReversal, - FinanceTransTypePaymentSmsNotificationFee, FinanceTransTypePaymentInstantTextMessageFee, - FinanceTransTypePhoneCallNotificationFee, FinanceTransTypePixTransactionCredit, - FinanceTransTypePixTransactionCreditFee, FinanceTransTypePixTransactionCreditRefund, - FinanceTransTypePixTransactionCreditRefundCancellation, FinanceTransTypePixTransactionDebit, - FinanceTransTypePixTransactionDebitFee, FinanceTransTypePixTransactionDebitRefund, - FinanceTransTypePostalServiceFee, FinanceTransTypeProductInvoiceFee, FinanceTransTypeConsumerInvoiceFee, - FinanceTransTypePromotionalCodeCredit, FinanceTransTypePromotionalCodeDebit, - FinanceTransTypeReceivableAnticipationGrossCredit, FinanceTransTypeReceivableAnticipationDebit, - FinanceTransTypeReceivableAnticipationFee, FinanceTransTypeReceivableAnticipationPartnerSettlement, - FinanceTransTypeRefundRequestCancelled, FinanceTransTypeRefundRequestFee, - FinanceTransTypeRefundRequestFeeReversal, FinanceTransTypeReversal, FinanceTransTypeTransfer, - FinanceTransTypeTransferFee, FinanceTransTypeTransferReversal, FinanceTransTypeMobilePhoneRecharge, - FinanceTransTypeRefundMobilePhoneRecharge, FinanceTransTypeCancelMobilePhoneRecharge, - FinanceTransTypeInstantTextMessageFee, FinanceTransTypeAsaasCardBalanceRefund, - FinanceTransTypeAsaasMoneyPaymentAnticipationFee, FinanceTransTypeBacenJudicialLock, - FinanceTransTypeBacenJudicialUnlock, FinanceTransTypeBacenJudicialTransfer, - FinanceTransTypeAsaasDebitCardRequestFee, FinanceTransTypeAsaasPrepaidCardRequestFee, - FinanceTransTypeExternalSettlementContractualEffectBatchCredit, - FinanceTransTypeExternalSettlementContractualEffectBatchReversal, - FinanceTransTypeAsaasCardBillPayment, FinanceTransTypeAsaasCardBillPaymentRefund, - FinanceTransTypeChildAccountKnownYourCustomerBatchFee, FinanceTransTypeContractedCustomerPlanFee: - return true - } - return false -} diff --git a/asaas/file.go b/asaas/file.go index 369a0e4..0ed17ba 100644 --- a/asaas/file.go +++ b/asaas/file.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/GabrielHCataldo/go-asaas/internal/util" "net/url" - "strings" ) type FileRequest struct { @@ -19,32 +18,9 @@ type FileTextPlainResponse struct { Errors []ErrorResponse `json:"errors,omitempty"` } -func (f *FileRequest) UnmarshalJSON(b []byte) error { - s := strings.Trim(string(b), `"`) - if s == "null" || s == `""` { - return nil - } - split := strings.Split(s, ";") - if len(split) != 3 { - return nil - } - mimeType := FileMimeType(strings.Replace(split[0], "data:", "", 1)) - name := strings.Replace(split[1], "name=", "", 1) - data, err := base64.StdEncoding.DecodeString(strings.Replace(split[2], "base64,", "", 1)) - if err != nil { - return err - } - *f = FileRequest{ - Name: name, - Mime: mimeType, - Data: data, - } - return err -} - func (f FileRequest) MarshalJSON() ([]byte, error) { result := `null` - if util.IsNotBlank(&f.Name) && f.Mime.IsEnumValid() && len(f.Data) > 0 { + if util.IsNotBlank(&f.Name) && f.Mime != "" && len(f.Data) > 0 { name := url.PathEscape(f.Name) b64 := base64.StdEncoding.EncodeToString(f.Data) result = fmt.Sprintf(`"data:%s;name=%s;base64,%s"`, f.Mime.String(), name, b64) diff --git a/asaas/fiscal_info.go b/asaas/fiscal_info.go index 4f67825..c6bee5c 100644 --- a/asaas/fiscal_info.go +++ b/asaas/fiscal_info.go @@ -54,8 +54,8 @@ type FiscalInfoResponse struct { RpsNumber int `json:"rpsNumber,omitempty"` LoteNumber int `json:"loteNumber,omitempty"` Username string `json:"username,omitempty"` - PasswordSent string `json:"passwordSent,omitempty"` - AccessTokenSent string `json:"accessTokenSent,omitempty"` + PasswordSent bool `json:"passwordSent,omitempty"` + AccessTokenSent bool `json:"accessTokenSent,omitempty"` CertificateSent bool `json:"certificateSent,omitempty"` SpecialTaxRegime string `json:"specialTaxRegime,omitempty"` Email string `json:"email,omitempty"` @@ -83,8 +83,8 @@ type MunicipalSettingsResponse struct { } type SpecialTaxRegimeResponse struct { - Label string `json:"label,omitempty"` - Value float64 `json:"value,omitempty"` + Label string `json:"label,omitempty"` + Value string `json:"value,omitempty"` } type FiscalInfoServiceResponse struct { diff --git a/asaas/fiscal_info_test.go b/asaas/fiscal_info_test.go index ed40fde..9732f09 100644 --- a/asaas/fiscal_info_test.go +++ b/asaas/fiscal_info_test.go @@ -8,7 +8,6 @@ import ( func TestFiscalInfoSave(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nFiscalInfo := NewFiscalInfo(EnvSandbox, accessToken) @@ -18,11 +17,11 @@ func TestFiscalInfoSave(t *testing.T) { SimplesNacional: Pointer(true), CulturalProjectsPromoter: nil, Cnae: Pointer("6201501"), - SpecialTaxRegime: nil, - ServiceListItem: nil, - RpsSerie: nil, + SpecialTaxRegime: Pointer("test"), + ServiceListItem: Pointer("test"), + RpsSerie: Pointer("E"), RpsNumber: Pointer(21), - LoteNumber: nil, + LoteNumber: Pointer(21), Username: nil, Password: Pointer("test"), AccessToken: nil, @@ -34,7 +33,6 @@ func TestFiscalInfoSave(t *testing.T) { func TestFiscalInfoGet(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nFiscalInfo := NewFiscalInfo(EnvSandbox, accessToken) @@ -44,7 +42,6 @@ func TestFiscalInfoGet(t *testing.T) { func TestFiscalInfoGetMunicipalSettings(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nFiscalInfo := NewFiscalInfo(EnvSandbox, accessToken) @@ -54,7 +51,6 @@ func TestFiscalInfoGetMunicipalSettings(t *testing.T) { func TestFiscalInfoGetAllServices(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nFiscalInfo := NewFiscalInfo(EnvSandbox, accessToken) diff --git a/asaas/installment.go b/asaas/installment.go index 984b5ea..220d0bd 100644 --- a/asaas/installment.go +++ b/asaas/installment.go @@ -98,7 +98,7 @@ type Installment interface { // # DOCS // // Atualizar splits do parcelamento: https://docs.asaas.com/reference/atualizar-split-do-parcelamento - UpdateSplitsById(ctx context.Context, installmentId string, body []SplitRequest) (*UpdateInstallmentSplitsResponse, + UpdateSplitsById(ctx context.Context, installmentId string, body UpdateSplitsRequest) (*UpdateInstallmentSplitsResponse, error) // RefundById (Estornar parcelamento) // @@ -163,33 +163,33 @@ type Installment interface { // // # Resposta: 200 // - // DeleteResponse = not nil + // DeleteNumericResponse = not nil // // Error = nil // - // Se DeleteResponse.IsSuccess() for true quer dizer que foi excluída. + // Se DeleteNumericResponse.IsSuccess() for true quer dizer que foi excluída. // - // Se caso DeleteResponse.IsFailure() for true quer dizer que não foi excluída. + // Se caso DeleteNumericResponse.IsFailure() for true quer dizer que não foi excluída. // // # Resposta: 404 // - // DeleteResponse = not nil + // DeleteNumericResponse = not nil // // Error = nil // - // DeleteResponse.IsNoContent() = true + // DeleteNumericResponse.IsNoContent() = true // // ID(s) informado no parâmetro não foi encontrado. // // # Resposta: 400/401/500 // - // DeleteResponse = not nil + // DeleteNumericResponse = not nil // // Error = nil // - // DeleteResponse.IsFailure() = true + // DeleteNumericResponse.IsFailure() = true // - // Para qualquer outra resposta inesperada da API, possuímos o campo DeleteResponse.Errors preenchido com as informações + // Para qualquer outra resposta inesperada da API, possuímos o campo DeleteNumericResponse.Errors preenchido com as informações // de erro, sendo 400 retornado da API Asaas com as instruções de requisição conforme a documentação, // diferente disso retornará uma mensagem padrão no index 0 do slice com campo ErrorResponse.Code retornando a // descrição status http (Ex: "401 Unauthorized") e no campo ErrorResponse.Description retornará com o valor @@ -197,7 +197,7 @@ type Installment interface { // // # Error // - // DeleteResponse = nil + // DeleteNumericResponse = nil // // error = not nil // @@ -209,7 +209,7 @@ type Installment interface { // # DOCS // // Remover parcelamento: https://docs.asaas.com/reference/remover-parcelamento - DeleteById(ctx context.Context, installmentId string) (*DeleteResponse, error) + DeleteById(ctx context.Context, installmentId string) (*DeleteNumericResponse, error) // GetById (Recuperar um único parcelamento) // // O identificador único do parcelamento no Asaas pode ser obtido por meio do atributo installment, @@ -376,10 +376,10 @@ func NewInstallment(env Env, accessToken string) Installment { } } -func (i installment) UpdateSplitsById(ctx context.Context, installmentId string, body []SplitRequest) ( +func (i installment) UpdateSplitsById(ctx context.Context, installmentId string, body UpdateSplitsRequest) ( *UpdateInstallmentSplitsResponse, error) { req := NewRequest[UpdateInstallmentSplitsResponse](ctx, i.env, i.accessToken) - return req.make(http.MethodPost, fmt.Sprintf("/v3/installments/%s/splits", installmentId), body) + return req.make(http.MethodPut, fmt.Sprintf("/v3/installments/%s/splits", installmentId), body) } func (i installment) RefundById(ctx context.Context, installmentId string) (*InstallmentResponse, error) { @@ -387,8 +387,8 @@ func (i installment) RefundById(ctx context.Context, installmentId string) (*Ins return req.make(http.MethodPost, fmt.Sprintf("/v3/installments/%s/refund", installmentId), nil) } -func (i installment) DeleteById(ctx context.Context, installmentId string) (*DeleteResponse, error) { - req := NewRequest[DeleteResponse](ctx, i.env, i.accessToken) +func (i installment) DeleteById(ctx context.Context, installmentId string) (*DeleteNumericResponse, error) { + req := NewRequest[DeleteNumericResponse](ctx, i.env, i.accessToken) return req.make(http.MethodDelete, fmt.Sprintf("/v3/installments/%s", installmentId), nil) } diff --git a/asaas/installment_test.go b/asaas/installment_test.go index 685bd62..0d9e418 100644 --- a/asaas/installment_test.go +++ b/asaas/installment_test.go @@ -7,33 +7,30 @@ import ( ) func TestInstallmentUpdateSplitsById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initBankSlipCharge(true) + accessToken := getEnvValue(EnvAccessToken) installmentId := getEnvValue(EnvChargeInstallmentId) - assertFatalStringBlank(t, installmentId) walletIdSecondary := getEnvValue(EnvWalletIdSecondary) - assertFatalStringBlank(t, walletIdSecondary) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nInstallment := NewInstallment(EnvSandbox, accessToken) - resp, err := nInstallment.UpdateSplitsById(ctx, installmentId, []SplitRequest{ - { - WalletId: walletIdSecondary, - FixedValue: 0, - PercentualValue: 50, - TotalFixedValue: 0, + resp, err := nInstallment.UpdateSplitsById(ctx, installmentId, UpdateSplitsRequest{ + Splits: []SplitRequest{ + { + WalletId: walletIdSecondary, + FixedValue: 0, + PercentualValue: 50, + TotalFixedValue: 0, + }, }, }) assertResponseSuccess(t, resp, err) } func TestInstallmentDeleteById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initBankSlipCharge(true) + accessToken := getEnvValue(EnvAccessToken) installmentId := getEnvValue(EnvChargeInstallmentId) - assertFatalStringBlank(t, installmentId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nInstallment := NewInstallment(EnvSandbox, accessToken) @@ -42,11 +39,9 @@ func TestInstallmentDeleteById(t *testing.T) { } func TestInstallmentRefundById(t *testing.T) { + initCreditCardCharge(true) accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) - initCreditCardCharge(false, true) installmentId := getEnvValue(EnvChargeInstallmentId) - assertFatalStringBlank(t, installmentId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nInstallment := NewInstallment(EnvSandbox, accessToken) @@ -55,9 +50,8 @@ func TestInstallmentRefundById(t *testing.T) { } func TestInstallmentGetById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initBankSlipCharge(true) + accessToken := getEnvValue(EnvAccessToken) installmentId := getEnvValue(EnvChargeInstallmentId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() @@ -67,11 +61,9 @@ func TestInstallmentGetById(t *testing.T) { } func TestInstallmentGetPaymentBookById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initBankSlipCharge(true) + accessToken := getEnvValue(EnvAccessToken) installmentId := getEnvValue(EnvChargeInstallmentId) - assertFatalStringBlank(t, installmentId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nInstallment := NewInstallment(EnvSandbox, accessToken) @@ -83,12 +75,11 @@ func TestInstallmentGetPaymentBookById(t *testing.T) { } func TestInstallmentGetAll(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initBankSlipCharge(true) + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nInstallment := NewInstallment(EnvSandbox, accessToken) - resp, errAsaas := nInstallment.GetAll(ctx, PageableDefaultRequest{}) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nInstallment.GetAll(ctx, PageableDefaultRequest{}) + assertResponseSuccess(t, resp, err) } diff --git a/asaas/invoice.go b/asaas/invoice.go index 9f589fb..930a656 100644 --- a/asaas/invoice.go +++ b/asaas/invoice.go @@ -97,7 +97,7 @@ type UpdateInvoiceSettingRequest struct { // Observações adicionais da nota fiscal. Observations *string `json:"observations,omitempty"` // Impostos da nota fiscal. - Taxes *InvoiceTaxesRequest `json:"taxes,omitempty"` + Taxes InvoiceTaxesRequest `json:"taxes,omitempty"` } type InvoiceTaxesRequest struct { diff --git a/asaas/invoice_test.go b/asaas/invoice_test.go index bdce09d..5edc350 100644 --- a/asaas/invoice_test.go +++ b/asaas/invoice_test.go @@ -7,11 +7,9 @@ import ( ) func TestInvoiceSchedule(t *testing.T) { + initCreditCardCharge(false) accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) - initCreditCardCharge(true, false) chargeId := getEnvValue(EnvCreditCardChargeId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nInvoice := NewInvoice(EnvSandbox, accessToken) @@ -35,11 +33,9 @@ func TestInvoiceSchedule(t *testing.T) { } func TestInvoiceAuthorizeById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initInvoice() + accessToken := getEnvValue(EnvAccessToken) invoiceId := getEnvValue(EnvCreditCardChargeId) - assertFatalStringBlank(t, invoiceId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nInvoice := NewInvoice(EnvSandbox, accessToken) @@ -48,11 +44,9 @@ func TestInvoiceAuthorizeById(t *testing.T) { } func TestInvoiceUpdateById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initInvoice() + accessToken := getEnvValue(EnvAccessToken) invoiceId := getEnvValue(EnvCreditCardChargeId) - assertFatalStringBlank(t, invoiceId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nInvoice := NewInvoice(EnvSandbox, accessToken) @@ -73,11 +67,9 @@ func TestInvoiceUpdateById(t *testing.T) { } func TestInvoiceCancelById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initInvoice() + accessToken := getEnvValue(EnvAccessToken) invoiceId := getEnvValue(EnvCreditCardChargeId) - assertFatalStringBlank(t, invoiceId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nInvoice := NewInvoice(EnvSandbox, accessToken) @@ -86,9 +78,8 @@ func TestInvoiceCancelById(t *testing.T) { } func TestInvoiceGetById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initInvoice() + accessToken := getEnvValue(EnvAccessToken) invoiceId := getEnvValue(EnvCreditCardChargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() @@ -98,13 +89,12 @@ func TestInvoiceGetById(t *testing.T) { } func TestInvoiceGetAll(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initInvoice() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nInvoice := NewInvoice(EnvSandbox, accessToken) - resp, errAsaas := nInvoice.GetAll(ctx, GetAllInvoicesRequest{ + resp, err := nInvoice.GetAll(ctx, GetAllInvoicesRequest{ EffectiveDateGE: Date{}, EffectiveDateLE: Date{}, Payment: "", @@ -115,5 +105,5 @@ func TestInvoiceGetAll(t *testing.T) { Offset: 0, Limit: 10, }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } diff --git a/asaas/main_test.go b/asaas/main_test.go index f091114..af07521 100644 --- a/asaas/main_test.go +++ b/asaas/main_test.go @@ -41,6 +41,9 @@ const EnvPaymentLinkImageId = "ASAAS_PAYMENT_LINK_IMAGE_ID" const EnvPixKeyId = "ASAAS_PIX_KEY_ID" const EnvPixTransactionId = "ASAAS_PIX_TRANSACTION_ID" const EnvSubaccountId = "ASAAS_SUBACCOUNT_ID" +const EnvSubaccountAccessToken = "ASAAS_SUBACCOUNT_ACCESS_TOKEN" +const EnvSubaccountDocumentId = "ASAAS_SUBACCOUNT_DOCUMENT_ID" +const EnvSubaccountDocumentType = "ASAAS_SUBACCOUNT_DOCUMENT_TYPE" const EnvSubaccountDocumentSentId = "ASAAS_SUBACCOUNT_DOCUMENT_SENT_ID" const EnvTransferId = "ASAAS_TRANSFER_ID" const EnvSubscriptionId = "ASAAS_SUBSCRIPTION_ID" @@ -76,7 +79,8 @@ func TestMain(m *testing.M) { func getEnvValue(env string) string { v := os.Getenv(env) if util.IsBlank(&v) { - logError("error getEnvValue:", env, " is required env") + logErrorSkipCaller(4, "error getEnvValue:", env, "is required env") + return "undefined" } return v } @@ -96,11 +100,8 @@ func setEnv(env, v string) bool { } func initCustomer() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } clearCustomerId() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() customerAsaas := NewCustomer(EnvSandbox, accessToken) @@ -113,7 +114,7 @@ func initCustomer() { Address: "Rua General Osório", AddressNumber: "1500", }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -121,40 +122,28 @@ func initCustomer() { } func initCustomerDeleted() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } initCustomer() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - if util.IsBlank(&customerId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() customerAsaas := NewCustomer(EnvSandbox, accessToken) resp, err := customerAsaas.DeleteById(ctx, customerId) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } - setEnv(EnvCustomerDeletedId, resp.Id) + setEnv(EnvCustomerDeletedId, customerId) } -func initCreditCardCharge(capture bool, withInstallment bool) { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } - clearCreditCardChargeId() +func initCreditCardCharge(withInstallment bool) { initCustomer() + clearCreditCardChargeId() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - if util.IsBlank(&customerId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() - now := time.Now() + now := DateNow() req := CreateChargeRequest{ Customer: customerId, BillingType: BillingTypeCreditCard, @@ -177,7 +166,7 @@ func initCreditCardCharge(capture bool, withInstallment bool) { PostalCode: "89223-005", AddressNumber: "277", }, - AuthorizeOnly: !capture, + AuthorizeOnly: false, RemoteIp: "191.253.125.194", } if withInstallment { @@ -186,50 +175,37 @@ func initCreditCardCharge(capture bool, withInstallment bool) { } chargeAsaas := NewCharge(EnvSandbox, accessToken) resp, err := chargeAsaas.Create(ctx, req) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } - success := setEnv(EnvCreditCardChargeId, resp.Id) - if !success { - return - } - if withInstallment { - setEnv(EnvChargeInstallmentId, resp.Installment) - } + setEnv(EnvCreditCardChargeId, resp.Id) + setEnv(EnvChargeInstallmentId, resp.Installment) } func initPixCharge() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } - clearPixChargeId() initCustomer() + clearPixChargeId() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - if util.IsBlank(&customerId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() - now := time.Now() + now := DateNow() chargeAsaas := NewCharge(EnvSandbox, accessToken) resp, err := chargeAsaas.Create(ctx, CreateChargeRequest{ + Customer: customerId, BillingType: BillingTypePix, DueDate: NewDate(now.Year(), now.Month(), now.Day(), now.Location()), Value: 100, Description: "Cobrança via teste unitário em Golang", }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } - success := setEnv(EnvPixChargeId, resp.Id) - if !success { - return - } + setEnv(EnvPixChargeId, resp.Id) pixQrCodeResp, err := chargeAsaas.GetPixQrCodeById(ctx, resp.Id) - if err != nil || pixQrCodeResp.IsFailure() { + if err != nil || pixQrCodeResp.IsNoContent() || pixQrCodeResp.IsFailure() { logError("error resp:", pixQrCodeResp, "err: ", err) return } @@ -237,20 +213,15 @@ func initPixCharge() { } func initBankSlipCharge(withInstallment bool) { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } - clearBankSlipChargeId() initCustomer() + clearBankSlipChargeId() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - if util.IsBlank(&customerId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() - now := time.Now() + now := DateNow() req := CreateChargeRequest{ + Customer: customerId, BillingType: BillingTypeBankSlip, DueDate: NewDate(now.Year(), now.Month(), now.Day(), now.Location()), Value: 100, @@ -262,39 +233,28 @@ func initBankSlipCharge(withInstallment bool) { } chargeAsaas := NewCharge(EnvSandbox, accessToken) resp, err := chargeAsaas.Create(ctx, req) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } - success := setEnv(EnvBankSlipChargeId, resp.Id) - if !success { - return - } + setEnv(EnvBankSlipChargeId, resp.Id) identificationFieldResp, err := chargeAsaas.GetIdentificationFieldById(ctx, resp.Id) - if err != nil || identificationFieldResp.IsFailure() { + if err != nil || identificationFieldResp.IsNoContent() || identificationFieldResp.IsFailure() { logError("error resp:", identificationFieldResp, "err: ", err) return } setEnv(EnvChargeIdentificationField, identificationFieldResp.IdentificationField) - if withInstallment { - setEnv(EnvChargeInstallmentId, resp.Installment) - } + setEnv(EnvChargeInstallmentId, resp.Installment) } func initUndefinedCharge() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } - clearUndefinedChargeId() initCustomer() + clearUndefinedChargeId() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - if util.IsBlank(&customerId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() - now := time.Now() + now := DateNow() chargeAsaas := NewCharge(EnvSandbox, accessToken) resp, err := chargeAsaas.Create(ctx, CreateChargeRequest{ Customer: customerId, @@ -303,7 +263,7 @@ func initUndefinedCharge() { DueDate: NewDate(now.Year(), now.Month(), now.Day(), now.Location()), Description: "Cobrança via teste unitário em Golang", }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -311,45 +271,33 @@ func initUndefinedCharge() { } func initChargeDeleted() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } initUndefinedCharge() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - if util.IsBlank(&chargeId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() chargeAsaas := NewCharge(EnvSandbox, accessToken) resp, err := chargeAsaas.DeleteById(ctx, chargeId) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } - setEnv(EnvChargeDeletedId, resp.Id) + setEnv(EnvChargeDeletedId, chargeId) } func initChargeReceivedInCash() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } initUndefinedCharge() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - if util.IsBlank(&chargeId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() - now := time.Now() + now := DateNow() chargeAsaas := NewCharge(EnvSandbox, accessToken) resp, err := chargeAsaas.ReceiveInCashById(ctx, chargeId, ChargeReceiveInCashRequest{ PaymentDate: NewDate(now.Year(), now.Month(), now.Day(), now.Location()), Value: 100, }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -357,19 +305,10 @@ func initChargeReceivedInCash() { } func initChargeDocumentId() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } initUndefinedCharge() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvUndefinedChargeId) - if util.IsBlank(&chargeId) { - return - } f, err := os.Open(getEnvValue(EnvFileName)) - if err != nil { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCharge := NewCharge(EnvSandbox, accessToken) @@ -377,7 +316,7 @@ func initChargeDocumentId() { Type: DocumentTypeDocument, File: f, }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -385,22 +324,16 @@ func initChargeDocumentId() { } func initAnticipation() { + initCreditCardCharge(false) accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } - initCreditCardCharge(true, false) chargeId := getEnvValue(EnvCreditCardChargeId) - if util.IsBlank(&chargeId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() anticipationAsaas := NewAnticipation(EnvSandbox, accessToken) resp, err := anticipationAsaas.Request(ctx, AnticipationRequest{ Payment: chargeId, }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -408,29 +341,19 @@ func initAnticipation() { } func initBillPayment() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } - clearBillPaymentId() initBankSlipCharge(false) - chargeId := getEnvValue(EnvBankSlipChargeId) - if util.IsBlank(&chargeId) { - return - } + clearBillPaymentId() + accessToken := getEnvValue(EnvAccessToken) identificationField := getEnvValue(EnvChargeIdentificationField) - if util.IsBlank(&chargeId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() - now := time.Now() + now := DateNow() billPaymentAsaas := NewBillPayment(EnvSandbox, accessToken) resp, err := billPaymentAsaas.Create(ctx, CreateBillPaymentRequest{ IdentificationField: identificationField, ScheduleDate: NewDate(now.Year(), now.Month(), now.Day()+1, now.Location()), }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error create bill payment resp:", resp, "err: ", err) return } @@ -456,15 +379,9 @@ func initImage() { } func initCreditBureauReport() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } initCustomer() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - if util.IsBlank(&customerId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nCreditBureau := NewCreditBureau(EnvSandbox, accessToken) @@ -473,7 +390,7 @@ func initCreditBureauReport() { CpfCnpj: "", State: "SP", }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -482,9 +399,6 @@ func initCreditBureauReport() { func initFiscalInfo() { accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nFiscalInfo := NewFiscalInfo(EnvSandbox, accessToken) @@ -494,30 +408,27 @@ func initFiscalInfo() { SimplesNacional: Pointer(true), CulturalProjectsPromoter: nil, Cnae: Pointer("6201501"), - SpecialTaxRegime: nil, + SpecialTaxRegime: Pointer("test"), ServiceListItem: nil, - RpsSerie: nil, + RpsSerie: Pointer("E"), RpsNumber: Pointer(21), - LoteNumber: nil, + LoteNumber: Pointer(21), Username: nil, Password: Pointer("test"), AccessToken: nil, CertificateFile: nil, CertificatePassword: nil, }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } } func initInvoice() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } + initCreditCardCharge(false) clearInvoiceId() - initCreditCardCharge(true, false) + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvCreditCardChargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() @@ -538,7 +449,7 @@ func initInvoice() { UpdatePayment: false, Taxes: InvoiceTaxesRequest{}, }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -546,11 +457,8 @@ func initInvoice() { } func initMobilePhoneRecharge() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } clearMobilePhoneRechargeId() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nMobilePhone := NewMobilePhone(EnvSandbox, accessToken) @@ -558,7 +466,7 @@ func initMobilePhoneRecharge() { PhoneNumber: "47997576130", Value: 20, }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -566,16 +474,10 @@ func initMobilePhoneRecharge() { } func initNegativity() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } - clearNegativityId() initBankSlipCharge(false) + clearNegativityId() + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvBankSlipChargeId) - if util.IsBlank(&chargeId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nNegativity := NewNegativity(EnvSandbox, accessToken) @@ -591,7 +493,7 @@ func initNegativity() { CustomerAddressNumber: "150", CustomerProvince: "Centro", }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -599,20 +501,14 @@ func initNegativity() { } func initNotification() { + initCreditCardCharge(false) accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } - initCreditCardCharge(false, false) customerId := getEnvValue(EnvCustomerId) - if util.IsBlank(&customerId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nNotification := NewNotification(EnvSandbox, accessToken) resp, err := nNotification.GetAllByCustomer(ctx, customerId) - if err != nil || resp.IsFailure() || resp.IsNoContent() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -620,11 +516,8 @@ func initNotification() { } func initPaymentLink() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } clearPaymentLinkId() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPaymentLink := NewPaymentLink(EnvSandbox, accessToken) @@ -633,7 +526,7 @@ func initPaymentLink() { BillingType: BillingTypeUndefined, ChargeType: ChargeTypeDetached, }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -641,41 +534,25 @@ func initPaymentLink() { } func initPaymentLinkDeleted() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } initPaymentLink() + accessToken := getEnvValue(EnvAccessToken) paymentLinkId := getEnvValue(EnvPaymentLinkId) - if util.IsBlank(&paymentLinkId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPaymentLink := NewPaymentLink(EnvSandbox, accessToken) resp, err := nPaymentLink.DeleteById(ctx, paymentLinkId) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } - setEnv(EnvPaymentLinkDeletedId, resp.Id) + setEnv(EnvPaymentLinkDeletedId, paymentLinkId) } func initPaymentLinkImage() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } initPaymentLink() + accessToken := getEnvValue(EnvAccessToken) paymentLinkId := getEnvValue(EnvPaymentLinkId) - if util.IsBlank(&paymentLinkId) { - return - } - f, err := os.Open(getEnvValue(EnvImageName)) - if err != nil { - logError("error open image:", err) - return - } + f, _ := os.Open(getEnvValue(EnvImageName)) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPaymentLink := NewPaymentLink(EnvSandbox, accessToken) @@ -683,7 +560,7 @@ func initPaymentLinkImage() { Main: false, Image: f, }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -691,16 +568,13 @@ func initPaymentLinkImage() { } func initPixKey() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } clearPixKeyId() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPix := NewPix(EnvSandbox, accessToken) resp, err := nPix.CreateKey(ctx) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -708,16 +582,10 @@ func initPixKey() { } func initPixTransaction() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } - clearPixTransactionId() initPixCharge() + clearPixTransactionId() + accessToken := getEnvValue(EnvAccessToken) pixQrCodePayload := getEnvValue(EnvChargePixQrCodePayload) - if util.IsBlank(&pixQrCodePayload) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPix := NewPix(EnvSandbox, accessToken) @@ -730,7 +598,7 @@ func initPixTransaction() { Description: "", ScheduleDate: Date{}, }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -738,56 +606,71 @@ func initPixTransaction() { } func initSubaccount() { - accessToken := getEnvValue(EnvAccessTokenSecondary) - if util.IsBlank(&accessToken) { - return - } clearSubaccount() + accessToken := getEnvValue(EnvAccessTokenSecondary) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubaccount := NewSubaccount(EnvSandbox, accessToken) resp, err := nSubaccount.Create(ctx, CreateSubaccountRequest{ Name: "Unit test go", - Email: "unittestgo@gmail.com", - CpfCnpj: cpf.Generate(), - BirthDate: NewDate(1999, 1, 21, time.Local), - MobilePhone: "47997576131", + Email: util.GenerateEmail(), + CpfCnpj: "69257172000141", + CompanyType: CompanyTypeLimited, + MobilePhone: util.GenerateMobilePhone(), Address: "Rua Maria de Souza Maba", AddressNumber: "123", Province: "Fortaleza", PostalCode: "89056-220", }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } setEnv(EnvSubaccountId, resp.Id) + setEnv(EnvSubaccountAccessToken, resp.ApiKey) } func initSubaccountDocument() { - accessToken := getEnvValue(EnvAccessTokenSecondary) - if util.IsBlank(&accessToken) { - return - } - clearSubaccountDocumentSentId() initSubaccount() - subaccountId := getEnvValue(EnvSubaccountId) - if util.IsBlank(&subaccountId) { + subaccountAccessToken := getEnvValue(EnvSubaccountAccessToken) + ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) + defer cancel() + nSubaccount := NewSubaccount(EnvSandbox, subaccountAccessToken) + resp, err := nSubaccount.GetPendingDocuments(ctx) + if err != nil || resp.IsNoContent() || resp.IsFailure() { + logError("error resp:", resp, "err: ", err) return } - f, err := os.Open(getEnvValue(EnvFileName)) - if err != nil { - logError("error open file:", err) + var subaccountDocument SubaccountDocumentResponse + for _, documentToSent := range resp.Data { + if documentToSent.Status == SubaccountDocumentStatusNotSent && + documentToSent.Type != SubaccountDocumentTypeIdentification { + subaccountDocument = documentToSent + } + } + if util.IsBlank(&subaccountDocument.Id) { + logError("subaccountDocument not found") return } + setEnv(EnvSubaccountDocumentId, subaccountDocument.Id) + setEnv(EnvSubaccountDocumentType, string(subaccountDocument.Type)) +} + +func initSubaccountDocumentSent() { + initSubaccountDocument() + clearSubaccountDocumentSentId() + subaccountAccessToken := getEnvValue(EnvSubaccountAccessToken) + subaccountDocumentId := getEnvValue(EnvSubaccountDocumentId) + subaccountDocumentType := getEnvValue(EnvSubaccountDocumentType) + f, _ := os.Open(getEnvValue(EnvImageName)) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() - nSubaccount := NewSubaccount(EnvSandbox, accessToken) - resp, err := nSubaccount.SendWhiteLabelDocument(ctx, subaccountId, SubaccountSendDocumentRequest{ - Type: SubaccountDocumentTypeCustom, + nSubaccount := NewSubaccount(EnvSandbox, subaccountAccessToken) + resp, err := nSubaccount.SendWhiteLabelDocument(ctx, subaccountDocumentId, SendWhiteLabelDocumentRequest{ + Type: SubaccountDocumentType(subaccountDocumentType), DocumentFile: f, }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -795,15 +678,9 @@ func initSubaccountDocument() { } func initTransfer() { - accessToken := getEnvValue(EnvAccessTokenSecondary) - if util.IsBlank(&accessToken) { - return - } clearTransferId() + accessToken := getEnvValue(EnvAccessToken) walletId := getEnvValue(EnvWalletIdSecondary) - if util.IsBlank(&walletId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nTransfer := NewTransfer(EnvSandbox, accessToken) @@ -811,7 +688,7 @@ func initTransfer() { Value: 10, WalletId: walletId, }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -820,9 +697,6 @@ func initTransfer() { func initWebhook() { accessToken := getEnvValue(EnvAccessTokenSecondary) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nWebhook := NewWebhook(EnvSandbox, accessToken) @@ -834,26 +708,20 @@ func initWebhook() { Interrupted: Pointer(false), AuthToken: "", }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } } func initSubscription() { - accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } - clearSubscriptionId() initCustomer() + clearSubscriptionId() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - if util.IsBlank(&customerId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() - now := time.Now() + now := DateNow() nSubscription := NewSubscription(EnvSandbox, accessToken) resp, err := nSubscription.Create(ctx, CreateSubscriptionRequest{ Customer: customerId, @@ -863,7 +731,7 @@ func initSubscription() { Cycle: SubscriptionCycleMonthly, Description: "Unit test go", }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -872,14 +740,7 @@ func initSubscription() { func initSubscriptionInvoiceSetting() { accessToken := getEnvValue(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } - initSubscription() subscriptionId := getEnvValue(EnvSubscriptionId) - if util.IsBlank(&subscriptionId) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubscription := NewSubscription(EnvSandbox, accessToken) @@ -889,7 +750,7 @@ func initSubscriptionInvoiceSetting() { EffectiveDatePeriod: EffectiveDatePeriodOnNextMonth, Observations: "Unit test go", }) - if err != nil || resp.IsFailure() { + if err != nil || resp.IsNoContent() || resp.IsFailure() { logError("error resp:", resp, "err: ", err) return } @@ -897,9 +758,6 @@ func initSubscriptionInvoiceSetting() { func clearCustomerId() { accessToken := getEnvValueWithoutLogger(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() customerId := getEnvValueWithoutLogger(EnvCustomerId) @@ -913,9 +771,6 @@ func clearCustomerId() { func clearCreditCardChargeId() { accessToken := getEnvValueWithoutLogger(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() chargeId := getEnvValueWithoutLogger(EnvCreditCardChargeId) @@ -926,15 +781,11 @@ func clearCreditCardChargeId() { _, _ = chargeAsaas.RefundById(ctx, chargeId, RefundRequest{ Description: "unit test golang", }) - _, _ = chargeAsaas.DeleteById(ctx, chargeId) _ = os.Unsetenv(EnvCreditCardChargeId) } func clearPixChargeId() { accessToken := getEnvValueWithoutLogger(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() chargeId := getEnvValueWithoutLogger(EnvCreditCardChargeId) @@ -948,9 +799,6 @@ func clearPixChargeId() { func clearBankSlipChargeId() { accessToken := getEnvValueWithoutLogger(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() chargeId := getEnvValueWithoutLogger(EnvBankSlipChargeId) @@ -964,9 +812,6 @@ func clearBankSlipChargeId() { func clearUndefinedChargeId() { accessToken := getEnvValueWithoutLogger(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() chargeId := getEnvValueWithoutLogger(EnvBankSlipChargeId) @@ -980,9 +825,6 @@ func clearUndefinedChargeId() { func clearBillPaymentId() { accessToken := getEnvValueWithoutLogger(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() billPaymentId := getEnvValueWithoutLogger(EnvBillPaymentId) @@ -1005,9 +847,6 @@ func clearFileName() { func clearInvoiceId() { accessToken := getEnvValueWithoutLogger(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() invoiceId := getEnvValueWithoutLogger(EnvInvoiceId) @@ -1021,9 +860,6 @@ func clearInvoiceId() { func clearMobilePhoneRechargeId() { accessToken := getEnvValueWithoutLogger(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() rechargeId := getEnvValueWithoutLogger(EnvMobilePhoneRechargeId) @@ -1037,9 +873,6 @@ func clearMobilePhoneRechargeId() { func clearNegativityId() { accessToken := getEnvValueWithoutLogger(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() negativityId := getEnvValueWithoutLogger(EnvNegativityId) @@ -1053,9 +886,6 @@ func clearNegativityId() { func clearPaymentLinkId() { accessToken := getEnvValueWithoutLogger(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() paymentLinkId := getEnvValueWithoutLogger(EnvPaymentLinkId) @@ -1069,9 +899,6 @@ func clearPaymentLinkId() { func clearPixTransactionId() { accessToken := getEnvValueWithoutLogger(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() pixTransactionId := getEnvValueWithoutLogger(EnvPixTransactionId) @@ -1085,9 +912,6 @@ func clearPixTransactionId() { func clearPixKeyId() { accessToken := getEnvValueWithoutLogger(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() pixKeyId := getEnvValueWithoutLogger(EnvPixKeyId) @@ -1100,8 +924,8 @@ func clearPixKeyId() { } func clearSubaccount() { - accessToken := getEnvValueWithoutLogger(EnvAccessTokenSecondary) - if util.IsBlank(&accessToken) { + subaccountAccessToken := getEnvValueWithoutLogger(EnvSubaccountAccessToken) + if util.IsBlank(&subaccountAccessToken) { return } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) @@ -1110,7 +934,7 @@ func clearSubaccount() { if util.IsBlank(&subaccountId) { return } - accountAsaas := NewAccount(EnvSandbox, accessToken) + accountAsaas := NewAccount(EnvSandbox, subaccountAccessToken) _, _ = accountAsaas.DeleteWhiteLabelSubaccount(ctx, DeleteWhiteLabelSubaccountRequest{ RemoveReason: "Unit test go", }) @@ -1118,26 +942,20 @@ func clearSubaccount() { } func clearSubaccountDocumentSentId() { - accessToken := getEnvValueWithoutLogger(EnvAccessTokenSecondary) - if util.IsBlank(&accessToken) { - return - } + subaccountAccessToken := getEnvValueWithoutLogger(EnvSubaccountAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() documentSentId := getEnvValueWithoutLogger(EnvSubaccountDocumentSentId) if util.IsBlank(&documentSentId) { return } - subaccountAsaas := NewSubaccount(EnvSandbox, accessToken) + subaccountAsaas := NewSubaccount(EnvSandbox, subaccountAccessToken) _, _ = subaccountAsaas.DeleteWhiteLabelDocumentSentById(ctx, documentSentId) _ = os.Unsetenv(EnvSubaccountDocumentSentId) } func clearTransferId() { - accessToken := getEnvValueWithoutLogger(EnvAccessTokenSecondary) - if util.IsBlank(&accessToken) { - return - } + accessToken := getEnvValueWithoutLogger(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() transferId := getEnvValueWithoutLogger(EnvTransferId) @@ -1151,9 +969,6 @@ func clearTransferId() { func clearSubscriptionId() { accessToken := getEnvValueWithoutLogger(EnvAccessToken) - if util.IsBlank(&accessToken) { - return - } ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() subscriptionId := getEnvValueWithoutLogger(EnvSubscriptionId) diff --git a/asaas/mobile_phone_test.go b/asaas/mobile_phone_test.go index a24181a..136548d 100644 --- a/asaas/mobile_phone_test.go +++ b/asaas/mobile_phone_test.go @@ -8,62 +8,56 @@ import ( func TestMobilePhoneRecharge(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nMobilePhone := NewMobilePhone(EnvSandbox, accessToken) - resp, errAsaas := nMobilePhone.Recharge(ctx, MobilePhoneRechargeRequest{ + resp, err := nMobilePhone.Recharge(ctx, MobilePhoneRechargeRequest{ PhoneNumber: "47997576131", Value: 20, }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } func TestMobilePhoneCancelRechargeById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initMobilePhoneRecharge() + accessToken := getEnvValue(EnvAccessToken) rechargeId := getEnvValue(EnvMobilePhoneRechargeId) - assertFatalStringBlank(t, rechargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nMobilePhone := NewMobilePhone(EnvSandbox, accessToken) - resp, errAsaas := nMobilePhone.CancelRechargeById(ctx, rechargeId) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nMobilePhone.CancelRechargeById(ctx, rechargeId) + assertResponseSuccess(t, resp, err) } func TestMobilePhoneGetRechargeById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initMobilePhoneRecharge() + accessToken := getEnvValue(EnvAccessToken) rechargeId := getEnvValue(EnvMobilePhoneRechargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nMobilePhone := NewMobilePhone(EnvSandbox, accessToken) - resp, errAsaas := nMobilePhone.GetRechargeById(ctx, rechargeId) - assertResponseSuccess(t, resp, errAsaas) + resp, err := nMobilePhone.GetRechargeById(ctx, rechargeId) + assertResponseSuccess(t, resp, err) } func TestMobilePhoneGetAllRecharges(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initMobilePhoneRecharge() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nMobilePhone := NewMobilePhone(EnvSandbox, accessToken) - resp, errAsaas := nMobilePhone.GetAllRecharges(ctx, PageableDefaultRequest{ + resp, err := nMobilePhone.GetAllRecharges(ctx, PageableDefaultRequest{ Offset: 0, Limit: 10, }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } func TestMobilePhoneGetProviderByPhoneNumber(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nMobilePhone := NewMobilePhone(EnvSandbox, accessToken) - resp, errAsaas := nMobilePhone.GetProviderByPhoneNumber(ctx, "47997576131") - assertResponseSuccess(t, resp, errAsaas) + resp, err := nMobilePhone.GetProviderByPhoneNumber(ctx, "47997576131") + assertResponseSuccess(t, resp, err) } diff --git a/asaas/negativity_test.go b/asaas/negativity_test.go index 99c572e..6772ce3 100644 --- a/asaas/negativity_test.go +++ b/asaas/negativity_test.go @@ -8,15 +8,11 @@ import ( ) func TestNegativityCreate(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initBankSlipCharge(false) + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvBankSlipChargeId) - assertFatalStringBlank(t, chargeId) - f, err := os.Open(getEnvValue(EnvFileName)) - assertFatalErrorNonnull(t, err) - v, err := os.ReadFile(f.Name()) - assertFatalErrorNonnull(t, err) + f, _ := os.Open(getEnvValue(EnvFileName)) + v, _ := os.ReadFile(f.Name()) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nNegativity := NewNegativity(EnvSandbox, accessToken) @@ -43,11 +39,9 @@ func TestNegativityCreate(t *testing.T) { } func TestNegativitySimulate(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initBankSlipCharge(false) + accessToken := getEnvValue(EnvAccessToken) chargeId := getEnvValue(EnvBankSlipChargeId) - assertFatalStringBlank(t, chargeId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nNegativity := NewNegativity(EnvSandbox, accessToken) @@ -56,13 +50,10 @@ func TestNegativitySimulate(t *testing.T) { } func TestNegativityResendDocumentsById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initNegativity() + accessToken := getEnvValue(EnvAccessToken) negativityId := getEnvValue(EnvNegativityId) - assertFatalStringBlank(t, negativityId) - f, err := os.Open(getEnvValue(EnvFileName)) - assertFatalErrorNonnull(t, err) + f, _ := os.Open(getEnvValue(EnvFileName)) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nNegativity := NewNegativity(EnvSandbox, accessToken) @@ -73,11 +64,9 @@ func TestNegativityResendDocumentsById(t *testing.T) { } func TestNegativityCancelById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initNegativity() + accessToken := getEnvValue(EnvAccessToken) negativityId := getEnvValue(EnvNegativityId) - assertFatalStringBlank(t, negativityId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nNegativity := NewNegativity(EnvSandbox, accessToken) @@ -86,9 +75,8 @@ func TestNegativityCancelById(t *testing.T) { } func TestNegativityGetById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initNegativity() + accessToken := getEnvValue(EnvAccessToken) negativityId := getEnvValue(EnvNegativityId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() @@ -98,9 +86,8 @@ func TestNegativityGetById(t *testing.T) { } func TestNegativityGetAll(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initNegativity() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nNegativity := NewNegativity(EnvSandbox, accessToken) @@ -117,11 +104,9 @@ func TestNegativityGetAll(t *testing.T) { } func TestNegativityGetHistoryById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initNegativity() + accessToken := getEnvValue(EnvAccessToken) negativityId := getEnvValue(EnvNegativityId) - assertFatalStringBlank(t, negativityId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nNegativity := NewNegativity(EnvSandbox, accessToken) @@ -133,11 +118,9 @@ func TestNegativityGetHistoryById(t *testing.T) { } func TestNegativityGetPaymentsById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initNegativity() + accessToken := getEnvValue(EnvAccessToken) negativityId := getEnvValue(EnvNegativityId) - assertFatalStringBlank(t, negativityId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nNegativity := NewNegativity(EnvSandbox, accessToken) @@ -150,7 +133,6 @@ func TestNegativityGetPaymentsById(t *testing.T) { func TestNegativityGetChargesAvailableForDunning(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nNegativity := NewNegativity(EnvSandbox, accessToken) diff --git a/asaas/notification_test.go b/asaas/notification_test.go index f5f9779..50a4154 100644 --- a/asaas/notification_test.go +++ b/asaas/notification_test.go @@ -7,11 +7,9 @@ import ( ) func TestNotificationUpdateById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initNotification() + accessToken := getEnvValue(EnvAccessToken) notificationId := getEnvValue(EnvNotificationId) - assertFatalStringBlank(t, notificationId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nNotification := NewNotification(EnvSandbox, accessToken) @@ -29,13 +27,10 @@ func TestNotificationUpdateById(t *testing.T) { } func TestNotificationUpdateManyByCustomer(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initNotification() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - assertFatalStringBlank(t, customerId) notificationId := getEnvValue(EnvNotificationId) - assertFatalStringBlank(t, notificationId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nNotification := NewNotification(EnvSandbox, accessToken) @@ -59,11 +54,9 @@ func TestNotificationUpdateManyByCustomer(t *testing.T) { } func TestNotificationGetAllByCustomer(t *testing.T) { + initCreditCardCharge(false) accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) - initCreditCardCharge(false, false) customerId := getEnvValue(EnvCustomerId) - assertFatalStringBlank(t, customerId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nNotification := NewNotification(EnvSandbox, accessToken) diff --git a/asaas/payment_link.go b/asaas/payment_link.go index eb1028d..ccb0474 100644 --- a/asaas/payment_link.go +++ b/asaas/payment_link.go @@ -21,7 +21,7 @@ type CreatePaymentLinkRequest struct { // Valor do link de pagamentos, caso não informado o pagador poderá informar o quanto deseja pagar Value float64 `json:"value,omitempty"` // Caso seja possível o pagamento via boleto bancário, define a quantidade de dias úteis que o seu cliente poderá pagar o boleto após gerado - DueDateLimitDays int `json:"dueDateLimitDays,omitempty"` + DueDateLimitDays int `json:"dueDateLimitDays"` // Periodicidade da cobrança (REQUIRED se ChargeType = ChargeTypeRecurrent) SubscriptionCycle SubscriptionCycle `json:"subscriptionCycle,omitempty"` // Quantidade máxima de parcelas que seu cliente poderá parcelar o valor do link de pagamentos (REQUIRED se ChargeType = ChargeTypeInstallment) @@ -718,7 +718,7 @@ func (p paymentLink) UpdateImageAsMainById(ctx context.Context, paymentLinkId, i func (p paymentLink) RestoreById(ctx context.Context, paymentLinkId string) (*PaymentLinkResponse, error) { req := NewRequest[PaymentLinkResponse](ctx, p.env, p.accessToken) - return req.make(http.MethodPost, fmt.Sprintf("/v3/paymentLinks/%s", paymentLinkId), nil) + return req.make(http.MethodPost, fmt.Sprintf("/v3/paymentLinks/%s/restore", paymentLinkId), nil) } func (p paymentLink) DeleteById(ctx context.Context, paymentLinkId string) (*DeleteResponse, error) { diff --git a/asaas/payment_link_test.go b/asaas/payment_link_test.go index b728951..09f4c46 100644 --- a/asaas/payment_link_test.go +++ b/asaas/payment_link_test.go @@ -9,7 +9,6 @@ import ( func TestPaymentLinkCreate(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPaymentLink := NewPaymentLink(EnvSandbox, accessToken) @@ -30,13 +29,10 @@ func TestPaymentLinkCreate(t *testing.T) { } func TestPaymentLinkSendImageById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPaymentLink() + accessToken := getEnvValue(EnvAccessToken) paymentLinkId := getEnvValue(EnvPaymentLinkId) - assertFatalStringBlank(t, paymentLinkId) - f, err := os.Open(getEnvValue(EnvImageName)) - assertFatalErrorNonnull(t, err) + f, _ := os.Open(getEnvValue(EnvImageName)) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPaymentLink := NewPaymentLink(EnvSandbox, accessToken) @@ -48,11 +44,9 @@ func TestPaymentLinkSendImageById(t *testing.T) { } func TestPaymentLinkUpdateById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPaymentLink() + accessToken := getEnvValue(EnvAccessToken) paymentLinkId := getEnvValue(EnvPaymentLinkId) - assertFatalStringBlank(t, paymentLinkId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPaymentLink := NewPaymentLink(EnvSandbox, accessToken) @@ -73,13 +67,10 @@ func TestPaymentLinkUpdateById(t *testing.T) { } func TestPaymentLinkUpdateImageAsMainById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPaymentLinkImage() + accessToken := getEnvValue(EnvAccessToken) paymentLinkId := getEnvValue(EnvPaymentLinkId) - assertFatalStringBlank(t, paymentLinkId) paymentLinkImageId := getEnvValue(EnvPaymentLinkImageId) - assertFatalStringBlank(t, paymentLinkImageId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPaymentLink := NewPaymentLink(EnvSandbox, accessToken) @@ -88,11 +79,9 @@ func TestPaymentLinkUpdateImageAsMainById(t *testing.T) { } func TestPaymentLinkDeleteById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPaymentLinkImage() + accessToken := getEnvValue(EnvAccessToken) paymentLinkId := getEnvValue(EnvPaymentLinkId) - assertFatalStringBlank(t, paymentLinkId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPaymentLink := NewPaymentLink(EnvSandbox, accessToken) @@ -101,11 +90,9 @@ func TestPaymentLinkDeleteById(t *testing.T) { } func TestPaymentLinkRestoreById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPaymentLinkDeleted() + accessToken := getEnvValue(EnvAccessToken) paymentLinkId := getEnvValue(EnvPaymentLinkDeletedId) - assertFatalStringBlank(t, paymentLinkId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPaymentLink := NewPaymentLink(EnvSandbox, accessToken) @@ -114,13 +101,10 @@ func TestPaymentLinkRestoreById(t *testing.T) { } func TestPaymentLinkDeleteImageById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPaymentLinkImage() + accessToken := getEnvValue(EnvAccessToken) paymentLinkId := getEnvValue(EnvPaymentLinkId) - assertFatalStringBlank(t, paymentLinkId) paymentLinkImageId := getEnvValue(EnvPaymentLinkImageId) - assertFatalStringBlank(t, paymentLinkImageId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPaymentLink := NewPaymentLink(EnvSandbox, accessToken) @@ -129,9 +113,8 @@ func TestPaymentLinkDeleteImageById(t *testing.T) { } func TestPaymentLinkGetById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPaymentLinkImage() + accessToken := getEnvValue(EnvAccessToken) paymentLinkId := getEnvValue(EnvPaymentLinkId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() @@ -141,8 +124,8 @@ func TestPaymentLinkGetById(t *testing.T) { } func TestPaymentLinkGetImageById(t *testing.T) { + initPaymentLinkImage() accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) paymentLinkId := getEnvValue(EnvPaymentLinkId) paymentLinkImageId := getEnvValue(EnvPaymentLinkImageId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) @@ -153,9 +136,8 @@ func TestPaymentLinkGetImageById(t *testing.T) { } func TestPaymentLinkGetAll(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPaymentLink() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPaymentLink := NewPaymentLink(EnvSandbox, accessToken) @@ -170,8 +152,8 @@ func TestPaymentLinkGetAll(t *testing.T) { } func TestPaymentLinkGetImagesById(t *testing.T) { + initPaymentLinkImage() accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) paymentLinkId := getEnvValue(EnvPaymentLinkId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() diff --git a/asaas/pix_test.go b/asaas/pix_test.go index 90d7eb0..5b2a59d 100644 --- a/asaas/pix_test.go +++ b/asaas/pix_test.go @@ -7,11 +7,9 @@ import ( ) func TestPixPayQrCode(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPixCharge() + accessToken := getEnvValue(EnvAccessToken) pixQrCodePayload := getEnvValue(EnvChargePixQrCodePayload) - assertFatalStringBlank(t, pixQrCodePayload) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPix := NewPix(EnvSandbox, accessToken) @@ -28,11 +26,9 @@ func TestPixPayQrCode(t *testing.T) { } func TestPixDecodeQrCode(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPixCharge() + accessToken := getEnvValue(EnvAccessToken) pixQrCodePayload := getEnvValue(EnvChargePixQrCodePayload) - assertFatalStringBlank(t, pixQrCodePayload) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPix := NewPix(EnvSandbox, accessToken) @@ -44,11 +40,9 @@ func TestPixDecodeQrCode(t *testing.T) { } func TestPixCancelTransactionById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPixTransaction() + accessToken := getEnvValue(EnvAccessToken) pixTransactionId := getEnvValue(EnvPixTransactionId) - assertFatalStringBlank(t, pixTransactionId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPix := NewPix(EnvSandbox, accessToken) @@ -58,7 +52,6 @@ func TestPixCancelTransactionById(t *testing.T) { func TestPixCreateKey(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPix := NewPix(EnvSandbox, accessToken) @@ -68,10 +61,9 @@ func TestPixCreateKey(t *testing.T) { func TestPixCreateStaticKey(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() - now := time.Now() + now := DatetimeNow() nPix := NewPix(EnvSandbox, accessToken) resp, err := nPix.CreateStaticKey(ctx, CreatePixKeyStaticRequest{ AddressKey: "", @@ -87,11 +79,9 @@ func TestPixCreateStaticKey(t *testing.T) { } func TestPixDeleteKeyById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPixKey() + accessToken := getEnvValue(EnvAccessToken) pixKeyId := getEnvValue(EnvPixKeyId) - assertFatalStringBlank(t, pixKeyId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPix := NewPix(EnvSandbox, accessToken) @@ -100,9 +90,8 @@ func TestPixDeleteKeyById(t *testing.T) { } func TestPixGetTransactionById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPixTransaction() + accessToken := getEnvValue(EnvAccessToken) pixTransactionId := getEnvValue(EnvPixTransactionId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() @@ -112,9 +101,8 @@ func TestPixGetTransactionById(t *testing.T) { } func TestPixGetKeyById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPixKey() + accessToken := getEnvValue(EnvAccessToken) pixKeyId := getEnvValue(EnvPixKeyId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() @@ -124,9 +112,8 @@ func TestPixGetKeyById(t *testing.T) { } func TestPixGetAllTransactions(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPixTransaction() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPix := NewPix(EnvSandbox, accessToken) @@ -141,17 +128,16 @@ func TestPixGetAllTransactions(t *testing.T) { } func TestPixGetAllKeys(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initPixKey() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nPix := NewPix(EnvSandbox, accessToken) - resp, errAsaas := nPix.GetAllKeys(ctx, GetAllPixKeysRequest{ + resp, err := nPix.GetAllKeys(ctx, GetAllPixKeysRequest{ Status: "", StatusList: "", Offset: 0, Limit: 10, }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } diff --git a/asaas/request.go b/asaas/request.go index 0290a36..c40d7d3 100644 --- a/asaas/request.go +++ b/asaas/request.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "encoding/json" - "errors" "fmt" "github.com/GabrielHCataldo/go-asaas/internal/util" "io" @@ -174,24 +173,15 @@ func (r request[T]) createHttpRequestMultipartForm( } func (r request[T]) closeBody(Body io.ReadCloser) { - err := Body.Close() - if err != nil { - logError("error close read body:", err) - } + _ = Body.Close() } func (r request[T]) closeWriter(writer *multipart.Writer) { - err := writer.Close() - if err != nil { - logError("error close writer:", err) - } + _ = writer.Close() } func (r request[T]) closeCloser(c io.Closer) { - err := c.Close() - if err != nil { - logError("error close reader closer:", err) - } + _ = c.Close() } func (r request[T]) readResponse(res *http.Response, result *T) error { @@ -202,12 +192,14 @@ func (r request[T]) readResponse(res *http.Response, result *T) error { logInfoSkipCaller(6, r.env, "response status:", res.StatusCode, "body:", string(respBody)) if len(respBody) == 0 { return nil - } else if x, ok := any(*result).(FileTextPlainResponse); ok { + } else if x, ok := any(*result).(FileTextPlainResponse); ok && res.StatusCode == http.StatusOK { x.Data = string(respBody) *result = any(x).(T) return nil + } else if util.IsJson(respBody) { + return json.Unmarshal(respBody, result) } - return json.Unmarshal(respBody, result) + return nil } func (r request[T]) prepareMultipartPayload(payload any) (map[string][]io.Reader, error) { @@ -222,14 +214,9 @@ func (r request[T]) prepareMultipartPayload(payload any) (map[string][]io.Reader } k := util.GetJsonFieldNameByReflect(ft) vf := util.GetValueByReflect(fd) - if util.IsBlank(&k) || vf == nil { - continue - } var b bool var s string var in int - var in32 int32 - var in64 int64 var f *os.File var fs []*os.File var ok bool @@ -239,21 +226,18 @@ func (r request[T]) prepareMultipartPayload(payload any) (map[string][]io.Reader multipartPayload[k] = []io.Reader{strings.NewReader(s)} } else if in, ok = vf.(int); ok { multipartPayload[k] = []io.Reader{strings.NewReader(strconv.Itoa(in))} - } else if in32, ok = vf.(int32); ok { - multipartPayload[k] = []io.Reader{strings.NewReader(strconv.Itoa(int(in32)))} - } else if in64, ok = vf.(int64); ok { - multipartPayload[k] = []io.Reader{strings.NewReader(strconv.Itoa(int(in64)))} } else if f, ok = vf.(*os.File); ok && f != nil { multipartPayload[k] = []io.Reader{f} } else if fs, ok = vf.([]*os.File); ok && fs != nil { var files []io.Reader for _, file := range fs { - if file == nil { - continue + if file != nil { + files = append(files, file) } - files = append(files, file) } multipartPayload[k] = files + } else if vf != nil { + multipartPayload[k] = []io.Reader{strings.NewReader(fmt.Sprintf(`%s`, vf))} } } return multipartPayload, nil @@ -281,9 +265,7 @@ func (r request[T]) prepareResponseUnexpected(res *http.Response) (*T, error) { var respBody T rv := reflect.ValueOf(&respBody) fv := rv.Elem().FieldByName("Errors") - if rv.Kind() == reflect.Struct && fv.Kind() != reflect.Slice { - return nil, errors.New("poorly formatted response structure, does not contain the errors field") - } else if fv.Kind() == reflect.Slice { + if fv.Kind() == reflect.Slice { fv.Set(reflect.MakeSlice(fv.Type(), 1, 1)) fv.Index(0).Set(reflect.ValueOf(ErrorResponse{ Code: res.Status, diff --git a/asaas/response.go b/asaas/response.go index d070aa7..e2e3a12 100644 --- a/asaas/response.go +++ b/asaas/response.go @@ -8,6 +8,12 @@ type DeleteResponse struct { Errors []ErrorResponse `json:"errors,omitempty"` } +type DeleteNumericResponse struct { + Id int `json:"id,omitempty"` + Deleted bool `json:"deleted,omitempty"` + Errors []ErrorResponse `json:"errors,omitempty"` +} + type response interface { IsSuccess() bool IsFailure() bool @@ -557,6 +563,18 @@ func (d DeleteResponse) IsNoContent() bool { return len(d.Errors) == 0 && util.IsBlank(&d.Id) } +func (d DeleteNumericResponse) IsSuccess() bool { + return len(d.Errors) == 0 && d.Deleted && d.Id > 0 +} + +func (d DeleteNumericResponse) IsFailure() bool { + return !d.IsSuccess() +} + +func (d DeleteNumericResponse) IsNoContent() bool { + return len(d.Errors) == 0 && d.Id == 0 +} + func (c ChargeDocumentResponse) IsSuccess() bool { return len(c.Errors) == 0 && util.IsNotBlank(&c.Id) && c.File != nil } @@ -606,7 +624,7 @@ func (c ChargeCreationLimitResponse) IsNoContent() bool { } func (c ChargeStatusResponse) IsSuccess() bool { - return len(c.Errors) == 0 && c.Status.IsEnumValid() + return len(c.Errors) == 0 && c.Status != "" } func (c ChargeStatusResponse) IsFailure() bool { @@ -614,7 +632,7 @@ func (c ChargeStatusResponse) IsFailure() bool { } func (c ChargeStatusResponse) IsNoContent() bool { - return len(c.Errors) == 0 && !c.Status.IsEnumValid() + return len(c.Errors) == 0 && c.Status == "" } func (c CreditCardTokenizeResponse) IsSuccess() bool { diff --git a/asaas/split.go b/asaas/split.go index 44eb3a3..0c6911b 100644 --- a/asaas/split.go +++ b/asaas/split.go @@ -11,6 +11,11 @@ type SplitRequest struct { TotalFixedValue float64 `json:"totalFixedValue,omitempty"` } +type UpdateSplitsRequest struct { + // Dados de split para atualizar (REQUIRED) + Splits []SplitRequest `json:"splits,omitempty"` +} + type SplitResponse struct { Id string `json:"id,omitempty"` WalletId string `json:"walletId,omitempty"` diff --git a/asaas/subaccount.go b/asaas/subaccount.go index 4947f82..142234e 100644 --- a/asaas/subaccount.go +++ b/asaas/subaccount.go @@ -72,7 +72,7 @@ type CreateSubaccountWebhookRequest struct { Type WebhookType `json:"type,omitempty"` } -type SubaccountSendDocumentRequest struct { +type SendWhiteLabelDocumentRequest struct { // Tipo de documento (REQUIRED) Type SubaccountDocumentType `json:"type,omitempty"` // Arquivo (REQUIRED) @@ -233,7 +233,7 @@ type Subaccount interface { // # DOCS // // Enviar documentos via API: https://docs.asaas.com/reference/enviar-documentos-via-api - SendWhiteLabelDocument(ctx context.Context, subaccountId string, body SubaccountSendDocumentRequest) ( + SendWhiteLabelDocument(ctx context.Context, documentId string, body SendWhiteLabelDocumentRequest) ( *SubaccountDocumentSentResponse, error) // UpdateWhiteLabelDocumentSentById (Atualizar documento enviado) // @@ -545,10 +545,10 @@ func (s subaccount) Create(ctx context.Context, body CreateSubaccountRequest) (* return req.make(http.MethodPost, "/v3/accounts", body) } -func (s subaccount) SendWhiteLabelDocument(ctx context.Context, subaccountId string, body SubaccountSendDocumentRequest) ( +func (s subaccount) SendWhiteLabelDocument(ctx context.Context, documentId string, body SendWhiteLabelDocumentRequest) ( *SubaccountDocumentSentResponse, error) { req := NewRequest[SubaccountDocumentSentResponse](ctx, s.env, s.accessToken) - return req.makeMultipartForm(http.MethodPost, fmt.Sprintf("/v3/myAccount/documents/%s", subaccountId), body) + return req.makeMultipartForm(http.MethodPost, fmt.Sprintf("/v3/myAccount/documents/%s", documentId), body) } func (s subaccount) UpdateWhiteLabelDocumentSentById( diff --git a/asaas/subaccount_test.go b/asaas/subaccount_test.go index 4153823..9228a74 100644 --- a/asaas/subaccount_test.go +++ b/asaas/subaccount_test.go @@ -2,7 +2,7 @@ package asaas import ( "context" - "github.com/mvrilo/go-cpf" + "github.com/GabrielHCataldo/go-asaas/internal/util" "os" "testing" "time" @@ -10,19 +10,18 @@ import ( func TestSubaccountCreate(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubaccount := NewSubaccount(EnvSandbox, accessToken) resp, err := nSubaccount.Create(ctx, CreateSubaccountRequest{ Name: "Unit test go", - Email: "unittestgo@gmail.com", + Email: util.GenerateEmail(), LoginEmail: "", - CpfCnpj: cpf.Generate(), - BirthDate: NewDate(1999, 1, 21, time.Local), - CompanyType: "", + CpfCnpj: "81452811000125", + BirthDate: NewDate(1999, 6, 12, time.Local), + CompanyType: CompanyTypeLimited, Phone: "", - MobilePhone: "47997576131", + MobilePhone: util.GenerateMobilePhone(), Site: "", Address: "Rua Maria de Souza Maba", AddressNumber: "123", @@ -35,57 +34,50 @@ func TestSubaccountCreate(t *testing.T) { } func TestSubaccountSendWhiteLabelDocument(t *testing.T) { + initSubaccountDocument() accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) - initSubaccount() - subaccountId := getEnvValue(EnvSubaccountId) - assertFatalStringBlank(t, subaccountId) - f, err := os.Open(getEnvValue(EnvFileName)) - assertFatalErrorNonnull(t, err) + subaccountDocumentId := getEnvValue(EnvSubaccountDocumentId) + subaccountDocumentType := getEnvValue(EnvSubaccountDocumentType) + f, _ := os.Open(getEnvValue(EnvImageName)) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubaccount := NewSubaccount(EnvSandbox, accessToken) - resp, err := nSubaccount.SendWhiteLabelDocument(ctx, subaccountId, SubaccountSendDocumentRequest{ - Type: SubaccountDocumentTypeCustom, + resp, err := nSubaccount.SendWhiteLabelDocument(ctx, subaccountDocumentId, SendWhiteLabelDocumentRequest{ + Type: SubaccountDocumentType(subaccountDocumentType), DocumentFile: f, }) assertResponseSuccess(t, resp, err) } func TestSubaccountUpdateWhiteLabelDocumentSentById(t *testing.T) { - accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) initSubaccount() - subaccountId := getEnvValue(EnvSubaccountId) - assertFatalStringBlank(t, subaccountId) - f, err := os.Open(getEnvValue(EnvFileName)) - assertFatalErrorNonnull(t, err) + accessToken := getEnvValue(EnvAccessTokenSecondary) + subaccountDocumentSentId := getEnvValue(EnvSubaccountDocumentSentId) + f, _ := os.Open(getEnvValue(EnvFileName)) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubaccount := NewSubaccount(EnvSandbox, accessToken) - resp, err := nSubaccount.UpdateWhiteLabelDocumentSentById(ctx, subaccountId, UpdateWhiteLabelDocumentSentRequest{ - DocumentFile: f, - }) + resp, err := nSubaccount.UpdateWhiteLabelDocumentSentById(ctx, subaccountDocumentSentId, + UpdateWhiteLabelDocumentSentRequest{ + DocumentFile: f, + }) assertResponseSuccess(t, resp, err) } func TestSubaccountDeleteWhiteLabelDocumentSentById(t *testing.T) { + initSubaccountDocumentSent() accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) - initSubaccountDocument() - subaccountDocumentSendId := getEnvValue(EnvSubaccountDocumentSentId) - assertFatalStringBlank(t, subaccountDocumentSendId) + subaccountDocumentSentId := getEnvValue(EnvSubaccountDocumentSentId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubaccount := NewSubaccount(EnvSandbox, accessToken) - resp, err := nSubaccount.DeleteWhiteLabelDocumentSentById(ctx, subaccountDocumentSendId) + resp, err := nSubaccount.DeleteWhiteLabelDocumentSentById(ctx, subaccountDocumentSentId) assertResponseSuccess(t, resp, err) } func TestSubaccountGetById(t *testing.T) { - accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) initSubaccount() + accessToken := getEnvValue(EnvAccessTokenSecondary) subaccountId := getEnvValue(EnvSubaccountId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() @@ -95,25 +87,23 @@ func TestSubaccountGetById(t *testing.T) { } func TestSubaccountGetDocumentSentById(t *testing.T) { + initSubaccountDocumentSent() accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) - initSubaccountDocument() - subaccountDocumentSendId := getEnvValue(EnvSubaccountDocumentSentId) + subaccountDocumentSentId := getEnvValue(EnvSubaccountDocumentSentId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubaccount := NewSubaccount(EnvSandbox, accessToken) - resp, err := nSubaccount.GetDocumentSentById(ctx, subaccountDocumentSendId) + resp, err := nSubaccount.GetDocumentSentById(ctx, subaccountDocumentSentId) assertResponseSuccess(t, resp, err) } func TestSubaccountGetAll(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initSubaccount() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubaccount := NewSubaccount(EnvSandbox, accessToken) - resp, errAsaas := nSubaccount.GetAll(ctx, GetAllSubaccountsRequest{ + resp, err := nSubaccount.GetAll(ctx, GetAllSubaccountsRequest{ CpfCnpj: "", Email: "", Name: "", @@ -121,13 +111,12 @@ func TestSubaccountGetAll(t *testing.T) { Offset: 0, Limit: 10, }) - assertResponseSuccess(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } func TestSubaccountGetPendingDocuments(t *testing.T) { + initSubaccountDocumentSent() accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) - initSubaccountDocument() ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubaccount := NewSubaccount(EnvSandbox, accessToken) diff --git a/asaas/subscription_test.go b/asaas/subscription_test.go index 83830db..a239764 100644 --- a/asaas/subscription_test.go +++ b/asaas/subscription_test.go @@ -7,14 +7,12 @@ import ( ) func TestSubscriptionCreate(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initCustomer() + accessToken := getEnvValue(EnvAccessToken) customerId := getEnvValue(EnvCustomerId) - assertFatalStringBlank(t, customerId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() - now := time.Now() + now := DateNow() nSubscription := NewSubscription(EnvSandbox, accessToken) resp, err := nSubscription.Create(ctx, CreateSubscriptionRequest{ Customer: customerId, @@ -39,11 +37,9 @@ func TestSubscriptionCreate(t *testing.T) { } func TestSubscriptionCreateInvoiceSettingById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initSubscription() + accessToken := getEnvValue(EnvAccessToken) subscriptionId := getEnvValue(EnvSubscriptionId) - assertFatalStringBlank(t, subscriptionId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubscription := NewSubscription(EnvSandbox, accessToken) @@ -63,11 +59,9 @@ func TestSubscriptionCreateInvoiceSettingById(t *testing.T) { } func TestSubscriptionUpdateById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initSubscription() + accessToken := getEnvValue(EnvAccessToken) subscriptionId := getEnvValue(EnvSubscriptionId) - assertFatalStringBlank(t, subscriptionId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubscription := NewSubscription(EnvSandbox, accessToken) @@ -89,11 +83,9 @@ func TestSubscriptionUpdateById(t *testing.T) { } func TestSubscriptionUpdateInvoiceSettingsById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initSubscriptionInvoiceSetting() + accessToken := getEnvValue(EnvAccessToken) subscriptionId := getEnvValue(EnvSubscriptionId) - assertFatalStringBlank(t, subscriptionId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubscription := NewSubscription(EnvSandbox, accessToken) @@ -103,17 +95,15 @@ func TestSubscriptionUpdateInvoiceSettingsById(t *testing.T) { ReceivedOnly: nil, DaysBeforeDueDate: nil, Observations: nil, - Taxes: nil, + Taxes: InvoiceTaxesRequest{}, }) assertResponseSuccess(t, resp, err) } func TestSubscriptionDeleteById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initSubscription() + accessToken := getEnvValue(EnvAccessToken) subscriptionId := getEnvValue(EnvSubscriptionId) - assertFatalStringBlank(t, subscriptionId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubscription := NewSubscription(EnvSandbox, accessToken) @@ -121,12 +111,10 @@ func TestSubscriptionDeleteById(t *testing.T) { assertResponseSuccess(t, resp, err) } -func TestSubscription_DeleteInvoiceSettingById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) +func TestSubscriptionDeleteInvoiceSettingById(t *testing.T) { initSubscriptionInvoiceSetting() + accessToken := getEnvValue(EnvAccessToken) subscriptionId := getEnvValue(EnvSubscriptionId) - assertFatalStringBlank(t, subscriptionId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubscription := NewSubscription(EnvSandbox, accessToken) @@ -135,9 +123,8 @@ func TestSubscription_DeleteInvoiceSettingById(t *testing.T) { } func TestSubscriptionGetById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initSubscription() + accessToken := getEnvValue(EnvAccessToken) subscriptionId := getEnvValue(EnvSubscriptionId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() @@ -147,9 +134,8 @@ func TestSubscriptionGetById(t *testing.T) { } func TestSubscriptionGetInvoiceSettingById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initSubscriptionInvoiceSetting() + accessToken := getEnvValue(EnvAccessToken) subscriptionId := getEnvValue(EnvSubscriptionId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() @@ -159,14 +145,12 @@ func TestSubscriptionGetInvoiceSettingById(t *testing.T) { } func TestSubscriptionGetPaymentBookById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initSubscription() + accessToken := getEnvValue(EnvAccessToken) subscriptionId := getEnvValue(EnvSubscriptionId) - assertFatalStringBlank(t, subscriptionId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() - now := time.Now() + now := DateNow() nSubscription := NewSubscription(EnvSandbox, accessToken) resp, err := nSubscription.GetPaymentBookById(ctx, subscriptionId, SubscriptionPaymentBookRequest{ Month: int(now.Month()), @@ -174,13 +158,12 @@ func TestSubscriptionGetPaymentBookById(t *testing.T) { Sort: "", Order: "", }) - assertResponseSuccess(t, resp, err) + assertResponseFailure(t, resp, err) } func TestSubscriptionGetAll(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initSubscription() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubscription := NewSubscription(EnvSandbox, accessToken) @@ -201,11 +184,9 @@ func TestSubscriptionGetAll(t *testing.T) { } func TestSubscriptionGetAllChargesBySubscription(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initSubscription() + accessToken := getEnvValue(EnvAccessToken) subscriptionId := getEnvValue(EnvSubscriptionId) - assertFatalStringBlank(t, subscriptionId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubscription := NewSubscription(EnvSandbox, accessToken) @@ -216,11 +197,9 @@ func TestSubscriptionGetAllChargesBySubscription(t *testing.T) { } func TestSubscriptionGetAllInvoicesBySubscription(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initSubscription() + accessToken := getEnvValue(EnvAccessToken) subscriptionId := getEnvValue(EnvSubscriptionId) - assertFatalStringBlank(t, subscriptionId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nSubscription := NewSubscription(EnvSandbox, accessToken) @@ -233,5 +212,5 @@ func TestSubscriptionGetAllInvoicesBySubscription(t *testing.T) { Offset: 0, Limit: 10, }) - assertResponseSuccess(t, resp, err) + assertResponseNoContent(t, resp, err) } diff --git a/asaas/transfer_test.go b/asaas/transfer_test.go index 613fa04..75bcac5 100644 --- a/asaas/transfer_test.go +++ b/asaas/transfer_test.go @@ -9,7 +9,6 @@ import ( func TestTransferTransferToBank(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nTransfer := NewTransfer(EnvSandbox, accessToken) @@ -40,9 +39,7 @@ func TestTransferTransferToBank(t *testing.T) { func TestTransferTransferToAsaas(t *testing.T) { accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) walletId := getEnvValue(EnvWalletIdSecondary) - assertFatalStringBlank(t, walletId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nTransfer := NewTransfer(EnvSandbox, accessToken) @@ -54,11 +51,9 @@ func TestTransferTransferToAsaas(t *testing.T) { } func TestTransferCancelById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initTransfer() + accessToken := getEnvValue(EnvAccessToken) transferId := getEnvValue(EnvTransferId) - assertFatalStringBlank(t, transferId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nTransfer := NewTransfer(EnvSandbox, accessToken) @@ -67,9 +62,8 @@ func TestTransferCancelById(t *testing.T) { } func TestTransferGetById(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initTransfer() + accessToken := getEnvValue(EnvAccessToken) transferId := getEnvValue(EnvTransferId) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() @@ -79,9 +73,8 @@ func TestTransferGetById(t *testing.T) { } func TestTransferGetAll(t *testing.T) { - accessToken := getEnvValue(EnvAccessToken) - assertFatalStringBlank(t, accessToken) initTransfer() + accessToken := getEnvValue(EnvAccessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nTransfer := NewTransfer(EnvSandbox, accessToken) diff --git a/asaas/validator.go b/asaas/validator.go deleted file mode 100644 index 94fb2e2..0000000 --- a/asaas/validator.go +++ /dev/null @@ -1,154 +0,0 @@ -package asaas - -import ( - berrors "errors" - "github.com/GabrielHCataldo/go-asaas/internal/util" - "github.com/go-playground/validator/v10" - "log" - "reflect" - "time" -) - -var vld *validator.Validate - -func Validate() *validator.Validate { - if vld != nil { - return vld - } - vld = validator.New() - err := vld.RegisterValidation("enum", validateEnum) - if err != nil { - log.Fatal(err) - } - err = vld.RegisterValidation("phone", validatePhone) - if err != nil { - log.Fatal(err) - } - err = vld.RegisterValidation("full_name", validateFullName) - if err != nil { - log.Fatal(err) - } - err = vld.RegisterValidation("before_now", validateBeforeNow) - if err != nil { - log.Fatal(err) - } - err = vld.RegisterValidation("after_now", validateAfterNow) - if err != nil { - log.Fatal(err) - } - err = vld.RegisterValidation("document", validateDocument) - if err != nil { - log.Fatal(err) - } - err = vld.RegisterValidation("postal_code", validatePostalCode) - if err != nil { - log.Fatal(err) - } - err = vld.RegisterValidation("state", validateState) - if err != nil { - log.Fatal(err) - } - err = vld.RegisterValidation("color", validateColor) - if err != nil { - log.Fatal(err) - } - return vld -} - -func validatePhone(fl validator.FieldLevel) bool { - return util.IsPhoneNumber(fl.Field().String()) -} - -func validateFullName(fl validator.FieldLevel) bool { - return util.ValidateFullName(fl.Field().String()) -} - -func validateBeforeNow(fl validator.FieldLevel) bool { - var timeValidate time.Time - if fl.Field().Kind() == reflect.String { - t, err := time.Parse(time.RFC3339, fl.Field().String()) - if err != nil { - return false - } - timeValidate = t - } else if fl.Field().Type().String() == "asaas.Date" { - date, ok := fl.Field().Interface().(Date) - if !ok { - return false - } - timeValidate = time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, date.Location()) - } else { - datetime, ok := fl.Field().Interface().(time.Time) - if !ok { - return false - } - timeValidate = datetime - } - return timeValidate.UTC().Before(time.Now().UTC()) -} - -func validateAfterNow(fl validator.FieldLevel) bool { - var timeValidate time.Time - if fl.Field().Kind() == reflect.String { - t, err := time.Parse(time.RFC3339, fl.Field().String()) - if err != nil { - return false - } - timeValidate = t - } else if fl.Field().Type().String() == "asaas.Date" { - date, ok := fl.Field().Interface().(Date) - if !ok { - return false - } - timeValidate = time.Date(date.Year(), date.Month(), date.Day(), 23, 59, 0, 0, date.Location()) - } else { - datetime, ok := fl.Field().Interface().(time.Time) - if !ok { - return false - } - timeValidate = datetime - } - return timeValidate.UTC().After(time.Now().UTC()) -} - -func validateDocument(fl validator.FieldLevel) bool { - return util.IsCpfCnpj(fl.Field().String()) -} - -func validatePostalCode(fl validator.FieldLevel) bool { - return util.ValidatePostalCode(fl.Field().String()) -} - -func validateState(fl validator.FieldLevel) bool { - return util.ValidateState(fl.Field().String()) -} - -func validateEnum(fl validator.FieldLevel) bool { - value := fl.Field().Interface().(BaseEnum) - return value.IsEnumValid() -} - -func validateColor(fl validator.FieldLevel) bool { - return util.ValidateColorHex(fl.Field().String()) -} - -func validateBillingBody( - billingType BillingType, - cCard *CreditCardRequest, - cCardHolderInfoBody *CreditCardHolderInfoRequest, - cCardToken, - remoteIp string, -) error { - switch billingType { - case BillingTypeCreditCard: - if util.IsBlank(&cCardToken) && (cCard == nil || cCardHolderInfoBody == nil) { - return berrors.New("charge by credit card, enter the credit card or credit card token") - } else if cCard != nil && !util.ValidateExpirationCreditCard(cCard.ExpiryYear, cCard.ExpiryMonth) { - return berrors.New("expired card") - } else if util.IsBlank(&remoteIp) && !util.ValidateIp(remoteIp) { - return berrors.New("invalid remoteIp") - } - break - } - return nil -} diff --git a/asaas/webhook.go b/asaas/webhook.go index 8620557..de8c0fa 100644 --- a/asaas/webhook.go +++ b/asaas/webhook.go @@ -21,13 +21,13 @@ type SaveWebhookSettingRequest struct { } type WebhookResponse struct { - Type WebhookType `json:"type,omitempty"` Url string `json:"url,omitempty"` Email string `json:"email,omitempty"` - ApiVersion string `json:"apiVersion,omitempty"` + ApiVersion int `json:"apiVersion,omitempty"` Enabled bool `json:"enabled,omitempty"` Interrupted bool `json:"interrupted,omitempty"` AuthToken string `json:"authToken,omitempty"` + Type WebhookType `json:"type,omitempty"` Errors []ErrorResponse `json:"errors,omitempty"` } diff --git a/asaas/webhook_test.go b/asaas/webhook_test.go index 28b9513..1a89065 100644 --- a/asaas/webhook_test.go +++ b/asaas/webhook_test.go @@ -8,11 +8,10 @@ import ( func TestWebhookSaveSetting(t *testing.T) { accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nWebhook := NewWebhook(EnvSandbox, accessToken) - resp, errAsaas := nWebhook.SaveSetting(ctx, WebhookTypePayment, SaveWebhookSettingRequest{ + resp, err := nWebhook.SaveSetting(ctx, WebhookTypePayment, SaveWebhookSettingRequest{ Url: "https://test.com", Email: "test@gmail.com", ApiVersion: "3", @@ -20,16 +19,15 @@ func TestWebhookSaveSetting(t *testing.T) { Interrupted: Pointer(false), AuthToken: "", }) - assertResponseNoContent(t, resp, errAsaas) + assertResponseSuccess(t, resp, err) } func TestWebhookGetSetting(t *testing.T) { - accessToken := getEnvValue(EnvAccessTokenSecondary) - assertFatalStringBlank(t, accessToken) initWebhook() + accessToken := getEnvValue(EnvAccessTokenSecondary) ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second) defer cancel() nWebhook := NewWebhook(EnvSandbox, accessToken) - resp, errAsaas := nWebhook.GetSetting(ctx, WebhookTypePayment) - assertResponseNoContent(t, resp, errAsaas) + resp, err := nWebhook.GetSetting(ctx, WebhookTypePayment) + assertResponseSuccess(t, resp, err) } diff --git a/internal/resource/brazil-states.json b/internal/resource/brazil-states.json deleted file mode 100644 index 6ea413e..0000000 --- a/internal/resource/brazil-states.json +++ /dev/null @@ -1,110 +0,0 @@ -[ - { - "abbreviation": "AC", - "name": "Acre" - }, - { - "abbreviation": "AL", - "name": "Alagoas" - }, - { - "abbreviation": "AP", - "name": "Amapá" - }, - { - "abbreviation": "AM", - "name": "Amazonas" - }, - { - "abbreviation": "BA", - "name": "Bahia" - }, - { - "abbreviation": "CE", - "name": "Ceará" - }, - { - "abbreviation": "DF", - "name": "Distrito Federal" - }, - { - "abbreviation": "GO", - "name": "Goiás" - }, - { - "abbreviation": "ES", - "name": "Espirito Santo" - }, - { - "abbreviation": "MA", - "name": "Maranhão" - }, - { - "abbreviation": "MT", - "name": "Mato Grosso" - }, - { - "abbreviation": "MS", - "name": "Mato Grosso do Sul" - }, - { - "abbreviation": "MG", - "name": "Minas Gerais" - }, - { - "abbreviation": "PA", - "name": "Pará" - }, - { - "abbreviation": "PB", - "name": "Paraíba" - }, - { - "abbreviation": "PR", - "name": "Paraná" - }, - { - "abbreviation": "PE", - "name": "Pernambuco" - }, - { - "abbreviation": "PI", - "name": "Piauí" - }, - { - "abbreviation": "RJ", - "name": "Rio de Janeiro" - }, - { - "abbreviation": "RN", - "name": "Rio Grande do Norte" - }, - { - "abbreviation": "RS", - "name": "Rio Grande do Sul" - }, - { - "abbreviation": "RO", - "name": "Rondônia" - }, - { - "abbreviation": "RR", - "name": "Roraima" - }, - { - "abbreviation": "SP", - "name": "São Paulo" - }, - { - "abbreviation": "SC", - "name": "Santa Catarina" - }, - { - "abbreviation": "SE", - "name": "Sergipe" - }, - { - "abbreviation": "TO", - "name": "Tocantins" - } -] \ No newline at end of file diff --git a/internal/util/util.go b/internal/util/util.go index 604f099..9334164 100644 --- a/internal/util/util.go +++ b/internal/util/util.go @@ -2,8 +2,6 @@ package util import ( "encoding/json" - "github.com/klassmann/cpfcnpj" - "github.com/nyaruka/phonenumbers" "os" "path" "reflect" @@ -14,68 +12,6 @@ import ( "time" ) -func GetFileJson(uriFile string, dest any) error { - bytes, err := os.ReadFile(uriFile) - if err != nil { - return err - } - return json.Unmarshal(bytes, dest) -} - -func IsPhoneNumber(value string) bool { - num, err := phonenumbers.Parse(value, "BR") - if err == nil { - return phonenumbers.IsValidNumber(num) - } - return false -} - -func IsCpfCnpj(value string) bool { - return cpfcnpj.ValidateCPF(cpfcnpj.Clean(value)) || cpfcnpj.ValidateCNPJ(cpfcnpj.Clean(value)) -} - -func ValidateFullName(value string) bool { - regex := regexp.MustCompile(`^([a-zA-Z]{2,}\s[a-zA-Z]+'?-?[a-zA-Z]+\s?([a-zA-Z]+)?)`) - return regex.MatchString(value) -} - -func ValidatePostalCode(v string) bool { - regex := regexp.MustCompile(`^\d{5}-\d{3}?$`) - return regex.MatchString(v) -} - -func ValidateIp(v string) bool { - regex := regexp.MustCompile(`\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b`) - return regex.MatchString(v) -} - -func ValidateExpirationCreditCard(expiryYear, expiryMonth string) bool { - exp, err := time.Parse("2006-01-02", expiryYear+"-"+expiryMonth+"-01") - if err != nil || time.Now().UTC().After(exp.UTC()) { - return false - } - return true -} - -func ValidateState(v string) bool { - var brazilStates []map[string]string - err := GetFileJson("resource/brazil-states.json", &brazilStates) - if err == nil { - return true - } - for _, state := range brazilStates { - if state["abbreviation"] == v { - return true - } - } - return false -} - -func ValidateColorHex(v string) bool { - r := regexp.MustCompile(`^#(?:[0-9a-fA-F]{3}){1,2}$`) - return r.MatchString(v) -} - func IsBlank(value *string) bool { return value == nil || len(strings.TrimSpace(*value)) == 0 } @@ -125,3 +61,18 @@ func GetJsonFieldNameByReflect(f reflect.StructField) string { } return "" } + +func GenerateEmail() string { + randomNumber := strconv.Itoa(int(time.Now().UnixNano())) + return "unit" + randomNumber + "@gmail.com" +} + +func GenerateMobilePhone() string { + randomNumber := strconv.Itoa(int(time.Now().UnixNano())) + return "4799" + randomNumber[len(randomNumber)-7:] +} + +func IsJson(v []byte) bool { + var data map[string]any + return json.Unmarshal(v, &data) == nil +}