-
Notifications
You must be signed in to change notification settings - Fork 12
/
service_line_item_service.go
745 lines (672 loc) · 30.7 KB
/
service_line_item_service.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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
package service
import (
"context"
"fmt"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-api/mapper"
"sort"
"time"
"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/graph/model"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-api/repository"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-common-module/common"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-common-module/grpc_client"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-common-module/logger"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-common-module/tracing"
"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"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-neo4j-repository/neo4jutil"
commonpb "github.com/openline-ai/openline-customer-os/packages/server/events-processing-proto/gen/proto/go/api/grpc/v1/common"
servicelineitempb "github.com/openline-ai/openline-customer-os/packages/server/events-processing-proto/gen/proto/go/api/grpc/v1/service_line_item"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/log"
"github.com/pkg/errors"
)
type ServiceLineItemCreateData struct {
ContractId string `json:"contractId"`
SliName string `json:"sliName"`
SliPrice float64 `json:"sliPrice"`
SliQuantity int64 `json:"sliQuantity"`
SliBilledType neo4jenum.BilledType `json:"sliBilledType"`
ExternalReference *neo4jentity.ExternalSystemEntity `json:"externalReference"`
Source neo4jentity.DataSource `json:"source"`
AppSource string `json:"appSource"`
StartedAt *time.Time `json:"startedAt"`
EndedAt *time.Time `json:"endedAt"`
SliVatRate float64 `json:"sliVatRate"`
}
type ServiceLineItemUpdateData struct {
Id string `json:"id"`
IsRetroactiveCorrection bool `json:"isRetroactiveCorrection"`
SliName string `json:"sliName"`
SliPrice float64 `json:"sliPrice"`
SliQuantity int64 `json:"sliQuantity"`
SliBilledType neo4jenum.BilledType `json:"sliBilledType"`
SliComments string `json:"sliComments"`
Source neo4jentity.DataSource `json:"source"`
AppSource string `json:"appSource"`
SliVatRate float64 `json:"sliVatRate"`
StartedAt *time.Time `json:"startedAt"`
}
type ServiceLineItemNewVersionData struct {
Id string `json:"id"`
Name string `json:"sliName"`
Price float64 `json:"sliPrice"`
Quantity int64 `json:"sliQuantity"`
Comments string `json:"sliComments"`
Source neo4jentity.DataSource `json:"source"`
AppSource string `json:"appSource"`
VatRate float64 `json:"sliVatRate"`
StartedAt *time.Time `json:"startedAt"`
}
type ServiceLineItemService interface {
Create(ctx context.Context, serviceLineItemDetails ServiceLineItemCreateData) (string, error)
Update(ctx context.Context, serviceLineItemDetails ServiceLineItemUpdateData) error
Delete(ctx context.Context, serviceLineItemId string) (bool, error)
Close(ctx context.Context, serviceLineItemId string, endedAt *time.Time) error
CreateOrUpdateOrCloseInBulk(ctx context.Context, contractId string, sliBulkData []*ServiceLineItemDetails) ([]string, error)
NewVersion(ctx context.Context, data ServiceLineItemNewVersionData) (string, error)
}
type serviceLineItemService struct {
log logger.Logger
repositories *repository.Repositories
grpcClients *grpc_client.Clients
services *Services
}
func NewServiceLineItemService(log logger.Logger, repositories *repository.Repositories, grpcClients *grpc_client.Clients, services *Services) ServiceLineItemService {
return &serviceLineItemService{
log: log,
repositories: repositories,
grpcClients: grpcClients,
services: services,
}
}
func (s *serviceLineItemService) Create(ctx context.Context, serviceLineItemDetails ServiceLineItemCreateData) (string, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ServiceLineItem.Create")
defer span.Finish()
tracing.SetDefaultServiceSpanTags(ctx, span)
tracing.LogObjectAsJson(span, "serviceLineItemDetails", serviceLineItemDetails)
// check that quantity and price are not negative
if serviceLineItemDetails.SliQuantity < 0 || serviceLineItemDetails.SliPrice < 0 {
err := errors.New("quantity and price must not be negative")
tracing.TraceErr(span, err)
return "", err
}
createServiceLineItemRequest := servicelineitempb.CreateServiceLineItemGrpcRequest{
Tenant: common.GetTenantFromContext(ctx),
ContractId: serviceLineItemDetails.ContractId,
Name: serviceLineItemDetails.SliName,
Quantity: serviceLineItemDetails.SliQuantity,
Price: serviceLineItemDetails.SliPrice,
VatRate: serviceLineItemDetails.SliVatRate,
StartedAt: utils.ConvertTimeToTimestampPtr(serviceLineItemDetails.StartedAt),
EndedAt: utils.ConvertTimeToTimestampPtr(serviceLineItemDetails.EndedAt),
LoggedInUserId: common.GetUserIdFromContext(ctx),
SourceFields: &commonpb.SourceFields{
Source: string(serviceLineItemDetails.Source),
AppSource: utils.StringFirstNonEmpty(serviceLineItemDetails.AppSource, constants.AppSourceCustomerOsApi),
},
}
billedType, err := convertBilledTypeToProto(serviceLineItemDetails.SliBilledType, span)
if err != nil {
tracing.TraceErr(span, err)
return "", err
}
createServiceLineItemRequest.Billed = billedType
ctx = tracing.InjectSpanContextIntoGrpcMetadata(ctx, span)
response, err := utils.CallEventsPlatformGRPCWithRetry[*servicelineitempb.ServiceLineItemIdGrpcResponse](func() (*servicelineitempb.ServiceLineItemIdGrpcResponse, error) {
return s.grpcClients.ServiceLineItemClient.CreateServiceLineItem(ctx, &createServiceLineItemRequest)
})
if err != nil {
tracing.TraceErr(span, err)
return "", err
}
WaitForNodeCreatedInNeo4j(ctx, s.repositories, response.Id, neo4jutil.NodeLabelServiceLineItem, span)
span.LogFields(log.String("output - createdServiceLineItemId", response.Id))
return response.Id, nil
}
func (s *serviceLineItemService) NewVersion(ctx context.Context, data ServiceLineItemNewVersionData) (string, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ServiceLineItem.NewVersion")
defer span.Finish()
tracing.SetDefaultServiceSpanTags(ctx, span)
tracing.LogObjectAsJson(span, "serviceLineItemDetails", data)
if data.Id == "" {
err := fmt.Errorf("(ServiceLineItemService.NewVersion) contract line item id is missing")
s.log.Error(err.Error())
tracing.TraceErr(span, err)
return "", err
}
var baseServiceLineItemEntity *neo4jentity.ServiceLineItemEntity
// check that given id is parentId, then use latest version as base
serviceLineItems, err := s.services.CommonServices.ServiceLineItemService.GetServiceLineItemsByParentId(ctx, data.Id)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error on getting service line items by parent id {%s}: %s", data.Id, err.Error())
return "", err
}
// sort by startedAt descending and select first one
if len(*serviceLineItems) > 0 {
sort.Slice(*serviceLineItems, func(i, j int) bool {
return (*serviceLineItems)[i].StartedAt.After((*serviceLineItems)[j].StartedAt)
})
baseServiceLineItemEntity = &(*serviceLineItems)[0]
} else {
//if not found by parent id, treat data.id as SLI id
baseServiceLineItemEntity, err = s.services.CommonServices.ServiceLineItemService.GetById(ctx, data.Id)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error on getting contract line item by id {%s}: %s", data.Id, err.Error())
return "", err
}
}
if baseServiceLineItemEntity == nil {
err := fmt.Errorf("contract line item with id {%s} not found", data.Id)
tracing.TraceErr(span, err)
return "", err
}
contractEntity, err := s.services.ContractService.GetContractByServiceLineItem(ctx, baseServiceLineItemEntity.ID)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error on getting contract by service line item id {%s}: %s", baseServiceLineItemEntity.ID, err.Error())
return "", err
}
startedAt := utils.ToDate(utils.IfNotNilTimeWithDefault(data.StartedAt, utils.Now()))
// Check no SLI of the contract are cancelled
for _, sli := range *serviceLineItems {
if sli.Canceled {
err = fmt.Errorf("contract line item with id {%s} is already ended", sli.ID)
tracing.TraceErr(span, err)
return "", err
}
}
// Do not allow creating new version if there is an existing version with the same start date
for _, sli := range *serviceLineItems {
if utils.ToDate(sli.StartedAt).Equal(startedAt) {
err = fmt.Errorf("contract line item with id {%s} already exists with the same start date {%s}", sli.ID, startedAt.Format(time.DateOnly))
tracing.TraceErr(span, err)
return "", err
}
}
// Validate new version creation
if baseServiceLineItemEntity.Billed == neo4jenum.BilledTypeOnce {
err = fmt.Errorf("cannot create new version for one time contract line item with id {%s}", baseServiceLineItemEntity.ID)
tracing.TraceErr(span, err)
return "", err
}
// If contract was invoiced - do not allow creating new version in the past
contractInvoiced, err := s.repositories.Neo4jRepositories.ContractReadRepository.IsContractInvoiced(ctx, common.GetTenantFromContext(ctx), contractEntity.Id)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error on checking if contract was invoiced: %s", err.Error())
return "", err
}
if contractInvoiced && startedAt.Before(utils.Today()) {
err = fmt.Errorf("cannot create new version for contract line item with id {%s} in the past", baseServiceLineItemEntity.ID)
tracing.TraceErr(span, err)
return "", err
}
createServiceLineItemRequest := servicelineitempb.CreateServiceLineItemGrpcRequest{
Tenant: common.GetTenantFromContext(ctx),
LoggedInUserId: common.GetUserIdFromContext(ctx),
ContractId: contractEntity.Id,
ParentId: baseServiceLineItemEntity.ParentID,
Name: utils.StringFirstNonEmpty(data.Name, baseServiceLineItemEntity.Name),
Quantity: data.Quantity,
Price: data.Price,
VatRate: data.VatRate,
StartedAt: utils.ConvertTimeToTimestampPtr(&startedAt),
Comments: utils.IfNotNilString(data.Comments),
SourceFields: &commonpb.SourceFields{
Source: data.Source.String(),
AppSource: utils.StringFirstNonEmpty(data.AppSource, constants.AppSourceCustomerOsApi),
},
}
billedType, err := convertBilledTypeToProto(baseServiceLineItemEntity.Billed, span)
if err != nil {
tracing.TraceErr(span, err)
return "", err
}
createServiceLineItemRequest.Billed = billedType
ctx = tracing.InjectSpanContextIntoGrpcMetadata(ctx, span)
response, err := utils.CallEventsPlatformGRPCWithRetry[*servicelineitempb.ServiceLineItemIdGrpcResponse](func() (*servicelineitempb.ServiceLineItemIdGrpcResponse, error) {
return s.grpcClients.ServiceLineItemClient.CreateServiceLineItem(ctx, &createServiceLineItemRequest)
})
if err != nil {
tracing.TraceErr(span, err)
return "", err
}
return response.Id, err
}
func (s *serviceLineItemService) Update(ctx context.Context, serviceLineItemDetails ServiceLineItemUpdateData) error {
span, ctx := opentracing.StartSpanFromContext(ctx, "ServiceLineItemService.Update")
defer span.Finish()
tracing.SetDefaultServiceSpanTags(ctx, span)
tracing.LogObjectAsJson(span, "serviceLineItemDetails", serviceLineItemDetails)
if serviceLineItemDetails.Id == "" {
err := fmt.Errorf("(ServiceLineItemService.Update) contract line item id is missing")
s.log.Error(err.Error())
tracing.TraceErr(span, err)
return err
}
baseServiceLineItemEntity, err := s.services.CommonServices.ServiceLineItemService.GetById(ctx, serviceLineItemDetails.Id)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error on getting contract line item by id {%s}: %s", serviceLineItemDetails.Id, err.Error())
return err
}
contractEntity, err := s.services.ContractService.GetContractByServiceLineItem(ctx, serviceLineItemDetails.Id)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error on getting contract by service line item id {%s}: %s", serviceLineItemDetails.Id, err.Error())
return err
}
contractInvoiced, _ := s.repositories.Neo4jRepositories.ContractReadRepository.IsContractInvoiced(ctx, common.GetTenantFromContext(ctx), contractEntity.Id)
sliInvoiced, _ := s.repositories.Neo4jRepositories.ServiceLineItemReadRepository.WasServiceLineItemInvoiced(ctx, common.GetTenantFromContext(ctx), baseServiceLineItemEntity.ID)
startedAt := utils.ToDate(utils.IfNotNilTimeWithDefault(serviceLineItemDetails.StartedAt, baseServiceLineItemEntity.StartedAt))
// If no changes recorded, return
if baseServiceLineItemEntity.Name == serviceLineItemDetails.SliName &&
baseServiceLineItemEntity.Price == serviceLineItemDetails.SliPrice &&
baseServiceLineItemEntity.Quantity == serviceLineItemDetails.SliQuantity &&
baseServiceLineItemEntity.VatRate == serviceLineItemDetails.SliVatRate &&
baseServiceLineItemEntity.Comments == serviceLineItemDetails.SliComments &&
(utils.ToDate(baseServiceLineItemEntity.StartedAt).Equal(startedAt) || sliInvoiced) &&
baseServiceLineItemEntity.Billed == serviceLineItemDetails.SliBilledType {
span.LogFields(log.String("result", "No changes recorded"))
return nil
}
if baseServiceLineItemEntity.Canceled {
err = fmt.Errorf("contract line item with id {%s} is already ended", serviceLineItemDetails.Id)
tracing.TraceErr(span, err)
return err
}
// Check no SLI of the contract are cancelled
serviceLineItemsOfSameParent, err := s.services.CommonServices.ServiceLineItemService.GetServiceLineItemsByParentId(ctx, baseServiceLineItemEntity.ParentID)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error on getting service line items for contract {%s}: %s", contractEntity.Id, err.Error())
return err
}
for _, sli := range *serviceLineItemsOfSameParent {
if sli.Canceled {
err = fmt.Errorf("contract line item with id {%s} is already ended", sli.ID)
tracing.TraceErr(span, err)
return err
}
}
// check that quantity and price are not negative
if serviceLineItemDetails.SliQuantity < 0 || serviceLineItemDetails.SliPrice < 0 {
err := errors.New("quantity and price must not be negative")
tracing.TraceErr(span, err)
return err
}
// check that billing cycle is not changed
if serviceLineItemDetails.SliBilledType.String() == "" {
serviceLineItemDetails.SliBilledType = baseServiceLineItemEntity.Billed
}
if baseServiceLineItemEntity.Billed.String() != serviceLineItemDetails.SliBilledType.String() && baseServiceLineItemEntity.Billed.String() != "" {
err = fmt.Errorf("cannot change billing cycle for contract line item with id {%s}", serviceLineItemDetails.Id)
tracing.TraceErr(span, err)
return err
}
isRetroactiveCorrection := serviceLineItemDetails.IsRetroactiveCorrection
if baseServiceLineItemEntity.IsOneTime() ||
utils.ToDate(baseServiceLineItemEntity.StartedAt) == startedAt {
isRetroactiveCorrection = true
}
if isRetroactiveCorrection && sliInvoiced {
err = fmt.Errorf("service line item with id {%s} is included in invoice and cannot be updated", serviceLineItemDetails.Id)
tracing.TraceErr(span, err)
return err
}
// Do not allow updating past SLIs for invoiced contracts
if isRetroactiveCorrection && contractInvoiced {
tenantSettings, _ := s.services.CommonServices.TenantService.GetTenantSettings(ctx)
isInvoicingPostpaid := tenantSettings.InvoicingPostpaid
referenceDate := utils.Today()
if isInvoicingPostpaid && contractEntity.NextInvoiceDate != nil {
referenceDate = utils.ToDate(*contractEntity.NextInvoiceDate)
}
if startedAt.Before(referenceDate) {
err = fmt.Errorf("cannot update contract line item with id {%s} and start date before {%s}", serviceLineItemDetails.Id, referenceDate.Format(time.DateOnly))
tracing.TraceErr(span, err)
return err
}
}
span.LogFields(log.Bool("result.isRetroactiveCorrection", isRetroactiveCorrection))
if isRetroactiveCorrection == true {
serviceLineItemUpdateRequest := servicelineitempb.UpdateServiceLineItemGrpcRequest{
Tenant: common.GetTenantFromContext(ctx),
Id: serviceLineItemDetails.Id,
LoggedInUserId: common.GetUserIdFromContext(ctx),
Name: serviceLineItemDetails.SliName,
Quantity: serviceLineItemDetails.SliQuantity,
Price: serviceLineItemDetails.SliPrice,
Comments: serviceLineItemDetails.SliComments,
VatRate: serviceLineItemDetails.SliVatRate,
SourceFields: &commonpb.SourceFields{
Source: string(serviceLineItemDetails.Source),
AppSource: utils.StringFirstNonEmpty(serviceLineItemDetails.AppSource, constants.AppSourceCustomerOsApi),
},
}
billedType, err := convertBilledTypeToProto(serviceLineItemDetails.SliBilledType, span)
if err != nil {
tracing.TraceErr(span, err)
return err
}
serviceLineItemUpdateRequest.Billed = billedType
if baseServiceLineItemEntity.ParentID == baseServiceLineItemEntity.ID {
serviceLineItemUpdateRequest.StartedAt = utils.ConvertTimeToTimestampPtr(serviceLineItemDetails.StartedAt)
}
ctx = tracing.InjectSpanContextIntoGrpcMetadata(ctx, span)
_, err = utils.CallEventsPlatformGRPCWithRetry[*servicelineitempb.ServiceLineItemIdGrpcResponse](func() (*servicelineitempb.ServiceLineItemIdGrpcResponse, error) {
return s.grpcClients.ServiceLineItemClient.UpdateServiceLineItem(ctx, &serviceLineItemUpdateRequest)
})
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error from events processing: %s", err.Error())
return err
}
} else {
createServiceLineItemRequest := servicelineitempb.CreateServiceLineItemGrpcRequest{
Tenant: common.GetTenantFromContext(ctx),
LoggedInUserId: common.GetUserIdFromContext(ctx),
ContractId: contractEntity.Id,
ParentId: baseServiceLineItemEntity.ParentID,
Name: utils.StringFirstNonEmpty(serviceLineItemDetails.SliName, baseServiceLineItemEntity.Name),
Quantity: serviceLineItemDetails.SliQuantity,
Price: serviceLineItemDetails.SliPrice,
VatRate: serviceLineItemDetails.SliVatRate,
Comments: utils.IfNotNilString(serviceLineItemDetails.SliComments),
StartedAt: utils.ConvertTimeToTimestampPtr(serviceLineItemDetails.StartedAt),
SourceFields: &commonpb.SourceFields{
Source: serviceLineItemDetails.Source.String(),
AppSource: utils.StringFirstNonEmpty(serviceLineItemDetails.AppSource, constants.AppSourceCustomerOsApi),
},
}
billedType, err := convertBilledTypeToProto(baseServiceLineItemEntity.Billed, span)
if err != nil {
tracing.TraceErr(span, err)
return err
}
createServiceLineItemRequest.Billed = billedType
ctx = tracing.InjectSpanContextIntoGrpcMetadata(ctx, span)
_, err = utils.CallEventsPlatformGRPCWithRetry[*servicelineitempb.ServiceLineItemIdGrpcResponse](func() (*servicelineitempb.ServiceLineItemIdGrpcResponse, error) {
return s.grpcClients.ServiceLineItemClient.CreateServiceLineItem(ctx, &createServiceLineItemRequest)
})
if err != nil {
tracing.TraceErr(span, err)
return err
}
}
return nil
}
func (s *serviceLineItemService) Delete(ctx context.Context, serviceLineItemId string) (completed bool, err error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ServiceLineItemService.Delete")
defer span.Finish()
tracing.SetDefaultServiceSpanTags(ctx, span)
span.LogFields(log.String("serviceLineItemId", serviceLineItemId))
sliEntity, err := s.services.CommonServices.ServiceLineItemService.GetById(ctx, serviceLineItemId)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error on getting service line item by id {%s}: %s", serviceLineItemId, err.Error())
return false, err
}
// Check SLI is not invoiced
sliInvoiced, err := s.repositories.Neo4jRepositories.ServiceLineItemReadRepository.WasServiceLineItemInvoiced(ctx, common.GetTenantFromContext(ctx), serviceLineItemId)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error on checking if service line item was invoiced: %s", err.Error())
return false, err
}
if sliInvoiced {
err := fmt.Errorf("service line item with id {%s} is included in invoice and cannot be deleted", serviceLineItemId)
tracing.TraceErr(span, err)
s.log.Errorf(err.Error())
return false, err
}
// if contract is not draft prevent removing current or past SLIs
contractEntity, err := s.services.ContractService.GetContractByServiceLineItem(ctx, serviceLineItemId)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error on getting contract by service line item id {%s}: %s", serviceLineItemId, err.Error())
return false, err
}
if contractEntity.ContractStatus != neo4jenum.ContractStatusDraft && !sliEntity.StartedAt.After(utils.Today()) {
err = fmt.Errorf("cannot delete contract line item with id {%s} in the past", serviceLineItemId)
tracing.TraceErr(span, err)
return false, err
}
deleteRequest := servicelineitempb.DeleteServiceLineItemGrpcRequest{
Tenant: common.GetTenantFromContext(ctx),
Id: serviceLineItemId,
LoggedInUserId: common.GetUserIdFromContext(ctx),
AppSource: constants.AppSourceCustomerOsApi,
}
ctx = tracing.InjectSpanContextIntoGrpcMetadata(ctx, span)
_, err = utils.CallEventsPlatformGRPCWithRetry[*servicelineitempb.ServiceLineItemIdGrpcResponse](func() (*servicelineitempb.ServiceLineItemIdGrpcResponse, error) {
return s.grpcClients.ServiceLineItemClient.DeleteServiceLineItem(ctx, &deleteRequest)
})
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error from events processing: %s", err.Error())
return false, err
}
return false, nil
}
func (s *serviceLineItemService) Close(ctx context.Context, serviceLineItemId string, endedAt *time.Time) error {
span, ctx := opentracing.StartSpanFromContext(ctx, "ServiceLineItemService.Close")
defer span.Finish()
tracing.SetDefaultServiceSpanTags(ctx, span)
span.LogFields(log.String("serviceLineItemId", serviceLineItemId))
span.SetTag(tracing.SpanTagEntityId, serviceLineItemId)
contractEntity, err := s.services.ContractService.GetContractByServiceLineItem(ctx, serviceLineItemId)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error on getting contract by service line item id {%s}: %s", serviceLineItemId, err.Error())
return err
}
// if contract is draft - delete SLI
if contractEntity.IsDraft() {
_, err = s.Delete(ctx, serviceLineItemId)
return err
}
sliEntity, err := s.services.CommonServices.ServiceLineItemService.GetById(ctx, serviceLineItemId)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error on getting service line item by id {%s}: %s", serviceLineItemId, err.Error())
return err
}
// Future SLI to be deleted
if sliEntity.StartedAt.After(utils.Today()) {
_, err = s.Delete(ctx, serviceLineItemId)
return err
}
// closing past SLIs not allowed
if sliEntity.EndedAt != nil && sliEntity.EndedAt.Before(utils.Today()) {
err = fmt.Errorf("cannot close contract line item with id {%s} in the past", serviceLineItemId)
tracing.TraceErr(span, err)
return err
}
// First remove any future SLI
sliEntities, err := s.services.CommonServices.ServiceLineItemService.GetServiceLineItemsForContract(ctx, contractEntity.Id)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error on getting service line items for contract {%s}: %s", contractEntity.Id, err.Error())
return err
}
for _, sli := range *sliEntities {
if sli.StartedAt.After(utils.Today()) {
_, err = s.Delete(ctx, sli.ID)
if err != nil {
return err
}
}
}
closeRequest := servicelineitempb.CloseServiceLineItemGrpcRequest{
Tenant: common.GetTenantFromContext(ctx),
Id: serviceLineItemId,
LoggedInUserId: common.GetUserIdFromContext(ctx),
AppSource: constants.AppSourceCustomerOsApi,
EndedAt: utils.ConvertTimeToTimestampPtr(endedAt),
}
ctx = tracing.InjectSpanContextIntoGrpcMetadata(ctx, span)
_, err = utils.CallEventsPlatformGRPCWithRetry[*servicelineitempb.ServiceLineItemIdGrpcResponse](func() (*servicelineitempb.ServiceLineItemIdGrpcResponse, error) {
return s.grpcClients.ServiceLineItemClient.CloseServiceLineItem(ctx, &closeRequest)
})
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error from events processing: %s", err.Error())
return err
}
return nil
}
type ServiceLineItemDetails struct {
Id string
Name string
Price float64
Quantity int64
Billed neo4jenum.BilledType
Comments string
IsRetroactiveCorrection bool
VatRate float64
StartedAt *time.Time
CloseVersion bool
NewVersion bool
}
func (s *serviceLineItemService) CreateOrUpdateOrCloseInBulk(ctx context.Context, contractId string, sliBulkData []*ServiceLineItemDetails) ([]string, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ServiceLineItemService.CreateOrUpdateOrCloseInBulk")
defer span.Finish()
tracing.SetDefaultServiceSpanTags(ctx, span)
span.LogFields(log.String("contractId", contractId))
var responseIds []string
for _, serviceLineItem := range sliBulkData {
// check all quantity or price are not negative
if serviceLineItem.Quantity < 0 || serviceLineItem.Price < 0 {
err := fmt.Errorf("quantity and price must not be negative")
tracing.TraceErr(span, err)
return []string{}, err
}
}
for _, serviceLineItem := range sliBulkData {
if serviceLineItem.Id == "" {
itemId, err := s.Create(ctx, ServiceLineItemCreateData{
ContractId: contractId,
SliName: serviceLineItem.Name,
SliPrice: serviceLineItem.Price,
SliQuantity: serviceLineItem.Quantity,
SliBilledType: serviceLineItem.Billed,
SliVatRate: serviceLineItem.VatRate,
Source: neo4jentity.DataSourceOpenline,
AppSource: constants.AppSourceCustomerOsApi,
StartedAt: serviceLineItem.StartedAt,
})
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error from events processing: %s", err.Error())
return []string{}, err
}
responseIds = append(responseIds, itemId)
} else if serviceLineItem.CloseVersion {
err := s.Close(ctx, serviceLineItem.Id, nil)
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Failed to close service line item: %s", err.Error())
}
} else {
if serviceLineItem.NewVersion {
itemId, err := s.NewVersion(ctx, ServiceLineItemNewVersionData{
Id: serviceLineItem.Id,
Name: serviceLineItem.Name,
Price: serviceLineItem.Price,
Quantity: serviceLineItem.Quantity,
Comments: serviceLineItem.Comments,
Source: neo4jentity.DataSourceOpenline,
AppSource: constants.AppSourceCustomerOsApi,
VatRate: serviceLineItem.VatRate,
StartedAt: serviceLineItem.StartedAt,
})
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error from events processing: %s", err.Error())
return []string{}, err
}
responseIds = append(responseIds, itemId)
} else {
err := s.Update(ctx, ServiceLineItemUpdateData{
Id: serviceLineItem.Id,
IsRetroactiveCorrection: serviceLineItem.IsRetroactiveCorrection,
SliName: serviceLineItem.Name,
SliPrice: serviceLineItem.Price,
SliQuantity: serviceLineItem.Quantity,
SliBilledType: serviceLineItem.Billed,
SliComments: serviceLineItem.Comments,
SliVatRate: serviceLineItem.VatRate,
Source: neo4jentity.DataSourceOpenline,
AppSource: constants.AppSourceCustomerOsApi,
StartedAt: serviceLineItem.StartedAt,
})
if err != nil {
tracing.TraceErr(span, err)
s.log.Errorf("Error from events processing: %s", err.Error())
return []string{}, err
}
responseIds = append(responseIds, serviceLineItem.Id)
}
}
}
return responseIds, nil
}
func MapServiceLineItemBulkItemsToData(input []*model.ServiceLineItemBulkUpdateItem) []*ServiceLineItemDetails {
var arr []*ServiceLineItemDetails
for _, item := range input {
sli := MapServiceLineItemBulkItemToData(item)
if sli != nil {
arr = append(arr, sli)
}
}
return arr
}
func MapServiceLineItemBulkItemToData(input *model.ServiceLineItemBulkUpdateItem) *ServiceLineItemDetails {
if input == nil {
return nil
}
billed := neo4jenum.BilledTypeNone
if input.Billed != nil {
billed = mapper.MapBilledTypeFromModel(*input.Billed)
}
return &ServiceLineItemDetails{
Id: utils.IfNotNilString(input.ServiceLineItemID),
Name: utils.IfNotNilString(input.Name),
Price: utils.IfNotNilFloat64(input.Price),
Quantity: utils.IfNotNilInt64(input.Quantity),
Billed: billed,
Comments: utils.IfNotNilString(input.Comments),
IsRetroactiveCorrection: utils.IfNotNilBool(input.IsRetroactiveCorrection),
VatRate: utils.IfNotNilFloat64(input.VatRate),
StartedAt: input.ServiceStarted,
CloseVersion: utils.IfNotNilBool(input.CloseVersion),
NewVersion: utils.IfNotNilBool(input.NewVersion),
}
}
func convertBilledTypeToProto(billedType neo4jenum.BilledType, span opentracing.Span) (commonpb.BilledType, error) {
switch billedType {
case neo4jenum.BilledTypeMonthly:
return commonpb.BilledType_MONTHLY_BILLED, nil
case neo4jenum.BilledTypeQuarterly:
return commonpb.BilledType_QUARTERLY_BILLED, nil
case neo4jenum.BilledTypeAnnually:
return commonpb.BilledType_ANNUALLY_BILLED, nil
case neo4jenum.BilledTypeOnce:
return commonpb.BilledType_ONCE_BILLED, nil
case neo4jenum.BilledTypeUsage:
return commonpb.BilledType_USAGE_BILLED, nil
case neo4jenum.BilledTypeNone:
err := fmt.Errorf("billed type is not set")
tracing.TraceErr(span, err)
return commonpb.BilledType_NONE_BILLED, err
default:
err := fmt.Errorf("unknown billed type: %s", billedType)
tracing.TraceErr(span, err)
return commonpb.BilledType_NONE_BILLED, err
}
}