The amount is applied to the oldest invoices first.
Whatever is not refunded now is deducted from the remaining balance of the invoice.
Quantities are added through purchases and stocktakes only, so every change has a history.