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(notes 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{project} || $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,
1097 p.unit, p.bin, p.notes,
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 if ($form->{l_pricegroups} ) {
1126 SELECT parts_id, price, pricegroup_id
1131 my $sth = prepare_query($form, $dbh, $query);
1133 foreach my $part (@{ $form->{parts} }) {
1134 do_statement($form, $sth, $query, conv_i($part->{id}));
1136 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1137 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1144 $main::lxdebug->leave_sub();
1146 return wantarray ? @{ $form->{parts} } : $form->{parts};
1149 sub _create_filter_for_priceupdate {
1150 $main::lxdebug->enter_sub();
1153 my $myconfig = \%main::myconfig;
1154 my $form = $main::form;
1157 my $where = '1 = 1';
1159 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1161 $column =~ s/.*\.//;
1162 next unless ($form->{$column});
1164 $where .= qq| AND $item ILIKE ?|;
1165 push(@where_values, '%' . $form->{$column} . '%');
1168 foreach my $item (qw(description serialnumber)) {
1169 next unless ($form->{$item});
1171 $where .= qq| AND (${item} ILIKE ?)|;
1172 push(@where_values, '%' . $form->{$item} . '%');
1176 # items which were never bought, sold or on an order
1177 if ($form->{itemstatus} eq 'orphaned') {
1179 qq| AND (p.onhand = 0)
1182 SELECT DISTINCT parts_id FROM invoice
1184 SELECT DISTINCT parts_id FROM assembly
1186 SELECT DISTINCT parts_id FROM orderitems
1189 } elsif ($form->{itemstatus} eq 'active') {
1190 $where .= qq| AND p.obsolete = '0'|;
1192 } elsif ($form->{itemstatus} eq 'obsolete') {
1193 $where .= qq| AND p.obsolete = '1'|;
1195 } elsif ($form->{itemstatus} eq 'onhand') {
1196 $where .= qq| AND p.onhand > 0|;
1198 } elsif ($form->{itemstatus} eq 'short') {
1199 $where .= qq| AND p.onhand < p.rop|;
1203 foreach my $column (qw(make model)) {
1204 next unless ($form->{$column});
1205 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1206 push(@where_values, '%' . $form->{$column} . '%');
1209 $main::lxdebug->leave_sub();
1211 return ($where, @where_values);
1214 sub get_num_matches_for_priceupdate {
1215 $main::lxdebug->enter_sub();
1219 my $myconfig = \%main::myconfig;
1220 my $form = $main::form;
1222 my $dbh = $form->get_standard_dbh($myconfig);
1224 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1226 my $num_updated = 0;
1229 for my $column (qw(sellprice listprice)) {
1230 next if ($form->{$column} eq "");
1238 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1240 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1241 $num_updated += $result if (0 <= $result);
1250 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1251 WHERE $where) AND (pricegroup_id = ?)|;
1252 my $sth = prepare_query($form, $dbh, $query);
1254 for my $i (1 .. $form->{price_rows}) {
1255 next if ($form->{"price_$i"} eq "");
1257 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1258 $num_updated += $result if (0 <= $result);
1262 $main::lxdebug->leave_sub();
1264 return $num_updated;
1268 $main::lxdebug->enter_sub();
1270 my ($self, $myconfig, $form) = @_;
1272 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1273 my $num_updated = 0;
1275 # connect to database
1276 my $dbh = $form->dbconnect_noauto($myconfig);
1278 for my $column (qw(sellprice listprice)) {
1279 next if ($form->{$column} eq "");
1281 my $value = $form->parse_amount($myconfig, $form->{$column});
1284 if ($form->{"${column}_type"} eq "percent") {
1285 $value = ($value / 100) + 1;
1290 qq|UPDATE parts SET $column = $column $operator ?
1294 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1296 my $result = do_query($form, $dbh, $query, $value, @where_values);
1297 $num_updated += $result if (0 <= $result);
1301 qq|UPDATE prices SET price = price + ?
1305 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1306 WHERE $where) AND (pricegroup_id = ?)|;
1307 my $sth_add = prepare_query($form, $dbh, $q_add);
1310 qq|UPDATE prices SET price = price * ?
1314 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1315 WHERE $where) AND (pricegroup_id = ?)|;
1316 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1318 for my $i (1 .. $form->{price_rows}) {
1319 next if ($form->{"price_$i"} eq "");
1321 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1324 if ($form->{"pricegroup_type_$i"} eq "percent") {
1325 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1327 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1330 $num_updated += $result if (0 <= $result);
1334 $sth_multiply->finish();
1336 my $rc= $dbh->commit;
1339 $main::lxdebug->leave_sub();
1341 return $num_updated;
1345 $main::lxdebug->enter_sub();
1347 my ($self, $module, $myconfig, $form) = @_;
1349 # connect to database
1350 my $dbh = $form->dbconnect($myconfig);
1352 my @values = ('%' . $module . '%');
1357 qq|SELECT c.accno, c.description, c.link, c.id,
1358 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1359 FROM chart c, parts p
1360 WHERE (c.link LIKE ?) AND (p.id = ?)
1362 push(@values, conv_i($form->{id}));
1366 qq|SELECT c.accno, c.description, c.link, c.id,
1367 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1368 FROM chart c, defaults d
1373 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1374 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1375 foreach my $key (split(/:/, $ref->{link})) {
1376 if ($key =~ /\Q$module\E/) {
1377 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1378 || ($ref->{id} eq $ref->{income_accno_id})
1379 || ($ref->{id} eq $ref->{expense_accno_id})) {
1380 push @{ $form->{"${module}_links"}{$key} },
1381 { accno => $ref->{accno},
1382 description => $ref->{description},
1383 selected => "selected" };
1384 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1386 push @{ $form->{"${module}_links"}{$key} },
1387 { accno => $ref->{accno},
1388 description => $ref->{description},
1396 # get buchungsgruppen
1397 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1400 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1403 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1407 $main::lxdebug->leave_sub();
1410 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1412 $main::lxdebug->enter_sub();
1414 my ($self, $myconfig, $form, $sortorder) = @_;
1415 my $dbh = $form->dbconnect($myconfig);
1416 my $order = qq| p.partnumber|;
1417 my $where = qq|1 = 1|;
1420 if ($sortorder eq "all") {
1421 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1422 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1424 } elsif ($sortorder eq "partnumber") {
1425 $where .= qq| AND (partnumber ILIKE ?)|;
1426 push(@values, '%' . $form->{partnumber} . '%');
1428 } elsif ($sortorder eq "description") {
1429 $where .= qq| AND (description ILIKE ?)|;
1430 push(@values, '%' . $form->{description} . '%');
1431 $order = "description";
1436 qq|SELECT id, partnumber, description, unit, sellprice
1438 WHERE $where ORDER BY $order|;
1440 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1443 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1444 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1449 $form->{"id_$j"} = $ref->{id};
1450 $form->{"partnumber_$j"} = $ref->{partnumber};
1451 $form->{"description_$j"} = $ref->{description};
1452 $form->{"unit_$j"} = $ref->{unit};
1453 $form->{"sellprice_$j"} = $ref->{sellprice};
1454 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1460 $main::lxdebug->leave_sub();
1465 # gets sum of sold part with part_id
1467 $main::lxdebug->enter_sub();
1469 my ($dbh, $id) = @_;
1471 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1472 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1475 $main::lxdebug->leave_sub();
1478 } #end get_soldtotal
1480 sub retrieve_languages {
1481 $main::lxdebug->enter_sub();
1483 my ($self, $myconfig, $form) = @_;
1485 # connect to database
1486 my $dbh = $form->dbconnect($myconfig);
1492 if ($form->{language_values} ne "") {
1494 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1496 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1497 ORDER BY lower(l.description)|;
1498 @values = (conv_i($form->{id}));
1501 $query = qq|SELECT id, description
1503 ORDER BY lower(description)|;
1506 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1510 $main::lxdebug->leave_sub();
1515 sub follow_account_chain {
1516 $main::lxdebug->enter_sub(2);
1518 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1520 my @visited_accno_ids = ($accno_id);
1524 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1525 map { $_->{id} => $_ }
1526 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1527 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1529 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1530 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1534 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1535 last unless ($ref && $ref->{"is_valid"} &&
1536 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1537 $accno_id = $ref->{"new_chart_id"};
1538 $accno = $ref->{"accno"};
1539 push(@visited_accno_ids, $accno_id);
1542 $main::lxdebug->leave_sub(2);
1544 return ($accno_id, $accno);
1547 sub retrieve_accounts {
1548 $main::lxdebug->enter_sub;
1551 my $myconfig = shift;
1553 my $dbh = $form->get_standard_dbh;
1554 my %args = @_; # index => part_id
1556 $form->{taxzone_id} *= 1;
1558 return unless grep $_, values %args; # shortfuse if no part_id supplied
1560 # transdate madness.
1562 if ($form->{type} eq "invoice") {
1563 if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1564 $transdate = $form->{invdate};
1566 $transdate = $form->{deliverydate};
1568 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
1569 # if credit_note has a deliverydate, use this instead of invdate
1570 # useful for credit_notes of invoices from an old period with different tax
1571 # if there is no deliverydate then invdate is used, old default (see next elsif)
1572 $transdate = $form->{deliverydate};
1573 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1574 $transdate = $form->{invdate};
1576 $transdate = $form->{transdate};
1579 if ($transdate eq "") {
1580 $transdate = DateTime->today_local->to_lxoffice;
1582 $transdate = $dbh->quote($transdate);
1585 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1587 my @part_ids = grep { $_ } values %args;
1588 my $in = join ',', ('?') x @part_ids;
1590 my %accno_by_part = map { $_->{id} => $_ }
1591 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1593 p.id, p.inventory_accno_id AS is_part,
1594 bg.inventory_accno_id,
1595 bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
1596 bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
1597 c1.accno AS inventory_accno,
1598 c2.accno AS income_accno,
1599 c3.accno AS expense_accno
1601 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1602 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1603 LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
1604 LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
1608 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1609 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1611 LEFT JOIN chart c ON c.id = t.chart_id
1615 WHERE tk.chart_id = ? AND startdate <= ?
1616 ORDER BY startdate DESC LIMIT 1)
1619 while (my ($index => $part_id) = each %args) {
1620 my $ref = $accno_by_part{$part_id} or next;
1622 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1625 for my $type (qw(inventory income expense)) {
1626 next unless $ref->{"${type}_accno_id"};
1627 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1628 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1631 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1633 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1634 $ref = $sth_tax->fetchrow_hashref or next;
1636 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1637 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1639 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1644 $::lxdebug->leave_sub;
1647 sub get_basic_part_info {
1648 $main::lxdebug->enter_sub();
1653 Common::check_params(\%params, qw(id));
1655 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1658 $main::lxdebug->leave_sub();
1662 my $myconfig = \%main::myconfig;
1663 my $form = $main::form;
1665 my $dbh = $form->get_standard_dbh($myconfig);
1667 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1669 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1671 if ('' eq ref $params{id}) {
1672 $info = $info->[0] || { };
1674 $main::lxdebug->leave_sub();
1678 my %info_map = map { $_->{id} => $_ } @{ $info };
1680 $main::lxdebug->leave_sub();
1685 sub prepare_parts_for_printing {
1686 $main::lxdebug->enter_sub();
1691 my $myconfig = \%main::myconfig;
1692 my $form = $main::form;
1694 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1696 my $prefix = $params{prefix} || 'id_';
1697 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1699 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1702 $main::lxdebug->leave_sub();
1706 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1707 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1709 LEFT JOIN vendor v ON (mm.make = v.id)
1710 WHERE mm.parts_id IN ($placeholders)|;
1714 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1716 while (my $ref = $sth->fetchrow_hashref()) {
1717 $makemodel{$ref->{parts_id}} ||= [];
1718 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1723 my @columns = qw(ean image microfiche drawing weight);
1725 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1727 WHERE id IN ($placeholders)|;
1729 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1731 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1733 foreach my $i (1 .. $rowcount) {
1734 my $id = $form->{"${prefix}${i}"};
1738 foreach (@columns) {
1739 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1742 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1743 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1745 next if (!$makemodel{$id});
1747 foreach my $ref (@{ $makemodel{$id} }) {
1748 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1752 $main::lxdebug->leave_sub();