/
ContiguousIntervalUsageInArrear.java
731 lines (620 loc) · 33 KB
/
ContiguousIntervalUsageInArrear.java
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
/*
* Copyright 2014-2016 Groupon, Inc
* Copyright 2014-2016 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.billing.invoice.usage;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
import org.joda.time.LocalDate;
import org.killbill.billing.callcontext.InternalTenantContext;
import org.killbill.billing.catalog.api.BillingMode;
import org.killbill.billing.catalog.api.CatalogApiException;
import org.killbill.billing.catalog.api.Currency;
import org.killbill.billing.catalog.api.Limit;
import org.killbill.billing.catalog.api.Tier;
import org.killbill.billing.catalog.api.TieredBlock;
import org.killbill.billing.catalog.api.Usage;
import org.killbill.billing.catalog.api.UsageType;
import org.killbill.billing.invoice.api.InvoiceItem;
import org.killbill.billing.invoice.api.InvoiceItemType;
import org.killbill.billing.invoice.generator.BillingIntervalDetail;
import org.killbill.billing.invoice.model.UsageInvoiceItem;
import org.killbill.billing.junction.BillingEvent;
import org.killbill.billing.usage.RawUsage;
import org.killbill.billing.usage.api.RolledUpUnit;
import org.killbill.billing.usage.api.RolledUpUsage;
import org.killbill.billing.util.config.definition.InvoiceConfig.UsageDetailMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import static org.killbill.billing.invoice.usage.UsageUtils.getCapacityInArrearTier;
import static org.killbill.billing.invoice.usage.UsageUtils.getCapacityInArrearUnitTypes;
import static org.killbill.billing.invoice.usage.UsageUtils.getConsumableInArrearTieredBlocks;
import static org.killbill.billing.invoice.usage.UsageUtils.getConsumableInArrearUnitTypes;
/**
* There is one such class per subscriptionId, matching a given in arrear/consumable usage section and
* referenced through a contiguous list of billing events.
*/
public class ContiguousIntervalUsageInArrear {
private static final Logger log = LoggerFactory.getLogger(ContiguousIntervalUsageInArrear.class);
private final List<LocalDate> transitionTimes;
private final List<BillingEvent> billingEvents;
private final Usage usage;
private final Set<String> unitTypes;
private final List<RawUsage> rawSubscriptionUsage;
private final LocalDate targetDate;
private final UUID accountId;
private final UUID invoiceId;
private final AtomicBoolean isBuilt;
private final LocalDate rawUsageStartDate;
private final InternalTenantContext internalTenantContext;
private final UsageDetailMode usageDetailMode;
private static final ObjectMapper objectMapper = new ObjectMapper();
public ContiguousIntervalUsageInArrear(final Usage usage,
final UUID accountId,
final UUID invoiceId,
final List<RawUsage> rawSubscriptionUsage,
final LocalDate targetDate,
final LocalDate rawUsageStartDate,
final UsageDetailMode usageDetailMode,
final InternalTenantContext internalTenantContext) {
this.usage = usage;
this.accountId = accountId;
this.invoiceId = invoiceId;
this.unitTypes = usage.getUsageType() == UsageType.CAPACITY ? getCapacityInArrearUnitTypes(usage) : getConsumableInArrearUnitTypes(usage);
this.rawSubscriptionUsage = rawSubscriptionUsage;
this.targetDate = targetDate;
this.rawUsageStartDate = rawUsageStartDate;
this.internalTenantContext = internalTenantContext;
this.billingEvents = Lists.newLinkedList();
this.transitionTimes = Lists.newLinkedList();
this.isBuilt = new AtomicBoolean(false);
this.usageDetailMode = usageDetailMode;
}
/**
* Builds the transitionTimes associated to that usage section. Those are determined based on billing events for when to start and when to stop,
* the per usage billingPeriod and finally the targetDate.
* <p/>
* Those transition dates define the well defined billing granularity periods that should be billed for that specific usage section.
*
* @param closedInterval whether there was a last billing event referencing the usage section or whether this is ongoing and
* then targetDate will define the endDate.
*/
public ContiguousIntervalUsageInArrear build(final boolean closedInterval) {
Preconditions.checkState(!isBuilt.get());
Preconditions.checkState((!closedInterval && billingEvents.size() >= 1) ||
(closedInterval && billingEvents.size() >= 2));
final LocalDate startDate = internalTenantContext.toLocalDate(billingEvents.get(0).getEffectiveDate());
if (targetDate.isBefore(startDate)) {
return this;
}
final LocalDate endDate = closedInterval ? internalTenantContext.toLocalDate(billingEvents.get(billingEvents.size() - 1).getEffectiveDate()) : targetDate;
final BillingIntervalDetail bid = new BillingIntervalDetail(startDate, endDate, targetDate, getBCD(), usage.getBillingPeriod(), usage.getBillingMode());
int numberOfPeriod = 0;
// First billingCycleDate prior startDate
LocalDate nextBillCycleDate = bid.getFutureBillingDateFor(numberOfPeriod);
if (startDate.compareTo(rawUsageStartDate) >= 0) {
transitionTimes.add(startDate);
}
while (!nextBillCycleDate.isAfter(endDate)) {
if (nextBillCycleDate.isAfter(startDate)) {
if (nextBillCycleDate.compareTo(rawUsageStartDate) >= 0) {
transitionTimes.add(nextBillCycleDate);
}
}
numberOfPeriod++;
nextBillCycleDate = bid.getFutureBillingDateFor(numberOfPeriod);
}
if (closedInterval &&
transitionTimes.size() > 0 &&
endDate.isAfter(transitionTimes.get(transitionTimes.size() - 1))) {
transitionTimes.add(endDate);
}
isBuilt.set(true);
return this;
}
/**
* Compute the missing usage invoice items based on what should be billed and what has been billed ($ amount comparison).
*
* @param existingUsage existing on disk usage items for the subscription
* @throws CatalogApiException
*/
public UsageInArrearItemsAndNextNotificationDate computeMissingItemsAndNextNotificationDate(final List<InvoiceItem> existingUsage) throws CatalogApiException {
Preconditions.checkState(isBuilt.get());
if (transitionTimes.size() < 2) {
return new UsageInArrearItemsAndNextNotificationDate(ImmutableList.<InvoiceItem>of(), computeNextNotificationDate());
}
final List<InvoiceItem> result = Lists.newLinkedList();
// We start by generating 'marker' USAGE items with $0 that will allow to correctly insert the next notification for when there is no USAGE to bill.
// Those will be removed by the invoicing code later so as to not end up with superfluous $0 items
LocalDate prevDate = null;
for (final LocalDate curDate : transitionTimes) {
if (prevDate != null) {
final InvoiceItem item = new UsageInvoiceItem(invoiceId, accountId, getBundleId(), getSubscriptionId(), getPlanName(),
getPhaseName(), usage.getName(), prevDate, curDate, BigDecimal.ZERO, getCurrency());
result.add(item);
}
prevDate = curDate;
}
final List<RolledUpUsage> allUsage = getRolledUpUsage();
for (final RolledUpUsage ru : allUsage) {
int tierNum = 1;
List<UsageInArrearDetail> toBeBilledUsageDetails = Lists.newLinkedList();
BigDecimal toBeBilledUsage = BigDecimal.ZERO;
if (usage.getUsageType() == UsageType.CAPACITY) {
toBeBilledUsageDetails.addAll(computeToBeBilledCapacityInArrear(ru.getRolledUpUnits(), tierNum));
} else /* UsageType.CONSUMABLE */{
// Compute total price amount that should be billed for that period of time (and usage section) across unitTypes.
for (final RolledUpUnit cur : ru.getRolledUpUnits()) {
if (!unitTypes.contains(cur.getUnitType())) {
log.warn("ContiguousIntervalConsumableInArrear is skipping unitType " + cur.getUnitType());
continue;
}
toBeBilledUsageDetails.addAll(computeToBeBilledConsumableInArrear(cur, tierNum++));
}
}
toBeBilledUsage = toBeBilledForUnit(toBeBilledUsageDetails);
// Retrieves current price amount billed for that period of time (and usage section)
final Iterable<InvoiceItem> billedItems = getBilledItems(ru.getStart(), ru.getEnd(), existingUsage);
final BigDecimal billedUsage = computeBilledUsage(billedItems);
// Compare the two and add the missing piece if required.
if (!billedItems.iterator().hasNext() || billedUsage.compareTo(toBeBilledUsage) < 0) {
toBeBilledUsageDetails = reconcileExistedBilledWithToBeBilled(billedItems, toBeBilledUsageDetails);
final BigDecimal amountToBill = toBeBilledForUnit(toBeBilledUsageDetails);
if (amountToBill.compareTo(BigDecimal.ZERO) > 0) {
if (UsageDetailMode.DETAIL == usageDetailMode){
for (UsageInArrearDetail toBeBilledUsageDetail : toBeBilledUsageDetails){
final InvoiceItem item = new UsageInvoiceItem(invoiceId, accountId, getBundleId(), getSubscriptionId(), getPlanName(),
getPhaseName(), usage.getName(), ru.getStart(), ru.getEnd(), toBeBilledUsageDetail.getAmount(), toBeBilledUsageDetail.getTierPrice(), getCurrency(),toBeBilledUsageDetail.getQuantity(),null);
result.add(item);
}
} else {
final InvoiceItem item = new UsageInvoiceItem(invoiceId, accountId, getBundleId(), getSubscriptionId(), getPlanName(),
getPhaseName(), usage.getName(), ru.getStart(), ru.getEnd(), amountToBill, null, getCurrency(),null, toJson(toBeBilledUsageDetails));
result.add(item);
}
}
}
}
final LocalDate nextNotificationdate = computeNextNotificationDate();
return new UsageInArrearItemsAndNextNotificationDate(result, nextNotificationdate);
}
private LocalDate computeNextNotificationDate() {
LocalDate result = null;
final Iterator<BillingEvent> eventIt = billingEvents.iterator();
BillingEvent nextEvent = eventIt.next();
while (eventIt.hasNext()) {
final BillingEvent thisEvent = nextEvent;
nextEvent = eventIt.next();
final LocalDate startDate = internalTenantContext.toLocalDate(thisEvent.getEffectiveDate());
final LocalDate endDate = internalTenantContext.toLocalDate(nextEvent.getEffectiveDate());
final BillingIntervalDetail bid = new BillingIntervalDetail(startDate, endDate, targetDate, thisEvent.getBillCycleDayLocal(), usage.getBillingPeriod(), BillingMode.IN_ARREAR);
final LocalDate nextBillingCycleDate = bid.getNextBillingCycleDate();
result = (result == null || result.compareTo(nextBillingCycleDate) < 0) ? nextBillingCycleDate : result;
}
final LocalDate startDate = internalTenantContext.toLocalDate(nextEvent.getEffectiveDate());
final BillingIntervalDetail bid = new BillingIntervalDetail(startDate, null, targetDate, nextEvent.getBillCycleDayLocal(), usage.getBillingPeriod(), BillingMode.IN_ARREAR);
final LocalDate nextBillingCycleDate = bid.getNextBillingCycleDate();
result = (result == null || result.compareTo(nextBillingCycleDate) < 0) ? nextBillingCycleDate : result;
return result;
}
@VisibleForTesting
List<RolledUpUsage> getRolledUpUsage() {
final Iterator<RawUsage> rawUsageIterator = rawSubscriptionUsage.iterator();
if (!rawUsageIterator.hasNext()) {
return ImmutableList.of();
}
final List<RolledUpUsage> result = new ArrayList<RolledUpUsage>();
//
// Skip all items before our first transition date
//
// prevRawUsage keeps track of first unconsumed raw usage element
RawUsage prevRawUsage = null;
while (rawUsageIterator.hasNext()) {
final RawUsage curRawUsage = rawUsageIterator.next();
if (curRawUsage.getDate().compareTo(transitionTimes.get(0)) >= 0) {
prevRawUsage = curRawUsage;
break;
}
}
// Optimize path where all raw usage items are outside or our transitionTimes range
if (prevRawUsage.getDate().compareTo(transitionTimes.get(transitionTimes.size() - 1)) >= 0) {
return ImmutableList.of();
}
//
// Loop through each interval [prevDate, curDate) and consume as many rawSubscriptionUsage elements within that range
// to create one RolledUpUsage per interval. If an interval does not have any rawSubscriptionUsage element, there will be no
// matching RolledUpUsage for that interval, and we'll detect that in the 'computeMissingItems' logic
//
LocalDate prevDate = null;
for (final LocalDate curDate : transitionTimes) {
if (prevDate != null) {
// Allocate new perRangeUnitToAmount for this interval and populate with rawSubscriptionUsage items
final Map<String, Long> perRangeUnitToAmount = new HashMap<String, Long>();
// Start consuming prevRawUsage element if it exists and falls into the range
if (prevRawUsage != null) {
if (prevRawUsage.getDate().compareTo(prevDate) >= 0 && prevRawUsage.getDate().compareTo(curDate) < 0) {
final Long currentAmount = perRangeUnitToAmount.get(prevRawUsage.getUnitType());
final Long updatedAmount = computeUpdatedAmount(currentAmount, prevRawUsage.getAmount());
perRangeUnitToAmount.put(prevRawUsage.getUnitType(), updatedAmount);
prevRawUsage = null;
}
}
//
// If prevRawUsage != null it means that our first and current rawSubscriptionUsage does not fall into that interval; we can't
// just 'continue' as we need to correctly set next 'prevDate'
// If prevRawUsage == null, then consume as much as we can for that interval. Note that the stop condition requires consuming
// one additional element which will become the prevRawUsage for the next interval.
//
if (prevRawUsage == null) {
while (rawUsageIterator.hasNext()) {
final RawUsage curRawUsage = rawUsageIterator.next();
if (curRawUsage.getDate().compareTo(curDate) >= 0) {
prevRawUsage = curRawUsage;
break;
}
final Long currentAmount = perRangeUnitToAmount.get(curRawUsage.getUnitType());
final Long updatedAmount = computeUpdatedAmount(currentAmount, curRawUsage.getAmount());
perRangeUnitToAmount.put(curRawUsage.getUnitType(), updatedAmount);
}
}
// If we did find some usage for that date range, let's populate the result
if (!perRangeUnitToAmount.isEmpty()) {
final List<RolledUpUnit> rolledUpUnits = new ArrayList<RolledUpUnit>(perRangeUnitToAmount.size());
for (final String unitType : perRangeUnitToAmount.keySet()) {
rolledUpUnits.add(new DefaultRolledUpUnit(unitType, perRangeUnitToAmount.get(unitType)));
}
result.add(new DefaultRolledUpUsage(getSubscriptionId(), prevDate, curDate, rolledUpUnits));
}
}
prevDate = curDate;
}
return result;
}
/**
* Based on usage type compute new amount
*
* @param currentAmount
* @param newAmount
* @return
*/
private Long computeUpdatedAmount(@Nullable Long currentAmount, @Nullable Long newAmount) {
currentAmount = currentAmount == null ? 0L : currentAmount;
newAmount = newAmount == null ? 0L : newAmount;
if (usage.getUsageType() == UsageType.CAPACITY) {
return Math.max(currentAmount, newAmount);
} else /* UsageType.CONSUMABLE */ {
return currentAmount + newAmount;
}
}
private Limit getTierLimit(final Tier tier, final String unitType) {
for (final Limit cur : tier.getLimits()) {
if (cur.getUnit().getName().equals(unitType)) {
return cur;
}
}
Preconditions.checkState(false, "Could not find unit type " + unitType + " in usage tier ");
return null;
}
/**
* @param roUnits the list of rolled up units for the period
* @return the price amount that should be billed for that period/unitType
* @throws CatalogApiException
*/
@VisibleForTesting
List<UsageInArrearDetail> computeToBeBilledCapacityInArrear(final List<RolledUpUnit> roUnits, int tierNum) throws CatalogApiException {
Preconditions.checkState(isBuilt.get());
final List<Tier> tiers = getCapacityInArrearTier(usage);
for (final Tier cur : tiers) {
List<UsageInArrearDetail> toBeBilledDetails = Lists.newLinkedList();
boolean complies = true;
for (final RolledUpUnit ro : roUnits) {
final Limit tierLimit = getTierLimit(cur, ro.getUnitType());
// We ignore the min and only look at the max Limit as the tiers should be contiguous.
// Specifying a -1 value for last max tier will make the validation works
if (tierLimit.getMax() != (double) -1 && ro.getAmount().doubleValue() > tierLimit.getMax()) {
complies = false;
break;
}
toBeBilledDetails.add(new UsageInArrearDetail(tierNum++, ro.getUnitType(), cur.getRecurringPrice().getPrice(getCurrency()), ro.getAmount().intValue(), BigDecimal.ZERO, null, null));
}
if (complies) {
toBeBilledDetails.get(toBeBilledDetails.size() - 1).setAmount(cur.getRecurringPrice().getPrice(getCurrency()));
return toBeBilledDetails;
}
}
// Probably invalid catalog config
final Joiner joiner = Joiner.on(", ");
joiner.join(roUnits);
Preconditions.checkState(false, "Could not find tier for usage " + usage.getName()+ "matching with data = " + joiner.join(roUnits));
return null;
}
/**
* @param roUnit the rolled up unit for the period
* @return the price amount that should be billed for that period/unitType
* @throws CatalogApiException
*/
@VisibleForTesting
List<UsageInArrearDetail> computeToBeBilledConsumableInArrear(final RolledUpUnit roUnit, int tierNum) throws CatalogApiException {
Preconditions.checkState(isBuilt.get());
final List<TieredBlock> tieredBlocks = getConsumableInArrearTieredBlocks(usage, roUnit.getUnitType());
switch (usage.getTierBlockPolicy()) {
case ALL_TIERS:
return computeToBeBilledConsumableInArrearWith_ALL_TIERS(tieredBlocks, roUnit.getAmount(), tierNum);
case TOP_TIER:
return Arrays.asList(computeToBeBilledConsumableInArrearWith_TOP_TIER(tieredBlocks, roUnit.getAmount(), tierNum));
default:
throw new IllegalStateException("Unknown TierBlockPolicy " + usage.getTierBlockPolicy());
}
}
List<UsageInArrearDetail> computeToBeBilledConsumableInArrearWith_ALL_TIERS(final List<TieredBlock> tieredBlocks, final Long units, int tierNum) throws CatalogApiException {
List<UsageInArrearDetail> toBeBilledDetails = Lists.newLinkedList();
BigDecimal result = BigDecimal.ZERO;
int remainingUnits = units.intValue();
for (final TieredBlock tieredBlock : tieredBlocks) {
final int blockTierSize = tieredBlock.getSize().intValue();
final int tmp = remainingUnits / blockTierSize + (remainingUnits % blockTierSize == 0 ? 0 : 1);
final int nbUsedTierBlocks;
if (tmp > tieredBlock.getMax()) {
nbUsedTierBlocks = tieredBlock.getMax().intValue();
remainingUnits -= tieredBlock.getMax() * blockTierSize;
} else {
nbUsedTierBlocks = tmp;
remainingUnits = 0;
}
toBeBilledDetails.add(new UsageInArrearDetail(tierNum, tieredBlock.getUnit().getName(), tieredBlock.getPrice().getPrice(getCurrency()), nbUsedTierBlocks));
}
return toBeBilledDetails;
}
UsageInArrearDetail computeToBeBilledConsumableInArrearWith_TOP_TIER(final List<TieredBlock> tieredBlocks, final Long units, int tierNum) throws CatalogApiException {
int remainingUnits = units.intValue();
// By default last last tierBlock
TieredBlock targetBlock = tieredBlocks.get(tieredBlocks.size() - 1);
// Loop through all tier block
for (final TieredBlock tieredBlock : tieredBlocks) {
final int blockTierSize = tieredBlock.getSize().intValue();
final int tmp = remainingUnits / blockTierSize + (remainingUnits % blockTierSize == 0 ? 0 : 1);
if (tmp > tieredBlock.getMax()) {
remainingUnits -= tieredBlock.getMax() * blockTierSize;
} else {
targetBlock = tieredBlock;
break;
}
}
final int lastBlockTierSize = targetBlock.getSize().intValue();
final int nbBlocks = units.intValue() / lastBlockTierSize + (units.intValue() % lastBlockTierSize == 0 ? 0 : 1);
return new UsageInArrearDetail(tierNum, targetBlock.getUnit().getName(), targetBlock.getPrice().getPrice(getCurrency()), nbBlocks);
}
/**
* @param filteredUsageForInterval the list of invoiceItem to consider
* @return the price amount that was already billed for that period and usage section (across unitTypes)
*/
@VisibleForTesting
BigDecimal computeBilledUsage(final Iterable<InvoiceItem> filteredUsageForInterval) {
Preconditions.checkState(isBuilt.get());
BigDecimal billedAmount = BigDecimal.ZERO;
for (final InvoiceItem ii : filteredUsageForInterval) {
billedAmount = billedAmount.add(ii.getAmount());
}
// Return the billed $ amount (not the # of units)
return billedAmount;
}
Iterable<InvoiceItem> getBilledItems(final LocalDate startDate, final LocalDate endDate, final List<InvoiceItem> existingUsage) {
Preconditions.checkState(isBuilt.get());
return Iterables.filter(existingUsage, new Predicate<InvoiceItem>() {
@Override
public boolean apply(final InvoiceItem input) {
if (input.getInvoiceItemType() != InvoiceItemType.USAGE) {
return false;
}
// STEPH what happens if we discover usage period that overlap (one side or both side) the [startDate, endDate] interval
final UsageInvoiceItem usageInput = (UsageInvoiceItem) input;
return usageInput.getUsageName().equals(usage.getName()) &&
usageInput.getStartDate().compareTo(startDate) >= 0 &&
usageInput.getEndDate().compareTo(endDate) <= 0;
}
});
}
@VisibleForTesting
List<LocalDate> getTransitionTimes() {
return transitionTimes;
}
public void addBillingEvent(final BillingEvent event) {
Preconditions.checkState(!isBuilt.get());
billingEvents.add(event);
}
public Usage getUsage() {
return usage;
}
public int getBCD() {
return billingEvents.get(0).getBillCycleDayLocal();
}
public UUID getBundleId() {
return billingEvents.get(0).getSubscription().getBundleId();
}
public UUID getSubscriptionId() {
return billingEvents.get(0).getSubscription().getId();
}
// STEPH_USAGE planName/phaseName,BCD,... might not be correct if we changed plan but Usage section was exactly similar
public String getPlanName() {
return billingEvents.get(0).getPlan().getName();
}
public String getPhaseName() {
return billingEvents.get(0).getPlanPhase().getName();
}
public Currency getCurrency() {
return billingEvents.get(0).getCurrency();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ContiguousIntervalConsumableInArrear{");
sb.append("transitionTimes=").append(transitionTimes);
sb.append(", billingEvents=").append(billingEvents);
sb.append(", rawSubscriptionUsage=").append(rawSubscriptionUsage);
sb.append(", rawUsageStartDate=").append(rawUsageStartDate);
sb.append('}');
return sb.toString();
}
public class UsageInArrearItemsAndNextNotificationDate {
private final List<InvoiceItem> invoiceItems;
private final LocalDate nextNotificationDate;
public UsageInArrearItemsAndNextNotificationDate(final List<InvoiceItem> invoiceItems, final LocalDate nextNotificationDate) {
this.invoiceItems = invoiceItems;
this.nextNotificationDate = nextNotificationDate;
}
public List<InvoiceItem> getInvoiceItems() {
return invoiceItems;
}
public LocalDate getNextNotificationDate() {
return nextNotificationDate;
}
}
public BigDecimal toBeBilledForUnit(List<UsageInArrearDetail> toBeBilledDetails){
BigDecimal result = BigDecimal.ZERO;
for (UsageInArrearDetail toBeBilled: toBeBilledDetails){
result = result.add(toBeBilled.getAmount());
}
return result;
}
private List<UsageInArrearDetail> reconcileExistedBilledWithToBeBilled(Iterable<InvoiceItem> billedItems, List<UsageInArrearDetail> toBeBilledUsageInArrearDetails) {
for (final InvoiceItem bi : billedItems) {
List<UsageInArrearDetail> billedUsageItemDetails = fromJson(bi.getItemDetails());
if (billedUsageItemDetails != null && billedUsageItemDetails.size() > 0) {
for (final UsageInArrearDetail toBeBilledConsumable : toBeBilledUsageInArrearDetails) {
billedUsageItemDetails = toBeBilledConsumable.reconcile(billedUsageItemDetails);
}
if (billedUsageItemDetails != null && billedUsageItemDetails.size() > 0) {
for (final UsageInArrearDetail billedUsage : billedUsageItemDetails) {
toBeBilledUsageInArrearDetails.add(new UsageInArrearDetail(billedUsage.getTier(), billedUsage.getTierUnit(), billedUsage.getTierPrice(),
billedUsage.getQuantity(), billedUsage.getAmount().negate(), null, bi.getId().toString()));
}
}
} else {
toBeBilledUsageInArrearDetails.add(new UsageInArrearDetail(bi.getRate(), bi.getQuantity(), bi.getAmount().negate(), bi.getId().toString()));
}
}
return toBeBilledUsageInArrearDetails;
}
private static final String toJson(List<UsageInArrearDetail> toBeBilledUsageInArrearDetails) {
String result = null;
if (toBeBilledUsageInArrearDetails != null && toBeBilledUsageInArrearDetails.size() > 0){
try {
result = objectMapper.writeValueAsString(toBeBilledUsageInArrearDetails);
} catch (JsonProcessingException e) {
Preconditions.checkState(false, e.getMessage());
}
}
return result;
}
private static final List<UsageInArrearDetail> fromJson(String itemDetails){
List<UsageInArrearDetail> toBeBilledUsageInArrearDetails = null;
if (itemDetails != null){
try {
toBeBilledUsageInArrearDetails = objectMapper.readValue(itemDetails, new TypeReference<List<UsageInArrearDetail>>() {});
} catch (IOException e) {
Preconditions.checkState(false, e.getMessage());
}
}
return toBeBilledUsageInArrearDetails;
}
public class UsageInArrearDetail {
private final int tier;
private final String tierUnit;
private final BigDecimal tierPrice;
private final Integer quantity;
private String reference;
private BigDecimal existingUsageAmount;
private BigDecimal amount;
public UsageInArrearDetail(BigDecimal tierPrice, Integer quantity, BigDecimal existingUsageAmount, String reference) {
this(0, null, tierPrice, quantity, existingUsageAmount, BigDecimal.ZERO, reference);
}
public UsageInArrearDetail(int tier, String tierUnit, BigDecimal tierPrice, Integer quantity) {
this(tier, tierUnit, tierPrice, quantity, tierPrice.multiply(new BigDecimal(quantity)), null, null);
}
@JsonCreator
public UsageInArrearDetail(@JsonProperty("tier") int tier, @JsonProperty("tierUnit") String tierUnit,
@JsonProperty("tierPrice") BigDecimal tierPrice, @JsonProperty("quantity") Integer quantity,
@JsonProperty("amount") BigDecimal amount, @JsonProperty("existingUsageAmount") BigDecimal existingUsageAmount,
@JsonProperty("reference") String reference) {
this.tier = tier;
this.tierUnit = tierUnit;
this.tierPrice = tierPrice;
this.quantity = quantity;
this.amount = amount;
this.existingUsageAmount = existingUsageAmount;
this.reference = reference;
}
public int getTier() {
return tier;
}
public String getTierUnit() {
return tierUnit;
}
public BigDecimal getTierPrice() {
return tierPrice;
}
public Integer getQuantity() {
return quantity;
}
public BigDecimal getExistingUsageAmount() {
return existingUsageAmount;
}
public void setExistingUsageAmount(BigDecimal existingUsageAmount) {
this.existingUsageAmount = existingUsageAmount;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public void setReference(String reference) {
this.reference = reference;
}
public List<UsageInArrearDetail> reconcile(List<UsageInArrearDetail> billedUsageItemDetails) {
List<UsageInArrearDetail> unreconciledUsage = Lists.newLinkedList();
for (UsageInArrearDetail billedUsageDetail : billedUsageItemDetails) {
if (tierUnit.equals(billedUsageDetail.tierUnit)) {
existingUsageAmount = billedUsageDetail.amount.abs();
amount = amount.subtract(existingUsageAmount);
} else {
unreconciledUsage.add(billedUsageDetail);
}
}
return unreconciledUsage;
}
}
}