Skip to content

Send and receive SMS messages using your Android phone programmatically via a simple HTTP API

Add the frontend

Acho Arnoldade3a3d64d03
diff --git a/api/docs/docs.go b/api/docs/docs.go
index f0a3cc7d..d5a3831f 100644
--- a/api/docs/docs.go
+++ b/api/docs/docs.go
@@ -2380,7 +2380,18 @@ const docTemplate = `{
"tags": [
"Users"
],
- "summary": "Generate a subscription invoice",
+ "summary": "Generate a subscription payment invoice",
+ "parameters": [
+ {
+ "description": "Generate subscription payment invoice parameters",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/requests.UserPaymentInvoice"
+ }
+ }
+ ],
"responses": {
"200": {
"description": "OK",
@@ -3798,6 +3809,48 @@ const docTemplate = `{
}
}
},
+ "requests.UserPaymentInvoice": {
+ "type": "object",
+ "required": [
+ "address",
+ "city",
+ "country",
+ "name",
+ "notes",
+ "state",
+ "zip_code"
+ ],
+ "properties": {
+ "address": {
+ "type": "string",
+ "example": "221B Baker Street, London"
+ },
+ "city": {
+ "type": "string",
+ "example": "Los Angeles"
+ },
+ "country": {
+ "type": "string",
+ "example": "US"
+ },
+ "name": {
+ "type": "string",
+ "example": "Acme Corp"
+ },
+ "notes": {
+ "type": "string",
+ "example": "Thank you for your business!"
+ },
+ "state": {
+ "type": "string",
+ "example": "CA"
+ },
+ "zip_code": {
+ "type": "string",
+ "example": "9800"
+ }
+ }
+ },
"requests.UserUpdate": {
"type": "object",
"required": [
diff --git a/api/docs/swagger.json b/api/docs/swagger.json
index 88c252d1..8559c8ec 100644
--- a/api/docs/swagger.json
+++ b/api/docs/swagger.json
@@ -2156,7 +2156,18 @@
"consumes": ["application/json"],
"produces": ["application/pdf"],
"tags": ["Users"],
- "summary": "Generate a subscription invoice",
+ "summary": "Generate a subscription payment invoice",
+ "parameters": [
+ {
+ "description": "Generate subscription payment invoice parameters",
+ "name": "payload",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/requests.UserPaymentInvoice"
+ }
+ }
+ ],
"responses": {
"200": {
"description": "OK",
@@ -3477,6 +3488,48 @@
}
}
},
+ "requests.UserPaymentInvoice": {
+ "type": "object",
+ "required": [
+ "address",
+ "city",
+ "country",
+ "name",
+ "notes",
+ "state",
+ "zip_code"
+ ],
+ "properties": {
+ "address": {
+ "type": "string",
+ "example": "221B Baker Street, London"
+ },
+ "city": {
+ "type": "string",
+ "example": "Los Angeles"
+ },
+ "country": {
+ "type": "string",
+ "example": "US"
+ },
+ "name": {
+ "type": "string",
+ "example": "Acme Corp"
+ },
+ "notes": {
+ "type": "string",
+ "example": "Thank you for your business!"
+ },
+ "state": {
+ "type": "string",
+ "example": "CA"
+ },
+ "zip_code": {
+ "type": "string",
+ "example": "9800"
+ }
+ }
+ },
"requests.UserUpdate": {
"type": "object",
"required": ["active_phone_id", "timezone"],
diff --git a/api/docs/swagger.yaml b/api/docs/swagger.yaml
index 28274519..16811ab3 100644
--- a/api/docs/swagger.yaml
+++ b/api/docs/swagger.yaml
@@ -742,6 +742,38 @@ definitions:
- newsletter_enabled
- webhook_enabled
type: object
+ requests.UserPaymentInvoice:
+ properties:
+ address:
+ example: 221B Baker Street, London
+ type: string
+ city:
+ example: Los Angeles
+ type: string
+ country:
+ example: US
+ type: string
+ name:
+ example: Acme Corp
+ type: string
+ notes:
+ example: Thank you for your business!
+ type: string
+ state:
+ example: CA
+ type: string
+ zip_code:
+ example: "9800"
+ type: string
+ required:
+ - address
+ - city
+ - country
+ - name
+ - notes
+ - state
+ - zip_code
+ type: object
requests.UserUpdate:
properties:
active_phone_id:
@@ -2930,6 +2962,13 @@ paths:
description:
Generates a new invoice PDF file for the given subscription payment
with given parameters.
+ parameters:
+ - description: Generate subscription payment invoice parameters
+ in: body
+ name: payload
+ required: true
+ schema:
+ $ref: "#/definitions/requests.UserPaymentInvoice"
produces:
- application/pdf
responses:
@@ -2955,7 +2994,7 @@ paths:
$ref: "#/definitions/responses.InternalServerError"
security:
- ApiKeyAuth: []
- summary: Generate a subscription invoice
+ summary: Generate a subscription payment invoice
tags:
- Users
/users/subscription/payments:
diff --git a/api/pkg/di/container.go b/api/pkg/di/container.go
index 07bce2c3..d9a912f4 100644
--- a/api/pkg/di/container.go
+++ b/api/pkg/di/container.go
@@ -648,6 +648,7 @@ func (container *Container) UserHandlerValidator() (validator *validators.UserHa
return validators.NewUserHandlerValidator(
container.Logger(),
container.Tracer(),
+ container.UserService(),
)
}
@@ -934,6 +935,7 @@ func (container *Container) UserService() (service *services.UserService) {
container.LemonsqueezyClient(),
container.EventDispatcher(),
container.FirebaseAuthClient(),
+ container.HTTPClient("lemonsqueezy"),
)
}
diff --git a/api/pkg/handlers/billing_handler.go b/api/pkg/handlers/billing_handler.go
index bcdb5248..3d65ee9a 100644
--- a/api/pkg/handlers/billing_handler.go
+++ b/api/pkg/handlers/billing_handler.go
@@ -65,7 +65,7 @@ func (h *BillingHandler) UsageHistory(c *fiber.Ctx) error {
var request requests.BillingUsageHistory
if err := c.QueryParser(&request); err != nil {
- msg := fmt.Sprintf("cannot marshall params [%s] into %T", c.OriginalURL(), request)
+ msg := fmt.Sprintf("cannot marshall params [%s] into %T", c.Body(), request)
ctxLogger.Warn(stacktrace.Propagate(err, msg))
return h.responseBadRequest(c, err)
}
diff --git a/api/pkg/handlers/user_handler.go b/api/pkg/handlers/user_handler.go
index 574edf27..2d3895da 100644
--- a/api/pkg/handlers/user_handler.go
+++ b/api/pkg/handlers/user_handler.go
@@ -46,7 +46,7 @@ func (h *UserHandler) RegisterRoutes(router fiber.Router, middlewares ...fiber.H
router.Put("/v1/users/:userID/notifications", h.computeRoute(middlewares, h.UpdateNotifications)...)
router.Get("/v1/users/subscription-update-url", h.computeRoute(middlewares, h.subscriptionUpdateURL)...)
router.Delete("/v1/users/subscription", h.computeRoute(middlewares, h.cancelSubscription)...)
- router.Get("/v1/users/subscription/invoices", h.computeRoute(middlewares, h.subscriptionPayments)...)
+ router.Get("/v1/users/subscription/payments", h.computeRoute(middlewares, h.subscriptionPayments)...)
router.Post("/v1/users/subscription/invoices/:subscriptionInvoiceID", h.computeRoute(middlewares, h.subscriptionInvoice)...)
}
@@ -161,11 +161,9 @@ func (h *UserHandler) Delete(c *fiber.Ctx) error {
// @Failure 500 {object} responses.InternalServerError
// @Router /users/{userID}/notifications [put]
func (h *UserHandler) UpdateNotifications(c *fiber.Ctx) error {
- ctx, span := h.tracer.StartFromFiberCtx(c)
+ ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)
defer span.End()
- ctxLogger := h.tracer.CtxLogger(h.logger, span)
-
var request requests.UserNotificationUpdate
if err := c.BodyParser(&request); err != nil {
msg := fmt.Sprintf("cannot marshall params [%s] into %T", c.OriginalURL(), request)
@@ -303,12 +301,13 @@ func (h *UserHandler) subscriptionPayments(c *fiber.Ctx) error {
}
// subscriptionInvoice generates an invoice for a given subscription invoice ID
-// @Summary Generate a subscription invoice
+// @Summary Generate a subscription payment invoice
// @Description Generates a new invoice PDF file for the given subscription payment with given parameters.
// @Security ApiKeyAuth
// @Tags Users
// @Accept json
// @Produce application/pdf
+// @Param payload body requests.UserPaymentInvoice true "Generate subscription payment invoice parameters"
// @Success 200 {file} file
// @Failure 400 {object} responses.BadRequest
// @Failure 401 {object} responses.Unauthorized
@@ -319,17 +318,29 @@ func (h *UserHandler) subscriptionInvoice(c *fiber.Ctx) error {
ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)
defer span.End()
- invoiceID := c.Params("subscriptionInvoiceID")
+ var request requests.UserPaymentInvoice
+ if err := c.BodyParser(&request); err != nil {
+ msg := fmt.Sprintf("cannot marshall params [%s] into %T", c.Body(), request)
+ ctxLogger.Warn(stacktrace.Propagate(err, msg))
+ return h.responseBadRequest(c, err)
+ }
+
+ request.SubscriptionInvoiceID = c.Params("subscriptionInvoiceID")
+ if errors := h.validator.ValidatePaymentInvoice(ctx, h.userIDFomContext(c), request.Sanitize()); len(errors) != 0 {
+ msg := fmt.Sprintf("validation errors [%s], while validating subscription payment invoice request [%s]", spew.Sdump(errors), c.Body())
+ ctxLogger.Warn(stacktrace.NewError(msg))
+ return h.responseUnprocessableEntity(c, errors, "validation errors while generating payment invoice")
+ }
- data, err := h.service.GenerateReceipt(ctx, h.userIDFomContext(c))
+ data, err := h.service.GenerateReceipt(ctx, request.UserInvoiceGenerateParams(h.userIDFomContext(c)))
if err != nil {
- msg := fmt.Sprintf("cannot generate receipt for invoice ID [%s] and user [%s]", invoiceID, h.userFromContext(c))
+ msg := fmt.Sprintf("cannot generate receipt for invoice ID [%s] and user [%s]", request.SubscriptionInvoiceID, h.userFromContext(c))
ctxLogger.Error(stacktrace.Propagate(err, msg))
return h.responseInternalServerError(c)
}
c.Set(fiber.HeaderContentType, "application/pdf")
- c.Set(fiber.HeaderContentDisposition, fmt.Sprintf("attachment; filename=\"%s.pdf\"", invoiceID))
+ c.Set(fiber.HeaderContentDisposition, fmt.Sprintf("attachment; filename=\"httpsms.com - %s.pdf\"", request.SubscriptionInvoiceID))
return c.SendStream(data)
}
diff --git a/api/pkg/requests/user_payment_invoice_request.go b/api/pkg/requests/user_payment_invoice_request.go
new file mode 100644
index 00000000..4d196f4a
--- /dev/null
+++ b/api/pkg/requests/user_payment_invoice_request.go
@@ -0,0 +1,46 @@
+package requests
+
+import (
+ "github.com/NdoleStudio/httpsms/pkg/entities"
+ "github.com/NdoleStudio/httpsms/pkg/services"
+)
+
+// UserPaymentInvoice is the payload for generating a subscription payment invoice
+type UserPaymentInvoice struct {
+ request
+ Name string `json:"name" example:"Acme Corp"`
+ Address string `json:"address" example:"221B Baker Street, London"`
+ City string `json:"city" example:"Los Angeles"`
+ State string `json:"state" example:"CA"`
+ Country string `json:"country" example:"US"`
+ ZipCode string `json:"zip_code" example:"9800"`
+ Notes string `json:"notes" example:"Thank you for your business!"`
+ SubscriptionInvoiceID string `json:"subscriptionInvoiceID" swaggerignore:"true"` // used internally for validation
+}
+
+// Sanitize sets defaults to MessageReceive
+func (input *UserPaymentInvoice) Sanitize() UserPaymentInvoice {
+ input.Name = input.sanitizeAddress(input.Name)
+ input.Address = input.sanitizeAddress(input.Address)
+ input.City = input.sanitizeAddress(input.City)
+ input.State = input.sanitizeAddress(input.State)
+ input.Country = input.sanitizeAddress(input.Country)
+ input.ZipCode = input.sanitizeAddress(input.ZipCode)
+ input.Notes = input.sanitizeAddress(input.Notes)
+ return *input
+}
+
+// UserInvoiceGenerateParams converts UserPaymentInvoice to services.UserInvoiceGenerateParams
+func (input *UserPaymentInvoice) UserInvoiceGenerateParams(userID entities.UserID) *services.UserInvoiceGenerateParams {
+ return &services.UserInvoiceGenerateParams{
+ UserID: userID,
+ SubscriptionInvoiceID: input.SubscriptionInvoiceID,
+ Name: input.Name,
+ Address: input.Address,
+ City: input.City,
+ State: input.State,
+ Country: input.Country,
+ Notes: input.Notes,
+ ZipCode: input.ZipCode,
+ }
+}
diff --git a/api/pkg/services/user_service.go b/api/pkg/services/user_service.go
index 860e1a42..bd586eaa 100644
--- a/api/pkg/services/user_service.go
+++ b/api/pkg/services/user_service.go
@@ -4,12 +4,12 @@ import (
"context"
"fmt"
"io"
+ "net/http"
"time"
"firebase.google.com/go/auth"
- "github.com/NdoleStudio/httpsms/pkg/events"
-
"github.com/NdoleStudio/httpsms/pkg/emails"
+ "github.com/NdoleStudio/httpsms/pkg/events"
"github.com/NdoleStudio/lemonsqueezy-go"
"github.com/NdoleStudio/httpsms/pkg/repositories"
@@ -31,6 +31,7 @@ type UserService struct {
dispatcher *EventDispatcher
authClient *auth.Client
lemonsqueezyClient *lemonsqueezy.Client
+ httpClient *http.Client
}
// NewUserService creates a new UserService
@@ -43,6 +44,7 @@ func NewUserService(
lemonsqueezyClient *lemonsqueezy.Client,
dispatcher *EventDispatcher,
authClient *auth.Client,
+ httpClient *http.Client,
) (s *UserService) {
return &UserService{
logger: logger.WithService(fmt.Sprintf("%T", s)),
@@ -53,6 +55,7 @@ func NewUserService(
dispatcher: dispatcher,
authClient: authClient,
lemonsqueezyClient: lemonsqueezyClient,
+ httpClient: httpClient,
}
}
@@ -83,13 +86,48 @@ func (service *UserService) GetSubscriptionPayments(ctx context.Context, userID
return invoicesResponse.Data, nil
}
+// UserInvoiceGenerateParams are parameters for generating a subscription payment invoice
+type UserInvoiceGenerateParams struct {
+ UserID entities.UserID
+ SubscriptionInvoiceID string
+ Name string
+ Address string
+ City string
+ State string
+ Country string
+ ZipCode string
+ Notes string
+}
+
// GenerateReceipt generates a receipt for a subscription payment.
-func (service *UserService) GenerateReceipt(ctx context.Context, userID entities.UserID) (reader io.Reader, err error) {
+func (service *UserService) GenerateReceipt(ctx context.Context, params *UserInvoiceGenerateParams) (io.Reader, error) {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
- ctxLogger.Info(fmt.Sprintf("generating receipt for user [%s]", userID))
- return nil, nil
+ payload := map[string]string{
+ "name": params.Name,
+ "address": params.Address,
+ "city": params.City,
+ "state": params.State,
+ "country": params.Country,
+ "zip_code": params.ZipCode,
+ "notes": params.Notes,
+ }
+
+ invoice, _, err := service.lemonsqueezyClient.SubscriptionInvoices.Generate(ctx, params.SubscriptionInvoiceID, payload)
+ if err != nil {
+ msg := fmt.Sprintf("could not generate subscription payment invoice user with ID [%s] and subscription invoice ID [%s]", params.UserID, params.SubscriptionInvoiceID)
+ return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ response, err := service.httpClient.Get(invoice.Meta.Urls.DownloadInvoice)
+ if err != nil {
+ msg := fmt.Sprintf("could not download subscription payment invoice for user with ID [%s] and subscription invoice ID [%s]", params.UserID, params.SubscriptionInvoiceID)
+ return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ ctxLogger.Info(fmt.Sprintf("generated subscription payment invoice for user with ID [%s] and subscription invoice ID [%s]", params.UserID, params.SubscriptionInvoiceID))
+ return response.Body, nil
}
// Get fetches or creates an entities.User
diff --git a/api/pkg/validators/user_handler_validator.go b/api/pkg/validators/user_handler_validator.go
index 553a1cd8..4c05bd1b 100644
--- a/api/pkg/validators/user_handler_validator.go
+++ b/api/pkg/validators/user_handler_validator.go
@@ -5,26 +5,32 @@ import (
"fmt"
"net/url"
+ "github.com/NdoleStudio/httpsms/pkg/entities"
"github.com/NdoleStudio/httpsms/pkg/requests"
+ "github.com/NdoleStudio/httpsms/pkg/services"
"github.com/NdoleStudio/httpsms/pkg/telemetry"
+ "github.com/palantir/stacktrace"
"github.com/thedevsaddam/govalidator"
)
// UserHandlerValidator validates models used in handlers.UserHandler
type UserHandlerValidator struct {
validator
- logger telemetry.Logger
- tracer telemetry.Tracer
+ logger telemetry.Logger
+ tracer telemetry.Tracer
+ service *services.UserService
}
// NewUserHandlerValidator creates a new handlers.UserHandler validator
func NewUserHandlerValidator(
logger telemetry.Logger,
tracer telemetry.Tracer,
+ service *services.UserService,
) (v *UserHandlerValidator) {
return &UserHandlerValidator{
- logger: logger.WithService(fmt.Sprintf("%T", v)),
- tracer: tracer,
+ service: service,
+ logger: logger.WithService(fmt.Sprintf("%T", v)),
+ tracer: tracer,
}
}
@@ -41,3 +47,83 @@ func (validator *UserHandlerValidator) ValidateUpdate(_ context.Context, request
return v.ValidateStruct()
}
+
+// ValidatePaymentInvoice validates the requests.UserPaymentInvoice request
+func (validator *UserHandlerValidator) ValidatePaymentInvoice(ctx context.Context, userID entities.UserID, request requests.UserPaymentInvoice) url.Values {
+ ctx, span, ctxLogger := validator.tracer.StartWithLogger(ctx, validator.logger)
+ defer span.End()
+
+ rules := govalidator.MapData{
+ "name": []string{
+ "required",
+ "min:1",
+ "max:100",
+ },
+ "address": []string{
+ "required",
+ "min:1",
+ "max:200",
+ },
+ "city": []string{
+ "required",
+ "min:1",
+ "max:100",
+ },
+ "state": []string{
+ "min:1",
+ "max:100",
+ },
+ "country": []string{
+ "required",
+ "len:2",
+ },
+ "zip_code": []string{
+ "required",
+ "min:1",
+ "max:20",
+ },
+ "notes": []string{
+ "max:1000",
+ },
+ }
+ if request.Country == "CA" {
+ rules["state"] = []string{
+ "required",
+ "in:AB,BC,MB,NB,NL,NS,NT,NU,ON,PE,QC,SK,YT",
+ }
+ }
+
+ if request.Country == "US" {
+ rules["state"] = []string{
+ "required",
+ "in:AL,AK,AZ,AR,CA,CO,CT,DE,FL,GA,HI,ID,IL,IN,IA,KS,KY,LA,ME,MD,MA,MI,MN,MS,MO,MT,NE,NV,NH,NJ,NM,NY,NC,ND,OH,OK,OR,PA,RI,SC,SD,TN,TX,UT,VT,VA,WA,WV,WI,WY",
+ }
+ }
+
+ v := govalidator.New(govalidator.Options{
+ Data: &request,
+ Rules: rules,
+ })
+
+ validationErrors := v.ValidateStruct()
+ if len(validationErrors) > 0 {
+ return validationErrors
+ }
+
+ payments, err := validator.service.GetSubscriptionPayments(ctx, userID)
+ if err != nil {
+ msg := fmt.Sprintf("cannot get subscription payments for user with ID [%s]", userID)
+ ctxLogger.Error(validator.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg)))
+ validationErrors.Add("subscriptionInvoiceID", "failed to validate subscription payment invoice ID")
+ return validationErrors
+ }
+
+ for _, payment := range payments {
+ if payment.ID == request.SubscriptionInvoiceID {
+ return validationErrors
+ }
+ }
+
+ validationErrors.Add("subscriptionInvoiceID", "failed to validate the subscription payment invoice ID")
+ return validationErrors
+}
diff --git a/web/models/api.ts b/web/models/api.ts
index 99f15064..94feb0b0 100644
--- a/web/models/api.ts
+++ b/web/models/api.ts
@@ -427,6 +427,23 @@ export interface RequestsUserNotificationUpdate {
webhook_enabled: boolean
}
+export interface RequestsUserPaymentInvoice {
+ /** @example "221B Baker Street, London" */
+ address: string
+ /** @example "Los Angeles" */
+ city: string
+ /** @example "US" */
+ country: string
+ /** @example "Acme Corp" */
+ name: string
+ /** @example "Thank you for your business!" */
+ notes: string
+ /** @example "CA" */
+ state: string
+ /** @example "9800" */
+ zip_code: string
+}
+
export interface RequestsUserUpdate {
/** @example "32343a19-da5e-4b1b-a767-3298a73703cb" */
active_phone_id: string
@@ -609,14 +626,6 @@ export interface ResponsesUnprocessableEntity {
status: string
}
-export interface ResponsesUserInvoicesResponse {
- data: ResponsesSubscriptionInvoicesAPIResponse
- /** @example "Request handled successfully" */
- message: string
- /** @example "success" */
- status: string
-}
-
export interface ResponsesUserResponse {
data: EntitiesUser
/** @example "Request handled successfully" */
@@ -625,23 +634,7 @@ export interface ResponsesUserResponse {
status: string
}
-export interface ResponsesWebhookResponse {
- data: EntitiesWebhook
- /** @example "Request handled successfully" */
- message: string
- /** @example "success" */
- status: string
-}
-
-export interface ResponsesWebhooksResponse {
- data: EntitiesWebhook[]
- /** @example "Request handled successfully" */
- message: string
- /** @example "success" */
- status: string
-}
-
-export interface ResponsesSubscriptionInvoicesAPIResponse {
+export interface ResponsesUserSubscriptionPaymentsResponse {
data: {
attributes: {
billing_reason: string
@@ -671,10 +664,28 @@ export interface ResponsesSubscriptionInvoicesAPIResponse {
total_formatted: string
total_usd: number
updated_at: string
- user_email: string
- user_name: string
}
id: string
type: string
}[]
+ /** @example "Request handled successfully" */
+ message: string
+ /** @example "success" */
+ status: string
+}
+
+export interface ResponsesWebhookResponse {
+ data: EntitiesWebhook
+ /** @example "Request handled successfully" */
+ message: string
+ /** @example "success" */
+ status: string
+}
+
+export interface ResponsesWebhooksResponse {
+ data: EntitiesWebhook[]
+ /** @example "Request handled successfully" */
+ message: string
+ /** @example "success" */
+ status: string
}
diff --git a/web/pages/billing/index.vue b/web/pages/billing/index.vue
index 74862f7a..750dc1ae 100644
--- a/web/pages/billing/index.vue
+++ b/web/pages/billing/index.vue
@@ -300,16 +300,19 @@
>.
</p>
<v-progress-circular
- v-if="invoices == null && loadingSubscriptionInvoices"
+ v-if="payments == null && loadingSubscriptionPayments"
:size="20"
:width="2"
color="primary"
indeterminate
></v-progress-circular>
- <v-simple-table v-if="invoices">
+ <v-simple-table v-if="payments">
<template #default>
<thead>
<tr class="text-uppercase">
+ <th v-if="$vuetify.breakpoint.lgAndUp" class="text-left">
+ ID
+ </th>
<th class="text-left">Timestamp</th>
<th class="text-left">Status</th>
<th v-if="$vuetify.breakpoint.lgAndUp" class="text-left">
@@ -320,7 +323,10 @@
</tr>
</thead>
<tbody>
- <tr v-for="payment in invoices.data" :key="payment.id">
+ <tr v-for="payment in payments.data" :key="payment.id">
+ <td v-if="$vuetify.breakpoint.lgAndUp">
+ {{ payment.id }}
+ </td>
<td>
{{ payment.attributes.created_at | timestamp }}
</td>
@@ -348,7 +354,11 @@
{{ payment.attributes.total_formatted }}
</td>
<td class="text-right">
- <v-btn color="primary" small>
+ <v-btn
+ color="primary"
+ small
+ @click="showInvoiceDialog(payment)"
+ >
<v-icon left>{{ mdiInvoice }}</v-icon>
Invoice
</v-btn>
@@ -407,6 +417,150 @@
</v-row>
</v-container>
</div>
+ <v-dialog
+ v-model="subscriptionInvoiceDialog"
+ persistent
+ overlay-opacity="0.9"
+ max-width="600px"
+ >
+ <v-card>
+ <v-card-title class="text-h4"> Generate Invoice </v-card-title>
+ <v-card-subtitle class="mt-n1">
+ Create an invoice for your
+ <b>{{ selectedPayment?.attributes.total_formatted }}</b> payment on
+ {{ selectedPayment?.attributes.created_at | timestamp }}
+ </v-card-subtitle>
+ <v-card-text>
+ <v-container>
+ <v-row>
+ <v-col cols="12">
+ <v-text-field
+ dense
+ :disabled="loading"
+ :error="errorMessages.has('name')"
+ :error-messages="errorMessages.get('name')"
+ v-model="invoiceFormName"
+ label="Name"
+ placeholder="e.g Acme Corporation"
+ persistent-placeholder
+ outlined
+ ></v-text-field>
+ </v-col>
+ <v-col cols="12">
+ <v-text-field
+ dense
+ :disabled="loading"
+ :error="errorMessages.has('address')"
+ :error-messages="errorMessages.get('address')"
+ v-model="invoiceFormAddress"
+ label="Address"
+ placeholder="e.g 221B Baker Street"
+ persistent-placeholder
+ outlined
+ ></v-text-field>
+ </v-col>
+ </v-row>
+ <v-row>
+ <v-col cols="6">
+ <v-text-field
+ dense
+ :disabled="loading"
+ :error="errorMessages.has('city')"
+ :error-messages="errorMessages.get('city')"
+ v-model="invoiceFormCity"
+ label="City"
+ placeholder="e.g Los Angeles"
+ persistent-placeholder
+ outlined
+ ></v-text-field>
+ </v-col>
+ <v-col cols="6">
+ <v-text-field
+ v-if="invoiceStateOptions.length === 0"
+ dense
+ :disabled="loading"
+ :error="errorMessages.has('state')"
+ :error-messages="errorMessages.get('state')"
+ v-model="invoiceFormState"
+ label="State"
+ placeholder="e.g CA"
+ persistent-placeholder
+ outlined
+ ></v-text-field>
+ <v-autocomplete
+ v-else
+ dense
+ :disabled="loading"
+ :error="errorMessages.has('state')"
+ :error-messages="errorMessages.get('state')"
+ v-model="invoiceFormState"
+ :items="invoiceStateOptions"
+ label="State"
+ outlined
+ placeholder="e.g CA"
+ persistent-placeholder
+ ></v-autocomplete>
+ </v-col>
+ </v-row>
+ <v-row>
+ <v-col cols="6">
+ <v-text-field
+ dense
+ :disabled="loading"
+ :error="errorMessages.has('zip_code')"
+ :error-messages="errorMessages.get('zip_code')"
+ v-model="invoiceFormZipCode"
+ label="Zip Code"
+ placeholder="e.g 46001"
+ persistent-placeholder
+ outlined
+ ></v-text-field>
+ </v-col>
+ <v-col cols="6">
+ <v-autocomplete
+ dense
+ :disabled="loading"
+ :error="errorMessages.has('country')"
+ :error-messages="errorMessages.get('country')"
+ v-model="invoiceFormCountry"
+ :items="countries"
+ label="Country"
+ placeholder="e.g United States"
+ outlined
+ persistent-placeholder
+ ></v-autocomplete>
+ </v-col>
+ </v-row>
+ <v-row>
+ <v-col cols="12">
+ <v-textarea
+ dense
+ :disabled="loading"
+ :error="errorMessages.has('notes')"
+ :error-messages="errorMessages.get('notes')"
+ rows="3"
+ v-model="invoiceFormNotes"
+ label="Notes (optional)"
+ placeholder="e.g Thanks for doing business with us!"
+ persistent-placeholder
+ outlined
+ ></v-textarea>
+ </v-col>
+ </v-row>
+ </v-container>
+ </v-card-text>
+ <v-card-actions class="mt-n8 pb-4">
+ <v-btn :loading="loading" color="primary" @click="generateInvoice">
+ <v-icon left>{{ mdiDownloadOutline }}</v-icon>
+ Download Invoice
+ </v-btn>
+ <v-spacer></v-spacer>
+ <v-btn color="error" text @click="subscriptionInvoiceDialog = false">
+ Close
+ </v-btn>
+ </v-card-actions>
+ </v-card>
+ </v-dialog>
</v-container>
</template>
@@ -417,6 +571,7 @@ import {
mdiAccountCircle,
mdiShieldCheck,
mdiDelete,
+ mdiDownloadOutline,
mdiCog,
mdiContentSave,
mdiCheck,
@@ -430,9 +585,12 @@ import {
mdiSquareEditOutline,
} from '@mdi/js'
import {
- EntitiesPhoneAPIKey,
- ResponsesSubscriptionInvoicesAPIResponse,
+ RequestsUserPaymentInvoice,
+ ResponsesUnprocessableEntity,
+ ResponsesUserSubscriptionPaymentsResponse,
} from '~/models/api'
+import { ErrorMessages, getErrorMessages } from '~/plugins/errors'
+import { AxiosError } from 'axios'
type PaymentPlan = {
name: string
@@ -441,6 +599,14 @@ type PaymentPlan = {
messagesPerMonth: number
}
+type subscriptionPayment = {
+ attributes: {
+ created_at: string
+ total_formatted: string
+ }
+ id: string
+}
+
export default Vue.extend({
name: 'BillingIndex',
middleware: ['auth'],
@@ -449,6 +615,7 @@ export default Vue.extend({
mdiEye,
mdiEyeOff,
mdiArrowLeft,
+ mdiDownloadOutline,
mdiAccountCircle,
mdiCheck,
mdiAlert,
@@ -462,9 +629,267 @@ export default Vue.extend({
mdiCreditCard,
mdiSquareEditOutline,
loading: true,
- loadingSubscriptionInvoices: false,
+ loadingSubscriptionPayments: false,
dialog: false,
- invoices: null as ResponsesSubscriptionInvoicesAPIResponse | null,
+ payments: null as ResponsesUserSubscriptionPaymentsResponse | null,
+ selectedPayment: null as subscriptionPayment | null,
+ errorMessages: new ErrorMessages(),
+ invoiceFormName: '',
+ invoiceFormAddress: '',
+ invoiceFormCity: '',
+ invoiceFormState: '',
+ invoiceFormZipCode: '',
+ invoiceFormCountry: '',
+ invoiceFormNotes: '',
+ subscriptionInvoiceDialog: false,
+ countries: [
+ { text: 'Afghanistan', value: 'AF' },
+ { text: 'Åland Islands', value: 'AX' },
+ { text: 'Albania', value: 'AL' },
+ { text: 'Algeria', value: 'DZ' },
+ { text: 'American Samoa', value: 'AS' },
+ { text: 'Andorra', value: 'AD' },
+ { text: 'Angola', value: 'AO' },
+ { text: 'Anguilla', value: 'AI' },
+ { text: 'Antarctica', value: 'AQ' },
+ { text: 'Antigua and Barbuda', value: 'AG' },
+ { text: 'Argentina', value: 'AR' },
+ { text: 'Armenia', value: 'AM' },
+ { text: 'Aruba', value: 'AW' },
+ { text: 'Australia', value: 'AU' },
+ { text: 'Austria', value: 'AT' },
+ { text: 'Azerbaijan', value: 'AZ' },
+ { text: 'Bahamas', value: 'BS' },
+ { text: 'Bahrain', value: 'BH' },
+ { text: 'Bangladesh', value: 'BD' },
+ { text: 'Barbados', value: 'BB' },
+ { text: 'Belarus', value: 'BY' },
+ { text: 'Belgium', value: 'BE' },
+ { text: 'Belize', value: 'BZ' },
+ { text: 'Benin', value: 'BJ' },
+ { text: 'Bermuda', value: 'BM' },
+ { text: 'Bhutan', value: 'BT' },
+ { text: 'Bolivia', value: 'BO' },
+ { text: 'Bonaire', value: 'BQ' },
+ { text: 'Bosnia and Herzegovina', value: 'BA' },
+ { text: 'Botswana', value: 'BW' },
+ { text: 'Bouvet Island', value: 'BV' },
+ { text: 'Brazil', value: 'BR' },
+ { text: 'British Indian Ocean', value: 'IO' },
+ { text: 'Brunei Darussalam', value: 'BN' },
+ { text: 'Bulgaria', value: 'BG' },
+ { text: 'Burkina Faso', value: 'BF' },
+ { text: 'Burundi', value: 'BI' },
+ { text: 'Cabo Verde', value: 'CV' },
+ { text: 'Cambodia', value: 'KH' },
+ { text: 'Cameroon', value: 'CM' },
+ { text: 'Canada', value: 'CA' },
+ { text: 'Cayman Islands', value: 'KY' },
+ { text: 'Central African Republic', value: 'CF' },
+ { text: 'Chad', value: 'TD' },
+ { text: 'Chile', value: 'CL' },
+ { text: 'China', value: 'CN' },
+ { text: 'Christmas Island', value: 'CX' },
+ { text: 'Cocos (Keeling) Islands', value: 'CC' },
+ { text: 'Colombia', value: 'CO' },
+ { text: 'Comoros', value: 'KM' },
+ { text: 'Congo', value: 'CG' },
+ { text: 'Congo', value: 'CD' },
+ { text: 'Cook Islands', value: 'CK' },
+ { text: 'Costa Rica', value: 'CR' },
+ { text: "Côte d'Ivoire", value: 'CI' },
+ { text: 'Cuba', value: 'CU' },
+ { text: 'Curaçao', value: 'CW' },
+ { text: 'Cyprus', value: 'CY' },
+ { text: 'Czechia', value: 'CZ' },
+ { text: 'Denmark', value: 'DK' },
+ { text: 'Djibouti', value: 'DJ' },
+ { text: 'Dominica', value: 'DM' },
+ { text: 'Dominican Republic', value: 'DO' },
+ { text: 'Ecuador', value: 'EC' },
+ { text: 'Egypt', value: 'EG' },
+ { text: 'El Salvador', value: 'SV' },
+ { text: 'Equatorial Guinea', value: 'GQ' },
+ { text: 'Eritrea', value: 'ER' },
+ { text: 'Estonia', value: 'EE' },
+ { text: 'Eswatini', value: 'SZ' },
+ { text: 'Ethiopia', value: 'ET' },
+ { text: 'Falkland Islands', value: 'FK' },
+ { text: 'Faroe Islands', value: 'FO' },
+ { text: 'Fiji', value: 'FJ' },
+ { text: 'Finland', value: 'FI' },
+ { text: 'France', value: 'FR' },
+ { text: 'French Guiana', value: 'GF' },
+ { text: 'French Polynesia', value: 'PF' },
+ { text: 'French Southern Territories', value: 'TF' },
+ { text: 'Gabon', value: 'GA' },
+ { text: 'Gambia', value: 'GM' },
+ { text: 'Georgia', value: 'GE' },
+ { text: 'Germany', value: 'DE' },
+ { text: 'Ghana', value: 'GH' },
+ { text: 'Gibraltar', value: 'GI' },
+ { text: 'Greece', value: 'GR' },
+ { text: 'Greenland', value: 'GL' },
+ { text: 'Grenada', value: 'GD' },
+ { text: 'Guadeloupe', value: 'GP' },
+ { text: 'Guam', value: 'GU' },
+ { text: 'Guatemala', value: 'GT' },
+ { text: 'Guernsey', value: 'GG' },
+ { text: 'Guinea', value: 'GN' },
+ { text: 'Guinea-Bissau', value: 'GW' },
+ { text: 'Guyana', value: 'GY' },
+ { text: 'Haiti', value: 'HT' },
+ { text: 'Heard Island and McDonald Islands', value: 'HM' },
+ { text: 'Holy See', value: 'VA' },
+ { text: 'Honduras', value: 'HN' },
+ { text: 'Hong Kong', value: 'HK' },
+ { text: 'Hungary', value: 'HU' },
+ { text: 'Iceland', value: 'IS' },
+ { text: 'India', value: 'IN' },
+ { text: 'Indonesia', value: 'ID' },
+ { text: 'Iran', value: 'IR' },
+ { text: 'Iraq', value: 'IQ' },
+ { text: 'Ireland', value: 'IE' },
+ { text: 'Isle of Man', value: 'IM' },
+ { text: 'Israel', value: 'IL' },
+ { text: 'Italy', value: 'IT' },
+ { text: 'Jamaica', value: 'JM' },
+ { text: 'Japan', value: 'JP' },
+ { text: 'Jersey', value: 'JE' },
+ { text: 'Jordan', value: 'JO' },
+ { text: 'Kazakhstan', value: 'KZ' },
+ { text: 'Kenya', value: 'KE' },
+ { text: 'Kiribati', value: 'KI' },
+ { text: 'North Korea', value: 'KP' },
+ { text: 'South Korea', value: 'KR' },
+ { text: 'Kuwait', value: 'KW' },
+ { text: 'Kyrgyzstan', value: 'KG' },
+ { text: 'Lao People’s Democratic Republic', value: 'LA' },
+ { text: 'Latvia', value: 'LV' },
+ { text: 'Lebanon', value: 'LB' },
+ { text: 'Lesotho', value: 'LS' },
+ { text: 'Liberia', value: 'LR' },
+ { text: 'Libya', value: 'LY' },
+ { text: 'Liechtenstein', value: 'LI' },
+ { text: 'Lithuania', value: 'LT' },
+ { text: 'Luxembourg', value: 'LU' },
+ { text: 'Macao', value: 'MO' },
+ { text: 'Madagascar', value: 'MG' },
+ { text: 'Malawi', value: 'MW' },
+ { text: 'Malaysia', value: 'MY' },
+ { text: 'Maldives', value: 'MV' },
+ { text: 'Mali', value: 'ML' },
+ { text: 'Malta', value: 'MT' },
+ { text: 'Marshall Islands', value: 'MH' },
+ { text: 'Martinique', value: 'MQ' },
+ { text: 'Mauritania', value: 'MR' },
+ { text: 'Mauritius', value: 'MU' },
+ { text: 'Mayotte', value: 'YT' },
+ { text: 'Mexico', value: 'MX' },
+ { text: 'Micronesia', value: 'FM' },
+ { text: 'Moldova', value: 'MD' },
+ { text: 'Monaco', value: 'MC' },
+ { text: 'Mongolia', value: 'MN' },
+ { text: 'Montenegro', value: 'ME' },
+ { text: 'Montserrat', value: 'MS' },
+ { text: 'Morocco', value: 'MA' },
+ { text: 'Mozambique', value: 'MZ' },
+ { text: 'Myanmar', value: 'MM' },
+ { text: 'Namibia', value: 'NA' },
+ { text: 'Nauru', value: 'NR' },
+ { text: 'Nepal', value: 'NP' },
+ { text: 'Netherlands', value: 'NL' },
+ { text: 'New Caledonia', value: 'NC' },
+ { text: 'New Zealand', value: 'NZ' },
+ { text: 'Nicaragua', value: 'NI' },
+ { text: 'Niger', value: 'NE' },
+ { text: 'Nigeria', value: 'NG' },
+ { text: 'Niue', value: 'NU' },
+ { text: 'Norfolk Island', value: 'NF' },
+ { text: 'North Macedonia', value: 'MK' },
+ { text: 'Northern Mariana Islands', value: 'MP' },
+ { text: 'Norway', value: 'NO' },
+ { text: 'Oman', value: 'OM' },
+ { text: 'Pakistan', value: 'PK' },
+ { text: 'Palau', value: 'PW' },
+ { text: 'Panama', value: 'PA' },
+ { text: 'Papua New Guinea', value: 'PG' },
+ { text: 'Paraguay', value: 'PY' },
+ { text: 'Peru', value: 'PE' },
+ { text: 'Philippines', value: 'PH' },
+ { text: 'Pitcairn', value: 'PN' },
+ { text: 'Poland', value: 'PL' },
+ { text: 'Portugal', value: 'PT' },
+ { text: 'Puerto Rico', value: 'PR' },
+ { text: 'Qatar', value: 'QA' },
+ { text: 'Réunion', value: 'RE' },
+ { text: 'Romania', value: 'RO' },
+ { text: 'Russian Federation', value: 'RU' },
+ { text: 'Rwanda', value: 'RW' },
+ { text: 'Saint Barthélemy', value: 'BL' },
+ { text: 'Saint Helena, Ascension and Tristan da Cunha', value: 'SH' },
+ { text: 'Saint Kitts and Nevis', value: 'KN' },
+ { text: 'Saint Lucia', value: 'LC' },
+ { text: 'Saint Martin (French part)', value: 'MF' },
+ { text: 'Saint Pierre and Miquelon', value: 'PM' },
+ { text: 'Saint Vincent and the Grenadines', value: 'VC' },
+ { text: 'Samoa', value: 'WS' },
+ { text: 'San Marino', value: 'SM' },
+ { text: 'Sao Tome and Principe', value: 'ST' },
+ { text: 'Saudi Arabia', value: 'SA' },
+ { text: 'Senegal', value: 'SN' },
+ { text: 'Serbia', value: 'RS' },
+ { text: 'Seychelles', value: 'SC' },
+ { text: 'Sierra Leone', value: 'SL' },
+ { text: 'Singapore', value: 'SG' },
+ { text: 'Slovakia', value: 'SK' },
+ { text: 'Slovenia', value: 'SI' },
+ { text: 'Solomon Islands', value: 'SB' },
+ { text: 'Somalia', value: 'SO' },
+ { text: 'South Africa', value: 'ZA' },
+ { text: 'South Georgia and the South Sandwich Islands', value: 'GS' },
+ { text: 'South Sudan', value: 'SS' },
+ { text: 'Spain', value: 'ES' },
+ { text: 'Sri Lanka', value: 'LK' },
+ { text: 'Sudan', value: 'SD' },
+ { text: 'Suriname', value: 'SR' },
+ { text: 'Svalbard and Jan Mayen', value: 'SJ' },
+ { text: 'Sweden', value: 'SE' },
+ { text: 'Switzerland', value: 'CH' },
+ { text: 'Syrian Arab Republic', value: 'SY' },
+ { text: 'Taiwan, Province of China', value: 'TW' },
+ { text: 'Tajikistan', value: 'TJ' },
+ { text: 'Tanzania, United Republic of', value: 'TZ' },
+ { text: 'Thailand', value: 'TH' },
+ { text: 'Timor-Leste', value: 'TL' },
+ { text: 'Togo', value: 'TG' },
+ { text: 'Tokelau', value: 'TK' },
+ { text: 'Tonga', value: 'TO' },
+ { text: 'Trinidad and Tobago', value: 'TT' },
+ { text: 'Tunisia', value: 'TN' },
+ { text: 'Turkey', value: 'TR' },
+ { text: 'Turkmenistan', value: 'TM' },
+ { text: 'Turks and Caicos Islands', value: 'TC' },
+ { text: 'Tuvalu', value: 'TV' },
+ { text: 'Uganda', value: 'UG' },
+ { text: 'Ukraine', value: 'UA' },
+ { text: 'United Arab Emirates', value: 'AE' },
+ { text: 'United Kingdom', value: 'GB' },
+ { text: 'United States', value: 'US' },
+ { text: 'United States Minor Outlying Islands', value: 'UM' },
+ { text: 'Uruguay', value: 'UY' },
+ { text: 'Uzbekistan', value: 'UZ' },
+ { text: 'Vanuatu', value: 'VU' },
+ { text: 'Venezuela', value: 'VE' },
+ { text: 'Viet Nam', value: 'VN' },
+ { text: 'Virgin Islands (British)', value: 'VG' },
+ { text: 'Virgin Islands (U.S.)', value: 'VI' },
+ { text: 'Wallis and Futuna', value: 'WF' },
+ { text: 'Western Sahara', value: 'EH' },
+ { text: 'Yemen', value: 'YE' },
+ { text: 'Zambia', value: 'ZM' },
+ { text: 'Zimbabwe', value: 'ZW' },
+ ],
plans: [
{
name: 'Free',
@@ -541,6 +966,81 @@ export default Vue.extend({
}
},
computed: {
+ invoiceStateOptions() {
+ if (this.invoiceFormCountry === 'US') {
+ return [
+ { text: 'Alabama', value: 'AL' },
+ { text: 'Alaska', value: 'AK' },
+ { text: 'Arizona', value: 'AZ' },
+ { text: 'Arkansas', value: 'AR' },
+ { text: 'California', value: 'CA' },
+ { text: 'Colorado', value: 'CO' },
+ { text: 'Connecticut', value: 'CT' },
+ { text: 'Delaware', value: 'DE' },
+ { text: 'Florida', value: 'FL' },
+ { text: 'Georgia', value: 'GA' },
+ { text: 'Hawaii', value: 'HI' },
+ { text: 'Idaho', value: 'ID' },
+ { text: 'Illinois', value: 'IL' },
+ { text: 'Indiana', value: 'IN' },
+ { text: 'Iowa', value: 'IA' },
+ { text: 'Kansas', value: 'KS' },
+ { text: 'Kentucky', value: 'KY' },
+ { text: 'Louisiana', value: 'LA' },
+ { text: 'Maine', value: 'ME' },
+ { text: 'Maryland', value: 'MD' },
+ { text: 'Massachusetts', value: 'MA' },
+ { text: 'Michigan', value: 'MI' },
+ { text: 'Minnesota', value: 'MN' },
+ { text: 'Mississippi', value: 'MS' },
+ { text: 'Missouri', value: 'MO' },
+ { text: 'Montana', value: 'MT' },
+ { text: 'Nebraska', value: 'NE' },
+ { text: 'Nevada', value: 'NV' },
+ { text: 'New Hampshire', value: 'NH' },
+ { text: 'New Jersey', value: 'NJ' },
+ { text: 'New Mexico', value: 'NM' },
+ { text: 'New York', value: 'NY' },
+ { text: 'North Carolina', value: 'NC' },
+ { text: 'North Dakota', value: 'ND' },
+ { text: 'Ohio', value: 'OH' },
+ { text: 'Oklahoma', value: 'OK' },
+ { text: 'Oregon', value: 'OR' },
+ { text: 'Pennsylvania', value: 'PA' },
+ { text: 'Rhode Island', value: 'RI' },
+ { text: 'South Carolina', value: 'SC' },
+ { text: 'South Dakota', value: 'SD' },
+ { text: 'Tennessee', value: 'TN' },
+ { text: 'Texas', value: 'TX' },
+ { text: 'Utah', value: 'UT' },
+ { text: 'Vermont', value: 'VT' },
+ { text: 'Virginia', value: 'VA' },
+ { text: 'Washington', value: 'WA' },
+ { text: 'West Virginia', value: 'WV' },
+ { text: 'Wisconsin', value: 'WI' },
+ { text: 'Wyoming', value: 'WY' },
+ { text: 'District of Columbia', value: 'DC' },
+ ]
+ }
+ if (this.invoiceFormCountry === 'CA') {
+ return [
+ { text: 'Alberta', value: 'AB' },
+ { text: 'British Columbia', value: 'BC' },
+ { text: 'Manitoba', value: 'MB' },
+ { text: 'New Brunswick', value: 'NB' },
+ { text: 'Newfoundland and Labrador', value: 'NL' },
+ { text: 'Nova Scotia', value: 'NS' },
+ { text: 'Ontario', value: 'ON' },
+ { text: 'Prince Edward Island', value: 'PE' },
+ { text: 'Quebec', value: 'QC' },
+ { text: 'Saskatchewan', value: 'SK' },
+ { text: 'Northwest Territories', value: 'NT' },
+ { text: 'Nunavut', value: 'NU' },
+ { text: 'Yukon', value: 'YT' },
+ ]
+ }
+ return []
+ },
checkoutURL() {
const url = new URL(this.$config.checkoutURL)
const user = this.$store.getters.getAuthUser
@@ -599,15 +1099,45 @@ export default Vue.extend({
},
loadSubscriptionInvoices() {
- this.loadingSubscriptionInvoices = true
+ this.loadingSubscriptionPayments = true
this.$store
.dispatch('indexSubscriptionPayments')
- .then((invoices: ResponsesSubscriptionInvoicesAPIResponse) => {
- console.log(invoices)
- this.invoices = invoices
+ .then((response: ResponsesUserSubscriptionPaymentsResponse) => {
+ this.payments = response
+ })
+ .finally(() => {
+ this.loadingSubscriptionPayments = false
+ })
+ },
+
+ generateInvoice() {
+ this.errorMessages = new ErrorMessages()
+ this.loading = true
+ this.$store
+ .dispatch('generateSubscriptionPaymentInvoice', {
+ subscriptionInvoiceId: this.selectedPayment?.id!,
+ request: {
+ name: this.invoiceFormName,
+ address: this.invoiceFormAddress,
+ city: this.invoiceFormCity,
+ state: this.invoiceFormState,
+ zip_code: this.invoiceFormZipCode,
+ country: this.invoiceFormCountry,
+ notes: this.invoiceFormNotes,
+ },
+ } as {
+ subscriptionInvoiceId: string
+ request: RequestsUserPaymentInvoice
+ })
+ .then(() => {
+ this.subscriptionInvoiceDialog = false
+ })
+ .catch((error: ErrorMessages) => {
+ console.log(error)
+ this.errorMessages = error
})
.finally(() => {
- this.loadingSubscriptionInvoices = false
+ this.loading = false
})
},
@@ -637,6 +1167,11 @@ export default Vue.extend({
this.loading = false
})
},
+
+ showInvoiceDialog(payment: subscriptionPayment) {
+ this.selectedPayment = payment
+ this.subscriptionInvoiceDialog = true
+ },
},
})
</script>
diff --git a/web/store/index.ts b/web/store/index.ts
index 54fc875a..afeeaebd 100644
--- a/web/store/index.ts
+++ b/web/store/index.ts
@@ -16,6 +16,7 @@ import {
RequestsDiscordStore,
RequestsDiscordUpdate,
RequestsUserNotificationUpdate,
+ RequestsUserPaymentInvoice,
RequestsWebhookStore,
RequestsWebhookUpdate,
ResponsesDiscordResponse,
@@ -25,10 +26,9 @@ import {
ResponsesOkString,
ResponsesPhoneAPIKeyResponse,
ResponsesPhoneAPIKeysResponse,
- ResponsesSubscriptionInvoicesAPIResponse,
ResponsesUnprocessableEntity,
- ResponsesUserInvoicesResponse,
ResponsesUserResponse,
+ ResponsesUserSubscriptionPaymentsResponse,
ResponsesWebhookResponse,
ResponsesWebhooksResponse,
} from '~/models/api'
@@ -536,10 +536,10 @@ export const actions = {
},
indexSubscriptionPayments(context: ActionContext<State, State>) {
- return new Promise<ResponsesSubscriptionInvoicesAPIResponse>(
+ return new Promise<ResponsesUserSubscriptionPaymentsResponse>(
(resolve, reject) => {
axios
- .get<ResponsesUserInvoicesResponse>(
+ .get<ResponsesUserSubscriptionPaymentsResponse>(
`/v1/users/subscription/payments`,
{
params: {
@@ -547,9 +547,13 @@ export const actions = {
},
},
)
- .then((response: AxiosResponse<ResponsesUserInvoicesResponse>) => {
- resolve(response.data.data)
- })
+ .then(
+ (
+ response: AxiosResponse<ResponsesUserSubscriptionPaymentsResponse>,
+ ) => {
+ resolve(response.data)
+ },
+ )
.catch(async (error: AxiosError) => {
await Promise.all([
context.dispatch('addNotification', {
@@ -565,6 +569,75 @@ export const actions = {
)
},
+ generateSubscriptionPaymentInvoice(
+ context: ActionContext<State, State>,
+ payload: {
+ subscriptionInvoiceId: string
+ request: RequestsUserPaymentInvoice
+ },
+ ) {
+ return new Promise<void>((resolve, reject) => {
+ axios
+ .post(
+ `/v1/users/subscription/invoices/${payload.subscriptionInvoiceId}`,
+ payload.request,
+ {
+ responseType: 'blob',
+ },
+ )
+ .then(async (response: AxiosResponse) => {
+ // Create a Blob from the response data
+ const pdfBlob = new Blob([response.data], {
+ type: response.headers['content-type'],
+ })
+
+ // Create a temporary URL for the Blob
+ const url = window.URL.createObjectURL(pdfBlob)
+
+ // Create a temporary <a> element to trigger the download
+ const tempLink = document.createElement('a')
+ tempLink.href = url
+ tempLink.setAttribute(
+ 'download',
+ response.headers['content-disposition']
+ ?.split('filename=')[1]
+ .replaceAll('"', '') || 'Invoice.pdf',
+ ) // Set the desired filename for the downloaded file
+
+ // Append the <a> element to the body and click it to trigger the download
+ document.body.appendChild(tempLink)
+ tempLink.click()
+
+ // Clean up the temporary elements and URL
+ document.body.removeChild(tempLink)
+ window.URL.revokeObjectURL(url)
+
+ await context.dispatch('addNotification', {
+ message:
+ response.data.message ??
+ 'Your invoice has been generated successfully',
+ type: 'success',
+ })
+ resolve()
+ })
+ .catch(async (error: AxiosError) => {
+ const text = await (error.response as any).data.text()
+ if (error.response) {
+ error.response.data = JSON.parse(text)
+ }
+ await Promise.all([
+ context.dispatch('addNotification', {
+ message:
+ (error.response?.data as any)?.message ??
+ 'Error while generating your invoice',
+ type: 'error',
+ }),
+ ])
+ reject(getErrorMessages(error))
+ })
+ })
+ },
+
async handleAxiosError(
context: ActionContext<State, State>,
error: AxiosError<ResponsesUnprocessableEntity>,