-
Notifications
You must be signed in to change notification settings - Fork 12
/
invoice.resolvers.go
461 lines (407 loc) · 18.2 KB
/
invoice.resolvers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package resolver
// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.49
import (
"context"
"errors"
"github.com/99designs/gqlgen/graphql"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-api/constants"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-api/dataloader"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-api/graph/generated"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-api/graph/model"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-api/mapper"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-api/tracing"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-common-module/common"
commonService "github.com/openline-ai/openline-customer-os/packages/server/customer-os-common-module/service"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-common-module/utils"
neo4jentity "github.com/openline-ai/openline-customer-os/packages/server/customer-os-neo4j-repository/entity"
neo4jenum "github.com/openline-ai/openline-customer-os/packages/server/customer-os-neo4j-repository/enum"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/log"
"github.com/vektah/gqlparser/v2/ast"
)
// Organization is the resolver for the organization field.
func (r *invoiceResolver) Organization(ctx context.Context, obj *model.Invoice) (*model.Organization, error) {
ctx = tracing.EnrichCtxWithSpanCtxForGraphQL(ctx, graphql.GetOperationContext(ctx))
organizationEntity, err := dataloader.For(ctx).GetOrganizationForInvoice(ctx, obj.Metadata.ID)
if err != nil {
tracing.TraceErr(opentracing.SpanFromContext(ctx), err)
r.log.Errorf("error fetching organization for invoice %s: %s", obj.Metadata.ID, err.Error())
graphql.AddErrorf(ctx, "Error fetching organization for invoice %s", obj.Metadata.ID)
return nil, nil
}
return mapper.MapEntityToOrganization(organizationEntity), nil
}
// Contract is the resolver for the contract field.
func (r *invoiceResolver) Contract(ctx context.Context, obj *model.Invoice) (*model.Contract, error) {
ctx = tracing.EnrichCtxWithSpanCtxForGraphQL(ctx, graphql.GetOperationContext(ctx))
contractEntity, err := dataloader.For(ctx).GetContractForInvoice(ctx, obj.Metadata.ID)
if err != nil {
tracing.TraceErr(opentracing.SpanFromContext(ctx), err)
r.log.Errorf("error fetching contract for invoice %s: %s", obj.Metadata.ID, err.Error())
graphql.AddErrorf(ctx, "Error fetching contract for invoice %s", obj.Metadata.ID)
return nil, nil
}
return mapper.MapEntityToContract(contractEntity), nil
}
// InvoiceLineItems is the resolver for the invoiceLineItems field.
func (r *invoiceResolver) InvoiceLineItems(ctx context.Context, obj *model.Invoice) ([]*model.InvoiceLine, error) {
ctx = tracing.EnrichCtxWithSpanCtxForGraphQL(ctx, graphql.GetOperationContext(ctx))
entities, err := dataloader.For(ctx).GetInvoiceLinesForInvoice(ctx, obj.Metadata.ID)
if err != nil {
tracing.TraceErr(opentracing.SpanFromContext(ctx), err)
r.log.Errorf("failed to get invoice lines for invoice %s: %s", obj.Metadata.ID, err.Error())
graphql.AddErrorf(ctx, "Failed to fetch invoice lines for invoice %s", obj.Metadata.ID)
return nil, nil
}
return mapper.MapEntitiesToInvoiceLines(entities), nil
}
// ContractLineItem is the resolver for the contractLineItem field.
func (r *invoiceLineResolver) ContractLineItem(ctx context.Context, obj *model.InvoiceLine) (*model.ServiceLineItem, error) {
ctx = tracing.EnrichCtxWithSpanCtxForGraphQL(ctx, graphql.GetOperationContext(ctx))
serviceLineItemEntity, err := dataloader.For(ctx).GetServiceLineItemForInvoiceLine(ctx, obj.Metadata.ID)
if err != nil {
tracing.TraceErr(opentracing.SpanFromContext(ctx), err)
r.log.Errorf("Failed to get contract line item for invoice line %s: %s", obj.Metadata.ID, err.Error())
graphql.AddErrorf(ctx, "Failed to get contract line items for invoice line %s", obj.Metadata.ID)
return nil, nil
}
return mapper.MapEntityToServiceLineItem(serviceLineItemEntity), nil
}
// InvoiceNextDryRunForContract is the resolver for the invoice_NextDryRunForContract field.
func (r *mutationResolver) InvoiceNextDryRunForContract(ctx context.Context, contractID string) (string, error) {
ctx, span := tracing.StartGraphQLTracerSpan(ctx, "InvoiceResolver.InvoiceNextInvoiceDryRun", graphql.GetOperationContext(ctx))
defer span.Finish()
tracing.SetDefaultResolverSpanTags(ctx, span)
span.LogFields(log.Object("contractID", contractID))
invoiceId, err := r.Services.CommonServices.InvoiceService.NextInvoiceDryRun(ctx, contractID, constants.AppSourceCustomerOsApi)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to dry run next invoice for contract")
return "", err
}
return invoiceId, nil
}
// InvoiceUpdate is the resolver for the invoice_Update field.
func (r *mutationResolver) InvoiceUpdate(ctx context.Context, input model.InvoiceUpdateInput) (*model.Invoice, error) {
ctx, span := tracing.StartGraphQLTracerSpan(ctx, "MutationResolver.InvoiceUpdate", graphql.GetOperationContext(ctx))
defer span.Finish()
tracing.SetDefaultResolverSpanTags(ctx, span)
span.LogFields(log.String("request.id", input.ID))
err := r.Services.InvoiceService.UpdateInvoice(ctx, input)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to update invoice %s", input.ID)
return &model.Invoice{Metadata: &model.Metadata{
ID: input.ID,
}}, nil
}
invoiceEntity, err := r.Services.CommonServices.InvoiceService.GetById(ctx, input.ID)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed fetching invoice details. Invoice id: %s", input.ID)
return &model.Invoice{Metadata: &model.Metadata{
ID: input.ID,
}}, nil
}
return mapper.MapEntityToInvoice(invoiceEntity), nil
}
// InvoicePay is the resolver for the invoice_Pay field.
func (r *mutationResolver) InvoicePay(ctx context.Context, id string) (*model.Invoice, error) {
ctx, span := tracing.StartGraphQLTracerSpan(ctx, "MutationResolver.InvoicePay", graphql.GetOperationContext(ctx))
defer span.Finish()
tracing.SetDefaultResolverSpanTags(ctx, span)
span.LogFields(log.String("id", id))
invoice, err := r.Services.CommonServices.InvoiceService.GetById(ctx, id)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to fetch invoice %s", id)
return &model.Invoice{Metadata: &model.Metadata{
ID: id,
}}, nil
}
if invoice.DryRun {
tracing.TraceErr(span, errors.New("invoice is a dry run"))
graphql.AddErrorf(ctx, "Invoice is a dry run")
return &model.Invoice{Metadata: &model.Metadata{
ID: id,
}}, nil
}
if invoice.Status != neo4jenum.InvoiceStatusDue {
tracing.TraceErr(span, errors.New("invoice is not due"))
graphql.AddErrorf(ctx, "Invoice is not due")
return &model.Invoice{Metadata: &model.Metadata{
ID: id,
}}, nil
}
err = r.Services.CommonServices.InvoiceService.PayInvoice(ctx, id, constants.AppSourceCustomerOsApi)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to pay invoice %s", id)
return &model.Invoice{Metadata: &model.Metadata{
ID: id,
}}, nil
}
invoiceEntity, err := r.Services.CommonServices.InvoiceService.GetById(ctx, id)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed fetching invoice details. Invoice id: %s", id)
return &model.Invoice{Metadata: &model.Metadata{
ID: id,
}}, nil
}
return mapper.MapEntityToInvoice(invoiceEntity), nil
}
// InvoiceVoid is the resolver for the invoice_Void field.
func (r *mutationResolver) InvoiceVoid(ctx context.Context, id string) (*model.Invoice, error) {
ctx, span := tracing.StartGraphQLTracerSpan(ctx, "MutationResolver.InvoiceVoid", graphql.GetOperationContext(ctx))
defer span.Finish()
tracing.SetDefaultResolverSpanTags(ctx, span)
span.LogFields(log.String("id", id))
invoice, err := r.Services.CommonServices.InvoiceService.GetById(ctx, id)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to fetch invoice %s", id)
return &model.Invoice{Metadata: &model.Metadata{
ID: id,
}}, nil
}
if invoice.DryRun {
tracing.TraceErr(span, errors.New("invoice is a dry run"))
graphql.AddErrorf(ctx, "Invoice is a dry run")
return &model.Invoice{Metadata: &model.Metadata{
ID: id,
}}, nil
}
if invoice.Status == neo4jenum.InvoiceStatusVoid {
tracing.TraceErr(span, errors.New("invoice is already void"))
graphql.AddErrorf(ctx, "Invoice is already void")
return &model.Invoice{Metadata: &model.Metadata{
ID: id,
}}, nil
}
err = r.Services.CommonServices.InvoiceService.VoidInvoice(ctx, id, constants.AppSourceCustomerOsApi)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to void invoice %s", id)
return &model.Invoice{Metadata: &model.Metadata{
ID: id,
}}, nil
}
invoiceEntity, err := r.Services.CommonServices.InvoiceService.GetById(ctx, id)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed fetching invoice details. Invoice id: %s", id)
return &model.Invoice{Metadata: &model.Metadata{
ID: id,
}}, nil
}
return mapper.MapEntityToInvoice(invoiceEntity), nil
}
// InvoiceSimulate is the resolver for the invoice_Simulate field.
func (r *mutationResolver) InvoiceSimulate(ctx context.Context, input model.InvoiceSimulateInput) ([]*model.InvoiceSimulate, error) {
ctx, span := tracing.StartGraphQLTracerSpan(ctx, "InvoiceResolver.InvoiceSimulate", graphql.GetOperationContext(ctx))
defer span.Finish()
tracing.SetDefaultResolverSpanTags(ctx, span)
span.LogFields(log.Object("request.input", input))
simulateInvoiceData := commonService.SimulateInvoiceRequestData{
ContractId: input.ContractID,
}
for _, serviceLine := range input.ServiceLines {
simulateInvoiceData.ServiceLines = append(simulateInvoiceData.ServiceLines, commonService.SimulateInvoiceRequestServiceLineData{
Key: serviceLine.Key,
ServiceLineItemID: utils.IfNotNilString(serviceLine.ServiceLineItemID),
ParentID: utils.IfNotNilString(serviceLine.ParentID),
Description: serviceLine.Description,
BillingCycle: mapper.MapBilledTypeFromModel(serviceLine.BillingCycle),
Price: serviceLine.Price,
Quantity: serviceLine.Quantity,
ServiceStarted: serviceLine.ServiceStarted,
TaxRate: serviceLine.TaxRate,
Canceled: utils.IfNotNilBool(serviceLine.CloseVersion),
})
}
nextInvoices, err := r.Services.CommonServices.InvoiceService.SimulateInvoice(ctx, &simulateInvoiceData)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to simulate invoice")
return nil, err
}
var customer model.InvoiceCustomer
var provider model.InvoiceProvider
if len(nextInvoices) > 0 {
// Get FieldContext from the ctx
fc := graphql.GetFieldContext(ctx)
requestedCustomerDtls := false
requestedProviderDtls := false
for _, selected := range fc.Field.Selections {
if field, ok := selected.(*ast.Field); ok {
if field.Name == "customer" {
requestedCustomerDtls = true
}
if field.Name == "provider" {
requestedProviderDtls = true
}
}
}
// populate customer data
if requestedCustomerDtls {
contract, err := r.Services.CommonServices.ContractService.GetById(ctx, input.ContractID)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to get contract by id %s", input.ContractID)
return nil, err
}
customer = model.InvoiceCustomer{
Name: utils.StringPtr(contract.OrganizationLegalName),
Email: utils.StringPtr(contract.InvoiceEmail),
AddressLine1: utils.StringPtr(contract.AddressLine1),
AddressLine2: utils.StringPtr(contract.AddressLine2),
AddressZip: utils.StringPtr(contract.Zip),
AddressLocality: utils.StringPtr(contract.Locality),
AddressCountry: utils.StringPtr(contract.Country),
AddressRegion: utils.StringPtr(contract.Region),
}
}
// populate provider data
if requestedProviderDtls {
tenantBillingProfile, err := r.Services.TenantService.GetDefaultTenantBillingProfile(ctx)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to get tenant billing profile")
return nil, err
}
tenantSettings, err := r.Services.TenantService.GetTenantSettings(ctx)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to get tenant settings")
return nil, err
}
if tenantBillingProfile != nil {
provider = model.InvoiceProvider{
LogoRepositoryFileID: utils.StringPtr(tenantSettings.LogoRepositoryFileId),
Name: utils.StringPtr(tenantBillingProfile.LegalName),
AddressLine1: utils.StringPtr(tenantBillingProfile.AddressLine1),
AddressLine2: utils.StringPtr(tenantBillingProfile.AddressLine2),
AddressZip: utils.StringPtr(tenantBillingProfile.Zip),
AddressLocality: utils.StringPtr(tenantBillingProfile.Locality),
AddressCountry: utils.StringPtr(tenantBillingProfile.Country),
AddressRegion: utils.StringPtr(tenantBillingProfile.Region),
}
}
}
}
response := make([]*model.InvoiceSimulate, 0)
for _, nextInvoice := range nextInvoices {
invoice := model.InvoiceSimulate{
Postpaid: nextInvoice.Invoice.Postpaid,
OffCycle: nextInvoice.Invoice.OffCycle,
InvoicePeriodStart: nextInvoice.Invoice.PeriodStartDate,
InvoicePeriodEnd: nextInvoice.Invoice.PeriodEndDate,
Due: nextInvoice.Invoice.DueDate,
Issued: nextInvoice.Invoice.IssuedDate,
Currency: nextInvoice.Invoice.Currency.String(),
Note: nextInvoice.Invoice.Note,
Amount: nextInvoice.Invoice.Amount,
Subtotal: nextInvoice.Invoice.Amount,
TaxDue: nextInvoice.Invoice.Vat,
Total: nextInvoice.Invoice.TotalAmount,
InvoiceLineItems: []*model.InvoiceLineSimulate{},
Customer: &customer,
Provider: &provider,
}
for _, line := range nextInvoice.Lines {
invoiceLine := model.InvoiceLineSimulate{
Key: line.Id,
Description: line.Name,
Price: line.Price,
Quantity: line.Quantity,
Total: line.TotalAmount,
TaxDue: line.Vat,
Subtotal: line.Amount,
}
invoice.InvoiceLineItems = append(invoice.InvoiceLineItems, &invoiceLine)
}
response = append(response, &invoice)
}
return response, nil
}
// Invoice is the resolver for the invoice field.
func (r *queryResolver) Invoice(ctx context.Context, id string) (*model.Invoice, error) {
ctx, span := tracing.StartGraphQLTracerSpan(ctx, "InvoiceResolver.Invoice", graphql.GetOperationContext(ctx))
defer span.Finish()
tracing.SetDefaultResolverSpanTags(ctx, span)
span.LogFields(log.String("request.invoiceID", id))
if id == "" {
tracing.TraceErr(span, errors.New("missing invoice input id"))
graphql.AddErrorf(ctx, "Missing invoice input id")
return nil, nil
}
invoiceEntityPtr, err := r.Services.CommonServices.InvoiceService.GetById(ctx, id)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to get contract by id %s", id)
return nil, err
}
return mapper.MapEntityToInvoice(invoiceEntityPtr), nil
}
// Invoices is the resolver for the invoices field.
func (r *queryResolver) Invoices(ctx context.Context, pagination *model.Pagination, where *model.Filter, sort []*model.SortBy, organizationID *string) (*model.InvoicesPage, error) {
ctx, span := tracing.StartGraphQLTracerSpan(ctx, "InvoiceResolver.Invoices", graphql.GetOperationContext(ctx))
defer span.Finish()
tracing.SetDefaultResolverSpanTags(ctx, span)
if where != nil {
tracing.LogObjectAsJson(span, "request.where", where)
}
if sort != nil {
tracing.LogObjectAsJson(span, "request.sort", sort)
}
if pagination == nil {
pagination = &model.Pagination{Page: 0, Limit: 0}
}
span.LogFields(log.Int("request.pagination.page", pagination.Page), log.Int("request.pagination.limit", pagination.Limit))
paginatedResult, err := r.Services.InvoiceService.GetInvoices(ctx, utils.IfNotNilString(organizationID), pagination.Page, pagination.Limit, where, sort)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to get invoices")
return nil, err
}
countInvoices, err := r.Services.InvoiceService.CountInvoices(ctx, common.GetTenantFromContext(ctx), utils.IfNotNilString(organizationID), where)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to get organizations and contacts data")
return nil, nil
}
return &model.InvoicesPage{
Content: mapper.MapEntitiesToInvoices(paginatedResult.Rows.(*neo4jentity.InvoiceEntities)),
TotalPages: paginatedResult.TotalPages,
TotalElements: paginatedResult.TotalRows,
TotalAvailable: countInvoices,
}, err
}
// InvoiceByNumber is the resolver for the invoice_ByNumber field.
func (r *queryResolver) InvoiceByNumber(ctx context.Context, number string) (*model.Invoice, error) {
ctx, span := tracing.StartGraphQLTracerSpan(ctx, "InvoiceResolver.InvoiceByNumber", graphql.GetOperationContext(ctx))
defer span.Finish()
tracing.SetDefaultResolverSpanTags(ctx, span)
span.LogFields(log.String("request.invoiceNumber", number))
if number == "" {
tracing.TraceErr(span, errors.New("missing invoice number"))
graphql.AddErrorf(ctx, "Missing invoice number")
return nil, nil
}
invoiceEntityPtr, err := r.Services.CommonServices.InvoiceService.GetByNumber(ctx, number)
if err != nil {
tracing.TraceErr(span, err)
graphql.AddErrorf(ctx, "Failed to get invoice by number %s", number)
return nil, err
}
return mapper.MapEntityToInvoice(invoiceEntityPtr), nil
}
// Invoice returns generated.InvoiceResolver implementation.
func (r *Resolver) Invoice() generated.InvoiceResolver { return &invoiceResolver{r} }
// InvoiceLine returns generated.InvoiceLineResolver implementation.
func (r *Resolver) InvoiceLine() generated.InvoiceLineResolver { return &invoiceLineResolver{r} }
type invoiceResolver struct{ *Resolver }
type invoiceLineResolver struct{ *Resolver }