-
Notifications
You must be signed in to change notification settings - Fork 12
/
contract_read_repository.go
615 lines (547 loc) · 25.1 KB
/
contract_read_repository.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
package repository
import (
"fmt"
"github.com/neo4j/neo4j-go-driver/v5/neo4j"
"github.com/neo4j/neo4j-go-driver/v5/neo4j/db"
"github.com/neo4j/neo4j-go-driver/v5/neo4j/dbtype"
"github.com/openline-ai/openline-customer-os/packages/server/customer-os-common-module/utils"
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/tracing"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/log"
"golang.org/x/net/context"
"time"
)
type TenantAndContractId struct {
Tenant string
ContractId string
}
type ContractReadRepository interface {
GetContractById(ctx context.Context, tenant, contractId string) (*dbtype.Node, error)
GetContractByServiceLineItemId(ctx context.Context, tenant, serviceLineItemId string) (*dbtype.Node, error)
GetContractByOpportunityId(ctx context.Context, tenant string, opportunityId string) (*dbtype.Node, error)
GetContractsForOrganizations(ctx context.Context, tenant string, organizationIds []string) ([]*utils.DbNodeAndId, error)
GetContractForInvoice(ctx context.Context, tenant string, invoiceId string) (*dbtype.Node, error)
GetContractsForInvoices(ctx context.Context, tenant string, invoiceIds []string) ([]*utils.DbNodeAndId, error)
TenantsHasAtLeastOneContract(ctx context.Context, tenant string) (bool, error)
CountContracts(ctx context.Context, tenant string) (int64, error)
GetContractsToGenerateCycleInvoices(ctx context.Context, referenceTime time.Time, delayMinutes, limit int) ([]*utils.DbNodeAndTenant, error)
GetContractsToGenerateOffCycleInvoices(ctx context.Context, referenceTime time.Time, delayMinutes, limit int) ([]*utils.DbNodeAndTenant, error)
GetContractsToGenerateNextScheduledInvoices(ctx context.Context, referenceTime time.Time, delayMinutes int) ([]*utils.DbNodeAndTenant, error)
GetContractsForStatusRenewal(ctx context.Context, referenceTime time.Time, limit int) ([]TenantAndContractId, error)
GetContractsForRenewalRollout(ctx context.Context, referenceTime time.Time, limit int) ([]TenantAndContractId, error)
IsContractInvoiced(ctx context.Context, tenant, contractId string) (bool, error)
}
type contractReadRepository struct {
driver *neo4j.DriverWithContext
database string
}
func NewContractReadRepository(driver *neo4j.DriverWithContext, database string) ContractReadRepository {
return &contractReadRepository{
driver: driver,
database: database,
}
}
func (r *contractReadRepository) prepareReadSession(ctx context.Context) neo4j.SessionWithContext {
return utils.NewNeo4jReadSession(ctx, *r.driver, utils.WithDatabaseName(r.database))
}
func (r *contractReadRepository) GetContractById(ctx context.Context, tenant, contractId string) (*dbtype.Node, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractReadRepository.GetContractById")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, tenant)
span.SetTag(tracing.SpanTagEntityId, contractId)
span.LogFields(log.String("contractId", contractId))
cypher := `MATCH (:Tenant {name:$tenant})<-[:CONTRACT_BELONGS_TO_TENANT]-(c:Contract {id:$id}) RETURN c`
params := map[string]any{
"tenant": tenant,
"id": contractId,
}
span.LogFields(log.String("cypher", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := r.prepareReadSession(ctx)
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
queryResult, err := tx.Run(ctx, cypher, params)
return utils.ExtractSingleRecordFirstValueAsNode(ctx, queryResult, err)
})
if err != nil {
span.LogFields(log.Bool("result.found", false))
tracing.TraceErr(span, err)
return nil, err
}
span.LogFields(log.Bool("result.found", result != nil))
return result.(*dbtype.Node), nil
}
func (r *contractReadRepository) GetContractByServiceLineItemId(ctx context.Context, tenant string, serviceLineItemId string) (*dbtype.Node, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractReadRepository.GetContractByServiceLineItemId")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, tenant)
span.LogFields(log.String("serviceLineItemId", serviceLineItemId))
cypher := `MATCH (sli:ServiceLineItem {id:$id})<-[:HAS_SERVICE]-(c:Contract)-[:CONTRACT_BELONGS_TO_TENANT]->(:Tenant {name:$tenant}) RETURN c LIMIT 1`
params := map[string]any{
"id": serviceLineItemId,
"tenant": tenant,
}
span.LogFields(log.String("cypher", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := r.prepareReadSession(ctx)
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
queryResult, err := tx.Run(ctx, cypher, params)
return utils.ExtractAllRecordsFirstValueAsDbNodePtrs(ctx, queryResult, err)
})
if err != nil {
tracing.TraceErr(span, err)
return nil, err
}
records := result.([]*dbtype.Node)
span.LogFields(log.Int("result.count", len(records)))
if len(records) == 0 {
return nil, nil
} else {
return records[0], nil
}
}
func (r *contractReadRepository) GetContractByOpportunityId(ctx context.Context, tenant string, opportunityId string) (*dbtype.Node, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractReadRepository.GetContractByOpportunityId")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, tenant)
span.LogFields(log.String("opportunityId", opportunityId))
cypher := fmt.Sprintf(`MATCH (:Opportunity {id:$id})<-[:HAS_OPPORTUNITY]-(c:Contract:Contract_%s)-[:CONTRACT_BELONGS_TO_TENANT]->(:Tenant {name:$tenant}) RETURN c LIMIT 1`, tenant)
params := map[string]any{
"id": opportunityId,
"tenant": tenant,
}
span.LogFields(log.String("cypher", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := utils.NewNeo4jReadSession(ctx, *r.driver, utils.WithDatabaseName(r.database))
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
queryResult, err := tx.Run(ctx, cypher, params)
return utils.ExtractAllRecordsFirstValueAsDbNodePtrs(ctx, queryResult, err)
})
if err != nil {
tracing.TraceErr(span, err)
return nil, err
}
records := result.([]*dbtype.Node)
span.LogFields(log.Int("result.count", len(records)))
if len(records) == 0 {
return nil, nil
} else {
return records[0], nil
}
}
func (r *contractReadRepository) GetContractsForOrganizations(ctx context.Context, tenant string, organizationIds []string) ([]*utils.DbNodeAndId, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractReadRepository.GetContractsForOrganizations")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, tenant)
cypher := `MATCH (t:Tenant {name:$tenant})<-[:ORGANIZATION_BELONGS_TO_TENANT]-(o:Organization)-[:HAS_CONTRACT]->(contract:Contract)-[:CONTRACT_BELONGS_TO_TENANT]->(t)
WHERE o.id IN $organizationIds
RETURN contract, o.id ORDER BY contract.createdAt DESC`
params := map[string]any{
"tenant": tenant,
"organizationIds": organizationIds,
}
span.LogFields(log.String("cypher", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := r.prepareReadSession(ctx)
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
queryResult, err := tx.Run(ctx, cypher, params)
return utils.ExtractAllRecordsAsDbNodeAndId(ctx, queryResult, err)
})
if err != nil {
tracing.TraceErr(span, err)
return nil, err
}
span.LogFields(log.Int("result.count", len(result.([]*utils.DbNodeAndId))))
return result.([]*utils.DbNodeAndId), err
}
func (r *contractReadRepository) GetContractForInvoice(ctx context.Context, tenant string, invoiceId string) (*dbtype.Node, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractReadRepository.GetContractForInvoice")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, tenant)
cypher := fmt.Sprintf(`MATCH (:Tenant {name:$tenant})<-[:CONTRACT_BELONGS_TO_TENANT]-(c:Contract)-[:HAS_INVOICE]->(i:Invoice_%s)
WHERE i.id = $invoiceId
RETURN c`, tenant)
params := map[string]any{
"tenant": tenant,
"invoiceId": invoiceId,
}
span.LogFields(log.String("cypher", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := r.prepareReadSession(ctx)
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
queryResult, err := tx.Run(ctx, cypher, params)
return utils.ExtractAllRecordsFirstValueAsDbNodePtrs(ctx, queryResult, err)
})
if err != nil {
tracing.TraceErr(span, err)
return nil, err
}
records := result.([]*dbtype.Node)
span.LogFields(log.Int("result.count", len(records)))
if len(records) == 0 {
return nil, nil
} else {
return records[0], nil
}
}
func (r *contractReadRepository) GetContractsForInvoices(ctx context.Context, tenant string, invoiceIds []string) ([]*utils.DbNodeAndId, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractReadRepository.GetContractsForInvoices")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, tenant)
cypher := fmt.Sprintf(`MATCH (:Tenant {name:$tenant})<-[:CONTRACT_BELONGS_TO_TENANT]-(c:Contract)-[:HAS_INVOICE]->(i:Invoice_%s)
WHERE i.id IN $invoiceIds
RETURN c, i.id`, tenant)
params := map[string]any{
"tenant": tenant,
"invoiceIds": invoiceIds,
}
span.LogFields(log.String("cypher", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := r.prepareReadSession(ctx)
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
queryResult, err := tx.Run(ctx, cypher, params)
return utils.ExtractAllRecordsAsDbNodeAndId(ctx, queryResult, err)
})
if err != nil {
tracing.TraceErr(span, err)
return nil, err
}
span.LogFields(log.Int("result.count", len(result.([]*utils.DbNodeAndId))))
return result.([]*utils.DbNodeAndId), err
}
func (r *contractReadRepository) TenantsHasAtLeastOneContract(ctx context.Context, tenant string) (bool, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractReadRepository.TenantsHasAtLeastOneContract")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, tenant)
cypher := `MATCH (c:Contract)-[:CONTRACT_BELONGS_TO_TENANT]->(:Tenant{name:$tenant}) RETURN count(c) > 0`
params := map[string]any{
"tenant": tenant,
}
span.LogFields(log.String("cypher", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := r.prepareReadSession(ctx)
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
if queryResult, err := tx.Run(ctx, cypher, params); err != nil {
return false, err
} else {
return utils.ExtractSingleRecordFirstValueAsType[bool](ctx, queryResult, err)
}
})
if err != nil {
tracing.TraceErr(span, err)
return false, err
}
span.LogFields(log.Bool("result", result.(bool)))
return result.(bool), err
}
func (r *contractReadRepository) CountContracts(ctx context.Context, tenant string) (int64, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractRepository.CountContracts")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, tenant)
cypher := `MATCH (c:Contract)-[:CONTRACT_BELONGS_TO_TENANT]->(:Tenant {name:$tenant})MATCH (c)-[:ACTIVE_RENEWAL]->(op:Opportunity)
RETURN count(c)`
params := map[string]any{
"tenant": tenant,
}
span.LogFields(log.String("query", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := utils.NewNeo4jReadSession(ctx, *r.driver)
defer session.Close(ctx)
dbRecord, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
if queryResult, err := tx.Run(ctx, cypher, params); err != nil {
return nil, err
} else {
return queryResult.Single(ctx)
}
})
if err != nil {
return 0, err
}
contractsCount := dbRecord.(*db.Record).Values[0].(int64)
span.LogFields(log.Int64("result - contractsCount", contractsCount))
return contractsCount, nil
}
func (r *contractReadRepository) GetContractsToGenerateCycleInvoices(ctx context.Context, referenceTime time.Time, delayMinutes, limit int) ([]*utils.DbNodeAndTenant, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractReadRepository.GetContractsToGenerateCycleInvoices")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, "")
span.LogFields(log.Object("referenceTime", referenceTime), log.Int("delayMinutes", delayMinutes), log.Int("limit", limit))
cypher := `MATCH (ts:TenantSettings)<-[:HAS_SETTINGS]-(t:Tenant)<-[:ORGANIZATION_BELONGS_TO_TENANT]-(o:Organization)-[:HAS_CONTRACT]->(c:Contract)-[:HAS_SERVICE]->(:ServiceLineItem)
WHERE
ts.invoicingEnabled = true AND
(c.invoicingEnabled = true OR c.invoicingEnabled IS NULL) AND
(o.hide = false OR o.hide IS NULL) AND
(c.currency <> "" OR ts.baseCurrency <> "" ) AND
c.organizationLegalName IS NOT NULL AND
c.organizationLegalName <> "" AND
c.invoiceEmail IS NOT NULL AND
c.invoiceEmail <> "" AND
c.billingCycleInMonths > 0 AND
c.status IN $validContractStatuses AND
(c.nextInvoiceDate IS NULL OR date(c.nextInvoiceDate) <= date($referenceTime)) AND
(date(c.invoicingStartDate) <= date($referenceTime)) AND
(c.endedAt IS NULL OR date(c.endedAt) > date(coalesce(c.nextInvoiceDate, c.invoicingStartDate))) AND
(c.techInvoicingStartedAt IS NULL OR c.techInvoicingStartedAt + duration({minutes: $delayMinutes}) < $referenceTime)
RETURN distinct(c), t.name limit $limit`
params := map[string]any{
"referenceTime": referenceTime,
"validContractStatuses": []string{neo4jenum.ContractStatusLive.String()},
"delayMinutes": delayMinutes,
"limit": limit,
}
span.LogFields(log.String("query", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := utils.NewNeo4jReadSession(ctx, *r.driver)
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
queryResult, err := tx.Run(ctx, cypher, params)
if err != nil {
return nil, err
}
return utils.ExtractAllRecordsAsDbNodeAndTenant(ctx, queryResult, err)
})
if err != nil {
tracing.TraceErr(span, err)
return nil, err
}
span.LogFields(log.Int("result.count", len(result.([]*utils.DbNodeAndTenant))))
return result.([]*utils.DbNodeAndTenant), err
}
func (r *contractReadRepository) GetContractsToGenerateOffCycleInvoices(ctx context.Context, referenceTime time.Time, delayMinutes, limit int) ([]*utils.DbNodeAndTenant, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractReadRepository.GetContractsToGenerateOffCycleInvoices")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, "")
span.LogFields(log.Object("referenceTime", referenceTime), log.Int("delayMinutes", delayMinutes), log.Int("limit", limit))
cypher := `MATCH (ts:TenantSettings)<-[:HAS_SETTINGS]-(t:Tenant)<-[:ORGANIZATION_BELONGS_TO_TENANT]-(o:Organization)-[:HAS_CONTRACT]->(c:Contract)-[:HAS_SERVICE]->(sli:ServiceLineItem)
WHERE
ts.invoicingEnabled = true AND
(ts.invoicingPostpaid = false OR ts.invoicingPostpaid IS NULL) AND
(c.invoicingEnabled = true OR c.invoicingEnabled IS NULL) AND
(o.hide = false OR o.hide IS NULL) AND
(c.currency <> "" OR ts.baseCurrency <> "") AND
c.organizationLegalName IS NOT NULL AND
c.organizationLegalName <> "" AND
c.invoiceEmail IS NOT NULL AND
c.invoiceEmail <> "" AND
c.billingCycleInMonths > 0 AND
c.status IN $validContractStatuses AND
c.nextInvoiceDate IS NOT NULL AND
(c.endedAt IS NULL OR date(c.endedAt) > date($referenceTime)) AND
NOT EXISTS((sli)<-[:INVOICED]-(:InvoiceLine)--(:Invoice {dryRun:false})) AND
date(sli.startedAt) + duration({days: 1}) < date(c.nextInvoiceDate) AND
date(sli.startedAt) < date($referenceTime) AND
(sli.isCanceled = false OR sli.isCanceled IS NULL) AND
(c.techOffCycleInvoicingStartedAt IS NULL OR date(c.techOffCycleInvoicingStartedAt) < date($referenceTime) OR c.techOffCycleInvoicingStartedAt + duration({minutes: $delayMinutes}) < $referenceTime)
WITH c, sli, t
OPTIONAL MATCH (c)-[:HAS_SERVICE]->(invoicedSli:ServiceLineItem)<-[:INVOICED]-(il:InvoiceLine)
WHERE EXISTS((invoicedSli)<-[:INVOICED]-(il)--(:Invoice {dryRun:false}))
WITH c, sli, t, invoicedSli
ORDER BY c, sli, invoicedSli.startedAt DESC
WITH c, sli, t, head(collect(invoicedSli)) as lastInvoicedSli
WHERE lastInvoicedSli IS NULL OR date(lastInvoicedSli.startedAt) < date(sli.startedAt)
RETURN distinct(c), t.name limit $limit`
params := map[string]any{
"referenceTime": referenceTime,
"validContractStatuses": []string{neo4jenum.ContractStatusLive.String()},
"delayMinutes": delayMinutes,
"limit": limit,
}
span.LogFields(log.String("query", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := utils.NewNeo4jReadSession(ctx, *r.driver)
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
queryResult, err := tx.Run(ctx, cypher, params)
if err != nil {
return nil, err
}
return utils.ExtractAllRecordsAsDbNodeAndTenant(ctx, queryResult, err)
})
if err != nil {
tracing.TraceErr(span, err)
return nil, err
}
span.LogFields(log.Int("result.count", len(result.([]*utils.DbNodeAndTenant))))
return result.([]*utils.DbNodeAndTenant), err
}
func (r *contractReadRepository) GetContractsToGenerateNextScheduledInvoices(ctx context.Context, referenceTime time.Time, delayMinutes int) ([]*utils.DbNodeAndTenant, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractReadRepository.GetContractsToGenerateNextScheduledInvoices")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, "")
span.LogFields(log.Object("referenceTime", referenceTime), log.Int("delayMinutes", delayMinutes))
cypher := `MATCH (ts:TenantSettings)<-[:HAS_SETTINGS]-(t:Tenant)<-[:ORGANIZATION_BELONGS_TO_TENANT]-(o:Organization)-[:HAS_CONTRACT]->(c:Contract)-[:HAS_SERVICE]->(sli:ServiceLineItem)
OPTIONAL MATCH (c)-[:HAS_INVOICE]->(i:Invoice {dryRun: true, preview: true})
WITH c, t, ts, o, i
WHERE
(i IS NULL OR i.createdAt < c.updatedAt OR i.createdAt < sli.updatedAt) AND
ts.invoicingEnabled = true AND
(c.invoicingEnabled = true OR c.invoicingEnabled IS NULL) AND
(o.hide = false OR o.hide IS NULL) AND
(c.currency <> "" OR ts.baseCurrency <> "" ) AND
c.organizationLegalName IS NOT NULL AND
c.organizationLegalName <> "" AND
c.invoiceEmail IS NOT NULL AND
c.invoiceEmail <> "" AND
c.billingCycleInMonths > 0 AND
c.status IN $validContractStatuses AND
(NOT c.invoicingStartDate IS NULL OR NOT c.nextInvoiceDate IS NULL) AND
(c.endedAt IS NULL OR date(c.endedAt) > date(coalesce(c.nextInvoiceDate, c.invoicingStartDate))) AND
(c.techNextPreviewInvoiceRequestedAt IS NULL OR c.techNextPreviewInvoiceRequestedAt + duration({minutes: $delayMinutes}) < $referenceTime)
RETURN distinct(c), t.name limit 100`
params := map[string]any{
"referenceTime": referenceTime,
"validContractStatuses": []string{neo4jenum.ContractStatusLive.String(),
neo4jenum.ContractStatusOutOfContract.String(),
neo4jenum.ContractStatusScheduled.String(),
neo4jenum.ContractStatusDraft.String()},
"delayMinutes": delayMinutes,
}
span.LogFields(log.String("query", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := utils.NewNeo4jReadSession(ctx, *r.driver)
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
queryResult, err := tx.Run(ctx, cypher, params)
if err != nil {
return nil, err
}
return utils.ExtractAllRecordsAsDbNodeAndTenant(ctx, queryResult, err)
})
if err != nil {
tracing.TraceErr(span, err)
return nil, err
}
span.LogFields(log.Int("result.count", len(result.([]*utils.DbNodeAndTenant))))
return result.([]*utils.DbNodeAndTenant), err
}
func (r *contractReadRepository) GetContractsForStatusRenewal(ctx context.Context, referenceTime time.Time, limit int) ([]TenantAndContractId, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractRepository.GetContractsForStatusRenewal")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, "")
span.LogFields(log.Object("referenceTime", referenceTime), log.Int("limit", limit))
cypher := `MATCH (t:Tenant)<-[:CONTRACT_BELONGS_TO_TENANT]-(c:Contract)
WHERE c.techStatusRenewalRequestedAt IS NULL OR c.techStatusRenewalRequestedAt + duration({hours: 2}) < $referenceTime
OPTIONAL MATCH (c)-[:ACTIVE_RENEWAL]->(op:RenewalOpportunity)
WITH t, c, op.renewedAt as renewedAt
WHERE (c.status <> $endedStatus AND c.endedAt < $referenceTime) OR
((c.endedAt IS NULL OR c.endedAt > $referenceTime) AND
(
(c.status in [$scheduledStatus, $endedStatus] AND c.serviceStartedAt < $referenceTime) OR
(c.status = $outOfContractStatus AND (c.autoRenew = true OR renewedAt > $referenceTime)) OR
(c.status = $outOfContractStatus AND renewedAt > $referenceTime) OR
(c.status = $liveStatus AND c.autoRenew = false AND renewedAt < $referenceTime) OR
(c.status = $draftStatus AND c.approved = true)
))
RETURN t.name, c.id LIMIT $limit`
params := map[string]any{
"referenceTime": referenceTime,
"endedStatus": neo4jenum.ContractStatusEnded,
"liveStatus": neo4jenum.ContractStatusLive,
"scheduledStatus": neo4jenum.ContractStatusScheduled,
"outOfContractStatus": neo4jenum.ContractStatusOutOfContract,
"draftStatus": neo4jenum.ContractStatusDraft,
"limit": limit,
}
span.LogFields(log.String("cypher", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := r.prepareReadSession(ctx)
defer session.Close(ctx)
records, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
queryResult, err := tx.Run(ctx, cypher, params)
if err != nil {
return nil, err
}
return queryResult.Collect(ctx)
})
if err != nil {
return nil, err
}
output := make([]TenantAndContractId, 0)
for _, v := range records.([]*neo4j.Record) {
output = append(output,
TenantAndContractId{
Tenant: v.Values[0].(string),
ContractId: v.Values[1].(string),
})
}
span.LogFields(log.Int("result.count", len(output)))
return output, nil
}
func (r *contractReadRepository) GetContractsForRenewalRollout(ctx context.Context, referenceTime time.Time, limit int) ([]TenantAndContractId, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractRepository.GetContractsForStatusRenewal")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, "")
span.LogFields(log.Object("referenceTime", referenceTime), log.Int("limit", limit))
cypher := `MATCH (t:Tenant)<-[:CONTRACT_BELONGS_TO_TENANT]-(c:Contract),
(c)-[:ACTIVE_RENEWAL]->(op:RenewalOpportunity)
WHERE
(c.techRolloutRenewalRequestedAt IS NULL OR c.techRolloutRenewalRequestedAt + duration({hours: 2}) < $referenceTime) AND
date(op.renewedAt) <= date($referenceTime) AND
(c.autoRenew = true OR op.renewalApproved = true) AND
c.status IN [$liveStatus, $outOfContractStatus, $scheduledStatus]
RETURN t.name, c.id LIMIT $limit`
params := map[string]any{
"referenceTime": referenceTime,
"liveStatus": neo4jenum.ContractStatusLive.String(),
"outOfContractStatus": neo4jenum.ContractStatusOutOfContract.String(),
"scheduledStatus": neo4jenum.ContractStatusScheduled.String(),
"limit": limit,
}
span.LogFields(log.String("cypher", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := r.prepareReadSession(ctx)
defer session.Close(ctx)
records, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
queryResult, err := tx.Run(ctx, cypher, params)
if err != nil {
return nil, err
}
return queryResult.Collect(ctx)
})
if err != nil {
return nil, err
}
output := make([]TenantAndContractId, 0)
for _, v := range records.([]*neo4j.Record) {
output = append(output,
TenantAndContractId{
Tenant: v.Values[0].(string),
ContractId: v.Values[1].(string),
})
}
span.LogFields(log.Int("result.count", len(output)))
return output, nil
}
func (r *contractReadRepository) IsContractInvoiced(ctx context.Context, tenant, contractId string) (bool, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "ContractRepository.IsContractInvoiced")
defer span.Finish()
tracing.SetNeo4jRepositorySpanTags(span, tenant)
span.SetTag(tracing.SpanTagEntityId, contractId)
cypher := `MATCH (:Tenant {name:$tenant})<-[:CONTRACT_BELONGS_TO_TENANT]-(c:Contract {id:$contractId})-[:HAS_INVOICE]->(i:Invoice {dryRun:false})
RETURN count(i) > 0`
params := map[string]any{
"contractId": contractId,
"tenant": tenant,
}
span.LogFields(log.String("cypher", cypher))
tracing.LogObjectAsJson(span, "params", params)
session := r.prepareReadSession(ctx)
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (any, error) {
queryResult, err := tx.Run(ctx, cypher, params)
return utils.ExtractSingleRecordFirstValueAsType[bool](ctx, queryResult, err)
})
if err != nil {
tracing.TraceErr(span, err)
return false, err
}
span.LogFields(log.Bool("result", result.(bool)))
return result.(bool), err
}