+sub storno {
+ my ($self, $form, $myconfig, $id) = @_;
+ $main::lxdebug->enter_sub();
+
+ my $rc = SL::DB->client->with_transaction(\&_storno, $self, $form, $myconfig, $id);
+
+ $::lxdebug->leave_sub;
+ return $rc;
+}
+
+sub _storno {
+ my ($self, $form, $myconfig, $id) = @_;
+
+ my ($query, $new_id, $storno_row, $acc_trans_rows);
+ my $dbh = SL::DB->client->dbh;
+
+ $query = qq|SELECT nextval('glid')|;
+ ($new_id) = selectrow_query($form, $dbh, $query);
+
+ $query = qq|SELECT * FROM gl WHERE id = ?|;
+ $storno_row = selectfirst_hashref_query($form, $dbh, $query, $id);
+
+ $storno_row->{id} = $new_id;
+ $storno_row->{storno_id} = $id;
+ $storno_row->{storno} = 't';
+ $storno_row->{reference} = 'Storno-' . $storno_row->{reference};
+
+ $query = qq|SELECT id FROM employee WHERE login = ?|;
+ my ($employee_id) = selectrow_query($form, $dbh, $query, $::myconfig{login});
+ $storno_row->{employee_id} = $employee_id;
+
+ delete @$storno_row{qw(itime mtime gldate)};
+
+ $query = sprintf 'INSERT INTO gl (%s) VALUES (%s)', join(', ', keys %$storno_row), join(', ', map '?', values %$storno_row);
+ do_query($form, $dbh, $query, (values %$storno_row));
+
+ $query = qq|UPDATE gl SET storno = 't' WHERE id = ?|;
+ do_query($form, $dbh, $query, $id);
+
+ # now copy acc_trans entries
+ $query = qq|SELECT * FROM acc_trans WHERE trans_id = ?|;
+ my $rowref = selectall_hashref_query($form, $dbh, $query, $id);
+
+ for my $row (@$rowref) {
+ delete @$row{qw(itime mtime acc_trans_id gldate)};
+ $query = sprintf 'INSERT INTO acc_trans (%s) VALUES (%s)', join(', ', keys %$row), join(', ', map '?', values %$row);
+ $row->{trans_id} = $new_id;
+ $row->{amount} *= -1;
+ do_query($form, $dbh, $query, (values %$row));
+ }
+
+ return 1;
+}
+
+sub get_chart_balances {
+ my ($self, @chart_ids) = @_;
+
+ return () unless @chart_ids;
+
+ my $placeholders = join ', ', ('?') x scalar(@chart_ids);
+ my $query = qq|SELECT chart_id, SUM(amount) AS sum
+ FROM acc_trans
+ WHERE chart_id IN (${placeholders})
+ GROUP BY chart_id|;
+
+ my %balances = selectall_as_map($::form, $::form->get_standard_dbh(\%::myconfig), $query, 'chart_id', 'sum', @chart_ids);
+
+ return %balances;
+}
+
+sub get_active_taxes_for_chart {
+ my ($self, $chart_id, $transdate, $tax_id) = @_;
+
+ my $chart = SL::DB::Chart->new(id => $chart_id)->load;
+ my $active_taxkey = $chart->get_active_taxkey($transdate);
+
+ my $where = [ chart_categories => { like => '%' . $chart->category . '%' } ];
+
+ if ( defined $tax_id && $tax_id >= 0 ) {
+ $where = [ or => [ chart_categories => { like => '%' . $chart->category . '%' },
+ id => $tax_id
+ ]
+ ];
+ }
+
+ my $taxes = SL::DB::Manager::Tax->get_all(
+ where => $where,
+ sort_by => 'taxkey, rate',
+ );
+
+ my $default_tax = first { $active_taxkey->tax_id == $_->id } @{ $taxes };
+ $default_tax->{is_default} = 1 if $default_tax;
+
+ return @{ $taxes };
+}
+