code: protected function buildInvoicePayments(SaleInterface $sale)
      {
          $currency = $sale->getCurrency()->getCode(); // TODO Deal with currency conversions.
          $payments = $this->buildPaymentList($sale);
          /** @var IM\InvoiceSubjectInterface $sale */
          $invoices = $this->buildInvoiceList($sale);
  
          foreach ($invoices as $x => &$i) {
              $oid = spl_object_id($i['invoice']);
              $this->cache[$oid] = [];
  
              foreach ($payments as $y => &$p) {
                  $r = new IM\InvoicePayment();
                  $r->setPayment($p['payment']);
  
                  $c = Money::compare($i['total'], $p['amount'], $currency);
  
                  if (0 === $c) { // Equal
                      $r->setAmount($p['amount']);
                      $i['total'] = 0;
                      $p['amount'] = 0; unset($payments[$y]);
                  } elseif (1 === $c) { // invoice > payment
                      $r->setAmount($p['amount']);
                      $i['total'] -= $p['amount'];
                      $p['amount'] = 0; unset($payments[$y]);
                  } else { // payment > invoice
                      $r->setAmount($i['total']);
                      $p['amount'] -= $i['total'];
                      $i['total'] = 0;
                  }
  
                  $this->cache[$oid][] = $r;
  
                  unset($p);
              }
  
              unset($i);
          }
      }
docs: Builds invoice payments for the given sale.
  
  @param SaleInterface $sale