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);
47 $main::lxdebug->enter_sub();
49 my ($self, $myconfig, $form) = @_;
52 my $dbh = $form->dbconnect($myconfig);
58 c1.accno AS inventory_accno,
59 c2.accno AS income_accno,
60 c3.accno AS expense_accno,
63 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
64 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
65 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
66 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
68 my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
70 # copy to $form variables
71 map { $form->{$_} = $ref->{$_} } (keys %{$ref});
75 # part or service item
76 $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
77 if ($form->{assembly}) {
78 $form->{item} = 'assembly';
80 # retrieve assembly items
82 qq|SELECT p.id, p.partnumber, p.description,
83 p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
84 pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
86 JOIN assembly a ON (a.parts_id = p.id)
87 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
88 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
91 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
93 $form->{assembly_rows} = 0;
94 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
95 $form->{assembly_rows}++;
96 foreach my $key (keys %{$ref}) {
97 $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
104 # setup accno hash for <option checked> {amount} is used in create_links
105 $form->{amount}{IC} = $form->{inventory_accno};
106 $form->{amount}{IC_income} = $form->{income_accno};
107 $form->{amount}{IC_sale} = $form->{income_accno};
108 $form->{amount}{IC_expense} = $form->{expense_accno};
109 $form->{amount}{IC_cogs} = $form->{expense_accno};
111 my @pricegroups = ();
112 my @pricegroups_not_used = ();
116 qq|SELECT p.parts_id, p.pricegroup_id, p.price,
117 (SELECT pg.pricegroup
119 WHERE pg.id = p.pricegroup_id) AS pricegroup
122 ORDER BY pricegroup|;
123 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
127 while (($form->{"klass_$i"}, $form->{"pricegroup_id_$i"},
128 $form->{"price_$i"}, $form->{"pricegroup_$i"})
129 = $sth->fetchrow_array()) {
130 push @pricegroups, $form->{"pricegroup_id_$i"};
137 $query = qq|SELECT id, pricegroup FROM pricegroup|;
138 $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
140 #find not used pricegroups
141 while (my $tmp = pop(@{ $form->{PRICEGROUPS} })) {
143 foreach my $item (@pricegroups) {
144 if ($item eq $tmp->{id}) {
149 push(@pricegroups_not_used, $tmp) unless ($in_use);
152 # if not used pricegroups are avaible
153 if (@pricegroups_not_used) {
155 foreach my $name (@pricegroups_not_used) {
156 $form->{"klass_$i"} = "$name->{id}";
157 $form->{"pricegroup_id_$i"} = "$name->{id}";
158 $form->{"pricegroup_$i"} = "$name->{pricegroup}";
164 $form->{price_rows} = $i - 1;
166 unless ($form->{item} eq 'service') {
169 if ($form->{makemodel}) {
171 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
172 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
173 my @values = ($form->{id});
174 $sth = $dbh->prepare($query);
175 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
179 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
180 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
185 $form->{makemodel_rows} = $i - 1;
191 $form->{language_values} = "";
192 $query = qq|SELECT language_id, translation, longdescription
195 my $trq = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
196 while (my $tr = $trq->fetchrow_hashref("NAME_lc")) {
197 $form->{language_values} .= "---+++---" . join('--++--', @{$tr}{qw(language_id translation longdescription)});
201 # now get accno for taxes
204 FROM chart c, partstax pt
205 WHERE (pt.chart_id = c.id) AND (pt.parts_id = ?)|;
206 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
207 while (my ($key) = $sth->fetchrow_array) {
208 $form->{amount}{$key} = $key;
214 my @referencing_tables = qw(invoice orderitems inventory rmaitems);
215 my %column_map = ( );
216 my $parts_id = conv_i($form->{id});
218 $form->{orphaned} = 1;
220 foreach my $table (@referencing_tables) {
221 my $column = $column_map{$table} || 'parts_id';
222 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
223 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
226 $form->{orphaned} = 0;
231 $form->{"unit_changeable"} = $form->{orphaned};
235 $main::lxdebug->leave_sub();
238 sub get_pricegroups {
239 $main::lxdebug->enter_sub();
241 my ($self, $myconfig, $form) = @_;
243 my $dbh = $form->dbconnect($myconfig);
246 my $query = qq|SELECT id, pricegroup FROM pricegroup|;
247 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
250 foreach my $pg (@{ $pricegroups }) {
251 $form->{"klass_$i"} = "$pg->{id}";
252 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
253 $form->{"pricegroup_id_$i"} = "$pg->{id}";
254 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
259 $form->{price_rows} = $i - 1;
263 $main::lxdebug->leave_sub();
268 sub retrieve_buchungsgruppen {
269 $main::lxdebug->enter_sub();
271 my ($self, $myconfig, $form) = @_;
275 my $dbh = $form->dbconnect($myconfig);
277 # get buchungsgruppen
278 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
279 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
281 $main::lxdebug->leave_sub();
285 $main::lxdebug->enter_sub();
287 my ($self, $myconfig, $form) = @_;
289 # connect to database, turn off AutoCommit
290 my $dbh = $form->dbconnect_noauto($myconfig);
293 # make up a unique handle and store in partnumber field
294 # then retrieve the record based on the unique handle to get the id
295 # replace the partnumber field with the actual variable
296 # add records for makemodel
298 # if there is a $form->{id} then replace the old entry
299 # delete all makemodel entries and add the new ones
301 # undo amount formatting
302 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
303 qw(rop weight listprice sellprice gv lastcost);
305 my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
307 $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
311 my $priceupdate = ', priceupdate = current_date';
316 $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
317 my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
319 # if item is part of an assembly adjust all assemblies
320 $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
321 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
322 while (my ($id, $qty) = $sth->fetchrow_array) {
323 &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
327 if ($form->{item} ne 'service') {
328 # delete makemodel records
329 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
332 if ($form->{item} eq 'assembly') {
333 # delete assembly records
334 do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
338 do_query($form, $dbh, qq|DELETE FROM partstax WHERE parts_id = ?|, conv_i($form->{id}));
340 # delete translations
341 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
343 # Check whether or not the prices have changed. If they haven't
344 # then 'priceupdate' should not be updated.
345 my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
346 $priceupdate = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
349 my ($count) = selectrow_query($form, $dbh, qq|SELECT COUNT(*) FROM parts WHERE partnumber = ?|, $form->{partnumber});
351 $main::lxdebug->leave_sub();
355 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
356 do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, '', '')|, $form->{id});
358 $form->{orphaned} = 1;
359 if ($form->{partnumber} eq "" && $form->{"item"} eq "service") {
360 $form->{partnumber} = $form->update_defaults($myconfig, "servicenumber");
362 if ($form->{partnumber} eq "" && $form->{"item"} ne "service") {
363 $form->{partnumber} = $form->update_defaults($myconfig, "articlenumber");
367 my $partsgroup_id = 0;
369 if ($form->{partsgroup}) {
370 (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
373 my ($subq_inventory, $subq_expense, $subq_income);
374 if ($form->{"item"} eq "part") {
376 qq|(SELECT bg.inventory_accno_id
377 FROM buchungsgruppen bg
378 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
380 $subq_inventory = "NULL";
383 if ($form->{"item"} ne "assembly") {
385 qq|(SELECT bg.expense_accno_id_0
386 FROM buchungsgruppen bg
387 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
389 $subq_expense = "NULL";
408 buchungsgruppen_id = ?,
410 inventory_accno_id = $subq_inventory,
411 income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
412 expense_accno_id = $subq_expense,
421 not_discountable = ?,
427 @values = ($form->{partnumber},
428 $form->{description},
429 $makemodel ? 't' : 'f',
430 $form->{assembly} ? 't' : 'f',
440 conv_i($form->{buchungsgruppen_id}),
441 conv_i($form->{payment_id}),
442 conv_i($form->{buchungsgruppen_id}),
443 $form->{obsolete} ? 't' : 'f',
446 $form->{shop} ? 't' : 'f',
450 $form->{has_sernumber} ? 't' : 'f',
451 $form->{not_discountable} ? 't' : 'f',
453 conv_i($partsgroup_id),
454 conv_i($form->{price_factor_id}),
457 do_query($form, $dbh, $query, @values);
459 # delete translation records
460 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
462 if ($form->{language_values} ne "") {
463 foreach my $item (split(/---\+\+\+---/, $form->{language_values})) {
464 my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
465 if ($translation ne "") {
466 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
467 VALUES ( ?, ?, ?, ? )|;
468 @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
469 do_query($form, $dbh, $query, @values);
474 # delete price records
475 do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
477 # insert price records only if different to sellprice
478 for my $i (1 .. $form->{price_rows}) {
479 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
481 $form->{"price_$i"} = $form->{sellprice};
485 || $form->{"klass_$i"}
486 || $form->{"pricegroup_id_$i"})
487 and $price != $form->{sellprice}
489 #$klass = $form->parse_amount($myconfig, $form->{"klass_$i"});
490 $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) | .
492 @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
493 do_query($form, $dbh, $query, @values);
497 # insert makemodel records
498 unless ($form->{item} eq 'service') {
501 for my $i (1 .. $form->{makemodel_rows}) {
502 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
504 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
505 if ($value == $form->{"old_lastcost_$i"})
507 if ($form->{"lastupdate_$i"} eq "") {
508 $lastupdate = 'now()';
510 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
513 $lastupdate = 'now()';
515 $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
516 qq|VALUES (?, ?, ?, ?, ?, ?)|;
517 @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
519 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},
589 'variables' => $form);
592 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 license 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 if ($form->{partnumber}) {
709 $where .= qq| ORDER BY p.partnumber|;
711 $where .= qq| ORDER BY p.description|;
714 # connect to database
715 my $dbh = $form->dbconnect($myconfig);
718 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
719 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
720 p.price_factor_id, pfac.factor AS price_factor
722 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
723 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
725 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
729 $main::lxdebug->leave_sub();
734 # Warning, deep magic ahead.
735 # This function gets all parts from the database according to the filters specified
738 # sort revers - sorting field + direction
741 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
742 # partnumber ean description partsgroup microfiche drawing
745 # 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
748 # itemstatus = active | onhand | short | obsolete | orphaned
749 # searchitems = part | assembly | service
752 # make model - makemodel
753 # serialnumber transdatefrom transdateto - invoice/orderitems
756 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
757 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
758 # l_soldtotal - aggreg join to display total of sold quantity
759 # onhand - as above, but masking the simple itemstatus results (doh!)
760 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
761 # l_serialnumber - belonges to serialnumber filter
762 # l_deliverydate - displays deliverydate is sold etc. flags are active
763 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
766 # onhand - as above, but masking the simple itemstatus results (doh!)
768 # search by overrides of description
770 # disabled sanity checks and changes:
771 # - searchitems = assembly will no longer disable bought
772 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
773 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
774 # - itemstatus = obsolete will no longer disable onhand, short
775 # - allow sorting by ean
776 # - serialnumber filter also works if l_serialnumber isn't ticked
777 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
780 $main::lxdebug->enter_sub();
782 my ($self, $myconfig, $form) = @_;
783 my $dbh = $form->get_standard_dbh($myconfig);
785 $form->{parts} = +{ };
786 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
788 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
789 my @makemodel_filters = qw(make model);
790 my @invoice_oi_filters = qw(serialnumber soldtotal);
791 my @apoe_filters = qw(transdate);
792 my @like_filters = (@simple_filters, @invoice_oi_filters);
793 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, qw(serialnumber));
794 my @simple_l_switches = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
795 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
796 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
797 my @deliverydate_flags = qw(deliverydate);
798 # my @other_flags = qw(onhand); # ToDO: implement these
799 # my @inactive_flags = qw(l_subtotal short l_linetotal);
801 my @select_tokens = qw(id factor);
802 my @where_tokens = qw(1=1);
803 my @group_tokens = ();
805 my %joins_needed = ();
808 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
809 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
810 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
813 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, id FROM invoice UNION
814 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, id FROM orderitems
815 ) AS ioi ON ioi.parts_id = p.id|,
818 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
819 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
820 SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber, quotation, customer_id, vendor_id, reqdate AS deliverydate, 'orderitems' AS ioi FROM oe
821 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
824 SELECT id, name, 'customer' AS cv FROM customer UNION
825 SELECT id, name, 'vendor' AS cv FROM vendor
826 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
827 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
829 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac);
832 deliverydate => 'apoe.', serialnumber => 'ioi.',
833 transdate => 'apoe.', trans_id => 'ioi.',
834 module => 'apoe.', name => 'cv.',
835 ordnumber => 'apoe.', make => 'mm.',
836 quonumber => 'apoe.', model => 'mm.',
837 invnumber => 'apoe.', partsgroup => 'pg.',
838 lastcost => 'p.', , soldtotal => ' ',
840 'SUM(ioi.qty)' => ' ',
843 serialnumber => 'ioi.',
844 quotation => 'apoe.',
850 # if the join condition in these blocks are met, the column
851 # of the scecified table will gently override (coalesce actually) the original value
852 # use it to conditionally coalesce values from subtables
853 my @column_override = (
854 # column name, prefix, joins_needed
855 [ 'description', 'ioi.', 'invoice_oi' ],
856 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
857 [ 'transdate', 'apoe.', 'apoe' ],
858 [ 'unit', 'ioi.', 'invoice_oi' ],
859 [ 'sellprice', 'ioi.', 'invoice_oi' ],
862 # careful with renames. these are HARD, and any filters done on the original column will break
863 my %renamed_columns = (
864 'factor' => 'price_factor',
865 'SUM(ioi.qty)' => 'soldtotal',
866 'ioi.id' => 'ioi_id',
870 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
871 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
874 my $make_token_builder = sub {
875 my $joins_needed = shift;
877 my ($col, $alias) = @_;
878 my @coalesce_tokens =
879 map { ($_->[1] || 'p.') . $_->[0] }
880 grep { !$_->[2] || $joins_needed->{$_->[2]} }
881 grep { $_->[0] eq $col }
882 @column_override, [ $col, $table_prefix{$col} ];
884 my $coalesce = scalar @coalesce_tokens > 1;
886 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
887 : shift @coalesce_tokens)
888 . ($alias && ($coalesce || $renamed_columns{$col})
889 ? " AS " . ($renamed_columns{$col} || $col)
894 #===== switches and simple filters ========#
896 # special case transdate
897 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
898 $form->{"l_transdate"} = 1;
899 push @select_tokens, 'transdate';
900 for (qw(transdatefrom transdateto)) {
901 next unless $form->{$_};
902 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
903 push @bind_vars, $form->{$_};
907 foreach (@like_filters) {
908 next unless $form->{$_};
909 $form->{"l_$_"} = '1'; # show the column
910 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
911 push @bind_vars, "%$form->{$_}%";
914 foreach (@simple_l_switches) {
915 next unless $form->{"l_$_"};
916 push @select_tokens, $_;
919 for ($form->{searchitems}) {
920 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
921 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
922 push @where_tokens, 'NOT p.assembly' if /service/;
923 push @where_tokens, ' p.assembly' if /assembly/;
926 for ($form->{itemstatus}) {
927 push @where_tokens, 'p.id NOT IN
928 (SELECT DISTINCT parts_id FROM invoice UNION
929 SELECT DISTINCT parts_id FROM assembly UNION
930 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
931 push @where_tokens, 'p.onhand = 0' if /orphaned/;
932 push @where_tokens, 'NOT p.obsolete' if /active/;
933 push @where_tokens, ' p.obsolete', if /obsolete/;
934 push @where_tokens, 'p.onhand > 0', if /onhand/;
935 push @where_tokens, 'p.onhand < p.rop', if /short/;
938 my $q_assembly_lastcost =
939 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
941 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
942 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
943 WHERE (a_lc.id = p.id)) AS lastcost|;
944 $table_prefix{$q_assembly_lastcost} = ' ';
946 # special case makemodel search
947 # all_parts is based upon the assumption that every parameter is named like the column it represents
948 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
949 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
951 push @where_tokens, 'mv.name ILIKE ?';
952 push @bind_vars, "%$form->{make}%";
954 if ($form->{model}) {
955 push @where_tokens, 'mm.model ILIKE ?';
956 push @bind_vars, "%$form->{model}%";
959 # special case: sorting by partnumber
960 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
961 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
962 # ToDO: implement proper functional sorting
963 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
964 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
965 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
966 # if $form->{sort} eq 'partnumber';
968 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
971 $limit_clause = " LIMIT 100" if $form->{top100};
972 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
974 #=== joins and complicated filters ========#
976 my $bsooqr = any { $form->{$_} } @oe_flags;
977 my @bsooqr_tokens = ();
979 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
980 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
981 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
982 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
983 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
984 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
985 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
986 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
987 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
988 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
990 $joins_needed{partsgroup} = 1;
991 $joins_needed{pfac} = 1;
992 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
993 $joins_needed{mv} = 1 if $joins_needed{makemodel};
994 $joins_needed{cv} = 1 if $bsooqr;
995 $joins_needed{apoe} = 1 if $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
996 $joins_needed{invoice_oi} = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
998 # in bsoorq, use qtys instead of onhand
999 if ($joins_needed{invoice_oi}) {
1000 $renamed_columns{onhand} = 'onhand_before_bsooqr';
1001 $renamed_columns{qty} = 'onhand';
1004 # special case for description search.
1005 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
1006 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
1007 # find the old entries in of @where_tokens and @bind_vars, and adjust them
1008 if ($joins_needed{invoice_oi}) {
1009 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
1010 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
1011 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
1012 splice @bind_vars, $bi, 0, $bind_vars[$bi];
1017 # now the master trick: soldtotal.
1018 if ($form->{l_soldtotal}) {
1019 push @where_tokens, 'NOT ioi.qty = 0';
1020 push @group_tokens, @select_tokens;
1021 map { s/.*\sAS\s+//si } @group_tokens;
1022 push @select_tokens, 'SUM(ioi.qty)';
1025 #============= build query ================#
1027 my $token_builder = $make_token_builder->(\%joins_needed);
1029 my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
1030 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
1031 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
1032 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
1034 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
1035 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
1036 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
1037 my $group_clause = ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens if scalar @group_tokens;
1039 my %oe_flag_to_cvar = (
1040 bought => 'invoice',
1042 onorder => 'orderitems',
1043 ordered => 'orderitems',
1044 rfq => 'orderitems',
1045 quoted => 'orderitems',
1048 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
1050 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1052 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1056 $where_clause .= qq| AND ($cvar_where)|;
1057 push @bind_vars, @cvar_values;
1060 my $query = <<" SQL";
1061 SELECT DISTINCT $select_clause
1070 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1072 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1074 # post processing for assembly parts lists (bom)
1075 # for each part get the assembly parts and add them into the partlist.
1077 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1079 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1081 p.sellprice, p.listprice, p.lastcost,
1082 p.rop, p.weight, p.priceupdate,
1083 p.image, p.drawing, p.microfiche,
1086 INNER JOIN assembly a ON (p.id = a.parts_id)
1089 my $sth = prepare_query($form, $dbh, $query);
1091 foreach my $item (@{ $form->{parts} }) {
1092 push(@assemblies, $item);
1093 do_statement($form, $sth, $query, conv_i($item->{id}));
1095 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1096 $ref->{assemblyitem} = 1;
1097 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1098 push(@assemblies, $ref);
1103 # copy assemblies to $form->{parts}
1104 $form->{parts} = \@assemblies;
1107 $main::lxdebug->leave_sub();
1109 return wantarray ? @{ $form->{parts} } : $form->{parts};
1112 sub _create_filter_for_priceupdate {
1113 $main::lxdebug->enter_sub();
1116 my $myconfig = \%main::myconfig;
1117 my $form = $main::form;
1120 my $where = '1 = 1';
1122 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1124 $column =~ s/.*\.//;
1125 next unless ($form->{$column});
1127 $where .= qq| AND $item ILIKE ?|;
1128 push(@where_values, '%' . $form->{$column} . '%');
1131 foreach my $item (qw(description serialnumber)) {
1132 next unless ($form->{$item});
1134 $where .= qq| AND (${item} ILIKE ?)|;
1135 push(@where_values, '%' . $form->{$item} . '%');
1139 # items which were never bought, sold or on an order
1140 if ($form->{itemstatus} eq 'orphaned') {
1142 qq| AND (p.onhand = 0)
1145 SELECT DISTINCT parts_id FROM invoice
1147 SELECT DISTINCT parts_id FROM assembly
1149 SELECT DISTINCT parts_id FROM orderitems
1152 } elsif ($form->{itemstatus} eq 'active') {
1153 $where .= qq| AND p.obsolete = '0'|;
1155 } elsif ($form->{itemstatus} eq 'obsolete') {
1156 $where .= qq| AND p.obsolete = '1'|;
1158 } elsif ($form->{itemstatus} eq 'onhand') {
1159 $where .= qq| AND p.onhand > 0|;
1161 } elsif ($form->{itemstatus} eq 'short') {
1162 $where .= qq| AND p.onhand < p.rop|;
1166 foreach my $column (qw(make model)) {
1167 next unless ($form->{$column});
1168 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1169 push(@where_values, '%' . $form->{$column} . '%');
1172 $main::lxdebug->leave_sub();
1174 return ($where, @where_values);
1177 sub get_num_matches_for_priceupdate {
1178 $main::lxdebug->enter_sub();
1182 my $myconfig = \%main::myconfig;
1183 my $form = $main::form;
1185 my $dbh = $form->get_standard_dbh($myconfig);
1187 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1189 my $num_updated = 0;
1192 for my $column (qw(sellprice listprice)) {
1193 next if ($form->{$column} eq "");
1201 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1203 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1204 $num_updated += $result if (0 <= $result);
1213 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1214 WHERE $where) AND (pricegroup_id = ?)|;
1215 my $sth = prepare_query($form, $dbh, $query);
1217 for my $i (1 .. $form->{price_rows}) {
1218 next if ($form->{"price_$i"} eq "");
1220 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1221 $num_updated += $result if (0 <= $result);
1225 $main::lxdebug->leave_sub();
1227 return $num_updated;
1231 $main::lxdebug->enter_sub();
1233 my ($self, $myconfig, $form) = @_;
1235 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1236 my $num_updated = 0;
1238 # connect to database
1239 my $dbh = $form->dbconnect_noauto($myconfig);
1241 for my $column (qw(sellprice listprice)) {
1242 next if ($form->{$column} eq "");
1244 my $value = $form->parse_amount($myconfig, $form->{$column});
1247 if ($form->{"${column}_type"} eq "percent") {
1248 $value = ($value / 100) + 1;
1253 qq|UPDATE parts SET $column = $column $operator ?
1257 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1259 my $result = do_query($form, $dbh, $query, $value, @where_values);
1260 $num_updated += $result if (0 <= $result);
1264 qq|UPDATE prices SET price = price + ?
1268 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1269 WHERE $where) AND (pricegroup_id = ?)|;
1270 my $sth_add = prepare_query($form, $dbh, $q_add);
1273 qq|UPDATE prices SET price = price * ?
1277 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1278 WHERE $where) AND (pricegroup_id = ?)|;
1279 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1281 for my $i (1 .. $form->{price_rows}) {
1282 next if ($form->{"price_$i"} eq "");
1284 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1287 if ($form->{"pricegroup_type_$i"} eq "percent") {
1288 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1290 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1293 $num_updated += $result if (0 <= $result);
1297 $sth_multiply->finish();
1299 my $rc= $dbh->commit;
1302 $main::lxdebug->leave_sub();
1304 return $num_updated;
1308 $main::lxdebug->enter_sub();
1310 my ($self, $module, $myconfig, $form) = @_;
1312 # connect to database
1313 my $dbh = $form->dbconnect($myconfig);
1315 my @values = ('%' . $module . '%');
1320 qq|SELECT c.accno, c.description, c.link, c.id,
1321 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1322 FROM chart c, parts p
1323 WHERE (c.link LIKE ?) AND (p.id = ?)
1325 push(@values, conv_i($form->{id}));
1329 qq|SELECT c.accno, c.description, c.link, c.id,
1330 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1331 FROM chart c, defaults d
1336 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1337 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1338 foreach my $key (split(/:/, $ref->{link})) {
1339 if ($key =~ /\Q$module\E/) {
1340 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1341 || ($ref->{id} eq $ref->{income_accno_id})
1342 || ($ref->{id} eq $ref->{expense_accno_id})) {
1343 push @{ $form->{"${module}_links"}{$key} },
1344 { accno => $ref->{accno},
1345 description => $ref->{description},
1346 selected => "selected" };
1347 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1349 push @{ $form->{"${module}_links"}{$key} },
1350 { accno => $ref->{accno},
1351 description => $ref->{description},
1359 # get buchungsgruppen
1360 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1363 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1366 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1370 $main::lxdebug->leave_sub();
1373 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1375 $main::lxdebug->enter_sub();
1377 my ($self, $myconfig, $form, $sortorder) = @_;
1378 my $dbh = $form->dbconnect($myconfig);
1379 my $order = qq| p.partnumber|;
1380 my $where = qq|1 = 1|;
1383 if ($sortorder eq "all") {
1384 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1385 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1387 } elsif ($sortorder eq "partnumber") {
1388 $where .= qq| AND (partnumber ILIKE ?)|;
1389 push(@values, '%' . $form->{partnumber} . '%');
1391 } elsif ($sortorder eq "description") {
1392 $where .= qq| AND (description ILIKE ?)|;
1393 push(@values, '%' . $form->{description} . '%');
1394 $order = "description";
1399 qq|SELECT id, partnumber, description, unit, sellprice
1401 WHERE $where ORDER BY $order|;
1403 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1406 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1407 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1412 $form->{"id_$j"} = $ref->{id};
1413 $form->{"partnumber_$j"} = $ref->{partnumber};
1414 $form->{"description_$j"} = $ref->{description};
1415 $form->{"unit_$j"} = $ref->{unit};
1416 $form->{"sellprice_$j"} = $ref->{sellprice};
1417 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1423 $main::lxdebug->leave_sub();
1428 # gets sum of sold part with part_id
1430 $main::lxdebug->enter_sub();
1432 my ($dbh, $id) = @_;
1434 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1435 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1438 $main::lxdebug->leave_sub();
1441 } #end get_soldtotal
1443 sub retrieve_languages {
1444 $main::lxdebug->enter_sub();
1446 my ($self, $myconfig, $form) = @_;
1448 # connect to database
1449 my $dbh = $form->dbconnect($myconfig);
1455 if ($form->{language_values} ne "") {
1457 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1459 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1460 ORDER BY lower(l.description)|;
1461 @values = (conv_i($form->{id}));
1464 $query = qq|SELECT id, description
1466 ORDER BY lower(description)|;
1469 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1473 $main::lxdebug->leave_sub();
1478 sub follow_account_chain {
1479 $main::lxdebug->enter_sub(2);
1481 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1483 my @visited_accno_ids = ($accno_id);
1487 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1488 map { $_->{id} => $_ }
1489 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1490 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1492 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1493 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1497 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1498 last unless ($ref && $ref->{"is_valid"} &&
1499 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1500 $accno_id = $ref->{"new_chart_id"};
1501 $accno = $ref->{"accno"};
1502 push(@visited_accno_ids, $accno_id);
1505 $main::lxdebug->leave_sub(2);
1507 return ($accno_id, $accno);
1510 sub retrieve_accounts {
1511 $main::lxdebug->enter_sub;
1514 my $myconfig = shift;
1516 my $dbh = $form->get_standard_dbh;
1517 my %args = @_; # index => part_id
1519 $form->{taxzone_id} *= 1;
1521 return unless grep $_, values %args; # shortfuse if no part_id supplied
1523 # transdate madness.
1525 if ($form->{type} eq "invoice") {
1526 if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1527 $transdate = $form->{invdate};
1529 $transdate = $form->{deliverydate};
1531 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1532 $transdate = $form->{invdate};
1534 $transdate = $form->{transdate};
1537 if ($transdate eq "") {
1538 $transdate = "current_date";
1540 $transdate = $dbh->quote($transdate);
1543 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1545 my @part_ids = grep { $_ } values %args;
1546 my $in = join ',', ('?') x @part_ids;
1548 my %accno_by_part = map { $_->{id} => $_ }
1549 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1551 p.id, p.inventory_accno_id AS is_part,
1552 bg.inventory_accno_id,
1553 bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
1554 bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
1555 c1.accno AS inventory_accno,
1556 c2.accno AS income_accno,
1557 c3.accno AS expense_accno
1559 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1560 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1561 LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
1562 LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
1566 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1567 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1569 LEFT JOIN chart c ON c.id = t.chart_id
1573 WHERE tk.chart_id = ? AND startdate <= ?
1574 ORDER BY startdate DESC LIMIT 1)
1577 while (my ($index => $part_id) = each %args) {
1578 my $ref = $accno_by_part{$part_id} or next;
1580 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1583 for my $type (qw(inventory income expense)) {
1584 next unless $ref->{"${type}_accno_id"};
1585 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1586 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1589 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1591 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1592 $ref = $sth_tax->fetchrow_hashref or next;
1594 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1595 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1597 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1602 $::lxdebug->leave_sub;
1605 sub get_basic_part_info {
1606 $main::lxdebug->enter_sub();
1611 Common::check_params(\%params, qw(id));
1613 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1616 $main::lxdebug->leave_sub();
1620 my $myconfig = \%main::myconfig;
1621 my $form = $main::form;
1623 my $dbh = $form->get_standard_dbh($myconfig);
1625 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1627 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1629 if ('' eq ref $params{id}) {
1630 $info = $info->[0] || { };
1632 $main::lxdebug->leave_sub();
1636 my %info_map = map { $_->{id} => $_ } @{ $info };
1638 $main::lxdebug->leave_sub();
1643 sub prepare_parts_for_printing {
1644 $main::lxdebug->enter_sub();
1649 my $myconfig = \%main::myconfig;
1650 my $form = $main::form;
1652 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1654 my $prefix = $params{prefix} || 'id_';
1655 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1657 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1660 $main::lxdebug->leave_sub();
1664 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1665 my $query = qq|SELECT mm.parts_id, mm.model, v.name AS make
1667 LEFT JOIN vendor v ON (mm.make = v.id)
1668 WHERE mm.parts_id IN ($placeholders)|;
1672 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1674 while (my $ref = $sth->fetchrow_hashref()) {
1675 $makemodel{$ref->{parts_id}} ||= [];
1676 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1681 my @columns = qw(ean image microfiche drawing weight);
1683 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1685 WHERE id IN ($placeholders)|;
1687 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1689 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1691 foreach my $i (1 .. $rowcount) {
1692 my $id = $form->{"${prefix}${i}"};
1696 foreach (@columns) {
1697 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1700 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1701 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1703 next if (!$makemodel{$id});
1705 foreach my $ref (@{ $makemodel{$id} }) {
1706 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1710 $main::lxdebug->leave_sub();