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->get_standard_dbh;
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}, $form->{unit});
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
502 for my $i (1 .. $form->{makemodel_rows}) {
503 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
505 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
506 if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
508 if ($form->{"lastupdate_$i"} eq "") {
509 $lastupdate = 'now()';
511 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
514 $lastupdate = 'now()';
516 $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
517 qq|VALUES (?, ?, ?, ?, ?, ?)|;
518 @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
520 do_query($form, $dbh, $query, @values);
525 foreach my $item (split(/ /, $form->{taxaccounts})) {
526 if ($form->{"IC_tax_$item"}) {
528 qq|INSERT INTO partstax (parts_id, chart_id)
529 VALUES (?, (SELECT id FROM chart WHERE accno = ?))|;
530 @values = (conv_i($form->{id}), $item);
531 do_query($form, $dbh, $query, @values);
535 # add assembly records
536 if ($form->{item} eq 'assembly') {
538 for my $i (1 .. $form->{assembly_rows}) {
539 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
541 if ($form->{"qty_$i"} != 0) {
542 $form->{"bom_$i"} *= 1;
543 $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
544 qq|VALUES (?, ?, ?, ?)|;
545 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
546 do_query($form, $dbh, $query, @values);
553 my $shippingdate = "$a[5]-$a[4]-$a[3]";
555 $form->get_employee($dbh);
559 #set expense_accno=inventory_accno if they are different => bilanz
561 ($form->{expense_accno} != $form->{inventory_accno})
562 ? $form->{inventory_accno}
563 : $form->{expense_accno};
565 # get tax rates and description
567 ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
569 qq|SELECT c.accno, c.description, t.rate, t.taxnumber
571 WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
573 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
575 $form->{taxaccount} = "";
576 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
577 $form->{taxaccount} .= "$ptr->{accno} ";
578 if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
579 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
580 $form->{"$ptr->{accno}_description"} = $ptr->{description};
581 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
582 $form->{taxaccount2} .= " $ptr->{accno} ";
586 CVar->save_custom_variables(dbh => $dbh,
588 trans_id => $form->{id},
593 my $rc = $dbh->commit;
595 $main::lxdebug->leave_sub();
600 sub update_assembly {
601 $main::lxdebug->enter_sub();
603 my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
605 my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
606 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
608 while (my ($pid, $aqty) = $sth->fetchrow_array) {
609 &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
614 qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
616 my @values = ($qty * ($form->{sellprice} - $sellprice),
617 $qty * ($form->{weight} - $weight), conv_i($id));
618 do_query($form, $dbh, $query, @values);
620 $main::lxdebug->leave_sub();
623 sub retrieve_assemblies {
624 $main::lxdebug->enter_sub();
626 my ($self, $myconfig, $form) = @_;
628 # connect to database
629 my $dbh = $form->dbconnect($myconfig);
631 my $where = qq|NOT p.obsolete|;
634 if ($form->{partnumber}) {
635 $where .= qq| AND (p.partnumber ILIKE ?)|;
636 push(@values, '%' . $form->{partnumber} . '%');
639 if ($form->{description}) {
640 $where .= qq| AND (p.description ILIKE ?)|;
641 push(@values, '%' . $form->{description} . '%');
644 # retrieve assembly items
646 qq|SELECT p.id, p.partnumber, p.description,
647 p.bin, p.onhand, p.rop,
648 (SELECT sum(p2.inventory_accno_id)
649 FROM parts p2, assembly a
650 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
652 WHERE NOT p.obsolete AND p.assembly $where|;
654 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
658 $main::lxdebug->leave_sub();
662 $main::lxdebug->enter_sub();
664 my ($self, $myconfig, $form) = @_;
665 my @values = (conv_i($form->{id}));
666 # connect to database, turn off AutoCommit
667 my $dbh = $form->dbconnect_noauto($myconfig);
669 my %columns = ( "assembly" => "id", "parts" => "id" );
671 for my $table (qw(prices partstax makemodel inventory assembly translation parts)) {
672 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
673 do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
677 my $rc = $dbh->commit;
680 $main::lxdebug->leave_sub();
686 $main::lxdebug->enter_sub();
688 my ($self, $myconfig, $form) = @_;
690 my $i = $form->{assembly_rows};
692 my $where = qq|1 = 1|;
695 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
697 while (my ($column, $table) = each(%columns)) {
698 next unless ($form->{"${column}_$i"});
699 $where .= qq| AND ${table}.${column} ILIKE ?|;
700 push(@values, '%' . $form->{"${column}_$i"} . '%');
704 $where .= qq| AND NOT (p.id = ?)|;
705 push(@values, conv_i($form->{id}));
708 # Search for part ID overrides all other criteria.
709 if ($form->{"id_${i}"}) {
710 $where = qq|p.id = ?|;
711 @values = ($form->{"id_${i}"});
714 if ($form->{partnumber}) {
715 $where .= qq| ORDER BY p.partnumber|;
717 $where .= qq| ORDER BY p.description|;
720 # connect to database
721 my $dbh = $form->dbconnect($myconfig);
724 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
725 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
726 p.price_factor_id, pfac.factor AS price_factor
728 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
729 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
731 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
735 $main::lxdebug->leave_sub();
740 # Warning, deep magic ahead.
741 # This function gets all parts from the database according to the filters specified
744 # sort revers - sorting field + direction
747 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
748 # partnumber ean description partsgroup microfiche drawing
751 # 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
754 # itemstatus = active | onhand | short | obsolete | orphaned
755 # searchitems = part | assembly | service
758 # make model - makemodel
759 # serialnumber transdatefrom transdateto - invoice/orderitems
762 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
763 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
764 # l_soldtotal - aggreg join to display total of sold quantity
765 # onhand - as above, but masking the simple itemstatus results (doh!)
766 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
767 # l_serialnumber - belonges to serialnumber filter
768 # l_deliverydate - displays deliverydate is sold etc. flags are active
769 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
772 # onhand - as above, but masking the simple itemstatus results (doh!)
774 # search by overrides of description
776 # disabled sanity checks and changes:
777 # - searchitems = assembly will no longer disable bought
778 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
779 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
780 # - itemstatus = obsolete will no longer disable onhand, short
781 # - allow sorting by ean
782 # - serialnumber filter also works if l_serialnumber isn't ticked
783 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
786 $main::lxdebug->enter_sub();
788 my ($self, $myconfig, $form) = @_;
789 my $dbh = $form->get_standard_dbh($myconfig);
791 $form->{parts} = +{ };
792 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
794 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
795 my @project_filters = qw(projectnumber projectdescription);
796 my @makemodel_filters = qw(make model);
797 my @invoice_oi_filters = qw(serialnumber soldtotal);
798 my @apoe_filters = qw(transdate);
799 my @like_filters = (@simple_filters, @invoice_oi_filters);
800 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
801 my @simple_l_switches = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
802 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
803 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
804 my @deliverydate_flags = qw(deliverydate);
805 # my @other_flags = qw(onhand); # ToDO: implement these
806 # my @inactive_flags = qw(l_subtotal short l_linetotal);
808 my @select_tokens = qw(id factor);
809 my @where_tokens = qw(1=1);
810 my @group_tokens = ();
812 my %joins_needed = ();
815 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
816 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
817 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
820 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
821 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
822 ) AS ioi ON ioi.parts_id = p.id|,
825 SELECT id, transdate, 'ir' AS module, ordnumber, quonumber, invnumber, FALSE AS quotation, NULL AS customer_id, vendor_id, NULL AS deliverydate, globalproject_id, 'invoice' AS ioi FROM ap UNION
826 SELECT id, transdate, 'is' AS module, ordnumber, quonumber, invnumber, FALSE AS quotation, customer_id, NULL AS vendor_id, deliverydate, globalproject_id, 'invoice' AS ioi FROM ar UNION
827 SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber, quotation, customer_id, vendor_id, reqdate AS deliverydate, globalproject_id, 'orderitems' AS ioi FROM oe
828 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
831 SELECT id, name, 'customer' AS cv FROM customer UNION
832 SELECT id, name, 'vendor' AS cv FROM vendor
833 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
834 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
835 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
837 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
840 deliverydate => 'apoe.', serialnumber => 'ioi.',
841 transdate => 'apoe.', trans_id => 'ioi.',
842 module => 'apoe.', name => 'cv.',
843 ordnumber => 'apoe.', make => 'mm.',
844 quonumber => 'apoe.', model => 'mm.',
845 invnumber => 'apoe.', partsgroup => 'pg.',
846 lastcost => 'p.', , soldtotal => ' ',
847 factor => 'pfac.', projectnumber => 'pj.',
848 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
851 serialnumber => 'ioi.',
852 quotation => 'apoe.',
858 # if the join condition in these blocks are met, the column
859 # of the scecified table will gently override (coalesce actually) the original value
860 # use it to conditionally coalesce values from subtables
861 my @column_override = (
862 # column name, prefix, joins_needed, nick name (in case column is named like another)
863 [ 'description', 'ioi.', 'invoice_oi' ],
864 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
865 [ 'transdate', 'apoe.', 'apoe' ],
866 [ 'unit', 'ioi.', 'invoice_oi' ],
867 [ 'sellprice', 'ioi.', 'invoice_oi' ],
870 # careful with renames. these are HARD, and any filters done on the original column will break
871 my %renamed_columns = (
872 'factor' => 'price_factor',
873 'SUM(ioi.qty)' => 'soldtotal',
874 'ioi.id' => 'ioi_id',
876 'projectdescription' => 'projectdescription',
880 projectdescription => 'description',
883 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
884 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
887 my $make_token_builder = sub {
888 my $joins_needed = shift;
890 my ($nick, $alias) = @_;
891 my ($col) = $real_column{$nick} || $nick;
892 my @coalesce_tokens =
893 map { ($_->[1] || 'p.') . $_->[0] }
894 grep { !$_->[2] || $joins_needed->{$_->[2]} }
895 grep { ($_->[3] || $_->[0]) eq $nick }
896 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
898 my $coalesce = scalar @coalesce_tokens > 1;
900 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
901 : shift @coalesce_tokens)
902 . ($alias && ($coalesce || $renamed_columns{$nick})
903 ? " AS " . ($renamed_columns{$nick} || $nick)
908 #===== switches and simple filters ========#
910 # special case transdate
911 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
912 $form->{"l_transdate"} = 1;
913 push @select_tokens, 'transdate';
914 for (qw(transdatefrom transdateto)) {
915 next unless $form->{$_};
916 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
917 push @bind_vars, $form->{$_};
921 if ($form->{"partsgroup_id"}) {
922 $form->{"l_partsgroup"} = '1'; # show the column
923 push @where_tokens, "pg.id = ?";
924 push @bind_vars, $form->{"partsgroup_id"};
927 foreach (@like_filters) {
928 next unless $form->{$_};
929 $form->{"l_$_"} = '1'; # show the column
930 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
931 push @bind_vars, "%$form->{$_}%";
934 foreach (@simple_l_switches) {
935 next unless $form->{"l_$_"};
936 push @select_tokens, $_;
939 for ($form->{searchitems}) {
940 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
941 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
942 push @where_tokens, 'NOT p.assembly' if /service/;
943 push @where_tokens, ' p.assembly' if /assembly/;
946 for ($form->{itemstatus}) {
947 push @where_tokens, 'p.id NOT IN
948 (SELECT DISTINCT parts_id FROM invoice UNION
949 SELECT DISTINCT parts_id FROM assembly UNION
950 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
951 push @where_tokens, 'p.onhand = 0' if /orphaned/;
952 push @where_tokens, 'NOT p.obsolete' if /active/;
953 push @where_tokens, ' p.obsolete', if /obsolete/;
954 push @where_tokens, 'p.onhand > 0', if /onhand/;
955 push @where_tokens, 'p.onhand < p.rop', if /short/;
958 my $q_assembly_lastcost =
959 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
961 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
962 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
963 WHERE (a_lc.id = p.id)) AS lastcost|;
964 $table_prefix{$q_assembly_lastcost} = ' ';
966 # special case makemodel search
967 # all_parts is based upon the assumption that every parameter is named like the column it represents
968 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
969 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
971 push @where_tokens, 'mv.name ILIKE ?';
972 push @bind_vars, "%$form->{make}%";
974 if ($form->{model}) {
975 push @where_tokens, 'mm.model ILIKE ?';
976 push @bind_vars, "%$form->{model}%";
979 # special case: sorting by partnumber
980 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
981 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
982 # ToDO: implement proper functional sorting
983 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
984 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
985 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
986 # if $form->{sort} eq 'partnumber';
988 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
991 $limit_clause = " LIMIT 100" if $form->{top100};
992 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
994 #=== joins and complicated filters ========#
996 my $bsooqr = any { $form->{$_} } @oe_flags;
997 my @bsooqr_tokens = ();
999 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
1000 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
1001 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
1002 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
1003 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
1004 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
1005 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
1006 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
1007 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
1008 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
1010 $joins_needed{partsgroup} = 1;
1011 $joins_needed{pfac} = 1;
1012 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
1013 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
1014 $joins_needed{mv} = 1 if $joins_needed{makemodel};
1015 $joins_needed{cv} = 1 if $bsooqr;
1016 $joins_needed{apoe} = 1 if $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
1017 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
1019 # special case for description search.
1020 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
1021 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
1022 # find the old entries in of @where_tokens and @bind_vars, and adjust them
1023 if ($joins_needed{invoice_oi}) {
1024 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
1025 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
1026 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
1027 splice @bind_vars, $bi, 0, $bind_vars[$bi];
1032 # now the master trick: soldtotal.
1033 if ($form->{l_soldtotal}) {
1034 push @where_tokens, 'NOT ioi.qty = 0';
1035 push @group_tokens, @select_tokens;
1036 map { s/.*\sAS\s+//si } @group_tokens;
1037 push @select_tokens, 'SUM(ioi.qty)';
1040 #============= build query ================#
1042 my $token_builder = $make_token_builder->(\%joins_needed);
1044 my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
1045 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
1046 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
1047 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
1049 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
1050 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
1051 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
1052 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
1054 my %oe_flag_to_cvar = (
1055 bought => 'invoice',
1057 onorder => 'orderitems',
1058 ordered => 'orderitems',
1059 rfq => 'orderitems',
1060 quoted => 'orderitems',
1063 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
1065 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1067 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1071 $where_clause .= qq| AND ($cvar_where)|;
1072 push @bind_vars, @cvar_values;
1075 my $query = <<" SQL";
1076 SELECT DISTINCT $select_clause
1085 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1087 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1089 # fix qty sign in ap. those are saved negative
1090 if ($bsooqr && $form->{bought}) {
1091 for my $row (@{ $form->{parts} }) {
1092 $row->{qty} *= -1 if $row->{module} eq 'ir';
1096 # post processing for assembly parts lists (bom)
1097 # for each part get the assembly parts and add them into the partlist.
1099 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1101 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1103 p.sellprice, p.listprice, p.lastcost,
1104 p.rop, p.weight, p.priceupdate,
1105 p.image, p.drawing, p.microfiche,
1108 INNER JOIN assembly a ON (p.id = a.parts_id)
1111 my $sth = prepare_query($form, $dbh, $query);
1113 foreach my $item (@{ $form->{parts} }) {
1114 push(@assemblies, $item);
1115 do_statement($form, $sth, $query, conv_i($item->{id}));
1117 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1118 $ref->{assemblyitem} = 1;
1119 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1120 push(@assemblies, $ref);
1125 # copy assemblies to $form->{parts}
1126 $form->{parts} = \@assemblies;
1129 $main::lxdebug->leave_sub();
1131 return wantarray ? @{ $form->{parts} } : $form->{parts};
1134 sub _create_filter_for_priceupdate {
1135 $main::lxdebug->enter_sub();
1138 my $myconfig = \%main::myconfig;
1139 my $form = $main::form;
1142 my $where = '1 = 1';
1144 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1146 $column =~ s/.*\.//;
1147 next unless ($form->{$column});
1149 $where .= qq| AND $item ILIKE ?|;
1150 push(@where_values, '%' . $form->{$column} . '%');
1153 foreach my $item (qw(description serialnumber)) {
1154 next unless ($form->{$item});
1156 $where .= qq| AND (${item} ILIKE ?)|;
1157 push(@where_values, '%' . $form->{$item} . '%');
1161 # items which were never bought, sold or on an order
1162 if ($form->{itemstatus} eq 'orphaned') {
1164 qq| AND (p.onhand = 0)
1167 SELECT DISTINCT parts_id FROM invoice
1169 SELECT DISTINCT parts_id FROM assembly
1171 SELECT DISTINCT parts_id FROM orderitems
1174 } elsif ($form->{itemstatus} eq 'active') {
1175 $where .= qq| AND p.obsolete = '0'|;
1177 } elsif ($form->{itemstatus} eq 'obsolete') {
1178 $where .= qq| AND p.obsolete = '1'|;
1180 } elsif ($form->{itemstatus} eq 'onhand') {
1181 $where .= qq| AND p.onhand > 0|;
1183 } elsif ($form->{itemstatus} eq 'short') {
1184 $where .= qq| AND p.onhand < p.rop|;
1188 foreach my $column (qw(make model)) {
1189 next unless ($form->{$column});
1190 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1191 push(@where_values, '%' . $form->{$column} . '%');
1194 $main::lxdebug->leave_sub();
1196 return ($where, @where_values);
1199 sub get_num_matches_for_priceupdate {
1200 $main::lxdebug->enter_sub();
1204 my $myconfig = \%main::myconfig;
1205 my $form = $main::form;
1207 my $dbh = $form->get_standard_dbh($myconfig);
1209 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1211 my $num_updated = 0;
1214 for my $column (qw(sellprice listprice)) {
1215 next if ($form->{$column} eq "");
1223 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1225 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1226 $num_updated += $result if (0 <= $result);
1235 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1236 WHERE $where) AND (pricegroup_id = ?)|;
1237 my $sth = prepare_query($form, $dbh, $query);
1239 for my $i (1 .. $form->{price_rows}) {
1240 next if ($form->{"price_$i"} eq "");
1242 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1243 $num_updated += $result if (0 <= $result);
1247 $main::lxdebug->leave_sub();
1249 return $num_updated;
1253 $main::lxdebug->enter_sub();
1255 my ($self, $myconfig, $form) = @_;
1257 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1258 my $num_updated = 0;
1260 # connect to database
1261 my $dbh = $form->dbconnect_noauto($myconfig);
1263 for my $column (qw(sellprice listprice)) {
1264 next if ($form->{$column} eq "");
1266 my $value = $form->parse_amount($myconfig, $form->{$column});
1269 if ($form->{"${column}_type"} eq "percent") {
1270 $value = ($value / 100) + 1;
1275 qq|UPDATE parts SET $column = $column $operator ?
1279 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1281 my $result = do_query($form, $dbh, $query, $value, @where_values);
1282 $num_updated += $result if (0 <= $result);
1286 qq|UPDATE prices SET price = price + ?
1290 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1291 WHERE $where) AND (pricegroup_id = ?)|;
1292 my $sth_add = prepare_query($form, $dbh, $q_add);
1295 qq|UPDATE prices SET price = price * ?
1299 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1300 WHERE $where) AND (pricegroup_id = ?)|;
1301 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1303 for my $i (1 .. $form->{price_rows}) {
1304 next if ($form->{"price_$i"} eq "");
1306 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1309 if ($form->{"pricegroup_type_$i"} eq "percent") {
1310 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1312 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1315 $num_updated += $result if (0 <= $result);
1319 $sth_multiply->finish();
1321 my $rc= $dbh->commit;
1324 $main::lxdebug->leave_sub();
1326 return $num_updated;
1330 $main::lxdebug->enter_sub();
1332 my ($self, $module, $myconfig, $form) = @_;
1334 # connect to database
1335 my $dbh = $form->dbconnect($myconfig);
1337 my @values = ('%' . $module . '%');
1342 qq|SELECT c.accno, c.description, c.link, c.id,
1343 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1344 FROM chart c, parts p
1345 WHERE (c.link LIKE ?) AND (p.id = ?)
1347 push(@values, conv_i($form->{id}));
1351 qq|SELECT c.accno, c.description, c.link, c.id,
1352 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1353 FROM chart c, defaults d
1358 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1359 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1360 foreach my $key (split(/:/, $ref->{link})) {
1361 if ($key =~ /\Q$module\E/) {
1362 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1363 || ($ref->{id} eq $ref->{income_accno_id})
1364 || ($ref->{id} eq $ref->{expense_accno_id})) {
1365 push @{ $form->{"${module}_links"}{$key} },
1366 { accno => $ref->{accno},
1367 description => $ref->{description},
1368 selected => "selected" };
1369 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1371 push @{ $form->{"${module}_links"}{$key} },
1372 { accno => $ref->{accno},
1373 description => $ref->{description},
1381 # get buchungsgruppen
1382 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1385 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1388 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1392 $main::lxdebug->leave_sub();
1395 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1397 $main::lxdebug->enter_sub();
1399 my ($self, $myconfig, $form, $sortorder) = @_;
1400 my $dbh = $form->dbconnect($myconfig);
1401 my $order = qq| p.partnumber|;
1402 my $where = qq|1 = 1|;
1405 if ($sortorder eq "all") {
1406 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1407 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1409 } elsif ($sortorder eq "partnumber") {
1410 $where .= qq| AND (partnumber ILIKE ?)|;
1411 push(@values, '%' . $form->{partnumber} . '%');
1413 } elsif ($sortorder eq "description") {
1414 $where .= qq| AND (description ILIKE ?)|;
1415 push(@values, '%' . $form->{description} . '%');
1416 $order = "description";
1421 qq|SELECT id, partnumber, description, unit, sellprice
1423 WHERE $where ORDER BY $order|;
1425 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1428 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1429 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1434 $form->{"id_$j"} = $ref->{id};
1435 $form->{"partnumber_$j"} = $ref->{partnumber};
1436 $form->{"description_$j"} = $ref->{description};
1437 $form->{"unit_$j"} = $ref->{unit};
1438 $form->{"sellprice_$j"} = $ref->{sellprice};
1439 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1445 $main::lxdebug->leave_sub();
1450 # gets sum of sold part with part_id
1452 $main::lxdebug->enter_sub();
1454 my ($dbh, $id) = @_;
1456 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1457 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1460 $main::lxdebug->leave_sub();
1463 } #end get_soldtotal
1465 sub retrieve_languages {
1466 $main::lxdebug->enter_sub();
1468 my ($self, $myconfig, $form) = @_;
1470 # connect to database
1471 my $dbh = $form->dbconnect($myconfig);
1477 if ($form->{language_values} ne "") {
1479 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1481 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1482 ORDER BY lower(l.description)|;
1483 @values = (conv_i($form->{id}));
1486 $query = qq|SELECT id, description
1488 ORDER BY lower(description)|;
1491 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1495 $main::lxdebug->leave_sub();
1500 sub follow_account_chain {
1501 $main::lxdebug->enter_sub(2);
1503 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1505 my @visited_accno_ids = ($accno_id);
1509 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1510 map { $_->{id} => $_ }
1511 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1512 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1514 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1515 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1519 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1520 last unless ($ref && $ref->{"is_valid"} &&
1521 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1522 $accno_id = $ref->{"new_chart_id"};
1523 $accno = $ref->{"accno"};
1524 push(@visited_accno_ids, $accno_id);
1527 $main::lxdebug->leave_sub(2);
1529 return ($accno_id, $accno);
1532 sub retrieve_accounts {
1533 $main::lxdebug->enter_sub;
1536 my $myconfig = shift;
1538 my $dbh = $form->get_standard_dbh;
1539 my %args = @_; # index => part_id
1541 $form->{taxzone_id} *= 1;
1543 return unless grep $_, values %args; # shortfuse if no part_id supplied
1545 # transdate madness.
1547 if ($form->{type} eq "invoice") {
1548 if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1549 $transdate = $form->{invdate};
1551 $transdate = $form->{deliverydate};
1553 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1554 $transdate = $form->{invdate};
1556 $transdate = $form->{transdate};
1559 if ($transdate eq "") {
1560 $transdate = DateTime->today_local->to_lxoffice;
1562 $transdate = $dbh->quote($transdate);
1565 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1567 my @part_ids = grep { $_ } values %args;
1568 my $in = join ',', ('?') x @part_ids;
1570 my %accno_by_part = map { $_->{id} => $_ }
1571 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1573 p.id, p.inventory_accno_id AS is_part,
1574 bg.inventory_accno_id,
1575 bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
1576 bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
1577 c1.accno AS inventory_accno,
1578 c2.accno AS income_accno,
1579 c3.accno AS expense_accno
1581 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1582 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1583 LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
1584 LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
1588 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1589 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1591 LEFT JOIN chart c ON c.id = t.chart_id
1595 WHERE tk.chart_id = ? AND startdate <= ?
1596 ORDER BY startdate DESC LIMIT 1)
1599 while (my ($index => $part_id) = each %args) {
1600 my $ref = $accno_by_part{$part_id} or next;
1602 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1605 for my $type (qw(inventory income expense)) {
1606 next unless $ref->{"${type}_accno_id"};
1607 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1608 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1611 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1613 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1614 $ref = $sth_tax->fetchrow_hashref or next;
1616 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1617 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1619 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1624 $::lxdebug->leave_sub;
1627 sub get_basic_part_info {
1628 $main::lxdebug->enter_sub();
1633 Common::check_params(\%params, qw(id));
1635 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1638 $main::lxdebug->leave_sub();
1642 my $myconfig = \%main::myconfig;
1643 my $form = $main::form;
1645 my $dbh = $form->get_standard_dbh($myconfig);
1647 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1649 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1651 if ('' eq ref $params{id}) {
1652 $info = $info->[0] || { };
1654 $main::lxdebug->leave_sub();
1658 my %info_map = map { $_->{id} => $_ } @{ $info };
1660 $main::lxdebug->leave_sub();
1665 sub prepare_parts_for_printing {
1666 $main::lxdebug->enter_sub();
1671 my $myconfig = \%main::myconfig;
1672 my $form = $main::form;
1674 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1676 my $prefix = $params{prefix} || 'id_';
1677 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1679 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1682 $main::lxdebug->leave_sub();
1686 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1687 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1689 LEFT JOIN vendor v ON (mm.make = v.id)
1690 WHERE mm.parts_id IN ($placeholders)|;
1694 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1696 while (my $ref = $sth->fetchrow_hashref()) {
1697 $makemodel{$ref->{parts_id}} ||= [];
1698 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1703 my @columns = qw(ean image microfiche drawing weight);
1705 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1707 WHERE id IN ($placeholders)|;
1709 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1711 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1713 foreach my $i (1 .. $rowcount) {
1714 my $id = $form->{"${prefix}${i}"};
1718 foreach (@columns) {
1719 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1722 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1723 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1725 next if (!$makemodel{$id});
1727 foreach my $ref (@{ $makemodel{$id} }) {
1728 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1732 $main::lxdebug->leave_sub();