1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
31 # Inventory Control backend
33 #======================================================================
38 use List::MoreUtils qw(all any uniq);
48 $main::lxdebug->enter_sub();
50 my ($self, $myconfig, $form) = @_;
53 my $dbh = $form->dbconnect($myconfig);
59 c1.accno AS inventory_accno,
60 c2.accno AS income_accno,
61 c3.accno AS expense_accno,
64 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
65 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
66 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
67 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
69 my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
71 # copy to $form variables
72 map { $form->{$_} = $ref->{$_} } (keys %{$ref});
76 # part or service item
77 $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
78 if ($form->{assembly}) {
79 $form->{item} = 'assembly';
81 # retrieve assembly items
83 qq|SELECT p.id, p.partnumber, p.description,
84 p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
85 pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
87 JOIN assembly a ON (a.parts_id = p.id)
88 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
89 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
92 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
94 $form->{assembly_rows} = 0;
95 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
96 $form->{assembly_rows}++;
97 foreach my $key (keys %{$ref}) {
98 $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
105 # setup accno hash for <option checked> {amount} is used in create_links
106 $form->{amount}{IC} = $form->{inventory_accno};
107 $form->{amount}{IC_income} = $form->{income_accno};
108 $form->{amount}{IC_sale} = $form->{income_accno};
109 $form->{amount}{IC_expense} = $form->{expense_accno};
110 $form->{amount}{IC_cogs} = $form->{expense_accno};
112 my @pricegroups = ();
113 my @pricegroups_not_used = ();
117 qq|SELECT p.parts_id, p.pricegroup_id, p.price,
118 (SELECT pg.pricegroup
120 WHERE pg.id = p.pricegroup_id) AS pricegroup
123 ORDER BY pricegroup|;
124 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
128 while (($form->{"klass_$i"}, $form->{"pricegroup_id_$i"},
129 $form->{"price_$i"}, $form->{"pricegroup_$i"})
130 = $sth->fetchrow_array()) {
131 push @pricegroups, $form->{"pricegroup_id_$i"};
138 $query = qq|SELECT id, pricegroup FROM pricegroup|;
139 $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
141 #find not used pricegroups
142 while (my $tmp = pop(@{ $form->{PRICEGROUPS} })) {
144 foreach my $item (@pricegroups) {
145 if ($item eq $tmp->{id}) {
150 push(@pricegroups_not_used, $tmp) unless ($in_use);
153 # if not used pricegroups are avaible
154 if (@pricegroups_not_used) {
156 foreach my $name (@pricegroups_not_used) {
157 $form->{"klass_$i"} = "$name->{id}";
158 $form->{"pricegroup_id_$i"} = "$name->{id}";
159 $form->{"pricegroup_$i"} = "$name->{pricegroup}";
165 $form->{price_rows} = $i - 1;
168 if ($form->{makemodel}) {
170 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
171 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
172 my @values = ($form->{id});
173 $sth = $dbh->prepare($query);
174 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
178 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
179 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
184 $form->{makemodel_rows} = $i - 1;
189 $form->{language_values} = "";
190 $query = qq|SELECT language_id, translation, longdescription
193 my $trq = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
194 while (my $tr = $trq->fetchrow_hashref("NAME_lc")) {
195 $form->{language_values} .= "---+++---" . join('--++--', @{$tr}{qw(language_id translation longdescription)});
199 # now get accno for taxes
202 FROM chart c, partstax pt
203 WHERE (pt.chart_id = c.id) AND (pt.parts_id = ?)|;
204 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
205 while (my ($key) = $sth->fetchrow_array) {
206 $form->{amount}{$key} = $key;
212 my @referencing_tables = qw(invoice orderitems inventory rmaitems);
213 my %column_map = ( );
214 my $parts_id = conv_i($form->{id});
216 $form->{orphaned} = 1;
218 foreach my $table (@referencing_tables) {
219 my $column = $column_map{$table} || 'parts_id';
220 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
221 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
224 $form->{orphaned} = 0;
229 $form->{"unit_changeable"} = $form->{orphaned};
233 $main::lxdebug->leave_sub();
236 sub get_pricegroups {
237 $main::lxdebug->enter_sub();
239 my ($self, $myconfig, $form) = @_;
241 my $dbh = $form->dbconnect($myconfig);
244 my $query = qq|SELECT id, pricegroup FROM pricegroup|;
245 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
248 foreach my $pg (@{ $pricegroups }) {
249 $form->{"klass_$i"} = "$pg->{id}";
250 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
251 $form->{"pricegroup_id_$i"} = "$pg->{id}";
252 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
257 $form->{price_rows} = $i - 1;
261 $main::lxdebug->leave_sub();
266 sub retrieve_buchungsgruppen {
267 $main::lxdebug->enter_sub();
269 my ($self, $myconfig, $form) = @_;
273 my $dbh = $form->dbconnect($myconfig);
275 # get buchungsgruppen
276 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
277 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
279 $main::lxdebug->leave_sub();
283 $main::lxdebug->enter_sub();
285 my ($self, $myconfig, $form) = @_;
287 # connect to database, turn off AutoCommit
288 my $dbh = $form->get_standard_dbh;
291 # make up a unique handle and store in partnumber field
292 # then retrieve the record based on the unique handle to get the id
293 # replace the partnumber field with the actual variable
294 # add records for makemodel
296 # if there is a $form->{id} then replace the old entry
297 # delete all makemodel entries and add the new ones
299 # undo amount formatting
300 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
301 qw(rop weight listprice sellprice gv lastcost);
303 my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
305 $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
309 my $priceupdate = ', priceupdate = current_date';
312 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
313 if (!$trans_number->is_unique) {
314 $::lxdebug->leave_sub;
319 $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
320 my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
322 # if item is part of an assembly adjust all assemblies
323 $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
324 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
325 while (my ($id, $qty) = $sth->fetchrow_array) {
326 &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
330 # delete makemodel records
331 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
333 if ($form->{item} eq 'assembly') {
334 # delete assembly records
335 do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
339 do_query($form, $dbh, qq|DELETE FROM partstax WHERE parts_id = ?|, conv_i($form->{id}));
341 # delete translations
342 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
344 # Check whether or not the prices have changed. If they haven't
345 # then 'priceupdate' should not be updated.
346 my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
347 $priceupdate = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
350 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, save => 1);
352 if ($form->{partnumber} && !$trans_number->is_unique) {
353 $::lxdebug->leave_sub;
357 $form->{partnumber} ||= $trans_number->create_unique;
359 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
360 do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit});
362 $form->{orphaned} = 1;
364 my $partsgroup_id = 0;
366 if ($form->{partsgroup}) {
367 (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
370 my ($subq_inventory, $subq_expense, $subq_income);
371 if ($form->{"item"} eq "part") {
373 qq|(SELECT bg.inventory_accno_id
374 FROM buchungsgruppen bg
375 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
377 $subq_inventory = "NULL";
380 if ($form->{"item"} ne "assembly") {
382 qq|(SELECT bg.expense_accno_id_0
383 FROM buchungsgruppen bg
384 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
386 $subq_expense = "NULL";
405 buchungsgruppen_id = ?,
407 inventory_accno_id = $subq_inventory,
408 income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
409 expense_accno_id = $subq_expense,
418 not_discountable = ?,
424 @values = ($form->{partnumber},
425 $form->{description},
426 $makemodel ? 't' : 'f',
427 $form->{assembly} ? 't' : 'f',
437 conv_i($form->{buchungsgruppen_id}),
438 conv_i($form->{payment_id}),
439 conv_i($form->{buchungsgruppen_id}),
440 $form->{obsolete} ? 't' : 'f',
443 $form->{shop} ? 't' : 'f',
447 $form->{has_sernumber} ? 't' : 'f',
448 $form->{not_discountable} ? 't' : 'f',
450 conv_i($partsgroup_id),
451 conv_i($form->{price_factor_id}),
454 do_query($form, $dbh, $query, @values);
456 # delete translation records
457 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
459 if ($form->{language_values} ne "") {
460 foreach my $item (split(/---\+\+\+---/, $form->{language_values})) {
461 my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
462 if ($translation ne "") {
463 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
464 VALUES ( ?, ?, ?, ? )|;
465 @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
466 do_query($form, $dbh, $query, @values);
471 # delete price records
472 do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
474 # insert price records only if different to sellprice
475 for my $i (1 .. $form->{price_rows}) {
476 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
478 $form->{"price_$i"} = $form->{sellprice};
482 || $form->{"klass_$i"}
483 || $form->{"pricegroup_id_$i"})
484 and $price != $form->{sellprice}
486 #$klass = $form->parse_amount($myconfig, $form->{"klass_$i"});
487 $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) | .
489 @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
490 do_query($form, $dbh, $query, @values);
494 # insert makemodel records
497 for my $i (1 .. $form->{makemodel_rows}) {
498 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
500 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
501 if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
503 if ($form->{"lastupdate_$i"} eq "") {
504 $lastupdate = 'now()';
506 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
509 $lastupdate = 'now()';
511 $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
512 qq|VALUES (?, ?, ?, ?, ?, ?)|;
513 @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
515 do_query($form, $dbh, $query, @values);
520 foreach my $item (split(/ /, $form->{taxaccounts})) {
521 if ($form->{"IC_tax_$item"}) {
523 qq|INSERT INTO partstax (parts_id, chart_id)
524 VALUES (?, (SELECT id FROM chart WHERE accno = ?))|;
525 @values = (conv_i($form->{id}), $item);
526 do_query($form, $dbh, $query, @values);
530 # add assembly records
531 if ($form->{item} eq 'assembly') {
533 for my $i (1 .. $form->{assembly_rows}) {
534 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
536 if ($form->{"qty_$i"} != 0) {
537 $form->{"bom_$i"} *= 1;
538 $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
539 qq|VALUES (?, ?, ?, ?)|;
540 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
541 do_query($form, $dbh, $query, @values);
548 my $shippingdate = "$a[5]-$a[4]-$a[3]";
550 $form->get_employee($dbh);
554 #set expense_accno=inventory_accno if they are different => bilanz
556 ($form->{expense_accno} != $form->{inventory_accno})
557 ? $form->{inventory_accno}
558 : $form->{expense_accno};
560 # get tax rates and description
562 ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
564 qq|SELECT c.accno, c.description, t.rate, t.taxnumber
566 WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
568 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
570 $form->{taxaccount} = "";
571 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
572 $form->{taxaccount} .= "$ptr->{accno} ";
573 if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
574 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
575 $form->{"$ptr->{accno}_description"} = $ptr->{description};
576 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
577 $form->{taxaccount2} .= " $ptr->{accno} ";
581 CVar->save_custom_variables(dbh => $dbh,
583 trans_id => $form->{id},
588 my $rc = $dbh->commit;
590 $main::lxdebug->leave_sub();
595 sub update_assembly {
596 $main::lxdebug->enter_sub();
598 my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
600 my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
601 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
603 while (my ($pid, $aqty) = $sth->fetchrow_array) {
604 &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
609 qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
611 my @values = ($qty * ($form->{sellprice} - $sellprice),
612 $qty * ($form->{weight} - $weight), conv_i($id));
613 do_query($form, $dbh, $query, @values);
615 $main::lxdebug->leave_sub();
618 sub retrieve_assemblies {
619 $main::lxdebug->enter_sub();
621 my ($self, $myconfig, $form) = @_;
623 # connect to database
624 my $dbh = $form->dbconnect($myconfig);
626 my $where = qq|NOT p.obsolete|;
629 if ($form->{partnumber}) {
630 $where .= qq| AND (p.partnumber ILIKE ?)|;
631 push(@values, '%' . $form->{partnumber} . '%');
634 if ($form->{description}) {
635 $where .= qq| AND (p.description ILIKE ?)|;
636 push(@values, '%' . $form->{description} . '%');
639 # retrieve assembly items
641 qq|SELECT p.id, p.partnumber, p.description,
642 p.bin, p.onhand, p.rop,
643 (SELECT sum(p2.inventory_accno_id)
644 FROM parts p2, assembly a
645 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
647 WHERE NOT p.obsolete AND p.assembly $where|;
649 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
653 $main::lxdebug->leave_sub();
657 $main::lxdebug->enter_sub();
659 my ($self, $myconfig, $form) = @_;
660 my @values = (conv_i($form->{id}));
661 # connect to database, turn off AutoCommit
662 my $dbh = $form->dbconnect_noauto($myconfig);
664 my %columns = ( "assembly" => "id", "parts" => "id" );
666 for my $table (qw(prices partstax makemodel inventory assembly translation parts)) {
667 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
668 do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
672 my $rc = $dbh->commit;
675 $main::lxdebug->leave_sub();
681 $main::lxdebug->enter_sub();
683 my ($self, $myconfig, $form) = @_;
685 my $i = $form->{assembly_rows};
687 my $where = qq|1 = 1|;
690 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
692 while (my ($column, $table) = each(%columns)) {
693 next unless ($form->{"${column}_$i"});
694 $where .= qq| AND ${table}.${column} ILIKE ?|;
695 push(@values, '%' . $form->{"${column}_$i"} . '%');
699 $where .= qq| AND NOT (p.id = ?)|;
700 push(@values, conv_i($form->{id}));
703 # Search for part ID overrides all other criteria.
704 if ($form->{"id_${i}"}) {
705 $where = qq|p.id = ?|;
706 @values = ($form->{"id_${i}"});
709 if ($form->{partnumber}) {
710 $where .= qq| ORDER BY p.partnumber|;
712 $where .= qq| ORDER BY p.description|;
715 # connect to database
716 my $dbh = $form->dbconnect($myconfig);
719 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
720 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
721 p.price_factor_id, pfac.factor AS price_factor
723 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
724 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
726 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
730 $main::lxdebug->leave_sub();
735 # Warning, deep magic ahead.
736 # This function gets all parts from the database according to the filters specified
739 # sort revers - sorting field + direction
742 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
743 # partnumber ean description partsgroup microfiche drawing
746 # 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
749 # itemstatus = active | onhand | short | obsolete | orphaned
750 # searchitems = part | assembly | service
753 # make model - makemodel
754 # serialnumber transdatefrom transdateto - invoice/orderitems
757 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
758 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
759 # l_soldtotal - aggreg join to display total of sold quantity
760 # onhand - as above, but masking the simple itemstatus results (doh!)
761 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
762 # l_serialnumber - belonges to serialnumber filter
763 # l_deliverydate - displays deliverydate is sold etc. flags are active
764 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
767 # onhand - as above, but masking the simple itemstatus results (doh!)
769 # search by overrides of description
771 # disabled sanity checks and changes:
772 # - searchitems = assembly will no longer disable bought
773 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
774 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
775 # - itemstatus = obsolete will no longer disable onhand, short
776 # - allow sorting by ean
777 # - serialnumber filter also works if l_serialnumber isn't ticked
778 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
781 $main::lxdebug->enter_sub();
783 my ($self, $myconfig, $form) = @_;
784 my $dbh = $form->get_standard_dbh($myconfig);
786 $form->{parts} = +{ };
787 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
789 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
790 my @project_filters = qw(projectnumber projectdescription);
791 my @makemodel_filters = qw(make model);
792 my @invoice_oi_filters = qw(serialnumber soldtotal);
793 my @apoe_filters = qw(transdate);
794 my @like_filters = (@simple_filters, @invoice_oi_filters);
795 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
796 my @simple_l_switches = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
797 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
798 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
799 my @deliverydate_flags = qw(deliverydate);
800 # my @other_flags = qw(onhand); # ToDO: implement these
801 # my @inactive_flags = qw(l_subtotal short l_linetotal);
803 my @select_tokens = qw(id factor);
804 my @where_tokens = qw(1=1);
805 my @group_tokens = ();
807 my %joins_needed = ();
810 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
811 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
812 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
815 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
816 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
817 ) AS ioi ON ioi.parts_id = p.id|,
820 SELECT id, transdate, 'ir' AS module, ordnumber, quonumber, invnumber, FALSE AS quotation, NULL AS customer_id, vendor_id, NULL AS deliverydate, globalproject_id, 'invoice' AS ioi FROM ap UNION
821 SELECT id, transdate, 'is' AS module, ordnumber, quonumber, invnumber, FALSE AS quotation, customer_id, NULL AS vendor_id, deliverydate, globalproject_id, 'invoice' AS ioi FROM ar UNION
822 SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber, quotation, customer_id, vendor_id, reqdate AS deliverydate, globalproject_id, 'orderitems' AS ioi FROM oe
823 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
826 SELECT id, name, 'customer' AS cv FROM customer UNION
827 SELECT id, name, 'vendor' AS cv FROM vendor
828 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
829 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
830 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
832 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
835 deliverydate => 'apoe.', serialnumber => 'ioi.',
836 transdate => 'apoe.', trans_id => 'ioi.',
837 module => 'apoe.', name => 'cv.',
838 ordnumber => 'apoe.', make => 'mm.',
839 quonumber => 'apoe.', model => 'mm.',
840 invnumber => 'apoe.', partsgroup => 'pg.',
841 lastcost => 'p.', , soldtotal => ' ',
842 factor => 'pfac.', projectnumber => 'pj.',
843 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
846 serialnumber => 'ioi.',
847 quotation => 'apoe.',
853 # if the join condition in these blocks are met, the column
854 # of the scecified table will gently override (coalesce actually) the original value
855 # use it to conditionally coalesce values from subtables
856 my @column_override = (
857 # column name, prefix, joins_needed, nick name (in case column is named like another)
858 [ 'description', 'ioi.', 'invoice_oi' ],
859 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
860 [ 'transdate', 'apoe.', 'apoe' ],
861 [ 'unit', 'ioi.', 'invoice_oi' ],
862 [ 'sellprice', 'ioi.', 'invoice_oi' ],
865 # careful with renames. these are HARD, and any filters done on the original column will break
866 my %renamed_columns = (
867 'factor' => 'price_factor',
868 'SUM(ioi.qty)' => 'soldtotal',
869 'ioi.id' => 'ioi_id',
871 'projectdescription' => 'projectdescription',
875 projectdescription => 'description',
878 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
879 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
882 my $make_token_builder = sub {
883 my $joins_needed = shift;
885 my ($nick, $alias) = @_;
886 my ($col) = $real_column{$nick} || $nick;
887 my @coalesce_tokens =
888 map { ($_->[1] || 'p.') . $_->[0] }
889 grep { !$_->[2] || $joins_needed->{$_->[2]} }
890 grep { ($_->[3] || $_->[0]) eq $nick }
891 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
893 my $coalesce = scalar @coalesce_tokens > 1;
895 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
896 : shift @coalesce_tokens)
897 . ($alias && ($coalesce || $renamed_columns{$nick})
898 ? " AS " . ($renamed_columns{$nick} || $nick)
903 #===== switches and simple filters ========#
905 # special case transdate
906 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
907 $form->{"l_transdate"} = 1;
908 push @select_tokens, 'transdate';
909 for (qw(transdatefrom transdateto)) {
910 next unless $form->{$_};
911 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
912 push @bind_vars, $form->{$_};
916 if ($form->{"partsgroup_id"}) {
917 $form->{"l_partsgroup"} = '1'; # show the column
918 push @where_tokens, "pg.id = ?";
919 push @bind_vars, $form->{"partsgroup_id"};
922 foreach (@like_filters) {
923 next unless $form->{$_};
924 $form->{"l_$_"} = '1'; # show the column
925 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
926 push @bind_vars, "%$form->{$_}%";
929 foreach (@simple_l_switches) {
930 next unless $form->{"l_$_"};
931 push @select_tokens, $_;
934 for ($form->{searchitems}) {
935 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
936 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
937 push @where_tokens, 'NOT p.assembly' if /service/;
938 push @where_tokens, ' p.assembly' if /assembly/;
941 for ($form->{itemstatus}) {
942 push @where_tokens, 'p.id NOT IN
943 (SELECT DISTINCT parts_id FROM invoice UNION
944 SELECT DISTINCT parts_id FROM assembly UNION
945 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
946 push @where_tokens, 'p.onhand = 0' if /orphaned/;
947 push @where_tokens, 'NOT p.obsolete' if /active/;
948 push @where_tokens, ' p.obsolete', if /obsolete/;
949 push @where_tokens, 'p.onhand > 0', if /onhand/;
950 push @where_tokens, 'p.onhand < p.rop', if /short/;
953 my $q_assembly_lastcost =
954 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
956 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
957 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
958 WHERE (a_lc.id = p.id)) AS lastcost|;
959 $table_prefix{$q_assembly_lastcost} = ' ';
961 # special case makemodel search
962 # all_parts is based upon the assumption that every parameter is named like the column it represents
963 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
964 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
966 push @where_tokens, 'mv.name ILIKE ?';
967 push @bind_vars, "%$form->{make}%";
969 if ($form->{model}) {
970 push @where_tokens, 'mm.model ILIKE ?';
971 push @bind_vars, "%$form->{model}%";
974 # special case: sorting by partnumber
975 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
976 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
977 # ToDO: implement proper functional sorting
978 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
979 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
980 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
981 # if $form->{sort} eq 'partnumber';
983 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
986 $limit_clause = " LIMIT 100" if $form->{top100};
987 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
989 #=== joins and complicated filters ========#
991 my $bsooqr = any { $form->{$_} } @oe_flags;
992 my @bsooqr_tokens = ();
994 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
995 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
996 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
997 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
998 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
999 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
1000 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
1001 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
1002 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
1003 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
1005 $joins_needed{partsgroup} = 1;
1006 $joins_needed{pfac} = 1;
1007 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
1008 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
1009 $joins_needed{mv} = 1 if $joins_needed{makemodel};
1010 $joins_needed{cv} = 1 if $bsooqr;
1011 $joins_needed{apoe} = 1 if $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
1012 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
1014 # special case for description search.
1015 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
1016 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
1017 # find the old entries in of @where_tokens and @bind_vars, and adjust them
1018 if ($joins_needed{invoice_oi}) {
1019 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
1020 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
1021 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
1022 splice @bind_vars, $bi, 0, $bind_vars[$bi];
1027 # now the master trick: soldtotal.
1028 if ($form->{l_soldtotal}) {
1029 push @where_tokens, 'NOT ioi.qty = 0';
1030 push @group_tokens, @select_tokens;
1031 map { s/.*\sAS\s+//si } @group_tokens;
1032 push @select_tokens, 'SUM(ioi.qty)';
1035 #============= build query ================#
1037 my $token_builder = $make_token_builder->(\%joins_needed);
1039 my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
1040 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
1041 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
1042 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
1044 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
1045 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
1046 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
1047 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
1049 my %oe_flag_to_cvar = (
1050 bought => 'invoice',
1052 onorder => 'orderitems',
1053 ordered => 'orderitems',
1054 rfq => 'orderitems',
1055 quoted => 'orderitems',
1058 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
1060 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1062 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1066 $where_clause .= qq| AND ($cvar_where)|;
1067 push @bind_vars, @cvar_values;
1070 my $query = <<" SQL";
1071 SELECT DISTINCT $select_clause
1080 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1082 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1084 # fix qty sign in ap. those are saved negative
1085 if ($bsooqr && $form->{bought}) {
1086 for my $row (@{ $form->{parts} }) {
1087 $row->{qty} *= -1 if $row->{module} eq 'ir';
1091 # post processing for assembly parts lists (bom)
1092 # for each part get the assembly parts and add them into the partlist.
1094 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1096 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1098 p.sellprice, p.listprice, p.lastcost,
1099 p.rop, p.weight, p.priceupdate,
1100 p.image, p.drawing, p.microfiche,
1103 INNER JOIN assembly a ON (p.id = a.parts_id)
1106 my $sth = prepare_query($form, $dbh, $query);
1108 foreach my $item (@{ $form->{parts} }) {
1109 push(@assemblies, $item);
1110 do_statement($form, $sth, $query, conv_i($item->{id}));
1112 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1113 $ref->{assemblyitem} = 1;
1114 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1115 push(@assemblies, $ref);
1120 # copy assemblies to $form->{parts}
1121 $form->{parts} = \@assemblies;
1124 $main::lxdebug->leave_sub();
1126 return wantarray ? @{ $form->{parts} } : $form->{parts};
1129 sub _create_filter_for_priceupdate {
1130 $main::lxdebug->enter_sub();
1133 my $myconfig = \%main::myconfig;
1134 my $form = $main::form;
1137 my $where = '1 = 1';
1139 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1141 $column =~ s/.*\.//;
1142 next unless ($form->{$column});
1144 $where .= qq| AND $item ILIKE ?|;
1145 push(@where_values, '%' . $form->{$column} . '%');
1148 foreach my $item (qw(description serialnumber)) {
1149 next unless ($form->{$item});
1151 $where .= qq| AND (${item} ILIKE ?)|;
1152 push(@where_values, '%' . $form->{$item} . '%');
1156 # items which were never bought, sold or on an order
1157 if ($form->{itemstatus} eq 'orphaned') {
1159 qq| AND (p.onhand = 0)
1162 SELECT DISTINCT parts_id FROM invoice
1164 SELECT DISTINCT parts_id FROM assembly
1166 SELECT DISTINCT parts_id FROM orderitems
1169 } elsif ($form->{itemstatus} eq 'active') {
1170 $where .= qq| AND p.obsolete = '0'|;
1172 } elsif ($form->{itemstatus} eq 'obsolete') {
1173 $where .= qq| AND p.obsolete = '1'|;
1175 } elsif ($form->{itemstatus} eq 'onhand') {
1176 $where .= qq| AND p.onhand > 0|;
1178 } elsif ($form->{itemstatus} eq 'short') {
1179 $where .= qq| AND p.onhand < p.rop|;
1183 foreach my $column (qw(make model)) {
1184 next unless ($form->{$column});
1185 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1186 push(@where_values, '%' . $form->{$column} . '%');
1189 $main::lxdebug->leave_sub();
1191 return ($where, @where_values);
1194 sub get_num_matches_for_priceupdate {
1195 $main::lxdebug->enter_sub();
1199 my $myconfig = \%main::myconfig;
1200 my $form = $main::form;
1202 my $dbh = $form->get_standard_dbh($myconfig);
1204 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1206 my $num_updated = 0;
1209 for my $column (qw(sellprice listprice)) {
1210 next if ($form->{$column} eq "");
1218 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1220 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1221 $num_updated += $result if (0 <= $result);
1230 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1231 WHERE $where) AND (pricegroup_id = ?)|;
1232 my $sth = prepare_query($form, $dbh, $query);
1234 for my $i (1 .. $form->{price_rows}) {
1235 next if ($form->{"price_$i"} eq "");
1237 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1238 $num_updated += $result if (0 <= $result);
1242 $main::lxdebug->leave_sub();
1244 return $num_updated;
1248 $main::lxdebug->enter_sub();
1250 my ($self, $myconfig, $form) = @_;
1252 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1253 my $num_updated = 0;
1255 # connect to database
1256 my $dbh = $form->dbconnect_noauto($myconfig);
1258 for my $column (qw(sellprice listprice)) {
1259 next if ($form->{$column} eq "");
1261 my $value = $form->parse_amount($myconfig, $form->{$column});
1264 if ($form->{"${column}_type"} eq "percent") {
1265 $value = ($value / 100) + 1;
1270 qq|UPDATE parts SET $column = $column $operator ?
1274 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1276 my $result = do_query($form, $dbh, $query, $value, @where_values);
1277 $num_updated += $result if (0 <= $result);
1281 qq|UPDATE prices SET price = price + ?
1285 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1286 WHERE $where) AND (pricegroup_id = ?)|;
1287 my $sth_add = prepare_query($form, $dbh, $q_add);
1290 qq|UPDATE prices SET price = price * ?
1294 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1295 WHERE $where) AND (pricegroup_id = ?)|;
1296 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1298 for my $i (1 .. $form->{price_rows}) {
1299 next if ($form->{"price_$i"} eq "");
1301 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1304 if ($form->{"pricegroup_type_$i"} eq "percent") {
1305 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1307 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1310 $num_updated += $result if (0 <= $result);
1314 $sth_multiply->finish();
1316 my $rc= $dbh->commit;
1319 $main::lxdebug->leave_sub();
1321 return $num_updated;
1325 $main::lxdebug->enter_sub();
1327 my ($self, $module, $myconfig, $form) = @_;
1329 # connect to database
1330 my $dbh = $form->dbconnect($myconfig);
1332 my @values = ('%' . $module . '%');
1337 qq|SELECT c.accno, c.description, c.link, c.id,
1338 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1339 FROM chart c, parts p
1340 WHERE (c.link LIKE ?) AND (p.id = ?)
1342 push(@values, conv_i($form->{id}));
1346 qq|SELECT c.accno, c.description, c.link, c.id,
1347 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1348 FROM chart c, defaults d
1353 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1354 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1355 foreach my $key (split(/:/, $ref->{link})) {
1356 if ($key =~ /\Q$module\E/) {
1357 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1358 || ($ref->{id} eq $ref->{income_accno_id})
1359 || ($ref->{id} eq $ref->{expense_accno_id})) {
1360 push @{ $form->{"${module}_links"}{$key} },
1361 { accno => $ref->{accno},
1362 description => $ref->{description},
1363 selected => "selected" };
1364 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1366 push @{ $form->{"${module}_links"}{$key} },
1367 { accno => $ref->{accno},
1368 description => $ref->{description},
1376 # get buchungsgruppen
1377 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1380 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1383 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1387 $main::lxdebug->leave_sub();
1390 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1392 $main::lxdebug->enter_sub();
1394 my ($self, $myconfig, $form, $sortorder) = @_;
1395 my $dbh = $form->dbconnect($myconfig);
1396 my $order = qq| p.partnumber|;
1397 my $where = qq|1 = 1|;
1400 if ($sortorder eq "all") {
1401 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1402 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1404 } elsif ($sortorder eq "partnumber") {
1405 $where .= qq| AND (partnumber ILIKE ?)|;
1406 push(@values, '%' . $form->{partnumber} . '%');
1408 } elsif ($sortorder eq "description") {
1409 $where .= qq| AND (description ILIKE ?)|;
1410 push(@values, '%' . $form->{description} . '%');
1411 $order = "description";
1416 qq|SELECT id, partnumber, description, unit, sellprice
1418 WHERE $where ORDER BY $order|;
1420 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1423 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1424 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1429 $form->{"id_$j"} = $ref->{id};
1430 $form->{"partnumber_$j"} = $ref->{partnumber};
1431 $form->{"description_$j"} = $ref->{description};
1432 $form->{"unit_$j"} = $ref->{unit};
1433 $form->{"sellprice_$j"} = $ref->{sellprice};
1434 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1440 $main::lxdebug->leave_sub();
1445 # gets sum of sold part with part_id
1447 $main::lxdebug->enter_sub();
1449 my ($dbh, $id) = @_;
1451 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1452 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1455 $main::lxdebug->leave_sub();
1458 } #end get_soldtotal
1460 sub retrieve_languages {
1461 $main::lxdebug->enter_sub();
1463 my ($self, $myconfig, $form) = @_;
1465 # connect to database
1466 my $dbh = $form->dbconnect($myconfig);
1472 if ($form->{language_values} ne "") {
1474 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1476 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1477 ORDER BY lower(l.description)|;
1478 @values = (conv_i($form->{id}));
1481 $query = qq|SELECT id, description
1483 ORDER BY lower(description)|;
1486 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1490 $main::lxdebug->leave_sub();
1495 sub follow_account_chain {
1496 $main::lxdebug->enter_sub(2);
1498 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1500 my @visited_accno_ids = ($accno_id);
1504 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1505 map { $_->{id} => $_ }
1506 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1507 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1509 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1510 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1514 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1515 last unless ($ref && $ref->{"is_valid"} &&
1516 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1517 $accno_id = $ref->{"new_chart_id"};
1518 $accno = $ref->{"accno"};
1519 push(@visited_accno_ids, $accno_id);
1522 $main::lxdebug->leave_sub(2);
1524 return ($accno_id, $accno);
1527 sub retrieve_accounts {
1528 $main::lxdebug->enter_sub;
1531 my $myconfig = shift;
1533 my $dbh = $form->get_standard_dbh;
1534 my %args = @_; # index => part_id
1536 $form->{taxzone_id} *= 1;
1538 return unless grep $_, values %args; # shortfuse if no part_id supplied
1540 # transdate madness.
1542 if ($form->{type} eq "invoice") {
1543 if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1544 $transdate = $form->{invdate};
1546 $transdate = $form->{deliverydate};
1548 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1549 $transdate = $form->{invdate};
1551 $transdate = $form->{transdate};
1554 if ($transdate eq "") {
1555 $transdate = DateTime->today_local->to_lxoffice;
1557 $transdate = $dbh->quote($transdate);
1560 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1562 my @part_ids = grep { $_ } values %args;
1563 my $in = join ',', ('?') x @part_ids;
1565 my %accno_by_part = map { $_->{id} => $_ }
1566 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1568 p.id, p.inventory_accno_id AS is_part,
1569 bg.inventory_accno_id,
1570 bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
1571 bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
1572 c1.accno AS inventory_accno,
1573 c2.accno AS income_accno,
1574 c3.accno AS expense_accno
1576 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1577 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1578 LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
1579 LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
1583 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1584 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1586 LEFT JOIN chart c ON c.id = t.chart_id
1590 WHERE tk.chart_id = ? AND startdate <= ?
1591 ORDER BY startdate DESC LIMIT 1)
1594 while (my ($index => $part_id) = each %args) {
1595 my $ref = $accno_by_part{$part_id} or next;
1597 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1600 for my $type (qw(inventory income expense)) {
1601 next unless $ref->{"${type}_accno_id"};
1602 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1603 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1606 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1608 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1609 $ref = $sth_tax->fetchrow_hashref or next;
1611 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1612 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1614 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1619 $::lxdebug->leave_sub;
1622 sub get_basic_part_info {
1623 $main::lxdebug->enter_sub();
1628 Common::check_params(\%params, qw(id));
1630 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1633 $main::lxdebug->leave_sub();
1637 my $myconfig = \%main::myconfig;
1638 my $form = $main::form;
1640 my $dbh = $form->get_standard_dbh($myconfig);
1642 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1644 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1646 if ('' eq ref $params{id}) {
1647 $info = $info->[0] || { };
1649 $main::lxdebug->leave_sub();
1653 my %info_map = map { $_->{id} => $_ } @{ $info };
1655 $main::lxdebug->leave_sub();
1660 sub prepare_parts_for_printing {
1661 $main::lxdebug->enter_sub();
1666 my $myconfig = \%main::myconfig;
1667 my $form = $main::form;
1669 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1671 my $prefix = $params{prefix} || 'id_';
1672 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1674 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1677 $main::lxdebug->leave_sub();
1681 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1682 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1684 LEFT JOIN vendor v ON (mm.make = v.id)
1685 WHERE mm.parts_id IN ($placeholders)|;
1689 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1691 while (my $ref = $sth->fetchrow_hashref()) {
1692 $makemodel{$ref->{parts_id}} ||= [];
1693 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1698 my @columns = qw(ean image microfiche drawing weight);
1700 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1702 WHERE id IN ($placeholders)|;
1704 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1706 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1708 foreach my $i (1 .. $rowcount) {
1709 my $id = $form->{"${prefix}${i}"};
1713 foreach (@columns) {
1714 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1717 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1718 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1720 next if (!$makemodel{$id});
1722 foreach my $ref (@{ $makemodel{$id} }) {
1723 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1727 $main::lxdebug->leave_sub();