1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
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 Control backend
33 #======================================================================
38 use List::MoreUtils qw(all any uniq);
48 $main::lxdebug->enter_sub();
50 my ($self, $myconfig, $form) = @_;
53 my $dbh = $form->dbconnect($myconfig);
59 c1.accno AS inventory_accno,
60 c2.accno AS income_accno,
61 c3.accno AS expense_accno,
64 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
65 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
66 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
67 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
69 my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
71 # copy to $form variables
72 map { $form->{$_} = $ref->{$_} } (keys %{$ref});
76 # part or service item
77 $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
78 if ($form->{assembly}) {
79 $form->{item} = 'assembly';
81 # retrieve assembly items
83 qq|SELECT p.id, p.partnumber, p.description,
84 p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
85 pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
87 JOIN assembly a ON (a.parts_id = p.id)
88 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
89 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
92 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
94 $form->{assembly_rows} = 0;
95 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
96 $form->{assembly_rows}++;
97 foreach my $key (keys %{$ref}) {
98 $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
105 # setup accno hash for <option checked> {amount} is used in create_links
106 $form->{amount}{IC} = $form->{inventory_accno};
107 $form->{amount}{IC_income} = $form->{income_accno};
108 $form->{amount}{IC_sale} = $form->{income_accno};
109 $form->{amount}{IC_expense} = $form->{expense_accno};
110 $form->{amount}{IC_cogs} = $form->{expense_accno};
112 my @pricegroups = ();
113 my @pricegroups_not_used = ();
117 qq|SELECT p.parts_id, p.pricegroup_id, p.price,
118 (SELECT pg.pricegroup
120 WHERE pg.id = p.pricegroup_id) AS pricegroup
123 ORDER BY pricegroup|;
124 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
128 while (($form->{"klass_$i"}, $form->{"pricegroup_id_$i"},
129 $form->{"price_$i"}, $form->{"pricegroup_$i"})
130 = $sth->fetchrow_array()) {
131 push @pricegroups, $form->{"pricegroup_id_$i"};
138 $query = qq|SELECT id, pricegroup FROM pricegroup|;
139 $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
141 #find not used pricegroups
142 while (my $tmp = pop(@{ $form->{PRICEGROUPS} })) {
144 foreach my $item (@pricegroups) {
145 if ($item eq $tmp->{id}) {
150 push(@pricegroups_not_used, $tmp) unless ($in_use);
153 # if not used pricegroups are avaible
154 if (@pricegroups_not_used) {
156 foreach my $name (@pricegroups_not_used) {
157 $form->{"klass_$i"} = "$name->{id}";
158 $form->{"pricegroup_id_$i"} = "$name->{id}";
159 $form->{"pricegroup_$i"} = "$name->{pricegroup}";
165 $form->{price_rows} = $i - 1;
167 unless ($form->{item} eq 'service') {
170 if ($form->{makemodel}) {
172 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
173 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
174 my @values = ($form->{id});
175 $sth = $dbh->prepare($query);
176 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
180 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
181 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
186 $form->{makemodel_rows} = $i - 1;
192 $form->{language_values} = "";
193 $query = qq|SELECT language_id, translation, longdescription
196 my $trq = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
197 while (my $tr = $trq->fetchrow_hashref("NAME_lc")) {
198 $form->{language_values} .= "---+++---" . join('--++--', @{$tr}{qw(language_id translation longdescription)});
202 # now get accno for taxes
205 FROM chart c, partstax pt
206 WHERE (pt.chart_id = c.id) AND (pt.parts_id = ?)|;
207 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
208 while (my ($key) = $sth->fetchrow_array) {
209 $form->{amount}{$key} = $key;
215 my @referencing_tables = qw(invoice orderitems inventory rmaitems);
216 my %column_map = ( );
217 my $parts_id = conv_i($form->{id});
219 $form->{orphaned} = 1;
221 foreach my $table (@referencing_tables) {
222 my $column = $column_map{$table} || 'parts_id';
223 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
224 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
227 $form->{orphaned} = 0;
232 $form->{"unit_changeable"} = $form->{orphaned};
236 $main::lxdebug->leave_sub();
239 sub get_pricegroups {
240 $main::lxdebug->enter_sub();
242 my ($self, $myconfig, $form) = @_;
244 my $dbh = $form->dbconnect($myconfig);
247 my $query = qq|SELECT id, pricegroup FROM pricegroup|;
248 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
251 foreach my $pg (@{ $pricegroups }) {
252 $form->{"klass_$i"} = "$pg->{id}";
253 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
254 $form->{"pricegroup_id_$i"} = "$pg->{id}";
255 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
260 $form->{price_rows} = $i - 1;
264 $main::lxdebug->leave_sub();
269 sub retrieve_buchungsgruppen {
270 $main::lxdebug->enter_sub();
272 my ($self, $myconfig, $form) = @_;
276 my $dbh = $form->dbconnect($myconfig);
278 # get buchungsgruppen
279 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
280 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
282 $main::lxdebug->leave_sub();
286 $main::lxdebug->enter_sub();
288 my ($self, $myconfig, $form) = @_;
290 # connect to database, turn off AutoCommit
291 my $dbh = $form->dbconnect_noauto($myconfig);
294 # make up a unique handle and store in partnumber field
295 # then retrieve the record based on the unique handle to get the id
296 # replace the partnumber field with the actual variable
297 # add records for makemodel
299 # if there is a $form->{id} then replace the old entry
300 # delete all makemodel entries and add the new ones
302 # undo amount formatting
303 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
304 qw(rop weight listprice sellprice gv lastcost);
306 my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
308 $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
312 my $priceupdate = ', priceupdate = current_date';
315 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
316 if (!$trans_number->is_unique) {
317 $::lxdebug->leave_sub;
322 $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
323 my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
325 # if item is part of an assembly adjust all assemblies
326 $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
327 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
328 while (my ($id, $qty) = $sth->fetchrow_array) {
329 &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
333 if ($form->{item} ne 'service') {
334 # delete makemodel records
335 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
338 if ($form->{item} eq 'assembly') {
339 # delete assembly records
340 do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
344 do_query($form, $dbh, qq|DELETE FROM partstax WHERE parts_id = ?|, conv_i($form->{id}));
346 # delete translations
347 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
349 # Check whether or not the prices have changed. If they haven't
350 # then 'priceupdate' should not be updated.
351 my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
352 $priceupdate = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
355 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, save => 1);
357 if ($form->{partnumber} && !$trans_number->is_unique) {
358 $::lxdebug->leave_sub;
362 $form->{partnumber} ||= $trans_number->create_unique;
364 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
365 do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, ?, '')|, $form->{id}, $form->{partnumber});
367 $form->{orphaned} = 1;
369 my $partsgroup_id = 0;
371 if ($form->{partsgroup}) {
372 (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
375 my ($subq_inventory, $subq_expense, $subq_income);
376 if ($form->{"item"} eq "part") {
378 qq|(SELECT bg.inventory_accno_id
379 FROM buchungsgruppen bg
380 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
382 $subq_inventory = "NULL";
385 if ($form->{"item"} ne "assembly") {
387 qq|(SELECT bg.expense_accno_id_0
388 FROM buchungsgruppen bg
389 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
391 $subq_expense = "NULL";
410 buchungsgruppen_id = ?,
412 inventory_accno_id = $subq_inventory,
413 income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
414 expense_accno_id = $subq_expense,
423 not_discountable = ?,
429 @values = ($form->{partnumber},
430 $form->{description},
431 $makemodel ? 't' : 'f',
432 $form->{assembly} ? 't' : 'f',
442 conv_i($form->{buchungsgruppen_id}),
443 conv_i($form->{payment_id}),
444 conv_i($form->{buchungsgruppen_id}),
445 $form->{obsolete} ? 't' : 'f',
448 $form->{shop} ? 't' : 'f',
452 $form->{has_sernumber} ? 't' : 'f',
453 $form->{not_discountable} ? 't' : 'f',
455 conv_i($partsgroup_id),
456 conv_i($form->{price_factor_id}),
459 do_query($form, $dbh, $query, @values);
461 # delete translation records
462 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
464 if ($form->{language_values} ne "") {
465 foreach my $item (split(/---\+\+\+---/, $form->{language_values})) {
466 my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
467 if ($translation ne "") {
468 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
469 VALUES ( ?, ?, ?, ? )|;
470 @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
471 do_query($form, $dbh, $query, @values);
476 # delete price records
477 do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
479 # insert price records only if different to sellprice
480 for my $i (1 .. $form->{price_rows}) {
481 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
483 $form->{"price_$i"} = $form->{sellprice};
487 || $form->{"klass_$i"}
488 || $form->{"pricegroup_id_$i"})
489 and $price != $form->{sellprice}
491 #$klass = $form->parse_amount($myconfig, $form->{"klass_$i"});
492 $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) | .
494 @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
495 do_query($form, $dbh, $query, @values);
499 # insert makemodel records
500 unless ($form->{item} eq 'service') {
503 for my $i (1 .. $form->{makemodel_rows}) {
504 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
506 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
507 if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
509 if ($form->{"lastupdate_$i"} eq "") {
510 $lastupdate = 'now()';
512 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
515 $lastupdate = 'now()';
517 $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
518 qq|VALUES (?, ?, ?, ?, ?, ?)|;
519 @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
521 do_query($form, $dbh, $query, @values);
527 foreach my $item (split(/ /, $form->{taxaccounts})) {
528 if ($form->{"IC_tax_$item"}) {
530 qq|INSERT INTO partstax (parts_id, chart_id)
531 VALUES (?, (SELECT id FROM chart WHERE accno = ?))|;
532 @values = (conv_i($form->{id}), $item);
533 do_query($form, $dbh, $query, @values);
537 # add assembly records
538 if ($form->{item} eq 'assembly') {
540 for my $i (1 .. $form->{assembly_rows}) {
541 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
543 if ($form->{"qty_$i"} != 0) {
544 $form->{"bom_$i"} *= 1;
545 $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
546 qq|VALUES (?, ?, ?, ?)|;
547 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
548 do_query($form, $dbh, $query, @values);
555 my $shippingdate = "$a[5]-$a[4]-$a[3]";
557 $form->get_employee($dbh);
561 #set expense_accno=inventory_accno if they are different => bilanz
563 ($form->{expense_accno} != $form->{inventory_accno})
564 ? $form->{inventory_accno}
565 : $form->{expense_accno};
567 # get tax rates and description
569 ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
571 qq|SELECT c.accno, c.description, t.rate, t.taxnumber
573 WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
575 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
577 $form->{taxaccount} = "";
578 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
579 $form->{taxaccount} .= "$ptr->{accno} ";
580 if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
581 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
582 $form->{"$ptr->{accno}_description"} = $ptr->{description};
583 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
584 $form->{taxaccount2} .= " $ptr->{accno} ";
588 CVar->save_custom_variables(dbh => $dbh,
590 trans_id => $form->{id},
595 my $rc = $dbh->commit;
598 $main::lxdebug->leave_sub();
603 sub update_assembly {
604 $main::lxdebug->enter_sub();
606 my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
608 my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
609 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
611 while (my ($pid, $aqty) = $sth->fetchrow_array) {
612 &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
617 qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
619 my @values = ($qty * ($form->{sellprice} - $sellprice),
620 $qty * ($form->{weight} - $weight), conv_i($id));
621 do_query($form, $dbh, $query, @values);
623 $main::lxdebug->leave_sub();
626 sub retrieve_assemblies {
627 $main::lxdebug->enter_sub();
629 my ($self, $myconfig, $form) = @_;
631 # connect to database
632 my $dbh = $form->dbconnect($myconfig);
634 my $where = qq|NOT p.obsolete|;
637 if ($form->{partnumber}) {
638 $where .= qq| AND (p.partnumber ILIKE ?)|;
639 push(@values, '%' . $form->{partnumber} . '%');
642 if ($form->{description}) {
643 $where .= qq| AND (p.description ILIKE ?)|;
644 push(@values, '%' . $form->{description} . '%');
647 # retrieve assembly items
649 qq|SELECT p.id, p.partnumber, p.description,
650 p.bin, p.onhand, p.rop,
651 (SELECT sum(p2.inventory_accno_id)
652 FROM parts p2, assembly a
653 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
655 WHERE NOT p.obsolete AND p.assembly $where|;
657 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
661 $main::lxdebug->leave_sub();
665 $main::lxdebug->enter_sub();
667 my ($self, $myconfig, $form) = @_;
668 my @values = (conv_i($form->{id}));
669 # connect to database, turn off AutoCommit
670 my $dbh = $form->dbconnect_noauto($myconfig);
672 my %columns = ( "assembly" => "id", "parts" => "id" );
674 for my $table (qw(prices partstax makemodel inventory assembly license translation parts)) {
675 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
676 do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
680 my $rc = $dbh->commit;
683 $main::lxdebug->leave_sub();
689 $main::lxdebug->enter_sub();
691 my ($self, $myconfig, $form) = @_;
693 my $i = $form->{assembly_rows};
695 my $where = qq|1 = 1|;
698 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
700 while (my ($column, $table) = each(%columns)) {
701 next unless ($form->{"${column}_$i"});
702 $where .= qq| AND ${table}.${column} ILIKE ?|;
703 push(@values, '%' . $form->{"${column}_$i"} . '%');
707 $where .= qq| AND NOT (p.id = ?)|;
708 push(@values, conv_i($form->{id}));
711 if ($form->{partnumber}) {
712 $where .= qq| ORDER BY p.partnumber|;
714 $where .= qq| ORDER BY p.description|;
717 # connect to database
718 my $dbh = $form->dbconnect($myconfig);
721 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
722 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
723 p.price_factor_id, pfac.factor AS price_factor
725 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
726 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
728 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
732 $main::lxdebug->leave_sub();
737 # Warning, deep magic ahead.
738 # This function gets all parts from the database according to the filters specified
741 # sort revers - sorting field + direction
744 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
745 # partnumber ean description partsgroup microfiche drawing
748 # l_partnumber l_description l_listprice l_sellprice l_lastcost l_priceupdate l_weight l_unit l_bin l_rop l_image l_drawing l_microfiche l_partsgroup
751 # itemstatus = active | onhand | short | obsolete | orphaned
752 # searchitems = part | assembly | service
755 # make model - makemodel
756 # serialnumber transdatefrom transdateto - invoice/orderitems
759 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
760 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
761 # l_soldtotal - aggreg join to display total of sold quantity
762 # onhand - as above, but masking the simple itemstatus results (doh!)
763 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
764 # l_serialnumber - belonges to serialnumber filter
765 # l_deliverydate - displays deliverydate is sold etc. flags are active
766 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
769 # onhand - as above, but masking the simple itemstatus results (doh!)
771 # search by overrides of description
773 # disabled sanity checks and changes:
774 # - searchitems = assembly will no longer disable bought
775 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
776 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
777 # - itemstatus = obsolete will no longer disable onhand, short
778 # - allow sorting by ean
779 # - serialnumber filter also works if l_serialnumber isn't ticked
780 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
783 $main::lxdebug->enter_sub();
785 my ($self, $myconfig, $form) = @_;
786 my $dbh = $form->get_standard_dbh($myconfig);
788 $form->{parts} = +{ };
789 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
791 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
792 my @makemodel_filters = qw(make model);
793 my @invoice_oi_filters = qw(serialnumber soldtotal);
794 my @apoe_filters = qw(transdate);
795 my @like_filters = (@simple_filters, @invoice_oi_filters);
796 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, qw(serialnumber));
797 my @simple_l_switches = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
798 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
799 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
800 my @deliverydate_flags = qw(deliverydate);
801 # my @other_flags = qw(onhand); # ToDO: implement these
802 # my @inactive_flags = qw(l_subtotal short l_linetotal);
804 my @select_tokens = qw(id factor);
805 my @where_tokens = qw(1=1);
806 my @group_tokens = ();
808 my %joins_needed = ();
811 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
812 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
813 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
816 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, id FROM invoice UNION
817 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, id FROM orderitems
818 ) AS ioi ON ioi.parts_id = p.id|,
821 SELECT id, transdate, 'ir' AS module, ordnumber, quonumber, invnumber, FALSE AS quotation, NULL AS customer_id, vendor_id, NULL AS deliverydate, 'invoice' AS ioi FROM ap UNION
822 SELECT id, transdate, 'is' AS module, ordnumber, quonumber, invnumber, FALSE AS quotation, customer_id, NULL AS vendor_id, deliverydate, 'invoice' AS ioi FROM ar UNION
823 SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber, quotation, customer_id, vendor_id, reqdate AS deliverydate, 'orderitems' AS ioi FROM oe
824 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
827 SELECT id, name, 'customer' AS cv FROM customer UNION
828 SELECT id, name, 'vendor' AS cv FROM vendor
829 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
830 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
832 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac);
835 deliverydate => 'apoe.', serialnumber => 'ioi.',
836 transdate => 'apoe.', trans_id => 'ioi.',
837 module => 'apoe.', name => 'cv.',
838 ordnumber => 'apoe.', make => 'mm.',
839 quonumber => 'apoe.', model => 'mm.',
840 invnumber => 'apoe.', partsgroup => 'pg.',
841 lastcost => 'p.', , soldtotal => ' ',
843 'SUM(ioi.qty)' => ' ',
846 serialnumber => 'ioi.',
847 quotation => 'apoe.',
853 # if the join condition in these blocks are met, the column
854 # of the scecified table will gently override (coalesce actually) the original value
855 # use it to conditionally coalesce values from subtables
856 my @column_override = (
857 # column name, prefix, joins_needed
858 [ 'description', 'ioi.', 'invoice_oi' ],
859 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
860 [ 'transdate', 'apoe.', 'apoe' ],
861 [ 'unit', 'ioi.', 'invoice_oi' ],
862 [ 'sellprice', 'ioi.', 'invoice_oi' ],
865 # careful with renames. these are HARD, and any filters done on the original column will break
866 my %renamed_columns = (
867 'factor' => 'price_factor',
868 'SUM(ioi.qty)' => 'soldtotal',
869 'ioi.id' => 'ioi_id',
873 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
874 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
877 my $make_token_builder = sub {
878 my $joins_needed = shift;
880 my ($col, $alias) = @_;
881 my @coalesce_tokens =
882 map { ($_->[1] || 'p.') . $_->[0] }
883 grep { !$_->[2] || $joins_needed->{$_->[2]} }
884 grep { $_->[0] eq $col }
885 @column_override, [ $col, $table_prefix{$col} ];
887 my $coalesce = scalar @coalesce_tokens > 1;
889 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
890 : shift @coalesce_tokens)
891 . ($alias && ($coalesce || $renamed_columns{$col})
892 ? " AS " . ($renamed_columns{$col} || $col)
897 #===== switches and simple filters ========#
899 # special case transdate
900 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
901 $form->{"l_transdate"} = 1;
902 push @select_tokens, 'transdate';
903 for (qw(transdatefrom transdateto)) {
904 next unless $form->{$_};
905 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
906 push @bind_vars, $form->{$_};
910 foreach (@like_filters) {
911 next unless $form->{$_};
912 $form->{"l_$_"} = '1'; # show the column
913 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
914 push @bind_vars, "%$form->{$_}%";
917 foreach (@simple_l_switches) {
918 next unless $form->{"l_$_"};
919 push @select_tokens, $_;
922 for ($form->{searchitems}) {
923 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
924 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
925 push @where_tokens, 'NOT p.assembly' if /service/;
926 push @where_tokens, ' p.assembly' if /assembly/;
929 for ($form->{itemstatus}) {
930 push @where_tokens, 'p.id NOT IN
931 (SELECT DISTINCT parts_id FROM invoice UNION
932 SELECT DISTINCT parts_id FROM assembly UNION
933 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
934 push @where_tokens, 'p.onhand = 0' if /orphaned/;
935 push @where_tokens, 'NOT p.obsolete' if /active/;
936 push @where_tokens, ' p.obsolete', if /obsolete/;
937 push @where_tokens, 'p.onhand > 0', if /onhand/;
938 push @where_tokens, 'p.onhand < p.rop', if /short/;
941 my $q_assembly_lastcost =
942 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
944 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
945 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
946 WHERE (a_lc.id = p.id)) AS lastcost|;
947 $table_prefix{$q_assembly_lastcost} = ' ';
949 # special case makemodel search
950 # all_parts is based upon the assumption that every parameter is named like the column it represents
951 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
952 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
954 push @where_tokens, 'mv.name ILIKE ?';
955 push @bind_vars, "%$form->{make}%";
957 if ($form->{model}) {
958 push @where_tokens, 'mm.model ILIKE ?';
959 push @bind_vars, "%$form->{model}%";
962 # special case: sorting by partnumber
963 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
964 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
965 # ToDO: implement proper functional sorting
966 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
967 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
968 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
969 # if $form->{sort} eq 'partnumber';
971 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
974 $limit_clause = " LIMIT 100" if $form->{top100};
975 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
977 #=== joins and complicated filters ========#
979 my $bsooqr = any { $form->{$_} } @oe_flags;
980 my @bsooqr_tokens = ();
982 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
983 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
984 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
985 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
986 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
987 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
988 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
989 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
990 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
991 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
993 $joins_needed{partsgroup} = 1;
994 $joins_needed{pfac} = 1;
995 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
996 $joins_needed{mv} = 1 if $joins_needed{makemodel};
997 $joins_needed{cv} = 1 if $bsooqr;
998 $joins_needed{apoe} = 1 if $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
999 $joins_needed{invoice_oi} = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
1001 # in bsoorq, use qtys instead of onhand
1002 if ($joins_needed{invoice_oi}) {
1003 $renamed_columns{onhand} = 'onhand_before_bsooqr';
1004 $renamed_columns{qty} = 'onhand';
1007 # special case for description search.
1008 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
1009 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
1010 # find the old entries in of @where_tokens and @bind_vars, and adjust them
1011 if ($joins_needed{invoice_oi}) {
1012 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
1013 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
1014 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
1015 splice @bind_vars, $bi, 0, $bind_vars[$bi];
1020 # now the master trick: soldtotal.
1021 if ($form->{l_soldtotal}) {
1022 push @where_tokens, 'NOT ioi.qty = 0';
1023 push @group_tokens, @select_tokens;
1024 map { s/.*\sAS\s+//si } @group_tokens;
1025 push @select_tokens, 'SUM(ioi.qty)';
1028 #============= build query ================#
1030 my $token_builder = $make_token_builder->(\%joins_needed);
1032 my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
1033 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
1034 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
1035 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
1037 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
1038 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
1039 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
1040 my $group_clause = ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens if scalar @group_tokens;
1042 my %oe_flag_to_cvar = (
1043 bought => 'invoice',
1045 onorder => 'orderitems',
1046 ordered => 'orderitems',
1047 rfq => 'orderitems',
1048 quoted => 'orderitems',
1051 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
1053 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1055 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1059 $where_clause .= qq| AND ($cvar_where)|;
1060 push @bind_vars, @cvar_values;
1063 my $query = <<" SQL";
1064 SELECT DISTINCT $select_clause
1073 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1075 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1077 # post processing for assembly parts lists (bom)
1078 # for each part get the assembly parts and add them into the partlist.
1080 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1082 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1084 p.sellprice, p.listprice, p.lastcost,
1085 p.rop, p.weight, p.priceupdate,
1086 p.image, p.drawing, p.microfiche,
1089 INNER JOIN assembly a ON (p.id = a.parts_id)
1092 my $sth = prepare_query($form, $dbh, $query);
1094 foreach my $item (@{ $form->{parts} }) {
1095 push(@assemblies, $item);
1096 do_statement($form, $sth, $query, conv_i($item->{id}));
1098 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1099 $ref->{assemblyitem} = 1;
1100 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1101 push(@assemblies, $ref);
1106 # copy assemblies to $form->{parts}
1107 $form->{parts} = \@assemblies;
1110 $main::lxdebug->leave_sub();
1112 return wantarray ? @{ $form->{parts} } : $form->{parts};
1115 sub _create_filter_for_priceupdate {
1116 $main::lxdebug->enter_sub();
1119 my $myconfig = \%main::myconfig;
1120 my $form = $main::form;
1123 my $where = '1 = 1';
1125 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1127 $column =~ s/.*\.//;
1128 next unless ($form->{$column});
1130 $where .= qq| AND $item ILIKE ?|;
1131 push(@where_values, '%' . $form->{$column} . '%');
1134 foreach my $item (qw(description serialnumber)) {
1135 next unless ($form->{$item});
1137 $where .= qq| AND (${item} ILIKE ?)|;
1138 push(@where_values, '%' . $form->{$item} . '%');
1142 # items which were never bought, sold or on an order
1143 if ($form->{itemstatus} eq 'orphaned') {
1145 qq| AND (p.onhand = 0)
1148 SELECT DISTINCT parts_id FROM invoice
1150 SELECT DISTINCT parts_id FROM assembly
1152 SELECT DISTINCT parts_id FROM orderitems
1155 } elsif ($form->{itemstatus} eq 'active') {
1156 $where .= qq| AND p.obsolete = '0'|;
1158 } elsif ($form->{itemstatus} eq 'obsolete') {
1159 $where .= qq| AND p.obsolete = '1'|;
1161 } elsif ($form->{itemstatus} eq 'onhand') {
1162 $where .= qq| AND p.onhand > 0|;
1164 } elsif ($form->{itemstatus} eq 'short') {
1165 $where .= qq| AND p.onhand < p.rop|;
1169 foreach my $column (qw(make model)) {
1170 next unless ($form->{$column});
1171 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1172 push(@where_values, '%' . $form->{$column} . '%');
1175 $main::lxdebug->leave_sub();
1177 return ($where, @where_values);
1180 sub get_num_matches_for_priceupdate {
1181 $main::lxdebug->enter_sub();
1185 my $myconfig = \%main::myconfig;
1186 my $form = $main::form;
1188 my $dbh = $form->get_standard_dbh($myconfig);
1190 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1192 my $num_updated = 0;
1195 for my $column (qw(sellprice listprice)) {
1196 next if ($form->{$column} eq "");
1204 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1206 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1207 $num_updated += $result if (0 <= $result);
1216 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1217 WHERE $where) AND (pricegroup_id = ?)|;
1218 my $sth = prepare_query($form, $dbh, $query);
1220 for my $i (1 .. $form->{price_rows}) {
1221 next if ($form->{"price_$i"} eq "");
1223 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1224 $num_updated += $result if (0 <= $result);
1228 $main::lxdebug->leave_sub();
1230 return $num_updated;
1234 $main::lxdebug->enter_sub();
1236 my ($self, $myconfig, $form) = @_;
1238 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1239 my $num_updated = 0;
1241 # connect to database
1242 my $dbh = $form->dbconnect_noauto($myconfig);
1244 for my $column (qw(sellprice listprice)) {
1245 next if ($form->{$column} eq "");
1247 my $value = $form->parse_amount($myconfig, $form->{$column});
1250 if ($form->{"${column}_type"} eq "percent") {
1251 $value = ($value / 100) + 1;
1256 qq|UPDATE parts SET $column = $column $operator ?
1260 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1262 my $result = do_query($form, $dbh, $query, $value, @where_values);
1263 $num_updated += $result if (0 <= $result);
1267 qq|UPDATE prices SET price = price + ?
1271 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1272 WHERE $where) AND (pricegroup_id = ?)|;
1273 my $sth_add = prepare_query($form, $dbh, $q_add);
1276 qq|UPDATE prices SET price = price * ?
1280 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1281 WHERE $where) AND (pricegroup_id = ?)|;
1282 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1284 for my $i (1 .. $form->{price_rows}) {
1285 next if ($form->{"price_$i"} eq "");
1287 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1290 if ($form->{"pricegroup_type_$i"} eq "percent") {
1291 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1293 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1296 $num_updated += $result if (0 <= $result);
1300 $sth_multiply->finish();
1302 my $rc= $dbh->commit;
1305 $main::lxdebug->leave_sub();
1307 return $num_updated;
1311 $main::lxdebug->enter_sub();
1313 my ($self, $module, $myconfig, $form) = @_;
1315 # connect to database
1316 my $dbh = $form->dbconnect($myconfig);
1318 my @values = ('%' . $module . '%');
1323 qq|SELECT c.accno, c.description, c.link, c.id,
1324 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1325 FROM chart c, parts p
1326 WHERE (c.link LIKE ?) AND (p.id = ?)
1328 push(@values, conv_i($form->{id}));
1332 qq|SELECT c.accno, c.description, c.link, c.id,
1333 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1334 FROM chart c, defaults d
1339 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1340 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1341 foreach my $key (split(/:/, $ref->{link})) {
1342 if ($key =~ /\Q$module\E/) {
1343 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1344 || ($ref->{id} eq $ref->{income_accno_id})
1345 || ($ref->{id} eq $ref->{expense_accno_id})) {
1346 push @{ $form->{"${module}_links"}{$key} },
1347 { accno => $ref->{accno},
1348 description => $ref->{description},
1349 selected => "selected" };
1350 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1352 push @{ $form->{"${module}_links"}{$key} },
1353 { accno => $ref->{accno},
1354 description => $ref->{description},
1362 # get buchungsgruppen
1363 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1366 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1369 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1373 $main::lxdebug->leave_sub();
1376 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1378 $main::lxdebug->enter_sub();
1380 my ($self, $myconfig, $form, $sortorder) = @_;
1381 my $dbh = $form->dbconnect($myconfig);
1382 my $order = qq| p.partnumber|;
1383 my $where = qq|1 = 1|;
1386 if ($sortorder eq "all") {
1387 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1388 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1390 } elsif ($sortorder eq "partnumber") {
1391 $where .= qq| AND (partnumber ILIKE ?)|;
1392 push(@values, '%' . $form->{partnumber} . '%');
1394 } elsif ($sortorder eq "description") {
1395 $where .= qq| AND (description ILIKE ?)|;
1396 push(@values, '%' . $form->{description} . '%');
1397 $order = "description";
1402 qq|SELECT id, partnumber, description, unit, sellprice
1404 WHERE $where ORDER BY $order|;
1406 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1409 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1410 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1415 $form->{"id_$j"} = $ref->{id};
1416 $form->{"partnumber_$j"} = $ref->{partnumber};
1417 $form->{"description_$j"} = $ref->{description};
1418 $form->{"unit_$j"} = $ref->{unit};
1419 $form->{"sellprice_$j"} = $ref->{sellprice};
1420 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1426 $main::lxdebug->leave_sub();
1431 # gets sum of sold part with part_id
1433 $main::lxdebug->enter_sub();
1435 my ($dbh, $id) = @_;
1437 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1438 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1441 $main::lxdebug->leave_sub();
1444 } #end get_soldtotal
1446 sub retrieve_languages {
1447 $main::lxdebug->enter_sub();
1449 my ($self, $myconfig, $form) = @_;
1451 # connect to database
1452 my $dbh = $form->dbconnect($myconfig);
1458 if ($form->{language_values} ne "") {
1460 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1462 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1463 ORDER BY lower(l.description)|;
1464 @values = (conv_i($form->{id}));
1467 $query = qq|SELECT id, description
1469 ORDER BY lower(description)|;
1472 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1476 $main::lxdebug->leave_sub();
1481 sub follow_account_chain {
1482 $main::lxdebug->enter_sub(2);
1484 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1486 my @visited_accno_ids = ($accno_id);
1490 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1491 map { $_->{id} => $_ }
1492 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1493 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1495 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1496 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1500 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1501 last unless ($ref && $ref->{"is_valid"} &&
1502 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1503 $accno_id = $ref->{"new_chart_id"};
1504 $accno = $ref->{"accno"};
1505 push(@visited_accno_ids, $accno_id);
1508 $main::lxdebug->leave_sub(2);
1510 return ($accno_id, $accno);
1513 sub retrieve_accounts {
1514 $main::lxdebug->enter_sub;
1517 my $myconfig = shift;
1519 my $dbh = $form->get_standard_dbh;
1520 my %args = @_; # index => part_id
1522 $form->{taxzone_id} *= 1;
1524 return unless grep $_, values %args; # shortfuse if no part_id supplied
1526 # transdate madness.
1528 if ($form->{type} eq "invoice") {
1529 if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1530 $transdate = $form->{invdate};
1532 $transdate = $form->{deliverydate};
1534 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1535 $transdate = $form->{invdate};
1537 $transdate = $form->{transdate};
1540 if ($transdate eq "") {
1541 $transdate = DateTime->today_local->to_lxoffice;
1543 $transdate = $dbh->quote($transdate);
1546 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1548 my @part_ids = grep { $_ } values %args;
1549 my $in = join ',', ('?') x @part_ids;
1551 my %accno_by_part = map { $_->{id} => $_ }
1552 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1554 p.id, p.inventory_accno_id AS is_part,
1555 bg.inventory_accno_id,
1556 bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
1557 bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
1558 c1.accno AS inventory_accno,
1559 c2.accno AS income_accno,
1560 c3.accno AS expense_accno
1562 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1563 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1564 LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
1565 LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
1569 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1570 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1572 LEFT JOIN chart c ON c.id = t.chart_id
1576 WHERE tk.chart_id = ? AND startdate <= ?
1577 ORDER BY startdate DESC LIMIT 1)
1580 while (my ($index => $part_id) = each %args) {
1581 my $ref = $accno_by_part{$part_id} or next;
1583 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1586 for my $type (qw(inventory income expense)) {
1587 next unless $ref->{"${type}_accno_id"};
1588 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1589 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1592 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1594 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1595 $ref = $sth_tax->fetchrow_hashref or next;
1597 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1598 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1600 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1605 $::lxdebug->leave_sub;
1608 sub get_basic_part_info {
1609 $main::lxdebug->enter_sub();
1614 Common::check_params(\%params, qw(id));
1616 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1619 $main::lxdebug->leave_sub();
1623 my $myconfig = \%main::myconfig;
1624 my $form = $main::form;
1626 my $dbh = $form->get_standard_dbh($myconfig);
1628 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1630 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1632 if ('' eq ref $params{id}) {
1633 $info = $info->[0] || { };
1635 $main::lxdebug->leave_sub();
1639 my %info_map = map { $_->{id} => $_ } @{ $info };
1641 $main::lxdebug->leave_sub();
1646 sub prepare_parts_for_printing {
1647 $main::lxdebug->enter_sub();
1652 my $myconfig = \%main::myconfig;
1653 my $form = $main::form;
1655 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1657 my $prefix = $params{prefix} || 'id_';
1658 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1660 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1663 $main::lxdebug->leave_sub();
1667 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1668 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1670 LEFT JOIN vendor v ON (mm.make = v.id)
1671 WHERE mm.parts_id IN ($placeholders)|;
1675 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1677 while (my $ref = $sth->fetchrow_hashref()) {
1678 $makemodel{$ref->{parts_id}} ||= [];
1679 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1684 my @columns = qw(ean image microfiche drawing weight);
1686 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1688 WHERE id IN ($placeholders)|;
1690 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1692 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1694 foreach my $i (1 .. $rowcount) {
1695 my $id = $form->{"${prefix}${i}"};
1699 foreach (@columns) {
1700 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1703 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1704 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1706 next if (!$makemodel{$id});
1708 foreach my $ref (@{ $makemodel{$id} }) {
1709 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1713 $main::lxdebug->leave_sub();