+sub action_unlink_bank_transaction {
+ my ($self, %params) = @_;
+
+ croak("No bank transaction ids") unless scalar @{ $::form->{ids}} > 0;
+
+ my $success_count;
+
+ foreach my $bt_id (@{ $::form->{ids}} ) {
+
+ my $bank_transaction = SL::DB::Manager::BankTransaction->find_by(id => $bt_id);
+ croak("No valid bank transaction found") unless (ref($bank_transaction) eq 'SL::DB::BankTransaction');
+ croak t8('Cannot unlink payment for a closed period!') if $bank_transaction->closed_period;
+
+ # everything in one transaction
+ my $rez = $bank_transaction->db->with_transaction(sub {
+ # 1. remove all reconciliations (due to underlying trigger, this has to be the first step)
+ my $rec_links = SL::DB::Manager::ReconciliationLink->get_all(where => [ bank_transaction_id => $bt_id ]);
+ $_->delete for @{ $rec_links };
+
+ my %trans_ids;
+ foreach my $acc_trans_id_entry (@{ SL::DB::Manager::BankTransactionAccTrans->get_all(where => [bank_transaction_id => $bt_id ] )}) {
+
+ my $acc_trans = SL::DB::Manager::AccTransaction->get_all(where => [acc_trans_id => $acc_trans_id_entry->acc_trans_id]);
+
+ # save trans_id and type
+ die "no type" unless ($acc_trans_id_entry->ar_id || $acc_trans_id_entry->ap_id || $acc_trans_id_entry->gl_id);
+ $trans_ids{$acc_trans_id_entry->ar_id} = 'ar' if $acc_trans_id_entry->ar_id;
+ $trans_ids{$acc_trans_id_entry->ap_id} = 'ap' if $acc_trans_id_entry->ap_id;
+ $trans_ids{$acc_trans_id_entry->gl_id} = 'gl' if $acc_trans_id_entry->gl_id;
+ # 2. all good -> ready to delete acc_trans and bt_acc link
+ $acc_trans_id_entry->delete;
+ $_->delete for @{ $acc_trans };
+ }
+ # 3. update arap.paid (may not be 0, yet)
+ # or in case of gl, delete whole entry
+ while (my ($trans_id, $type) = each %trans_ids) {
+ if ($type eq 'gl') {
+ SL::DB::Manager::GLTransaction->delete_all(where => [ id => $trans_id ]);
+ next;
+ }
+ die ("invalid type") unless $type =~ m/^(ar|ap)$/;