1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
31 # Inventory invoicing module
33 #======================================================================
37 use List::Util qw(max);
43 use SL::DATEV qw(:CONSTANTS);
46 use SL::GenericTranslations;
47 use SL::HTML::Restrict;
61 $main::lxdebug->enter_sub();
63 my ($self, $myconfig, $form, $locale) = @_;
65 $form->{duedate} ||= $form->{invdate};
68 my $dbh = $form->get_standard_dbh;
72 $form->{TEMPLATE_ARRAYS} = {};
74 push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
76 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
79 foreach my $pfac (@{ $form->{ALL_PRICE_FACTORS} }) {
80 $price_factors{$pfac->{id}} = $pfac;
82 $pfac->{formatted_factor} = $form->format_amount($myconfig, $pfac->{factor});
85 # sort items by partsgroup
86 for my $i (1 .. $form->{rowcount}) {
88 # if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
89 # $partsgroup = $form->{"partsgroup_$i"};
91 # push @partsgroup, [$i, $partsgroup];
92 push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
98 $projects = SL::DB::Manager::Project->get_all(query => [ id => \@project_ids ]);
99 %projects_by_id = map { $_->id => $_ } @$projects;
102 if ($projects_by_id{$form->{"globalproject_id"}}) {
103 $form->{globalprojectnumber} = $projects_by_id{$form->{"globalproject_id"}}->projectnumber;
104 $form->{globalprojectdescription} = $projects_by_id{$form->{"globalproject_id"}}->description;
106 for (@{ $projects_by_id{$form->{"globalproject_id"}}->cvars_by_config }) {
107 $form->{"project_cvar_" . $_->config->name} = $_->value_as_text;
117 # sort items by partsgroup
118 for $i (1 .. $form->{rowcount}) {
120 if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
121 $partsgroup = $form->{"partsgroup_$i"};
123 push @partsgroup, [$i, $partsgroup];
136 my $nodiscount_subtotal = 0;
137 my $discount_subtotal = 0;
139 my $subtotal_header = 0;
142 $form->{discount} = [];
144 # get some values of parts from db on store them in extra array,
145 # so that they can be sorted in later
146 my %prepared_template_arrays = IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
147 my @prepared_arrays = keys %prepared_template_arrays;
149 my $ic_cvar_configs = CVar->get_configs(module => 'IC');
150 my $project_cvar_configs = CVar->get_configs(module => 'Projects');
153 qw(runningnumber number description longdescription qty qty_nofmt unit bin
154 deliverydate_oe ordnumber_oe donumber_do transdate_oe invnumber invdate
155 partnotes serialnumber reqdate sellprice sellprice_nofmt listprice listprice_nofmt netprice netprice_nofmt
156 discount discount_nofmt p_discount discount_sub discount_sub_nofmt nodiscount_sub nodiscount_sub_nofmt
157 linetotal linetotal_nofmt nodiscount_linetotal nodiscount_linetotal_nofmt tax_rate projectnumber projectdescription
158 price_factor price_factor_name partsgroup weight weight_nofmt lineweight lineweight_nofmt);
160 push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
161 push @arrays, map { "project_cvar_$_->{name}" } @{ $project_cvar_configs };
163 my @tax_arrays = qw(taxbase tax taxdescription taxrate taxnumber);
165 my @payment_arrays = qw(payment paymentaccount paymentdate paymentsource paymentmemo);
167 map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays, @tax_arrays, @payment_arrays, @prepared_arrays);
170 foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
173 if ($item->[1] ne $sameitem) {
174 push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type} }, 'partsgroup');
175 push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, qq|$item->[1]|);
176 $sameitem = $item->[1];
178 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" } (@arrays, @prepared_arrays)));
181 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
183 if ($form->{"id_$i"} != 0) {
185 # add number, description and qty to $form->{number},
186 if ($form->{"subtotal_$i"} && !$subtotal_header) {
187 $subtotal_header = $i;
188 $position = int($position);
191 } elsif ($subtotal_header) {
193 $position = int($position);
194 $position = $position.".".$subposition;
196 $position = int($position);
200 my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
202 push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, $prepared_template_arrays{$_}[$i - 1]) for @prepared_arrays;
204 push @{ $form->{TEMPLATE_ARRAYS}->{entry_type} }, 'normal';
205 push @{ $form->{TEMPLATE_ARRAYS}->{runningnumber} }, $position;
206 push @{ $form->{TEMPLATE_ARRAYS}->{number} }, $form->{"partnumber_$i"};
207 push @{ $form->{TEMPLATE_ARRAYS}->{serialnumber} }, $form->{"serialnumber_$i"};
208 push @{ $form->{TEMPLATE_ARRAYS}->{bin} }, $form->{"bin_$i"};
209 push @{ $form->{TEMPLATE_ARRAYS}->{partnotes} }, $form->{"partnotes_$i"};
210 push @{ $form->{TEMPLATE_ARRAYS}->{description} }, $form->{"description_$i"};
211 push @{ $form->{TEMPLATE_ARRAYS}->{longdescription} }, $form->{"longdescription_$i"};
212 push @{ $form->{TEMPLATE_ARRAYS}->{qty} }, $form->format_amount($myconfig, $form->{"qty_$i"});
213 push @{ $form->{TEMPLATE_ARRAYS}->{qty_nofmt} }, $form->{"qty_$i"};
214 push @{ $form->{TEMPLATE_ARRAYS}->{unit} }, $form->{"unit_$i"};
215 push @{ $form->{TEMPLATE_ARRAYS}->{deliverydate_oe} }, $form->{"reqdate_$i"};
216 push @{ $form->{TEMPLATE_ARRAYS}->{sellprice} }, $form->{"sellprice_$i"};
217 push @{ $form->{TEMPLATE_ARRAYS}->{sellprice_nofmt} }, $form->parse_amount($myconfig, $form->{"sellprice_$i"});
218 push @{ $form->{TEMPLATE_ARRAYS}->{ordnumber_oe} }, $form->{"ordnumber_$i"};
219 push @{ $form->{TEMPLATE_ARRAYS}->{donumber_do} }, $form->{"donumber_$i"};
220 push @{ $form->{TEMPLATE_ARRAYS}->{transdate_oe} }, $form->{"transdate_$i"};
221 push @{ $form->{TEMPLATE_ARRAYS}->{invnumber} }, $form->{"invnumber"};
222 push @{ $form->{TEMPLATE_ARRAYS}->{invdate} }, $form->{"invdate"};
223 push @{ $form->{TEMPLATE_ARRAYS}->{price_factor} }, $price_factor->{formatted_factor};
224 push @{ $form->{TEMPLATE_ARRAYS}->{price_factor_name} }, $price_factor->{description};
225 push @{ $form->{TEMPLATE_ARRAYS}->{partsgroup} }, $form->{"partsgroup_$i"};
226 push @{ $form->{TEMPLATE_ARRAYS}->{reqdate} }, $form->{"reqdate_$i"};
227 push @{ $form->{TEMPLATE_ARRAYS}->{listprice} }, $form->format_amount($myconfig, $form->{"listprice_$i"}, 2);
228 push(@{ $form->{TEMPLATE_ARRAYS}->{listprice_nofmt} }, $form->{"listprice_$i"});
230 my $sellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
231 my ($dec) = ($sellprice =~ /\.(\d+)/);
232 my $decimalplaces = max 2, length($dec);
234 my $parsed_discount = $form->parse_amount($myconfig, $form->{"discount_$i"});
236 my $linetotal_exact = $form->{"qty_$i"} * $sellprice * (100 - $parsed_discount) / 100 / $price_factor->{factor};
237 my $linetotal = $form->round_amount($linetotal_exact, 2);
239 my $nodiscount_exact_linetotal = $form->{"qty_$i"} * $sellprice / $price_factor->{factor};
240 my $nodiscount_linetotal = $form->round_amount($nodiscount_exact_linetotal,2);
242 my $discount = $nodiscount_linetotal - $linetotal; # is always rounded because $nodiscount_linetotal and $linetotal are rounded
244 my $discount_round_error = $discount + ($linetotal_exact - $nodiscount_exact_linetotal); # not used
246 $form->{"netprice_$i"} = $form->round_amount($form->{"qty_$i"} ? ($linetotal / $form->{"qty_$i"}) : 0, $decimalplaces);
248 push @{ $form->{TEMPLATE_ARRAYS}->{netprice} }, ($form->{"netprice_$i"} != 0) ? $form->format_amount($myconfig, $form->{"netprice_$i"}, $decimalplaces) : '';
249 push @{ $form->{TEMPLATE_ARRAYS}->{netprice_nofmt} }, ($form->{"netprice_$i"} != 0) ? $form->{"netprice_$i"} : '';
251 $linetotal = ($linetotal != 0) ? $linetotal : '';
253 push @{ $form->{TEMPLATE_ARRAYS}->{discount} }, ($discount != 0) ? $form->format_amount($myconfig, $discount * -1, 2) : '';
254 push @{ $form->{TEMPLATE_ARRAYS}->{discount_nofmt} }, ($discount != 0) ? $discount * -1 : '';
255 push @{ $form->{TEMPLATE_ARRAYS}->{p_discount} }, $form->{"discount_$i"};
257 $form->{total} += $linetotal;
258 $form->{nodiscount_total} += $nodiscount_linetotal;
259 $form->{discount_total} += $discount;
261 if ($subtotal_header) {
262 $discount_subtotal += $linetotal;
263 $nodiscount_subtotal += $nodiscount_linetotal;
266 if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
267 push @{ $form->{TEMPLATE_ARRAYS}->{discount_sub} }, $form->format_amount($myconfig, $discount_subtotal, 2);
268 push @{ $form->{TEMPLATE_ARRAYS}->{discount_sub_nofmt} }, $discount_subtotal;
269 push @{ $form->{TEMPLATE_ARRAYS}->{nodiscount_sub} }, $form->format_amount($myconfig, $nodiscount_subtotal, 2);
270 push @{ $form->{TEMPLATE_ARRAYS}->{nodiscount_sub_nofmt} }, $nodiscount_subtotal;
272 $discount_subtotal = 0;
273 $nodiscount_subtotal = 0;
274 $subtotal_header = 0;
277 push @{ $form->{TEMPLATE_ARRAYS}->{$_} }, "" for qw(discount_sub nodiscount_sub discount_sub_nofmt nodiscount_sub_nofmt);
280 if (!$form->{"discount_$i"}) {
281 $nodiscount += $linetotal;
284 push @{ $form->{TEMPLATE_ARRAYS}->{linetotal} }, $form->format_amount($myconfig, $linetotal, 2);
285 push @{ $form->{TEMPLATE_ARRAYS}->{linetotal_nofmt} }, $linetotal_exact;
286 push @{ $form->{TEMPLATE_ARRAYS}->{nodiscount_linetotal} }, $form->format_amount($myconfig, $nodiscount_linetotal, 2);
287 push @{ $form->{TEMPLATE_ARRAYS}->{nodiscount_linetotal_nofmt} }, $nodiscount_linetotal;
289 my $project = $projects_by_id{$form->{"project_id_$i"}} || SL::DB::Project->new;
291 push @{ $form->{TEMPLATE_ARRAYS}->{projectnumber} }, $project->projectnumber;
292 push @{ $form->{TEMPLATE_ARRAYS}->{projectdescription} }, $project->description;
294 my $lineweight = $form->{"qty_$i"} * $form->{"weight_$i"};
295 $totalweight += $lineweight;
296 push @{ $form->{TEMPLATE_ARRAYS}->{weight} }, $form->format_amount($myconfig, $form->{"weight_$i"}, 3);
297 push @{ $form->{TEMPLATE_ARRAYS}->{weight_nofmt} }, $form->{"weight_$i"};
298 push @{ $form->{TEMPLATE_ARRAYS}->{lineweight} }, $form->format_amount($myconfig, $lineweight, 3);
299 push @{ $form->{TEMPLATE_ARRAYS}->{lineweight_nofmt} }, $lineweight;
301 @taxaccounts = split(/ /, $form->{"taxaccounts_$i"});
305 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
307 if ($form->{taxincluded}) {
310 $taxamount = $linetotal * $taxrate / (1 + $taxrate);
311 $taxbase = $linetotal - $taxamount;
313 $taxamount = $linetotal * $taxrate;
314 $taxbase = $linetotal;
317 if ($form->round_amount($taxrate, 7) == 0) {
318 if ($form->{taxincluded}) {
319 foreach my $accno (@taxaccounts) {
320 $taxamount = $form->round_amount($linetotal * $form->{"${accno}_rate"} / (1 + abs($form->{"${accno}_rate"})), 2);
322 $taxaccounts{$accno} += $taxamount;
323 $taxdiff += $taxamount;
325 $taxbase{$accno} += $taxbase;
327 $taxaccounts{ $taxaccounts[0] } += $taxdiff;
329 foreach my $accno (@taxaccounts) {
330 $taxaccounts{$accno} += $linetotal * $form->{"${accno}_rate"};
331 $taxbase{$accno} += $taxbase;
335 foreach my $accno (@taxaccounts) {
336 $taxaccounts{$accno} += $taxamount * $form->{"${accno}_rate"} / $taxrate;
337 $taxbase{$accno} += $taxbase;
340 my $tax_rate = $taxrate * 100;
341 push(@{ $form->{TEMPLATE_ARRAYS}->{tax_rate} }, qq|$tax_rate|);
342 if ($form->{"assembly_$i"}) {
345 # get parts and push them onto the stack
347 if ($form->{groupitems}) {
349 qq|ORDER BY pg.partsgroup, a.oid|;
351 $sortorder = qq|ORDER BY a.oid|;
355 qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
357 JOIN parts p ON (a.parts_id = p.id)
358 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
359 WHERE (a.bom = '1') AND (a.id = ?) $sortorder|;
360 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
362 while (my $ref = $sth->fetchrow_hashref('NAME_lc')) {
363 if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
364 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" } (@arrays, @prepared_arrays)));
365 $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
366 push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type} }, 'assembly-item-partsgroup');
367 push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
370 map { $form->{"a_$_"} = $ref->{$_} } qw(partnumber description);
372 push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type} }, 'assembly-item');
373 push(@{ $form->{TEMPLATE_ARRAYS}->{description} },
374 $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}
376 . qq| -- $form->{"a_partnumber"}, $form->{"a_description"}|);
377 map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" } (@arrays, @prepared_arrays)));
383 CVar->get_non_editable_ic_cvars(form => $form,
386 sub_module => 'invoice',
387 may_converted_from => ['delivery_order_items', 'orderitems', 'invoice']);
389 push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
390 CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
391 for @{ $ic_cvar_configs };
393 push @{ $form->{TEMPLATE_ARRAYS}->{"project_cvar_" . $_->config->name} }, $_->value_as_text for @{ $project->cvars_by_config };
397 $form->{totalweight} = $form->format_amount($myconfig, $totalweight, 3);
398 $form->{totalweight_nofmt} = $totalweight;
399 my $defaults = AM->get_defaults();
400 $form->{weightunit} = $defaults->{weightunit};
402 foreach my $item (sort keys %taxaccounts) {
403 $tax += $taxamount = $form->round_amount($taxaccounts{$item}, 2);
405 push(@{ $form->{TEMPLATE_ARRAYS}->{taxbase} }, $form->format_amount($myconfig, $taxbase{$item}, 2));
406 push(@{ $form->{TEMPLATE_ARRAYS}->{taxbase_nofmt} }, $taxbase{$item});
407 push(@{ $form->{TEMPLATE_ARRAYS}->{tax} }, $form->format_amount($myconfig, $taxamount, 2));
408 push(@{ $form->{TEMPLATE_ARRAYS}->{tax_nofmt} }, $taxamount );
409 push(@{ $form->{TEMPLATE_ARRAYS}->{taxrate} }, $form->format_amount($myconfig, $form->{"${item}_rate"} * 100));
410 push(@{ $form->{TEMPLATE_ARRAYS}->{taxrate_nofmt} }, $form->{"${item}_rate"} * 100);
411 push(@{ $form->{TEMPLATE_ARRAYS}->{taxnumber} }, $form->{"${item}_taxnumber"});
413 my $tax_obj = SL::DB::Manager::Tax->find_by(taxnumber => $form->{"${item}_taxnumber"});
414 my $description = $tax_obj ? $tax_obj->translated_attribute('taxdescription', $form->{language_id}, 0) : '';
415 push(@{ $form->{TEMPLATE_ARRAYS}->{taxdescription} }, $description . q{ } . 100 * $form->{"${item}_rate"} . q{%});
418 for my $i (1 .. $form->{paidaccounts}) {
419 if ($form->{"paid_$i"}) {
420 my ($accno, $description) = split(/--/, $form->{"AR_paid_$i"});
422 push(@{ $form->{TEMPLATE_ARRAYS}->{payment} }, $form->{"paid_$i"});
423 push(@{ $form->{TEMPLATE_ARRAYS}->{paymentaccount} }, $description);
424 push(@{ $form->{TEMPLATE_ARRAYS}->{paymentdate} }, $form->{"datepaid_$i"});
425 push(@{ $form->{TEMPLATE_ARRAYS}->{paymentsource} }, $form->{"source_$i"});
426 push(@{ $form->{TEMPLATE_ARRAYS}->{paymentmemo} }, $form->{"memo_$i"});
428 $form->{paid} += $form->parse_amount($myconfig, $form->{"paid_$i"});
431 if($form->{taxincluded}) {
432 $form->{subtotal} = $form->format_amount($myconfig, $form->{total} - $tax, 2);
433 $form->{subtotal_nofmt} = $form->{total} - $tax;
436 $form->{subtotal} = $form->format_amount($myconfig, $form->{total}, 2);
437 $form->{subtotal_nofmt} = $form->{total};
440 $form->{nodiscount_subtotal} = $form->format_amount($myconfig, $form->{nodiscount_total}, 2);
441 $form->{discount_total} = $form->format_amount($myconfig, $form->{discount_total}, 2);
442 $form->{nodiscount} = $form->format_amount($myconfig, $nodiscount, 2);
443 $form->{yesdiscount} = $form->format_amount($myconfig, $form->{nodiscount_total} - $nodiscount, 2);
445 $form->{invtotal} = ($form->{taxincluded}) ? $form->{total} : $form->{total} + $tax;
446 $form->{total} = $form->format_amount($myconfig, $form->{invtotal} - $form->{paid}, 2);
448 $form->{invtotal} = $form->format_amount($myconfig, $form->{invtotal}, 2);
449 $form->{paid} = $form->format_amount($myconfig, $form->{paid}, 2);
451 $form->set_payment_options($myconfig, $form->{invdate});
453 $form->{delivery_term} = SL::DB::Manager::DeliveryTerm->find_by(id => $form->{delivery_term_id} || undef);
454 $form->{delivery_term}->description_long($form->{delivery_term}->translated_attribute('description_long', $form->{language_id})) if $form->{delivery_term} && $form->{language_id};
456 $form->{username} = $myconfig->{name};
458 $main::lxdebug->leave_sub();
461 sub project_description {
462 $main::lxdebug->enter_sub();
464 my ($self, $dbh, $id) = @_;
465 my $form = \%main::form;
467 my $query = qq|SELECT description FROM project WHERE id = ?|;
468 my ($description) = selectrow_query($form, $dbh, $query, conv_i($id));
470 $main::lxdebug->leave_sub();
475 sub customer_details {
476 $main::lxdebug->enter_sub();
478 my ($self, $myconfig, $form, @wanted_vars) = @_;
480 # connect to database
481 my $dbh = $form->get_standard_dbh;
483 my $language_id = $form->{language_id};
485 # get contact id, set it if nessessary
488 my @values = (conv_i($form->{customer_id}));
491 if ($form->{cp_id}) {
492 $where = qq| AND (cp.cp_id = ?) |;
493 push(@values, conv_i($form->{cp_id}));
496 # get rest for the customer
498 qq|SELECT ct.*, cp.*, ct.notes as customernotes,
499 ct.phone AS customerphone, ct.fax AS customerfax, ct.email AS customeremail,
502 LEFT JOIN contacts cp on ct.id = cp.cp_cv_id
503 LEFT JOIN currencies cu ON (ct.currency_id = cu.id)
504 WHERE (ct.id = ?) $where
507 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
508 # we have no values, probably a invalid contact person. hotfix and first idea for issue #10
510 my $customer = SL::DB::Manager::Customer->find_by(id => $::form->{customer_id});
512 $ref->{name} = $customer->name;
513 $ref->{street} = $customer->street;
514 $ref->{zipcode} = $customer->zipcode;
515 $ref->{country} = $customer->country;
517 my $contact = SL::DB::Manager::Contact->find_by(cp_id => $::form->{cp_id});
519 $ref->{cp_name} = $contact->cp_name;
520 $ref->{cp_givenname} = $contact->cp_givenname;
521 $ref->{cp_gender} = $contact->cp_gender;
524 # remove id and taxincluded before copy back
525 delete @$ref{qw(id taxincluded)};
527 @wanted_vars = grep({ $_ } @wanted_vars);
528 if (scalar(@wanted_vars) > 0) {
530 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
531 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
534 map { $form->{$_} = $ref->{$_} } keys %$ref;
536 if ($form->{delivery_customer_id}) {
538 qq|SELECT *, notes as customernotes
542 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{delivery_customer_id}));
544 map { $form->{"dc_$_"} = $ref->{$_} } keys %$ref;
547 if ($form->{delivery_vendor_id}) {
549 qq|SELECT *, notes as customernotes
553 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{delivery_vendor_id}));
555 map { $form->{"dv_$_"} = $ref->{$_} } keys %$ref;
558 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
560 'trans_id' => $form->{customer_id});
561 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
563 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
564 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
565 'language_id' => $language_id,
566 'allow_fallback' => 1);
569 $main::lxdebug->leave_sub();
573 $main::lxdebug->enter_sub();
575 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
577 # connect to database, turn off autocommit
578 my $dbh = $provided_dbh ? $provided_dbh : $form->get_standard_dbh;
579 my $restricter = SL::HTML::Restrict->create;
581 my ($query, $sth, $null, $project_id, @values);
582 my $exchangerate = 0;
584 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
587 if (!$form->{employee_id}) {
588 $form->get_employee($dbh);
591 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
592 my $defaultcurrency = $form->{defaultcurrency};
594 my $all_units = AM->retrieve_units($myconfig, $form);
596 if (!$payments_only) {
597 if ($form->{storno}) {
598 _delete_transfers($dbh, $form, $form->{storno_id});
601 &reverse_invoice($dbh, $form);
602 _delete_transfers($dbh, $form, $form->{id});
605 my $trans_number = SL::TransNumber->new(type => $form->{type}, dbh => $dbh, number => $form->{invnumber}, save => 1);
606 $form->{invnumber} = $trans_number->create_unique unless $trans_number->is_unique;
608 $query = qq|SELECT nextval('glid')|;
609 ($form->{"id"}) = selectrow_query($form, $dbh, $query);
611 $query = qq|INSERT INTO ar (id, invnumber, currency_id, taxzone_id) VALUES (?, ?, (SELECT id FROM currencies WHERE name=?), ?)|;
612 do_query($form, $dbh, $query, $form->{"id"}, $form->{"id"}, $form->{currency}, $form->{taxzone_id});
614 if (!$form->{invnumber}) {
615 my $trans_number = SL::TransNumber->new(type => $form->{type}, dbh => $dbh, number => $form->{invnumber}, id => $form->{id});
616 $form->{invnumber} = $trans_number->create_unique;
621 my ($netamount, $invoicediff) = (0, 0);
622 my ($amount, $linetotal, $lastincomeaccno);
624 if ($form->{currency} eq $defaultcurrency) {
625 $form->{exchangerate} = 1;
627 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'buy');
630 $form->{exchangerate} =
633 : $form->parse_amount($myconfig, $form->{exchangerate});
635 $form->{expense_inventory} = "";
639 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
640 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
643 $form->{amount} = {};
644 $form->{amount_cogs} = {};
646 my @processed_invoice_ids;
648 foreach my $i (1 .. $form->{rowcount}) {
649 if ($form->{type} eq "credit_note") {
650 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"}) * -1;
651 $form->{shipped} = 1;
653 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
658 $form->{"marge_percent_$i"} = $form->parse_amount($myconfig, $form->{"marge_percent_$i"}) * 1;
659 $form->{"marge_absolut_$i"} = $form->parse_amount($myconfig, $form->{"marge_absolut_$i"}) * 1;
660 $form->{"lastcost_$i"} = $form->parse_amount($myconfig, $form->{"lastcost_$i"}) * 1;
662 if ($form->{storno}) {
663 $form->{"qty_$i"} *= -1;
666 if ($form->{"id_$i"}) {
670 if (defined($baseunits{$form->{"id_$i"}})) {
671 $item_unit = $baseunits{$form->{"id_$i"}};
674 $query = qq|SELECT unit FROM parts WHERE id = ?|;
675 ($item_unit) = selectrow_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
676 $baseunits{$form->{"id_$i"}} = $item_unit;
679 if (defined($all_units->{$item_unit}->{factor})
680 && ($all_units->{$item_unit}->{factor} ne '')
681 && ($all_units->{$item_unit}->{factor} != 0)) {
682 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
686 $baseqty = $form->{"qty_$i"} * $basefactor;
688 my ($allocated, $taxrate) = (0, 0);
692 map { $taxrate += $form->{"${_}_rate"} } split(/ /, $form->{"taxaccounts_$i"});
694 # keep entered selling price
696 $form->parse_amount($myconfig, $form->{"sellprice_$i"});
698 my ($dec) = ($fxsellprice =~ /\.(\d+)/);
700 my $decimalplaces = ($dec > 2) ? $dec : 2;
702 # undo discount formatting
703 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
706 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
708 # round linetotal to 2 decimal places
709 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
710 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
712 if ($form->{taxincluded}) {
713 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
714 $form->{"sellprice_$i"} =
715 $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
717 $taxamount = $linetotal * $taxrate;
720 $netamount += $linetotal;
722 if ($taxamount != 0) {
724 $form->{amount}{ $form->{id} }{$_} +=
725 $taxamount * $form->{"${_}_rate"} / $taxrate
726 } split(/ /, $form->{"taxaccounts_$i"});
729 # add amount to income, $form->{amount}{trans_id}{accno}
730 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
732 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
733 $linetotal = $form->round_amount($linetotal, 2);
735 # this is the difference from the inventory
736 $invoicediff += ($amount - $linetotal);
738 $form->{amount}{ $form->{id} }{ $form->{"income_accno_$i"} } +=
741 $lastincomeaccno = $form->{"income_accno_$i"};
743 # adjust and round sellprice
744 $form->{"sellprice_$i"} =
745 $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate},
748 next if $payments_only;
750 if ($form->{"inventory_accno_$i"} || $form->{"assembly_$i"}) {
752 if ($form->{"assembly_$i"}) {
753 # record assembly item as allocated
754 &process_assembly($dbh, $myconfig, $form, $position, $form->{"id_$i"}, $baseqty);
757 $allocated = &cogs($dbh, $myconfig, $form, $form->{"id_$i"}, $baseqty, $basefactor, $i);
761 # Get pricegroup_id and save it. Unfortunately the interface
762 # also uses ID "0" for signalling that none is selected, but "0"
763 # must not be stored in the database. Therefore we cannot simply
765 ($null, my $pricegroup_id) = split(/--/, $form->{"sellprice_pg_$i"});
767 $pricegroup_id = undef if !$pricegroup_id;
769 CVar->get_non_editable_ic_cvars(form => $form,
772 sub_module => 'invoice',
773 may_converted_from => ['delivery_order_items', 'orderitems', 'invoice']);
775 if (!$form->{"invoice_id_$i"}) {
776 # there is no persistent id, therefore create one with all necessary constraints
777 my $q_invoice_id = qq|SELECT nextval('invoiceid')|;
778 my $h_invoice_id = prepare_query($form, $dbh, $q_invoice_id);
779 do_statement($form, $h_invoice_id, $q_invoice_id);
780 $form->{"invoice_id_$i"} = $h_invoice_id->fetchrow_array();
781 my $q_create_invoice_id = qq|INSERT INTO invoice (id, trans_id, position, parts_id) values (?, ?, ?, ?)|;
782 do_query($form, $dbh, $q_create_invoice_id, conv_i($form->{"invoice_id_$i"}),
783 conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}));
784 $h_invoice_id->finish();
787 # save detail record in invoice table
789 UPDATE invoice SET trans_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?,
790 sellprice = ?, fxsellprice = ?, discount = ?, allocated = ?, assemblyitem = ?,
791 unit = ?, deliverydate = ?, project_id = ?, serialnumber = ?, pricegroup_id = ?,
792 ordnumber = ?, donumber = ?, transdate = ?, cusordnumber = ?, base_qty = ?, subtotal = ?,
793 marge_percent = ?, marge_total = ?, lastcost = ?, active_price_source = ?, active_discount_source = ?,
794 price_factor_id = ?, price_factor = (SELECT factor FROM price_factors WHERE id = ?), marge_price_factor = ?
798 @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
799 $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"},
800 $form->{"sellprice_$i"}, $fxsellprice,
801 $form->{"discount_$i"}, $allocated, 'f',
802 $form->{"unit_$i"}, conv_date($form->{"reqdate_$i"}), conv_i($form->{"project_id_$i"}),
803 $form->{"serialnumber_$i"}, $pricegroup_id,
804 $form->{"ordnumber_$i"}, $form->{"donumber_$i"}, conv_date($form->{"transdate_$i"}),
805 $form->{"cusordnumber_$i"}, $baseqty, $form->{"subtotal_$i"} ? 't' : 'f',
806 $form->{"marge_percent_$i"}, $form->{"marge_absolut_$i"},
807 $form->{"lastcost_$i"},
808 $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
809 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
810 conv_i($form->{"marge_price_factor_$i"}),
811 conv_i($form->{"invoice_id_$i"}));
812 do_query($form, $dbh, $query, @values);
813 push @processed_invoice_ids, $form->{"invoice_id_$i"};
815 CVar->save_custom_variables(module => 'IC',
816 sub_module => 'invoice',
817 trans_id => $form->{"invoice_id_$i"},
818 configs => $ic_cvar_configs,
820 name_prefix => 'ic_',
821 name_postfix => "_$i",
824 # link previous items with invoice items
825 foreach (qw(delivery_order_items orderitems invoice)) {
826 if (!$form->{useasnew} && $form->{"converted_from_${_}_id_$i"}) {
827 RecordLinks->create_links('dbh' => $dbh,
830 'from_ids' => $form->{"converted_from_${_}_id_$i"},
831 'to_table' => 'invoice',
832 'to_id' => $form->{"invoice_id_$i"},
835 delete $form->{"converted_from_${_}_id_$i"};
839 # total payments, don't move we need it here
840 for my $i (1 .. $form->{paidaccounts}) {
841 if ($form->{type} eq "credit_note") {
842 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"}) * -1;
844 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
846 $form->{paid} += $form->{"paid_$i"};
847 $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
850 my ($tax, $diff) = (0, 0);
852 $netamount = $form->round_amount($netamount, 2);
854 # figure out rounding errors for total amount vs netamount + taxes
855 if ($form->{taxincluded}) {
857 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
858 $diff += $amount - $netamount * $form->{exchangerate};
859 $netamount = $amount;
861 foreach my $item (split(/ /, $form->{taxaccounts})) {
862 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
863 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
864 $tax += $form->{amount}{ $form->{id} }{$item};
865 $netamount -= $form->{amount}{ $form->{id} }{$item};
868 $invoicediff += $diff;
869 ######## this only applies to tax included
870 if ($lastincomeaccno) {
871 $form->{amount}{ $form->{id} }{$lastincomeaccno} += $invoicediff;
875 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
876 $diff = $amount - $netamount * $form->{exchangerate};
877 $netamount = $amount;
878 foreach my $item (split(/ /, $form->{taxaccounts})) {
879 $form->{amount}{ $form->{id} }{$item} =
880 $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
883 $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate},
886 $amount - $form->{amount}{ $form->{id} }{$item} *
887 $form->{exchangerate};
888 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
889 $tax += $form->{amount}{ $form->{id} }{$item};
893 $form->{amount}{ $form->{id} }{ $form->{AR} } = $netamount + $tax;
895 $form->round_amount($form->{paid} * $form->{exchangerate} + $diff, 2);
898 $form->{amount}{ $form->{id} }{ $form->{AR} } *= -1;
900 # update exchangerate
901 if (($form->{currency} ne $defaultcurrency) && !$exchangerate) {
902 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate},
903 $form->{exchangerate}, 0);
906 $project_id = conv_i($form->{"globalproject_id"});
907 # entsprechend auch beim Bestimmen des Steuerschlüssels in Taxkey.pm berücksichtigen
908 my $taxdate = $form->{deliverydate} ? $form->{deliverydate} : $form->{invdate};
910 foreach my $trans_id (keys %{ $form->{amount_cogs} }) {
911 foreach my $accno (keys %{ $form->{amount_cogs}{$trans_id} }) {
912 next unless ($form->{expense_inventory} =~ /\Q$accno\E/);
914 $form->{amount_cogs}{$trans_id}{$accno} = $form->round_amount($form->{amount_cogs}{$trans_id}{$accno}, 2);
916 if (!$payments_only && ($form->{amount_cogs}{$trans_id}{$accno} != 0)) {
918 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, tax_id, taxkey, project_id, chart_link)
919 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, (SELECT id FROM tax WHERE taxkey=0), 0, ?, (SELECT link FROM chart WHERE accno = ?))|;
920 @values = (conv_i($trans_id), $accno, $form->{amount_cogs}{$trans_id}{$accno}, conv_date($form->{invdate}), conv_i($project_id), $accno);
921 do_query($form, $dbh, $query, @values);
922 $form->{amount_cogs}{$trans_id}{$accno} = 0;
926 foreach my $accno (keys %{ $form->{amount_cogs}{$trans_id} }) {
927 $form->{amount_cogs}{$trans_id}{$accno} = $form->round_amount($form->{amount_cogs}{$trans_id}{$accno}, 2);
929 if (!$payments_only && ($form->{amount_cogs}{$trans_id}{$accno} != 0)) {
931 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, tax_id, taxkey, project_id, chart_link)
932 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, (SELECT id FROM tax WHERE taxkey=0), 0, ?, (SELECT link FROM chart WHERE accno = ?))|;
933 @values = (conv_i($trans_id), $accno, $form->{amount_cogs}{$trans_id}{$accno}, conv_date($form->{invdate}), conv_i($project_id), $accno);
934 do_query($form, $dbh, $query, @values);
939 foreach my $trans_id (keys %{ $form->{amount} }) {
940 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
941 next unless ($form->{expense_inventory} =~ /\Q$accno\E/);
943 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
945 if (!$payments_only && ($form->{amount}{$trans_id}{$accno} != 0)) {
947 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, tax_id, taxkey, project_id, chart_link)
948 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
951 WHERE chart_id= (SELECT id
955 ORDER BY startdate DESC LIMIT 1),
958 WHERE chart_id= (SELECT id
962 ORDER BY startdate DESC LIMIT 1),
964 (SELECT link FROM chart WHERE accno = ?))|;
965 @values = (conv_i($trans_id), $accno, $form->{amount}{$trans_id}{$accno}, conv_date($form->{invdate}), $accno, conv_date($taxdate), $accno, conv_date($taxdate), conv_i($project_id), $accno);
966 do_query($form, $dbh, $query, @values);
967 $form->{amount}{$trans_id}{$accno} = 0;
971 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
972 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
974 if (!$payments_only && ($form->{amount}{$trans_id}{$accno} != 0)) {
976 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, tax_id, taxkey, project_id, chart_link)
977 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
980 WHERE chart_id= (SELECT id
984 ORDER BY startdate DESC LIMIT 1),
987 WHERE chart_id= (SELECT id
991 ORDER BY startdate DESC LIMIT 1),
993 (SELECT link FROM chart WHERE accno = ?))|;
994 @values = (conv_i($trans_id), $accno, $form->{amount}{$trans_id}{$accno}, conv_date($form->{invdate}), $accno, conv_date($taxdate), $accno, conv_date($taxdate), conv_i($project_id), $accno);
995 do_query($form, $dbh, $query, @values);
1000 # deduct payment differences from diff
1001 for my $i (1 .. $form->{paidaccounts}) {
1002 if ($form->{"paid_$i"} != 0) {
1004 $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
1005 $diff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
1009 # record payments and offsetting AR
1010 if (!$form->{storno}) {
1011 for my $i (1 .. $form->{paidaccounts}) {
1013 if ($form->{"acc_trans_id_$i"}
1015 && (SL::DB::Default->get->payments_changeable == 0)) {
1019 next if ($form->{"paid_$i"} == 0);
1021 my ($accno) = split(/--/, $form->{"AR_paid_$i"});
1022 $form->{"datepaid_$i"} = $form->{invdate}
1023 unless ($form->{"datepaid_$i"});
1024 $form->{datepaid} = $form->{"datepaid_$i"};
1028 if ($form->{currency} eq $defaultcurrency) {
1029 $form->{"exchangerate_$i"} = 1;
1031 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
1032 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
1036 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $diff, 2);
1038 if ($form->{amount}{ $form->{id} }{ $form->{AR} } != 0) {
1040 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, tax_id, taxkey, project_id, chart_link)
1041 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
1044 WHERE chart_id= (SELECT id
1048 ORDER BY startdate DESC LIMIT 1),
1051 WHERE chart_id= (SELECT id
1055 ORDER BY startdate DESC LIMIT 1),
1057 (SELECT link FROM chart WHERE accno = ?))|;
1058 @values = (conv_i($form->{"id"}), $form->{AR}, $amount, $form->{"datepaid_$i"}, $form->{AR}, conv_date($taxdate), $form->{AR}, conv_date($taxdate), $project_id, $form->{AR});
1059 do_query($form, $dbh, $query, @values);
1063 $form->{"paid_$i"} *= -1;
1064 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
1067 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, tax_id, taxkey, project_id, chart_link)
1068 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
1071 WHERE chart_id= (SELECT id
1075 ORDER BY startdate DESC LIMIT 1),
1078 WHERE chart_id= (SELECT id
1082 ORDER BY startdate DESC LIMIT 1),
1084 (SELECT link FROM chart WHERE accno = ?))|;
1085 @values = (conv_i($form->{"id"}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
1086 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($taxdate), $accno, conv_date($taxdate), $project_id, $accno);
1087 do_query($form, $dbh, $query, @values);
1089 # exchangerate difference
1090 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } +=
1091 $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $diff;
1095 $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
1096 $form->{"exchangerate_$i"};
1098 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
1100 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
1105 # update exchange rate
1106 if (($form->{currency} ne $defaultcurrency) && !$exchangerate) {
1107 $form->update_exchangerate($dbh, $form->{currency},
1108 $form->{"datepaid_$i"},
1109 $form->{"exchangerate_$i"}, 0);
1113 } else { # if (!$form->{storno})
1114 $form->{marge_total} *= -1;
1117 IO->set_datepaid(table => 'ar', id => $form->{id}, dbh => $dbh);
1119 # record exchange rate differences and gains/losses
1120 foreach my $accno (keys %{ $form->{fx} }) {
1121 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
1122 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
1123 if ( $form->{fx}{$accno}{$transdate} != 0 ) {
1126 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, tax_id, taxkey, project_id, chart_link)
1127 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1',
1130 WHERE chart_id= (SELECT id
1134 ORDER BY startdate DESC LIMIT 1),
1137 WHERE chart_id= (SELECT id
1141 ORDER BY startdate DESC LIMIT 1),
1143 (SELECT link FROM chart WHERE accno = ?))|;
1144 @values = (conv_i($form->{"id"}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $accno, conv_date($taxdate), $accno, conv_date($taxdate), conv_i($project_id), $accno);
1145 do_query($form, $dbh, $query, @values);
1150 if ($payments_only) {
1151 $query = qq|UPDATE ar SET paid = ? WHERE id = ?|;
1152 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
1154 $dbh->commit if !$provided_dbh;
1156 $main::lxdebug->leave_sub();
1160 $amount = $netamount + $tax;
1163 #erweiterung fuer lieferscheinnummer (donumber) 12.02.09 jb
1165 $query = qq|UPDATE ar set
1166 invnumber = ?, ordnumber = ?, quonumber = ?, cusordnumber = ?,
1167 transdate = ?, orddate = ?, quodate = ?, customer_id = ?,
1168 amount = ?, netamount = ?, paid = ?,
1169 duedate = ?, deliverydate = ?, invoice = ?, shippingpoint = ?,
1170 shipvia = ?, notes = ?, intnotes = ?,
1171 currency_id = (SELECT id FROM currencies WHERE name = ?),
1172 department_id = ?, payment_id = ?, taxincluded = ?,
1173 type = ?, language_id = ?, taxzone_id = ?, shipto_id = ?,
1174 employee_id = ?, salesman_id = ?, storno_id = ?, storno = ?,
1175 cp_id = ?, marge_total = ?, marge_percent = ?,
1176 globalproject_id = ?, delivery_customer_id = ?,
1177 transaction_description = ?, delivery_vendor_id = ?,
1178 donumber = ?, invnumber_for_credit_note = ?, direct_debit = ?,
1179 delivery_term_id = ?
1181 @values = ( $form->{"invnumber"}, $form->{"ordnumber"}, $form->{"quonumber"}, $form->{"cusordnumber"},
1182 conv_date($form->{"invdate"}), conv_date($form->{"orddate"}), conv_date($form->{"quodate"}), conv_i($form->{"customer_id"}),
1183 $amount, $netamount, $form->{"paid"},
1184 conv_date($form->{"duedate"}), conv_date($form->{"deliverydate"}), '1', $form->{"shippingpoint"},
1185 $form->{"shipvia"}, $restricter->process($form->{"notes"}), $form->{"intnotes"},
1186 $form->{"currency"}, conv_i($form->{"department_id"}), conv_i($form->{"payment_id"}), $form->{"taxincluded"} ? 't' : 'f',
1187 $form->{"type"}, conv_i($form->{"language_id"}), conv_i($form->{"taxzone_id"}), conv_i($form->{"shipto_id"}),
1188 conv_i($form->{"employee_id"}), conv_i($form->{"salesman_id"}), conv_i($form->{storno_id}), $form->{"storno"} ? 't' : 'f',
1189 conv_i($form->{"cp_id"}), 1 * $form->{marge_total} , 1 * $form->{marge_percent},
1190 conv_i($form->{"globalproject_id"}), conv_i($form->{"delivery_customer_id"}),
1191 $form->{transaction_description}, conv_i($form->{"delivery_vendor_id"}),
1192 $form->{"donumber"}, $form->{"invnumber_for_credit_note"}, $form->{direct_debit} ? 't' : 'f',
1193 conv_i($form->{delivery_term_id}),
1194 conv_i($form->{"id"}));
1195 do_query($form, $dbh, $query, @values);
1198 if ($form->{storno}) {
1201 paid = paid + amount,
1203 intnotes = ? || intnotes
1205 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{"storno_id"}));
1206 do_query($form, $dbh, qq|UPDATE ar SET paid = amount WHERE id = ?|, conv_i($form->{"id"}));
1209 $form->{name} = $form->{customer};
1210 $form->{name} =~ s/--\Q$form->{customer_id}\E//;
1213 if (!$form->{shipto_id}) {
1214 $form->add_shipto($dbh, $form->{id}, "AR");
1217 # save printed, emailed and queued
1218 $form->save_status($dbh);
1220 Common::webdav_folder($form);
1222 if ($form->{convert_from_ar_ids}) {
1223 RecordLinks->create_links('dbh' => $dbh,
1225 'from_table' => 'ar',
1226 'from_ids' => $form->{convert_from_ar_ids},
1228 'to_id' => $form->{id},
1230 delete $form->{convert_from_ar_ids};
1233 # Link this record to the records it was created from.
1234 if ($form->{convert_from_oe_ids}) {
1235 RecordLinks->create_links('dbh' => $dbh,
1237 'from_table' => 'oe',
1238 'from_ids' => $form->{convert_from_oe_ids},
1240 'to_id' => $form->{id},
1242 delete $form->{convert_from_oe_ids};
1245 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
1247 if (scalar @convert_from_do_ids) {
1248 DO->close_orders('dbh' => $dbh,
1249 'ids' => \@convert_from_do_ids);
1251 RecordLinks->create_links('dbh' => $dbh,
1253 'from_table' => 'delivery_orders',
1254 'from_ids' => \@convert_from_do_ids,
1256 'to_id' => $form->{id},
1259 delete $form->{convert_from_do_ids};
1261 ARAP->close_orders_if_billed('dbh' => $dbh,
1262 'arap_id' => $form->{id},
1265 # search for orphaned invoice items
1266 $query = sprintf 'SELECT id FROM invoice WHERE trans_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_invoice_ids;
1267 @values = (conv_i($form->{id}), map { conv_i($_) } @processed_invoice_ids);
1268 my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
1269 if (scalar @orphaned_ids) {
1270 # clean up invoice items
1271 $query = sprintf 'DELETE FROM invoice WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
1272 do_query($form, $dbh, $query, @orphaned_ids);
1275 # safety check datev export
1276 if ($::instance_conf->get_datev_check_on_sales_invoice) {
1277 my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
1278 $transdate ||= DateTime->today;
1280 my $datev = SL::DATEV->new(
1281 exporttype => DATEV_ET_BUCHUNGEN,
1282 format => DATEV_FORMAT_KNE,
1284 trans_id => $form->{id},
1289 if ($datev->errors) {
1291 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
1296 $dbh->commit if !$provided_dbh;
1298 $main::lxdebug->leave_sub();
1304 $::lxdebug->enter_sub;
1306 my ($self, $form, $dbh) = @_;
1308 my (@errors, @transfers);
1310 # do nothing, if transfer default is not requeseted at all
1311 if (!$::instance_conf->get_transfer_default) {
1312 $::lxdebug->leave_sub;
1318 foreach my $i (1 .. $form->{rowcount}) {
1319 next if !$form->{"id_$i"};
1320 my ($err, $wh_id, $bin_id) = _determine_wh_and_bin($dbh, $::instance_conf,
1323 $form->{"unit_$i"});
1324 if (!@{ $err } && $wh_id && $bin_id) {
1326 'parts_id' => $form->{"id_$i"},
1327 'qty' => $form->{"qty_$i"},
1328 'unit' => $form->{"unit_$i"},
1329 'transfer_type' => 'shipped',
1330 'src_warehouse_id' => $wh_id,
1331 'src_bin_id' => $bin_id,
1332 'project_id' => $form->{"project_id_$i"},
1333 'invoice_id' => $form->{"invoice_id_$i"},
1334 'comment' => $::locale->text("Default transfer invoice"),
1338 push @errors, @{ $err };
1342 WH->transfer(@transfers);
1345 $::lxdebug->leave_sub;
1349 sub _determine_wh_and_bin {
1350 $::lxdebug->enter_sub(2);
1352 my ($dbh, $conf, $part_id, $qty, $unit) = @_;
1355 my $part = SL::DB::Part->new(id => $part_id)->load;
1357 # ignore service if they are not configured to be transfered
1358 if ($part->is_service && !$conf->get_transfer_default_services) {
1359 $::lxdebug->leave_sub(2);
1365 push @errors, $::locale->text("Cannot transfer negative quantities.");
1369 # get/test default bin
1370 my ($default_wh_id, $default_bin_id);
1371 if ($conf->get_transfer_default_use_master_default_bin) {
1372 $default_wh_id = $conf->get_warehouse_id if $conf->get_warehouse_id;
1373 $default_bin_id = $conf->get_bin_id if $conf->get_bin_id;
1375 my $wh_id = $part->warehouse_id || $default_wh_id;
1376 my $bin_id = $part->bin_id || $default_bin_id;
1380 my ($max_qty, $error) = WH->get_max_qty_parts_bin(dbh => $dbh,
1381 parts_id => $part->id,
1384 push @errors, $::locale->text('Part "#1" has chargenumber or best before date set. So it cannot be transfered automaticaly.',
1385 $part->description);
1387 my $form_unit_obj = SL::DB::Unit->new(name => $unit)->load;
1388 my $part_unit_qty = $form_unit_obj->convert_to($qty, $part->unit_obj);
1389 my $diff_qty = $max_qty - $part_unit_qty;
1390 if (!@errors && $diff_qty < 0) {
1391 push @errors, $::locale->text('For part "#1" there are missing #2 #3 in the default warehouse/bin "#4/#5".',
1393 $::form->format_amount(\%::myconfig, -1*$diff_qty),
1394 $part->unit_obj->name,
1395 SL::DB::Warehouse->new(id => $wh_id)->load->description,
1396 SL::DB::Bin->new( id => $bin_id)->load->description);
1399 push @errors, $::locale->text('For part "#1" there is no default warehouse and bin defined.',
1400 $part->description);
1403 # transfer to special "ignore onhand" bin if requested and default bin does not work
1404 if (@errors && $conf->get_transfer_default_ignore_onhand && $conf->get_bin_id_ignore_onhand) {
1405 $wh_id = $conf->get_warehouse_id_ignore_onhand;
1406 $bin_id = $conf->get_bin_id_ignore_onhand;
1407 if ($wh_id && $bin_id) {
1410 push @errors, $::locale->text('For part "#1" there is no default warehouse and bin for ignoring onhand defined.',
1411 $part->description);
1415 $::lxdebug->leave_sub(2);
1416 return (\@errors, $wh_id, $bin_id);
1419 sub _delete_transfers {
1420 $::lxdebug->enter_sub;
1422 my ($dbh, $form, $id) = @_;
1424 my $query = qq|DELETE FROM inventory WHERE invoice_id
1425 IN (SELECT id FROM invoice WHERE trans_id = ?)|;
1427 do_query($form, $dbh, $query, $id);
1429 $::lxdebug->leave_sub;
1432 sub _delete_payments {
1433 $main::lxdebug->enter_sub();
1435 my ($self, $form, $dbh) = @_;
1437 my @delete_acc_trans_ids;
1439 # Delete old payment entries from acc_trans.
1441 qq|SELECT acc_trans_id
1443 WHERE (trans_id = ?) AND fx_transaction
1447 SELECT at.acc_trans_id
1449 LEFT JOIN chart c ON (at.chart_id = c.id)
1450 WHERE (trans_id = ?) AND (c.link LIKE '%AR_paid%')|;
1451 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1454 qq|SELECT at.acc_trans_id
1456 LEFT JOIN chart c ON (at.chart_id = c.id)
1457 WHERE (trans_id = ?)
1458 AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
1459 ORDER BY at.acc_trans_id
1461 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1463 if (@delete_acc_trans_ids) {
1464 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1465 do_query($form, $dbh, $query);
1468 $main::lxdebug->leave_sub();
1472 $main::lxdebug->enter_sub();
1474 my ($self, $myconfig, $form, $locale) = @_;
1476 # connect to database, turn off autocommit
1477 my $dbh = $form->get_standard_dbh;
1479 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1481 $old_form = save_form();
1483 # Delete all entries in acc_trans from prior payments.
1484 if (SL::DB::Default->get->payments_changeable != 0) {
1485 $self->_delete_payments($form, $dbh);
1488 # Save the new payments the user made before cleaning up $form.
1489 map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^gldate_\d+$|^acc_trans_id_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AR_paid_\d+$|^paidaccounts$/, keys %{ $form };
1491 # Clean up $form so that old content won't tamper the results.
1492 %keep_vars = map { $_, 1 } qw(login password id);
1493 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1495 # Retrieve the invoice from the database.
1496 $self->retrieve_invoice($myconfig, $form);
1498 # Set up the content of $form in the way that IS::post_invoice() expects.
1499 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1501 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1502 $item = $form->{invoice_details}->[$row - 1];
1504 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice discount);
1506 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1509 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1511 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1513 # Restore the payment options from the user input.
1514 map { $form->{$_} = $payments{$_} } keys %payments;
1516 # Get the AR accno (which is normally done by Form::create_links()).
1520 LEFT JOIN chart c ON (at.chart_id = c.id)
1521 WHERE (trans_id = ?)
1522 AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
1523 ORDER BY at.acc_trans_id
1526 ($form->{AR}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1528 # Post the new payments.
1529 $self->post_invoice($myconfig, $form, $dbh, 1);
1531 restore_form($old_form);
1533 my $rc = $dbh->commit();
1535 $main::lxdebug->leave_sub();
1540 sub process_assembly {
1541 $main::lxdebug->enter_sub();
1543 my ($dbh, $myconfig, $form, $position, $id, $totalqty) = @_;
1546 qq|SELECT a.parts_id, a.qty, p.assembly, p.partnumber, p.description, p.unit,
1547 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1549 JOIN parts p ON (a.parts_id = p.id)
1551 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
1553 while (my $ref = $sth->fetchrow_hashref('NAME_lc')) {
1557 $ref->{inventory_accno_id} *= 1;
1558 $ref->{expense_accno_id} *= 1;
1560 # multiply by number of assemblies
1561 $ref->{qty} *= $totalqty;
1563 if ($ref->{assembly}) {
1564 &process_assembly($dbh, $myconfig, $form, $position, $ref->{parts_id}, $ref->{qty});
1567 if ($ref->{inventory_accno_id}) {
1568 $allocated = &cogs($dbh, $myconfig, $form, $ref->{parts_id}, $ref->{qty});
1572 # save detail record for individual assembly item in invoice table
1574 qq|INSERT INTO invoice (trans_id, position, description, parts_id, qty, sellprice, fxsellprice, allocated, assemblyitem, unit)
1575 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1576 my @values = (conv_i($form->{id}), conv_i($position), $ref->{description},
1577 conv_i($ref->{parts_id}), $ref->{qty}, 0, 0, $allocated, 't', $ref->{unit});
1578 do_query($form, $dbh, $query, @values);
1584 $main::lxdebug->leave_sub();
1588 $main::lxdebug->enter_sub();
1590 # adjust allocated in table invoice according to FIFO princicple
1591 # for a certain part with part_id $id
1593 my ($dbh, $myconfig, $form, $id, $totalqty, $basefactor, $row) = @_;
1597 $form->{taxzone_id} *=1;
1598 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1599 my $taxzone_id = $form->{"taxzone_id"} * 1;
1601 qq|SELECT i.id, i.trans_id, i.base_qty, i.allocated, i.sellprice, i.price_factor,
1602 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
1603 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
1604 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid
1605 FROM invoice i, parts p
1606 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
1607 LEFT JOIN chart c2 ON ((SELECT tc.income_accno_id FROM taxzone_charts tc WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
1608 LEFT JOIN chart c3 ON ((SELECT tc.expense_accno_id FROM taxzone_charts tc WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
1609 WHERE (i.parts_id = p.id)
1610 AND (i.parts_id = ?)
1611 AND ((i.base_qty + i.allocated) < 0)
1613 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
1618 # all invoice entries of an example part:
1620 # id | trans_id | base_qty | allocated | sellprice | inventory_accno | income_accno | expense_accno
1621 # ---+----------+----------+-----------+-----------+-----------------+--------------+---------------
1622 # 4 | 4 | -5 | 5 | 20.00000 | 1140 | 4400 | 5400 bought 5 for 20
1623 # 5 | 5 | 4 | -4 | 50.00000 | 1140 | 4400 | 5400 sold 4 for 50
1624 # 6 | 6 | 1 | -1 | 50.00000 | 1140 | 4400 | 5400 sold 1 for 50
1625 # 7 | 7 | -5 | 1 | 20.00000 | 1140 | 4400 | 5400 bought 5 for 20
1626 # 8 | 8 | 1 | -1 | 50.00000 | 1140 | 4400 | 5400 sold 1 for 50
1628 # AND ((i.base_qty + i.allocated) < 0) filters out all but line with id=7, elsewhere i.base_qty + i.allocated has already reached 0
1629 # and all parts have been allocated
1631 # so transaction 8 only sees transaction 7 with unallocated parts and adjusts allocated for that transaction, before allocated was 0
1632 # 7 | 7 | -5 | 1 | 20.00000 | 1140 | 4400 | 5400 bought 5 for 20
1634 # in this example there are still 4 unsold articles
1637 # search all invoice entries for the part in question, adjusting "allocated"
1638 # until the total number of sold parts has been reached
1640 # ORDER BY trans_id ensures FIFO
1643 while (my $ref = $sth->fetchrow_hashref('NAME_lc')) {
1644 if (($qty = (($ref->{base_qty} * -1) - $ref->{allocated})) > $totalqty) {
1648 # update allocated in invoice
1649 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty);
1651 # total expenses and inventory
1652 # sellprice is the cost of the item
1653 my $linetotal = $form->round_amount(($ref->{sellprice} * $qty) / ( ($ref->{price_factor} || 1) * ( $basefactor || 1 )), 2);
1655 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
1656 # Bestandsmethode: when selling parts, deduct their purchase value from the inventory account
1657 $ref->{expense_accno} = ($form->{"expense_accno_$row"}) ? $form->{"expense_accno_$row"} : $ref->{expense_accno};
1659 $form->{amount_cogs}{ $form->{id} }{ $ref->{expense_accno} } += -$linetotal;
1660 $form->{expense_inventory} .= " " . $ref->{expense_accno};
1661 $ref->{inventory_accno} = ($form->{"inventory_accno_$row"}) ? $form->{"inventory_accno_$row"} : $ref->{inventory_accno};
1663 $form->{amount_cogs}{ $form->{id} }{ $ref->{inventory_accno} } -= -$linetotal;
1664 $form->{expense_inventory} .= " " . $ref->{inventory_accno};
1670 last if (($totalqty -= $qty) <= 0);
1675 $main::lxdebug->leave_sub();
1680 sub reverse_invoice {
1681 $main::lxdebug->enter_sub();
1683 my ($dbh, $form) = @_;
1685 # reverse inventory items
1687 qq|SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly, p.inventory_accno_id
1689 JOIN parts p ON (i.parts_id = p.id)
1690 WHERE i.trans_id = ?|;
1691 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id"}));
1693 while (my $ref = $sth->fetchrow_hashref('NAME_lc')) {
1695 if ($ref->{inventory_accno_id}) {
1696 # de-allocated purchases
1698 qq|SELECT i.id, i.trans_id, i.allocated
1700 WHERE (i.parts_id = ?) AND (i.allocated > 0)
1701 ORDER BY i.trans_id DESC|;
1702 my $sth2 = prepare_execute_query($form, $dbh, $query, conv_i($ref->{"parts_id"}));
1704 while (my $inhref = $sth2->fetchrow_hashref('NAME_lc')) {
1705 my $qty = $ref->{qty};
1706 if (($ref->{qty} - $inhref->{allocated}) > 0) {
1707 $qty = $inhref->{allocated};
1711 $form->update_balance($dbh, "invoice", "allocated", qq|id = $inhref->{id}|, $qty * -1);
1713 last if (($ref->{qty} -= $qty) <= 0);
1722 my @values = (conv_i($form->{id}));
1723 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE trans_id = ?|, @values);
1724 do_query($form, $dbh, qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AR')|, @values);
1726 $main::lxdebug->leave_sub();
1729 sub delete_invoice {
1730 $main::lxdebug->enter_sub();
1732 my ($self, $myconfig, $form) = @_;
1734 # connect to database
1735 my $dbh = $form->get_standard_dbh;
1737 &reverse_invoice($dbh, $form);
1738 _delete_transfers($dbh, $form, $form->{id});
1740 my @values = (conv_i($form->{id}));
1742 # Falls wir ein Storno haben, müssen zwei Felder in der stornierten Rechnung wieder
1743 # zurückgesetzt werden. Vgl:
1744 # id | storno | storno_id | paid | amount
1745 #----+--------+-----------+---------+-----------
1746 # 18 | f | | 0.00000 | 119.00000
1748 # 18 | t | | 119.00000 | 119.00000
1750 if($form->{storno}){
1751 # storno_id auslesen und korrigieren
1752 my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT storno_id FROM ar WHERE id = ?|,@values);
1753 do_query($form, $dbh, qq|UPDATE ar SET storno = 'f', paid = 0 WHERE id = ?|, $invoice_id);
1756 # delete spool files
1757 my @spoolfiles = selectall_array_query($form, $dbh, qq|SELECT spoolfile FROM status WHERE trans_id = ?|, @values);
1760 qq|DELETE FROM status WHERE trans_id = ?|,
1761 qq|DELETE FROM periodic_invoices WHERE ar_id = ?|,
1762 qq|DELETE FROM invoice WHERE trans_id = ?|,
1763 qq|DELETE FROM ar WHERE id = ?|,
1766 map { do_query($form, $dbh, $_, @values) } @queries;
1768 my $rc = $dbh->commit;
1771 my $spool = $::lx_office_conf{paths}->{spool};
1772 map { unlink "$spool/$_" if -f "$spool/$_"; } @spoolfiles;
1775 $main::lxdebug->leave_sub();
1780 sub retrieve_invoice {
1781 $main::lxdebug->enter_sub();
1783 my ($self, $myconfig, $form) = @_;
1785 # connect to database
1786 my $dbh = $form->get_standard_dbh;
1788 my ($sth, $ref, $query);
1790 my $query_transdate = !$form->{id} ? ", current_date AS invdate" : '';
1794 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
1795 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
1796 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
1797 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1798 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1802 $ref = selectfirst_hashref_query($form, $dbh, $query);
1803 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1806 my $id = conv_i($form->{id});
1809 #erweiterung um das entsprechende feld lieferscheinnummer (a.donumber) in der html-maske anzuzeigen 12.02.2009 jb
1813 a.invnumber, a.ordnumber, a.quonumber, a.cusordnumber,
1814 a.orddate, a.quodate, a.globalproject_id,
1815 a.transdate AS invdate, a.deliverydate, a.paid, a.storno, a.gldate,
1816 a.shippingpoint, a.shipvia, a.notes, a.intnotes, a.taxzone_id,
1817 a.duedate, a.taxincluded, (SELECT cu.name FROM currencies cu WHERE cu.id=a.currency_id) AS currency, a.shipto_id, a.cp_id,
1818 a.employee_id, a.salesman_id, a.payment_id,
1819 a.language_id, a.delivery_customer_id, a.delivery_vendor_id, a.type,
1820 a.transaction_description, a.donumber, a.invnumber_for_credit_note,
1821 a.marge_total, a.marge_percent, a.direct_debit, a.delivery_term_id,
1824 LEFT JOIN employee e ON (e.id = a.employee_id)
1826 $ref = selectfirst_hashref_query($form, $dbh, $query, $id);
1827 map { $form->{$_} = $ref->{$_} } keys %{ $ref };
1829 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "buy");
1831 foreach my $vc (qw(customer vendor)) {
1832 next if !$form->{"delivery_${vc}_id"};
1833 ($form->{"delivery_${vc}_string"}) = selectrow_query($form, $dbh, qq|SELECT name FROM customer WHERE id = ?|, $id);
1836 # get printed, emailed
1837 $query = qq|SELECT printed, emailed, spoolfile, formname FROM status WHERE trans_id = ?|;
1838 $sth = prepare_execute_query($form, $dbh, $query, $id);
1840 while ($ref = $sth->fetchrow_hashref('NAME_lc')) {
1841 $form->{printed} .= "$ref->{formname} " if $ref->{printed};
1842 $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
1843 $form->{queued} .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
1846 map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
1848 my $transdate = $form->{deliverydate} ? $dbh->quote($form->{deliverydate})
1849 : $form->{invdate} ? $dbh->quote($form->{invdate})
1853 my $taxzone_id = $form->{taxzone_id} *= 1;
1854 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1856 # retrieve individual items
1859 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
1860 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from as income_valid,
1861 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
1864 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.discount, i.parts_id AS id, i.unit, i.deliverydate AS reqdate,
1865 i.project_id, i.serialnumber, i.pricegroup_id, i.ordnumber, i.donumber, i.transdate, i.cusordnumber, i.subtotal, i.lastcost,
1866 i.price_factor_id, i.price_factor, i.marge_price_factor, i.active_price_source, i.active_discount_source,
1867 p.partnumber, p.assembly, p.notes AS partnotes, p.inventory_accno_id AS part_inventory_accno_id, p.formel, p.listprice,
1868 pr.projectnumber, pg.partsgroup, prg.pricegroup
1871 LEFT JOIN parts p ON (i.parts_id = p.id)
1872 LEFT JOIN project pr ON (i.project_id = pr.id)
1873 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1874 LEFT JOIN pricegroup prg ON (i.pricegroup_id = prg.id)
1876 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
1877 LEFT JOIN chart c2 ON ((SELECT tc.income_accno_id FROM taxzone_charts tc WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
1878 LEFT JOIN chart c3 ON ((SELECT tc.expense_accno_id FROM taxzone_charts tc WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
1880 WHERE (i.trans_id = ?) AND NOT (i.assemblyitem = '1') ORDER BY i.position|;
1882 $sth = prepare_execute_query($form, $dbh, $query, $id);
1884 while (my $ref = $sth->fetchrow_hashref('NAME_lc')) {
1885 # Retrieve custom variables.
1886 my $cvars = CVar->get_custom_variables(dbh => $dbh,
1888 sub_module => 'invoice',
1889 trans_id => $ref->{invoice_id},
1891 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
1893 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
1894 delete($ref->{"part_inventory_accno_id"});
1896 foreach my $type (qw(inventory income expense)) {
1897 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
1898 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
1899 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
1903 # get tax rates and description
1904 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1906 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
1907 LEFT JOIN chart c ON (c.id = t.chart_id)
1909 (SELECT tk.tax_id FROM taxkeys tk
1910 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
1911 AND startdate <= date($transdate)
1912 ORDER BY startdate DESC LIMIT 1)
1914 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1915 $ref->{taxaccounts} = "";
1917 while (my $ptr = $stw->fetchrow_hashref('NAME_lc')) {
1919 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1923 $ref->{taxaccounts} .= "$ptr->{accno} ";
1925 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1926 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1927 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1928 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1929 $form->{taxaccounts} .= "$ptr->{accno} ";
1934 $ref->{qty} *= -1 if $form->{type} eq "credit_note";
1936 chop $ref->{taxaccounts};
1937 push @{ $form->{invoice_details} }, $ref;
1942 Common::webdav_folder($form);
1945 my $rc = $dbh->commit;
1947 $main::lxdebug->leave_sub();
1953 $main::lxdebug->enter_sub();
1955 my ($self, $myconfig, $form) = @_;
1957 # connect to database
1958 my $dbh = $form->get_standard_dbh;
1960 my $dateformat = $myconfig->{dateformat};
1961 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1963 my (@values, $duedate, $ref, $query);
1965 if ($form->{invdate}) {
1966 $duedate = "to_date(?, '$dateformat')";
1967 push @values, $form->{invdate};
1969 $duedate = "current_date";
1972 my $cid = conv_i($form->{customer_id});
1975 if ($form->{payment_id}) {
1976 $payment_id = "(pt.id = ?) OR";
1977 push @values, conv_i($form->{payment_id});
1983 c.id AS customer_id, c.name AS customer, c.discount as customer_discount, c.creditlimit,
1984 c.email, c.cc, c.bcc, c.language_id, c.payment_id, c.delivery_term_id,
1985 c.street, c.zipcode, c.city, c.country,
1986 c.notes AS intnotes, c.klass as customer_klass, c.taxzone_id, c.salesman_id, cu.name AS curr,
1987 c.taxincluded_checked, c.direct_debit,
1988 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1989 b.discount AS tradediscount, b.description AS business
1991 LEFT JOIN business b ON (b.id = c.business_id)
1992 LEFT JOIN payment_terms pt ON ($payment_id (c.payment_id = pt.id))
1993 LEFT JOIN currencies cu ON (c.currency_id=cu.id)
1996 $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1998 delete $ref->{salesman_id} if !$ref->{salesman_id};
2000 map { $form->{$_} = $ref->{$_} } keys %$ref;
2002 # use customer currency
2003 $form->{currency} = $form->{curr};
2006 qq|SELECT sum(amount - paid) AS dunning_amount
2008 WHERE (paid < amount)
2009 AND (customer_id = ?)
2010 AND (dunning_config_id IS NOT NULL)|;
2011 $ref = selectfirst_hashref_query($form, $dbh, $query, $cid);
2012 map { $form->{$_} = $ref->{$_} } keys %$ref;
2015 qq|SELECT dnn.dunning_description AS max_dunning_level
2016 FROM dunning_config dnn
2017 WHERE id IN (SELECT dunning_config_id
2019 WHERE (paid < amount) AND (customer_id = ?) AND (dunning_config_id IS NOT NULL))
2020 ORDER BY dunning_level DESC LIMIT 1|;
2021 $ref = selectfirst_hashref_query($form, $dbh, $query, $cid);
2022 map { $form->{$_} = $ref->{$_} } keys %$ref;
2024 $form->{creditremaining} = $form->{creditlimit};
2025 $query = qq|SELECT SUM(amount - paid) FROM ar WHERE customer_id = ?|;
2026 my ($value) = selectrow_query($form, $dbh, $query, $cid);
2027 $form->{creditremaining} -= $value;
2031 (SELECT e.buy FROM exchangerate e
2032 WHERE e.currency_id = o.currency_id
2033 AND e.transdate = o.transdate)
2035 WHERE o.customer_id = ?
2036 AND o.quotation = '0'
2037 AND o.closed = '0'|;
2038 my $sth = prepare_execute_query($form, $dbh, $query, $cid);
2040 while (my ($amount, $exch) = $sth->fetchrow_array) {
2041 $exch = 1 unless $exch;
2042 $form->{creditremaining} -= $amount * $exch;
2046 # setup last accounts used for this customer
2047 if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
2049 qq|SELECT c.id, c.accno, c.description, c.link, c.category
2051 JOIN acc_trans ac ON (ac.chart_id = c.id)
2052 JOIN ar a ON (a.id = ac.trans_id)
2053 WHERE a.customer_id = ?
2054 AND NOT (c.link LIKE '%_tax%' OR c.link LIKE '%_paid%')
2055 AND a.id IN (SELECT max(a2.id) FROM ar a2 WHERE a2.customer_id = ?)|;
2056 $sth = prepare_execute_query($form, $dbh, $query, $cid, $cid);
2059 while ($ref = $sth->fetchrow_hashref('NAME_lc')) {
2060 if ($ref->{category} eq 'I') {
2062 $form->{"AR_amount_$i"} = "$ref->{accno}--$ref->{description}";
2064 if ($form->{initial_transdate}) {
2066 qq|SELECT tk.tax_id, t.rate
2068 LEFT JOIN tax t ON tk.tax_id = t.id
2069 WHERE (tk.chart_id = ?) AND (startdate <= date(?))
2070 ORDER BY tk.startdate DESC
2072 my ($tax_id, $rate) =
2073 selectrow_query($form, $dbh, $tax_query, $ref->{id},
2074 $form->{initial_transdate});
2075 $form->{"taxchart_$i"} = "${tax_id}--${rate}";
2078 if ($ref->{category} eq 'A') {
2079 $form->{ARselected} = $form->{AR_1} = $ref->{accno};
2083 $form->{rowcount} = $i if ($i && !$form->{type});
2086 $main::lxdebug->leave_sub();
2090 $main::lxdebug->enter_sub();
2092 my ($self, $myconfig, $form) = @_;
2094 # connect to database
2095 my $dbh = $form->get_standard_dbh;
2097 my $i = $form->{rowcount};
2099 my $where = qq|NOT p.obsolete = '1'|;
2102 foreach my $column (qw(p.partnumber p.description pgpartsgroup )) {
2103 my ($table, $field) = split m/\./, $column;
2104 next if !$form->{"${field}_${i}"};
2105 $where .= qq| AND lower(${column}) ILIKE ?|;
2106 push @values, '%' . $form->{"${field}_${i}"} . '%';
2110 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
2111 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
2112 push @values, $form->{"partnumber_$i"};
2114 # also search hits in makemodels, but only cache the results by id and merge later
2116 SELECT parts_id, model FROM makemodel LEFT JOIN parts ON parts.id = parts_id WHERE NOT parts.obsolete AND model ILIKE ?;
2118 my $mm_results = selectall_hashref_query($::form, $dbh, $mm_query, '%' . $form->{"partnumber_$i"} . '%');
2119 my @mm_ids = map { $_->{parts_id} } @$mm_results;
2120 push @{$mm_by_id{ $_->{parts_id} } ||= []}, $_ for @$mm_results;
2123 $where .= qq| OR p.id IN (| . join(',', ('?') x @mm_ids) . qq|)|;
2124 push @values, @mm_ids;
2128 # Search for part ID overrides all other criteria.
2129 if ($form->{"id_${i}"}) {
2130 $where = qq|p.id = ?|;
2131 @values = ($form->{"id_${i}"});
2134 if ($form->{"description_$i"}) {
2135 $where .= qq| ORDER BY p.description|;
2137 $where .= qq| ORDER BY p.partnumber|;
2141 if ($form->{type} eq "invoice") {
2143 $form->{deliverydate} ? $dbh->quote($form->{deliverydate}) :
2144 $form->{invdate} ? $dbh->quote($form->{invdate}) :
2148 $form->{transdate} ? $dbh->quote($form->{transdate}) :
2152 my $taxzone_id = $form->{taxzone_id} * 1;
2153 $taxzone_id = 0 if (0 > $taxzone_id) || (3 < $taxzone_id);
2157 p.id, p.partnumber, p.description, p.sellprice,
2158 p.listprice, p.inventory_accno_id, p.lastcost,
2161 c1.accno AS inventory_accno,
2162 c1.new_chart_id AS inventory_new_chart,
2163 date($transdate) - c1.valid_from AS inventory_valid,
2165 c2.accno AS income_accno,
2166 c2.new_chart_id AS income_new_chart,
2167 date($transdate) - c2.valid_from AS income_valid,
2169 c3.accno AS expense_accno,
2170 c3.new_chart_id AS expense_new_chart,
2171 date($transdate) - c3.valid_from AS expense_valid,
2173 p.unit, p.assembly, p.onhand,
2174 p.notes AS partnotes, p.notes AS longdescription,
2175 p.not_discountable, p.formel, p.payment_id AS part_payment_id,
2176 p.price_factor_id, p.weight,
2178 pfac.factor AS price_factor,
2183 LEFT JOIN chart c1 ON
2184 ((SELECT inventory_accno_id
2185 FROM buchungsgruppen
2186 WHERE id = p.buchungsgruppen_id) = c1.id)
2187 LEFT JOIN chart c2 ON
2188 ((SELECT tc.income_accno_id
2189 FROM taxzone_charts tc
2190 WHERE tc.buchungsgruppen_id = p.buchungsgruppen_id and tc.taxzone_id = ${taxzone_id}) = c2.id)
2191 LEFT JOIN chart c3 ON
2192 ((SELECT tc.expense_accno_id
2193 FROM taxzone_charts tc
2194 WHERE tc.buchungsgruppen_id = p.buchungsgruppen_id and tc.taxzone_id = ${taxzone_id}) = c3.id)
2195 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
2196 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
2198 my $sth = prepare_execute_query($form, $dbh, $query, @values);
2200 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
2202 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
2203 [ qq|SELECT tr.translation, tr.longdescription
2205 WHERE tr.language_id IN
2208 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
2211 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
2213 while (my $ref = $sth->fetchrow_hashref('NAME_lc')) {
2215 if ($mm_by_id{$ref->{id}}) {
2216 $ref->{makemodels} = $mm_by_id{$ref->{id}};
2217 push @{ $ref->{matches} ||= [] }, $::locale->text('Model') . ': ' . join ', ', map { $_->{model} } @{ $mm_by_id{$ref->{id}} };
2220 if ($ref->{ean} eq $::form->{"partnumber_$i"}) {
2221 push @{ $ref->{matches} ||= [] }, $::locale->text('EAN') . ': ' . $ref->{ean};
2224 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
2225 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
2226 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
2227 if (!$ref->{inventory_accno_id}) {
2228 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
2230 delete($ref->{inventory_accno_id});
2232 foreach my $type (qw(inventory income expense)) {
2233 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
2235 qq|SELECT accno, new_chart_id, date($transdate) - valid_from
2238 ($ref->{"${type}_accno"},
2239 $ref->{"${type}_new_chart"},
2240 $ref->{"${type}_valid"})
2241 = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
2245 if ($form->{payment_id} eq "") {
2246 $form->{payment_id} = $form->{part_payment_id};
2249 # get tax rates and description
2250 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
2252 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
2254 LEFT JOIN chart c ON (c.id = t.chart_id)
2258 WHERE tk.chart_id = (SELECT id from chart WHERE accno = ?)
2260 ORDER BY startdate DESC
2263 @values = ($accno_id, $transdate eq "current_date" ? "now" : $transdate);
2264 my $stw = $dbh->prepare($query);
2265 $stw->execute(@values) || $form->dberror($query);
2267 $ref->{taxaccounts} = "";
2269 while (my $ptr = $stw->fetchrow_hashref('NAME_lc')) {
2271 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
2275 $ref->{taxaccounts} .= "$ptr->{accno} ";
2277 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
2278 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
2279 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
2280 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
2281 $form->{taxaccounts} .= "$ptr->{accno} ";
2287 chop $ref->{taxaccounts};
2289 if ($form->{language_id}) {
2290 for my $spec (@translation_queries) {
2291 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
2292 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
2293 next unless $translation;
2294 $ref->{description} = $translation;
2295 $ref->{longdescription} = $longdescription;
2300 $ref->{onhand} *= 1;
2302 push @{ $form->{item_list} }, $ref;
2305 $_->[1]->finish for @translation_queries;
2307 foreach my $item (@{ $form->{item_list} }) {
2308 my $custom_variables = CVar->get_custom_variables(module => 'IC',
2309 trans_id => $item->{id},
2313 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
2316 $main::lxdebug->leave_sub();
2320 $main::lxdebug->enter_sub();
2322 my ($self, $myconfig, $form, $table) = @_;
2324 $main::lxdebug->leave_sub() and return 0 unless ($form->{id});
2326 # make sure there's no funny stuff in $table
2327 # ToDO: die when this happens and throw an error
2328 $main::lxdebug->leave_sub() and return 0 if ($table =~ /\W/);
2330 my $dbh = $form->get_standard_dbh;
2332 my $query = qq|SELECT storno FROM $table WHERE storno_id = ?|;
2333 my ($result) = selectrow_query($form, $dbh, $query, $form->{id});
2335 $main::lxdebug->leave_sub();
2341 $main::lxdebug->enter_sub();
2343 my ($self, $myconfig, $form, $table, $id) = @_;
2345 $main::lxdebug->leave_sub() and return 0 unless ($id);
2347 # make sure there's no funny stuff in $table
2348 # ToDO: die when this happens and throw an error
2349 $main::lxdebug->leave_sub() and return 0 if ($table =~ /\W/);
2351 my $dbh = $form->get_standard_dbh;
2353 my $query = qq|SELECT storno FROM $table WHERE id = ?|;
2354 my ($result) = selectrow_query($form, $dbh, $query, $id);
2356 $main::lxdebug->leave_sub();
2361 sub get_standard_accno_current_assets {
2362 $main::lxdebug->enter_sub();
2364 my ($self, $myconfig, $form) = @_;
2366 my $dbh = $form->get_standard_dbh;
2368 my $query = qq| SELECT accno FROM chart WHERE id = (SELECT ar_paid_accno_id FROM defaults)|;
2369 my ($result) = selectrow_query($form, $dbh, $query);
2371 $main::lxdebug->leave_sub();