@@ -, +, @@ --- Koha/Account.pm | 92 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) --- a/Koha/Account.pm +++ a/Koha/Account.pm @@ -485,6 +485,98 @@ sub add_credit { return $line; } +=head3 offset_amount + + my $credit = $account->offset_amount( + { + amount => $amount, + credit_type => $credit_type, + payment_type => $payment_type, + cash_register => $register_id, + interface => $interface, + library_id => $branchcode, + user_id => $staff_id, + debts => $debit_lines, + description => $description, + note => $note + } + ); + +This method allows an amount to be offset into a patrons account and immediately applied against debts. + +You can optionally pass a debts parameter which consists of an arrayref of Koha::Account::Line debit lines. + +$credit_type can be any of: + - 'PAYMENT' + - 'WRITEOFF' + - 'FORGIVEN' + +=cut + +sub offset_amount { + my ( $self, $params ) = @_; + + # check for mandatory params + my @mandatory = ( 'interface', 'amount', 'credit_type' ); + for my $param (@mandatory) { + unless ( defined( $params->{$param} ) ) { + Koha::Exceptions::MissingParameter->throw( + error => "The $param parameter is mandatory" ); + } + } + + # amount should always be passed as a positive value + my $amount = $params->{amount} * -1; + unless ( $amount < 0 ) { + Koha::Exceptions::Account::AmountNotPositive->throw( + error => 'Debit amount passed is not positive' ); + } + + my $credit; + my $schema = Koha::Database->new->schema; + try { + $schema->txn_do( + sub { + + # Add payin credit + $credit = $self->add_credit($params); + + # Offset debts passed first + if ( exists( $params->{debts} ) ) { + $credit->apply( + { + debits => $params->{debts}, + offset_type => $params->{credit_type} + } + ); + $credit->discard_changes; + } + + # Offset against remaining balance if AutoReconcile + $credit->apply( + { + debits => [ $self->outstanding_debits->as_list ], + offset_type => $params->{credit_type} + } + ) if ( C4::Context->preference("AccountAutoReconcile") ); + } + ); + } + catch { + if ( ref($_) eq 'Koha::Exceptions::Object::FKConstraint' ) { + if ( $_->broken_fk eq 'credit_type_code' ) { + Koha::Exceptions::Account::UnrecognisedType->throw( + error => 'Type of credit not recognised' ); + } + else { + $_->rethrow; + } + } + }; + + return $credit->discard_changes; +} + =head3 add_debit This method allows adding debits to a patron's account --