+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)$/;
+
+ # recalc and set paid via database query
+ my $query = qq|UPDATE $type SET paid =
+ (SELECT COALESCE(abs(sum(amount)),0) FROM acc_trans
+ WHERE trans_id = ?
+ AND chart_link ilike '%paid%')
+ WHERE id = ?|;
+
+ die if (do_query($::form, $bank_transaction->db->dbh, $query, $trans_id, $trans_id) == -1);
+ }
+ # 4. and delete all (if any) record links
+ my $rl = SL::DB::Manager::RecordLink->delete_all(where => [ from_id => $bt_id, from_table => 'bank_transactions' ]);
+
+ # 5. finally reset this bank transaction
+ $bank_transaction->invoice_amount(0);
+ $bank_transaction->cleared(0);
+ $bank_transaction->save;
+ # 6. and add a log entry in history_erp
+ SL::DB::History->new(
+ trans_id => $bank_transaction->id,
+ snumbers => 'bank_transaction_unlink_' . $bank_transaction->id,
+ employee_id => SL::DB::Manager::Employee->current->id,
+ what_done => 'bank_transaction',
+ addition => 'UNLINKED',
+ )->save();
+
+ 1;
+
+ }) || die t8('error while unlinking payment #1 : ', $bank_transaction->purpose) . $bank_transaction->db->error . "\n";