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, @makemodel_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|,
828 my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac);
831 deliverydate => 'apoe.', serialnumber => 'ioi.',
832 transdate => 'apoe.', trans_id => 'ioi.',
833 module => 'apoe.', name => 'cv.',
834 ordnumber => 'apoe.', make => 'mm.',
835 quonumber => 'apoe.', model => 'mm.',
836 invnumber => 'apoe.', partsgroup => 'pg.',
837 lastcost => 'p.', , soldtotal => ' ',
839 'SUM(ioi.qty)' => ' ',
842 serialnumber => 'ioi.',
843 quotation => 'apoe.',
849 # if the join condition in these blocks are met, the column
850 # of the scecified table will gently override (coalesce actually) the original value
851 # use it to conditionally coalesce values from subtables
852 my @column_override = (
853 # column name, prefix, joins_needed
854 [ 'description', 'ioi.', 'invoice_oi' ],
855 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
856 [ 'transdate', 'apoe.', 'apoe' ],
857 [ 'unit', 'ioi.', 'invoice_oi' ],
858 [ 'sellprice', 'ioi.', 'invoice_oi' ],
861 # careful with renames. these are HARD, and any filters done on the original column will break
862 my %renamed_columns = (
863 'factor' => 'price_factor',
864 'SUM(ioi.qty)' => 'soldtotal',
865 'ioi.id' => 'ioi_id',
869 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
870 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
873 my $make_token_builder = sub {
874 my $joins_needed = shift;
876 my ($col, $alias) = @_;
877 my @coalesce_tokens =
878 map { ($_->[1] || 'p.') . $_->[0] }
879 grep { !$_->[2] || $joins_needed->{$_->[2]} }
880 grep { $_->[0] eq $col }
881 @column_override, [ $col, $table_prefix{$col} ];
883 my $coalesce = scalar @coalesce_tokens > 1;
885 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
886 : shift @coalesce_tokens)
887 . ($alias && ($coalesce || $renamed_columns{$col})
888 ? " AS " . ($renamed_columns{$col} || $col)
893 #===== switches and simple filters ========#
895 # special case transdate
896 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
897 $form->{"l_transdate"} = 1;
898 push @select_tokens, 'transdate';
899 for (qw(transdatefrom transdateto)) {
900 next unless $form->{$_};
901 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
902 push @bind_vars, $form->{$_};
906 foreach (@like_filters) {
907 next unless $form->{$_};
908 $form->{"l_$_"} = '1'; # show the column
909 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
910 push @bind_vars, "%$form->{$_}%";
913 foreach (@simple_l_switches) {
914 next unless $form->{"l_$_"};
915 push @select_tokens, $_;
918 for ($form->{searchitems}) {
919 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
920 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
921 push @where_tokens, 'NOT p.assembly' if /service/;
922 push @where_tokens, ' p.assembly' if /assembly/;
925 for ($form->{itemstatus}) {
926 push @where_tokens, 'p.id NOT IN
927 (SELECT DISTINCT parts_id FROM invoice UNION
928 SELECT DISTINCT parts_id FROM assembly UNION
929 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
930 push @where_tokens, 'p.onhand = 0' if /orphaned/;
931 push @where_tokens, 'NOT p.obsolete' if /active/;
932 push @where_tokens, ' p.obsolete', if /obsolete/;
933 push @where_tokens, 'p.onhand > 0', if /onhand/;
934 push @where_tokens, 'p.onhand < p.rop', if /short/;
937 my $q_assembly_lastcost =
938 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
940 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
941 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
942 WHERE (a_lc.id = p.id)) AS lastcost|;
943 $table_prefix{$q_assembly_lastcost} = ' ';
945 # special case: sorting by partnumber
946 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
947 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
948 # ToDO: implement proper functional sorting
949 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
950 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
951 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
952 # if $form->{sort} eq 'partnumber';
954 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
957 $limit_clause = " LIMIT 100" if $form->{top100};
958 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
960 #=== joins and complicated filters ========#
962 my $bsooqr = any { $form->{$_} } @oe_flags;
963 my @bsooqr_tokens = ();
965 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
966 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
967 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
968 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
969 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
970 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
971 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
972 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
973 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
974 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
976 $joins_needed{partsgroup} = 1;
977 $joins_needed{pfac} = 1;
978 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
979 $joins_needed{cv} = 1 if $bsooqr;
980 $joins_needed{apoe} = 1 if $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
981 $joins_needed{invoice_oi} = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
983 # in bsoorq, use qtys instead of onhand
984 if ($joins_needed{invoice_oi}) {
985 $renamed_columns{onhand} = 'onhand_before_bsooqr';
986 $renamed_columns{qty} = 'onhand';
989 # special case for description search.
990 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
991 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
992 # find the old entries in of @where_tokens and @bind_vars, and adjust them
993 if ($joins_needed{invoice_oi}) {
994 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
995 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
996 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
997 splice @bind_vars, $bi, 0, $bind_vars[$bi];
1002 # now the master trick: soldtotal.
1003 if ($form->{l_soldtotal}) {
1004 push @where_tokens, 'NOT ioi.qty = 0';
1005 push @group_tokens, @select_tokens;
1006 map { s/.*\sAS\s+//si } @group_tokens;
1007 push @select_tokens, 'SUM(ioi.qty)';
1010 #============= build query ================#
1012 my $token_builder = $make_token_builder->(\%joins_needed);
1014 my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
1015 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
1016 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
1017 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
1019 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
1020 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
1021 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
1022 my $group_clause = ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens if scalar @group_tokens;
1024 my %oe_flag_to_cvar = (
1025 bought => 'invoice',
1027 onorder => 'orderitems',
1028 ordered => 'orderitems',
1029 rfq => 'orderitems',
1030 quoted => 'orderitems',
1033 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
1035 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1037 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1041 $where_clause .= qq| AND ($cvar_where)|;
1042 push @bind_vars, @cvar_values;
1045 my $query = <<" SQL";
1046 SELECT DISTINCT $select_clause
1055 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1057 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1059 # post processing for assembly parts lists (bom)
1060 # for each part get the assembly parts and add them into the partlist.
1062 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1064 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1066 p.sellprice, p.listprice, p.lastcost,
1067 p.rop, p.weight, p.priceupdate,
1068 p.image, p.drawing, p.microfiche,
1071 INNER JOIN assembly a ON (p.id = a.parts_id)
1074 my $sth = prepare_query($form, $dbh, $query);
1076 foreach my $item (@{ $form->{parts} }) {
1077 push(@assemblies, $item);
1078 do_statement($form, $sth, $query, conv_i($item->{id}));
1080 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1081 $ref->{assemblyitem} = 1;
1082 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1083 push(@assemblies, $ref);
1088 # copy assemblies to $form->{parts}
1089 $form->{parts} = \@assemblies;
1092 $main::lxdebug->leave_sub();
1094 return wantarray ? @{ $form->{parts} } : $form->{parts};
1097 sub _create_filter_for_priceupdate {
1098 $main::lxdebug->enter_sub();
1101 my $myconfig = \%main::myconfig;
1102 my $form = $main::form;
1105 my $where = '1 = 1';
1107 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1109 $column =~ s/.*\.//;
1110 next unless ($form->{$column});
1112 $where .= qq| AND $item ILIKE ?|;
1113 push(@where_values, '%' . $form->{$column} . '%');
1116 foreach my $item (qw(description serialnumber)) {
1117 next unless ($form->{$item});
1119 $where .= qq| AND (${item} ILIKE ?)|;
1120 push(@where_values, '%' . $form->{$item} . '%');
1124 # items which were never bought, sold or on an order
1125 if ($form->{itemstatus} eq 'orphaned') {
1127 qq| AND (p.onhand = 0)
1130 SELECT DISTINCT parts_id FROM invoice
1132 SELECT DISTINCT parts_id FROM assembly
1134 SELECT DISTINCT parts_id FROM orderitems
1137 } elsif ($form->{itemstatus} eq 'active') {
1138 $where .= qq| AND p.obsolete = '0'|;
1140 } elsif ($form->{itemstatus} eq 'obsolete') {
1141 $where .= qq| AND p.obsolete = '1'|;
1143 } elsif ($form->{itemstatus} eq 'onhand') {
1144 $where .= qq| AND p.onhand > 0|;
1146 } elsif ($form->{itemstatus} eq 'short') {
1147 $where .= qq| AND p.onhand < p.rop|;
1151 foreach my $column (qw(make model)) {
1152 next unless ($form->{$column});
1153 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1154 push(@where_values, '%' . $form->{$column} . '%');
1157 $main::lxdebug->leave_sub();
1159 return ($where, @where_values);
1162 sub get_num_matches_for_priceupdate {
1163 $main::lxdebug->enter_sub();
1167 my $myconfig = \%main::myconfig;
1168 my $form = $main::form;
1170 my $dbh = $form->get_standard_dbh($myconfig);
1172 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1174 my $num_updated = 0;
1177 for my $column (qw(sellprice listprice)) {
1178 next if ($form->{$column} eq "");
1186 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1188 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1189 $num_updated += $result if (0 <= $result);
1198 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1199 WHERE $where) AND (pricegroup_id = ?)|;
1200 my $sth = prepare_query($form, $dbh, $query);
1202 for my $i (1 .. $form->{price_rows}) {
1203 next if ($form->{"price_$i"} eq "");
1205 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1206 $num_updated += $result if (0 <= $result);
1210 $main::lxdebug->leave_sub();
1212 return $num_updated;
1216 $main::lxdebug->enter_sub();
1218 my ($self, $myconfig, $form) = @_;
1220 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1221 my $num_updated = 0;
1223 # connect to database
1224 my $dbh = $form->dbconnect_noauto($myconfig);
1226 for my $column (qw(sellprice listprice)) {
1227 next if ($form->{$column} eq "");
1229 my $value = $form->parse_amount($myconfig, $form->{$column});
1232 if ($form->{"${column}_type"} eq "percent") {
1233 $value = ($value / 100) + 1;
1238 qq|UPDATE parts SET $column = $column $operator ?
1242 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1244 my $result = do_query($form, $dbh, $query, $value, @where_values);
1245 $num_updated += $result if (0 <= $result);
1249 qq|UPDATE prices SET price = price + ?
1253 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1254 WHERE $where) AND (pricegroup_id = ?)|;
1255 my $sth_add = prepare_query($form, $dbh, $q_add);
1258 qq|UPDATE prices SET price = price * ?
1262 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1263 WHERE $where) AND (pricegroup_id = ?)|;
1264 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1266 for my $i (1 .. $form->{price_rows}) {
1267 next if ($form->{"price_$i"} eq "");
1269 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1272 if ($form->{"pricegroup_type_$i"} eq "percent") {
1273 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1275 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1278 $num_updated += $result if (0 <= $result);
1282 $sth_multiply->finish();
1284 my $rc= $dbh->commit;
1287 $main::lxdebug->leave_sub();
1289 return $num_updated;
1293 $main::lxdebug->enter_sub();
1295 my ($self, $module, $myconfig, $form) = @_;
1297 # connect to database
1298 my $dbh = $form->dbconnect($myconfig);
1300 my @values = ('%' . $module . '%');
1305 qq|SELECT c.accno, c.description, c.link, c.id,
1306 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1307 FROM chart c, parts p
1308 WHERE (c.link LIKE ?) AND (p.id = ?)
1310 push(@values, conv_i($form->{id}));
1314 qq|SELECT c.accno, c.description, c.link, c.id,
1315 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1316 FROM chart c, defaults d
1321 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1322 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1323 foreach my $key (split(/:/, $ref->{link})) {
1324 if ($key =~ /\Q$module\E/) {
1325 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1326 || ($ref->{id} eq $ref->{income_accno_id})
1327 || ($ref->{id} eq $ref->{expense_accno_id})) {
1328 push @{ $form->{"${module}_links"}{$key} },
1329 { accno => $ref->{accno},
1330 description => $ref->{description},
1331 selected => "selected" };
1332 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1334 push @{ $form->{"${module}_links"}{$key} },
1335 { accno => $ref->{accno},
1336 description => $ref->{description},
1344 # get buchungsgruppen
1345 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1348 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1351 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1355 $main::lxdebug->leave_sub();
1358 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1360 $main::lxdebug->enter_sub();
1362 my ($self, $myconfig, $form, $sortorder) = @_;
1363 my $dbh = $form->dbconnect($myconfig);
1364 my $order = qq| p.partnumber|;
1365 my $where = qq|1 = 1|;
1368 if ($sortorder eq "all") {
1369 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1370 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1372 } elsif ($sortorder eq "partnumber") {
1373 $where .= qq| AND (partnumber ILIKE ?)|;
1374 push(@values, '%' . $form->{partnumber} . '%');
1376 } elsif ($sortorder eq "description") {
1377 $where .= qq| AND (description ILIKE ?)|;
1378 push(@values, '%' . $form->{description} . '%');
1379 $order = "description";
1384 qq|SELECT id, partnumber, description, unit, sellprice
1386 WHERE $where ORDER BY $order|;
1388 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1391 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1392 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1397 $form->{"id_$j"} = $ref->{id};
1398 $form->{"partnumber_$j"} = $ref->{partnumber};
1399 $form->{"description_$j"} = $ref->{description};
1400 $form->{"unit_$j"} = $ref->{unit};
1401 $form->{"sellprice_$j"} = $ref->{sellprice};
1402 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1408 $main::lxdebug->leave_sub();
1413 # gets sum of sold part with part_id
1415 $main::lxdebug->enter_sub();
1417 my ($dbh, $id) = @_;
1419 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1420 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1423 $main::lxdebug->leave_sub();
1426 } #end get_soldtotal
1428 sub retrieve_languages {
1429 $main::lxdebug->enter_sub();
1431 my ($self, $myconfig, $form) = @_;
1433 # connect to database
1434 my $dbh = $form->dbconnect($myconfig);
1440 if ($form->{language_values} ne "") {
1442 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1444 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1445 ORDER BY lower(l.description)|;
1446 @values = (conv_i($form->{id}));
1449 $query = qq|SELECT id, description
1451 ORDER BY lower(description)|;
1454 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1458 $main::lxdebug->leave_sub();
1463 sub follow_account_chain {
1464 $main::lxdebug->enter_sub(2);
1466 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1468 my @visited_accno_ids = ($accno_id);
1472 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1473 map { $_->{id} => $_ }
1474 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1475 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1477 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1478 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1482 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1483 last unless ($ref && $ref->{"is_valid"} &&
1484 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1485 $accno_id = $ref->{"new_chart_id"};
1486 $accno = $ref->{"accno"};
1487 push(@visited_accno_ids, $accno_id);
1490 $main::lxdebug->leave_sub(2);
1492 return ($accno_id, $accno);
1495 sub retrieve_accounts {
1496 $main::lxdebug->enter_sub;
1499 my $myconfig = shift;
1501 my $dbh = $form->get_standard_dbh;
1502 my %args = @_; # index => part_id
1504 $form->{taxzone_id} *= 1;
1506 return unless grep $_, values %args; # shortfuse if no part_id supplied
1508 # transdate madness.
1510 if ($form->{type} eq "invoice") {
1511 if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1512 $transdate = $form->{invdate};
1514 $transdate = $form->{deliverydate};
1516 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1517 $transdate = $form->{invdate};
1519 $transdate = $form->{transdate};
1522 if ($transdate eq "") {
1523 $transdate = "current_date";
1525 $transdate = $dbh->quote($transdate);
1528 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1530 my @part_ids = grep { $_ } values %args;
1531 my $in = join ',', ('?') x @part_ids;
1533 my %accno_by_part = map { $_->{id} => $_ }
1534 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1536 p.id, p.inventory_accno_id AS is_part,
1537 bg.inventory_accno_id,
1538 bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
1539 bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
1540 c1.accno AS inventory_accno,
1541 c2.accno AS income_accno,
1542 c3.accno AS expense_accno
1544 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1545 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1546 LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
1547 LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
1551 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1552 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1554 LEFT JOIN chart c ON c.id = t.chart_id
1558 WHERE tk.chart_id = ? AND startdate <= ?
1559 ORDER BY startdate DESC LIMIT 1)
1562 while (my ($index => $part_id) = each %args) {
1563 my $ref = $accno_by_part{$part_id} or next;
1565 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1568 for my $type (qw(inventory income expense)) {
1569 next unless $ref->{"${type}_accno_id"};
1570 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1571 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1574 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1576 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1577 $ref = $sth_tax->fetchrow_hashref or next;
1579 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1580 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1582 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1587 $::lxdebug->leave_sub;
1590 sub get_basic_part_info {
1591 $main::lxdebug->enter_sub();
1596 Common::check_params(\%params, qw(id));
1598 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1601 $main::lxdebug->leave_sub();
1605 my $myconfig = \%main::myconfig;
1606 my $form = $main::form;
1608 my $dbh = $form->get_standard_dbh($myconfig);
1610 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1612 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1614 if ('' eq ref $params{id}) {
1615 $info = $info->[0] || { };
1617 $main::lxdebug->leave_sub();
1621 my %info_map = map { $_->{id} => $_ } @{ $info };
1623 $main::lxdebug->leave_sub();
1628 sub prepare_parts_for_printing {
1629 $main::lxdebug->enter_sub();
1634 my $myconfig = \%main::myconfig;
1635 my $form = $main::form;
1637 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1639 my $prefix = $params{prefix} || 'id_';
1640 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1642 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1645 $main::lxdebug->leave_sub();
1649 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1650 my $query = qq|SELECT mm.parts_id, mm.model, v.name AS make
1652 LEFT JOIN vendor v ON (mm.make = v.id)
1653 WHERE mm.parts_id IN ($placeholders)|;
1657 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1659 while (my $ref = $sth->fetchrow_hashref()) {
1660 $makemodel{$ref->{parts_id}} ||= [];
1661 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1666 my @columns = qw(ean image microfiche drawing weight);
1668 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1670 WHERE id IN ($placeholders)|;
1672 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1674 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1676 foreach my $i (1 .. $rowcount) {
1677 my $id = $form->{"${prefix}${i}"};
1681 foreach (@columns) {
1682 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1685 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1686 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1688 next if (!$makemodel{$id});
1690 foreach my $ref (@{ $makemodel{$id} }) {
1691 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1695 $main::lxdebug->leave_sub();