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
545133
public UsageInArrearItemsAndNextNotificationDate computeMissingItemsAndNextNotificationDate(final List<InvoiceItem> existingUsage) throws CatalogApiException, InvoiceApiException {

        Preconditions.checkState(isBuilt.get());

        if (transitionTimes.size() < 2) {
            return new UsageInArrearItemsAndNextNotificationDate(ImmutableList.<InvoiceItem>of(), ImmutableSet.of(), computeNextNotificationDate());
        }

        final List<InvoiceItem> result = Lists.newLinkedList();

        final RolledUpUnitsWithTracking allUsageWithTracking = getRolledUpUsage();
        final List<RolledUpUsage> allUsage = allUsageWithTracking.getUsage();

        final Set<TrackingRecordId> allTrackingIds = allUsageWithTracking.getTrackingIds();

        final Set<TrackingRecordId> existingTrackingIds = extractTrackingIds(allExistingTrackingIds);


        final Set<TrackingRecordId> newTrackingIds = Sets.filter(allTrackingIds, new Predicate<TrackingRecordId>() {
            @Override
            public boolean apply(final TrackingRecordId allRecord) {

                return ! Iterables.any(existingTrackingIds, new Predicate<TrackingRecordId>() {
                    @Override
                    public boolean apply(final TrackingRecordId existingRecord) {
                        return existingRecord.isSimilarRecord(allRecord);
                    }
                });
            }
        });


        // Each RolledUpUsage 'ru' is for a specific time period and across all units
        for (final RolledUpUsage ru : allUsage) {

            //
            // Previously billed items:
            //
            // 1. Retrieves current price amount billed for that period of time (and usage section)
            final Iterable<InvoiceItem> billedItems = getBilledItems(ru.getStart(), ru.getEnd(), existingUsage);
            // 2. Verify whether previously built items have the item_details section
            final boolean areAllBilledItemsWithDetails = areAllBilledItemsWithDetails(billedItems);
            // 3. verify if we already billed that period - use to decide whether we should include $0 items when there is nothing to bill for.
            final boolean isPeriodPreviouslyBilled = !Iterables.isEmpty(billedItems);
            // 4. Computes total billed usage amount
            final BigDecimal billedUsage = computeBilledUsage(billedItems);

            final List<RolledUpUnit> rolledUpUnits = ru.getRolledUpUnits();

            final UsageInArrearAggregate toBeBilledUsageDetails = getToBeBilledUsageDetails(rolledUpUnits, billedItems, areAllBilledItemsWithDetails);
            final BigDecimal toBeBilledUsageUnrounded = toBeBilledUsageDetails.getAmount();
            // See https://github.com/killbill/killbill/issues/1124
            final BigDecimal toBeBilledUsage = KillBillMoney.of(toBeBilledUsageUnrounded, getCurrency());
            populateResults(ru.getStart(), ru.getEnd(), billedUsage, toBeBilledUsage, toBeBilledUsageDetails, areAllBilledItemsWithDetails, isPeriodPreviouslyBilled, result);

        }
        final LocalDate nextNotificationDate = computeNextNotificationDate();
        return new UsageInArrearItemsAndNextNotificationDate(result, newTrackingIds, nextNotificationDate);
    }
1273945
def existing(self):
        
        catalog = api.portal.get_tool('portal_catalog')
        results = []
        layout_path = self._get_layout_path(
            self.request.form.get('layout', '')
        )
        for brain in catalog(layout=layout_path):
            results.append({
                'title': brain.Title,
                'url': brain.getURL()
            })
        return json.dumps({
            'total': len(results),
            'data': results
        })
184128
public void incrementCurrentSize() throws SIResourceException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "incrementCurrentSize");

        if (_currentTran != null)
        {
            _currentTran.incrementCurrentSize();
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "incrementCurrentSize");
    }
532665
@Override
    protected void alreadyProcessed(ClientlibRef ref, VisitorMode mode, ClientlibResourceFolder folder) {
        if (mode == EMBEDDED) {
            LOG.warn("Trying to embed already embedded / dependency {} again at {}", ref, folder);
        }
    }
1234444
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;
        }
    }
688431
@Check(CheckType.NORMAL)
	public void checkUnusedCapacities(SarlCapacityUses uses) {
		if (!isIgnored(UNUSED_AGENT_CAPACITY)) {
			final XtendTypeDeclaration container = uses.getDeclaringType();
			final JvmDeclaredType jvmContainer = (JvmDeclaredType) this.associations.getPrimaryJvmElement(container);
			final Map<String, JvmOperation> importedFeatures = CollectionLiterals.newHashMap();
			for (final JvmOperation operation : jvmContainer.getDeclaredOperations()) {
				if (Utils.isNameForHiddenCapacityImplementationCallingMethod(operation.getSimpleName())) {
					importedFeatures.put(operation.getSimpleName(), operation);
				}
			}

			final boolean isSkill = container instanceof SarlSkill;
			int index = 0;
			for (final JvmTypeReference capacity : uses.getCapacities()) {
				final LightweightTypeReference lreference = toLightweightTypeReference(capacity);
				if (isSkill && lreference.isAssignableFrom(jvmContainer)) {
					addIssue(MessageFormat.format(
							Messages.SARLValidator_22,
							capacity.getSimpleName()),
							uses,
							SARL_CAPACITY_USES__CAPACITIES,
							index, UNUSED_AGENT_CAPACITY,
							capacity.getSimpleName());
				} else {
					final String fieldName = Utils.createNameForHiddenCapacityImplementationAttribute(capacity.getIdentifier());
					final String operationName = Utils.createNameForHiddenCapacityImplementationCallingMethodFromFieldName(fieldName);
					final JvmOperation operation = importedFeatures.get(operationName);
					if (operation != null && !isLocallyUsed(operation, container)) {
						addIssue(MessageFormat.format(
								Messages.SARLValidator_78,
								capacity.getSimpleName()),
								uses,
								SARL_CAPACITY_USES__CAPACITIES,
								index, UNUSED_AGENT_CAPACITY,
								capacity.getSimpleName());
					}
				}
				++index;
			}
		}
	}
702717
@Fix(io.sarl.lang.validation.IssueCodes.USED_RESERVED_SARL_ANNOTATION)
	public void fixDiscouragedAnnotationUse(final Issue issue, IssueResolutionAcceptor acceptor) {
		AnnotationRemoveModification.accept(this, issue, acceptor);
	}
433398
public function setAmountsDec(\AgentSIB\Diadoc\Api\Proto\Invoicing\InvoiceItemAmountsDiff $value = null)
    {
        $this->AmountsDec = $value;
    }
375384
public function apply(Request $request, ParamConverter $configuration): void
    {
        $content = $request->getContent();

        if (!$content) {
            if ($configuration->isOptional()) {
                $request->attributes->set($configuration->getName(), null);

                return;
            }

            throw new MissingContentInRequestException();
        }

        $serializer = $this->serializerResolver->resolveByMediaType($configuration->getClass(), $request->headers->get('Content-Type'));
        $context = $this->serializationContextCollector->collect();

        $resource = $serializer->deserialize($content, $configuration->getClass(), $context);

        $request->attributes->set($configuration->getName(), $resource);
    }
488450
protected function addMissingUse(File $phpCsFile, int $stackPointer, string $missingUse): void
    {
        $previousUsePosition = $phpCsFile->findPrevious(T_USE, $stackPointer);
        if ($previousUsePosition !== false) {
            $endOfLastUse = $phpCsFile->findEndOfStatement($previousUsePosition);

            $phpCsFile->fixer->addNewline($endOfLastUse);
            $phpCsFile->fixer->addContent($endOfLastUse, 'use ' . $missingUse . ';');
        }
    }
82047
private void ensureTaxonomyDoesntExist(Request request) throws ResourceAlreadyExistsException {
        try {
            doGetResourceById(request);
            throw new ResourceAlreadyExistsException(String.format("Taxonomy '%s' already exists.",
                    request.getProperty("name")));
        } catch (ResourceNotFoundException e) {
            // expected case
        }
    }
703176
public function setUsage($usage)
    {
        if (is_array($usage) && !empty($usage)) {
            $this->usage = $usage;
        } elseif (is_string($usage) && ($usage != '')) {
            $this->usage = array($usage);
        }
    }
745841
public function usediscount()
    {
        $this->extend("onBeforeUseDiscount");

        $code_to_search = $this->request->param("ID");
        $code = false;

        if (!$code_to_search) {
            return $this->httpError(404, "Page not found");
        }

        // First check if the discount is already added (so we don't
        // query the DB if we don't have to).
        if (!$this->discount || ($this->discount && $this->discount->Code != $code_to_search)) {
            $codes = Discount::get()
                ->filter("Code", $code_to_search)
                ->exclude("Expires:LessThan", date("Y-m-d"));

            if ($codes->exists()) {
                $code = $codes->first();
                $this->discount = $code;
                $this->save();
            }
        } elseif ($this->discount && $this->discount->Code == $code_to_search) {
            $code = $this->discount;
        }

        return $this
            ->customise(array(
                "Discount" => $code
            ))->renderWith(array(
                'ShoppingCart_discount',
                'Checkout',
                'Page'
            ));
    }
635643
public function invoiceFor($description, $amount, array $options = [])
    {
        if (!$this->stripe_id) {
            throw new InvalidArgumentException('User is not a customer. See the createAsStripeCustomer method.');
        }

        $options = array_merge([
            'customer' => $this->stripe_id,
            'amount' => $amount,
            'currency' => $this->preferredCurrency(),
            'description' => $description,
        ], $options);

        StripeInvoiceItem::create(
            $options, ['api_key' => $this->getStripeKey()]
        );

        return $this->invoice();
    }
490766
@Override
  public final void makeOtherEntries(final Map<String, Object> pAddParam,
    final PaymentFrom pEntity, final IRequestData pRequestData,
      final boolean pIsNew) throws Exception {
    String actionAdd = pRequestData.getParameter("actionAdd");
    if ("makeAccEntries".equals(actionAdd)) {
      this.prcSalesInvoiceSave.calculateTotalPayment(pAddParam, pEntity
        .getSalesInvoice());
      getSrvOrm().updateEntity(pAddParam, pEntity.getSalesInvoice());
    }
  }
385749
@Override
    public void coreUpdateCatalog(long timestamp, boolean isStreamUpdate, final String catalogDiffs) throws EEException {
        LOG.trace("Loading Application Catalog...");
        int errorCode = 0;
        errorCode = nativeUpdateCatalog(pointer, timestamp, isStreamUpdate, getStringBytes(catalogDiffs));
        checkErrorCode(errorCode);
    }
1312156
public function addUsageAction(string $usage_code, array $options = []) {
		$codes = \Object\Controller\Model\UsageCodes::getStatic();
		if (empty($codes[$usage_code])) {
			Throw new \Exception('You must register usage code in overrides: ' . $usage_code);
		}
		// generate url
		if (empty($options['url'])) {
			if (in_array('*', $codes[$usage_code]['methods']) || in_array(\Request::method(), $codes[$usage_code]['methods'])) {
				$options['url'] = \Application::get('mvc.full') . '?' . http_build_query2(\Request::input());
			}
		}
		self::$usage_actions[] = [
			'usage_code' => $usage_code,
			'message' => $options['message'] ?? $codes[$usage_code]['message'],
			'replace' => $options['replace'] ?? [],
			'affected_rows' => $options['affected_rows'] ?? 0,
			'error_rows' => $options['error_rows'] ?? 0,
			'url' => $options['url'] ?? null,
			'history' => ($options['history'] ?? $codes[$usage_code]['history']) ? 1 : 0
		];
	}