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};
114 SELECT pg.pricegroup, pg.id AS pricegroup_id, COALESCE(pr.price, 0) AS price
116 LEFT JOIN prices pr ON (pr.pricegroup_id = pg.id) AND (pr.parts_id = ?)
117 ORDER BY lower(pg.pricegroup)
121 foreach $ref (selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}))) {
122 $form->{"${_}_${row}"} = $ref->{$_} for qw(pricegroup_id pricegroup price);
125 $form->{price_rows} = $row - 1;
128 if ($form->{makemodel}) {
130 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
131 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
132 my @values = ($form->{id});
133 $sth = $dbh->prepare($query);
134 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
138 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
139 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
144 $form->{makemodel_rows} = $i - 1;
149 $form->{language_values} = "";
150 $query = qq|SELECT language_id, translation, longdescription
153 my $trq = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
154 while (my $tr = $trq->fetchrow_hashref("NAME_lc")) {
155 $form->{language_values} .= "---+++---" . join('--++--', @{$tr}{qw(language_id translation longdescription)});
159 # now get accno for taxes
162 FROM chart c, partstax pt
163 WHERE (pt.chart_id = c.id) AND (pt.parts_id = ?)|;
164 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
165 while (my ($key) = $sth->fetchrow_array) {
166 $form->{amount}{$key} = $key;
172 my @referencing_tables = qw(invoice orderitems inventory rmaitems);
173 my %column_map = ( );
174 my $parts_id = conv_i($form->{id});
176 $form->{orphaned} = 1;
178 foreach my $table (@referencing_tables) {
179 my $column = $column_map{$table} || 'parts_id';
180 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
181 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
184 $form->{orphaned} = 0;
189 $form->{"unit_changeable"} = $form->{orphaned};
193 $main::lxdebug->leave_sub();
196 sub get_pricegroups {
197 $main::lxdebug->enter_sub();
199 my ($self, $myconfig, $form) = @_;
201 my $dbh = $form->dbconnect($myconfig);
204 my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
205 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
208 foreach my $pg (@{ $pricegroups }) {
209 $form->{"klass_$i"} = "$pg->{id}";
210 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
211 $form->{"pricegroup_id_$i"} = "$pg->{id}";
212 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
217 $form->{price_rows} = $i - 1;
221 $main::lxdebug->leave_sub();
226 sub retrieve_buchungsgruppen {
227 $main::lxdebug->enter_sub();
229 my ($self, $myconfig, $form) = @_;
233 my $dbh = $form->dbconnect($myconfig);
235 # get buchungsgruppen
236 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
237 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
239 $main::lxdebug->leave_sub();
243 $main::lxdebug->enter_sub();
245 my ($self, $myconfig, $form) = @_;
247 # connect to database, turn off AutoCommit
248 my $dbh = $form->get_standard_dbh;
251 # make up a unique handle and store in partnumber field
252 # then retrieve the record based on the unique handle to get the id
253 # replace the partnumber field with the actual variable
254 # add records for makemodel
256 # if there is a $form->{id} then replace the old entry
257 # delete all makemodel entries and add the new ones
259 # undo amount formatting
260 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
261 qw(rop weight listprice sellprice gv lastcost);
263 my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
265 $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
269 my $priceupdate = ', priceupdate = current_date';
272 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
273 if (!$trans_number->is_unique) {
274 $::lxdebug->leave_sub;
279 $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
280 my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
282 # if item is part of an assembly adjust all assemblies
283 $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
284 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
285 while (my ($id, $qty) = $sth->fetchrow_array) {
286 &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
290 # delete makemodel records
291 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
293 if ($form->{item} eq 'assembly') {
294 # delete assembly records
295 do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
299 do_query($form, $dbh, qq|DELETE FROM partstax WHERE parts_id = ?|, conv_i($form->{id}));
301 # delete translations
302 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
304 # Check whether or not the prices have changed. If they haven't
305 # then 'priceupdate' should not be updated.
306 my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
307 $priceupdate = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
310 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, save => 1);
312 if ($form->{partnumber} && !$trans_number->is_unique) {
313 $::lxdebug->leave_sub;
317 $form->{partnumber} ||= $trans_number->create_unique;
319 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
320 do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit});
322 $form->{orphaned} = 1;
324 my $partsgroup_id = 0;
326 if ($form->{partsgroup}) {
327 (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
330 my ($subq_inventory, $subq_expense, $subq_income);
331 if ($form->{"item"} eq "part") {
333 qq|(SELECT bg.inventory_accno_id
334 FROM buchungsgruppen bg
335 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
337 $subq_inventory = "NULL";
340 if ($form->{"item"} ne "assembly") {
342 qq|(SELECT bg.expense_accno_id_0
343 FROM buchungsgruppen bg
344 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
346 $subq_expense = "NULL";
365 buchungsgruppen_id = ?,
367 inventory_accno_id = $subq_inventory,
368 income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
369 expense_accno_id = $subq_expense,
378 not_discountable = ?,
384 @values = ($form->{partnumber},
385 $form->{description},
386 $makemodel ? 't' : 'f',
387 $form->{assembly} ? 't' : 'f',
397 conv_i($form->{buchungsgruppen_id}),
398 conv_i($form->{payment_id}),
399 conv_i($form->{buchungsgruppen_id}),
400 $form->{obsolete} ? 't' : 'f',
403 $form->{shop} ? 't' : 'f',
407 $form->{has_sernumber} ? 't' : 'f',
408 $form->{not_discountable} ? 't' : 'f',
410 conv_i($partsgroup_id),
411 conv_i($form->{price_factor_id}),
414 do_query($form, $dbh, $query, @values);
416 # delete translation records
417 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
419 if ($form->{language_values} ne "") {
420 foreach my $item (split(/---\+\+\+---/, $form->{language_values})) {
421 my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
422 if ($translation ne "") {
423 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
424 VALUES ( ?, ?, ?, ? )|;
425 @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
426 do_query($form, $dbh, $query, @values);
431 # delete price records
432 do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
434 $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) VALUES(?, ?, ?)|;
435 $sth = prepare_query($form, $dbh, $query);
437 # insert price records only if different to sellprice
438 for my $i (1 .. $form->{price_rows}) {
439 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
440 next unless $price && ($price != $form->{sellprice});
442 @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
443 do_statement($form, $sth, $query, @values);
448 # insert makemodel records
451 for my $i (1 .. $form->{makemodel_rows}) {
452 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
454 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
455 if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
457 if ($form->{"lastupdate_$i"} eq "") {
458 $lastupdate = 'now()';
460 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
463 $lastupdate = 'now()';
465 $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
466 qq|VALUES (?, ?, ?, ?, ?, ?)|;
467 @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
469 do_query($form, $dbh, $query, @values);
474 foreach my $item (split(/ /, $form->{taxaccounts})) {
475 if ($form->{"IC_tax_$item"}) {
477 qq|INSERT INTO partstax (parts_id, chart_id)
478 VALUES (?, (SELECT id FROM chart WHERE accno = ?))|;
479 @values = (conv_i($form->{id}), $item);
480 do_query($form, $dbh, $query, @values);
484 # add assembly records
485 if ($form->{item} eq 'assembly') {
487 for my $i (1 .. $form->{assembly_rows}) {
488 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
490 if ($form->{"qty_$i"} != 0) {
491 $form->{"bom_$i"} *= 1;
492 $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
493 qq|VALUES (?, ?, ?, ?)|;
494 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
495 do_query($form, $dbh, $query, @values);
502 my $shippingdate = "$a[5]-$a[4]-$a[3]";
504 $form->get_employee($dbh);
508 #set expense_accno=inventory_accno if they are different => bilanz
510 ($form->{expense_accno} != $form->{inventory_accno})
511 ? $form->{inventory_accno}
512 : $form->{expense_accno};
514 # get tax rates and description
516 ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
518 qq|SELECT c.accno, c.description, t.rate, t.taxnumber
520 WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
522 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
524 $form->{taxaccount} = "";
525 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
526 $form->{taxaccount} .= "$ptr->{accno} ";
527 if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
528 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
529 $form->{"$ptr->{accno}_description"} = $ptr->{description};
530 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
531 $form->{taxaccount2} .= " $ptr->{accno} ";
535 CVar->save_custom_variables(dbh => $dbh,
537 trans_id => $form->{id},
542 my $rc = $dbh->commit;
544 $main::lxdebug->leave_sub();
549 sub update_assembly {
550 $main::lxdebug->enter_sub();
552 my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
554 my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
555 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
557 while (my ($pid, $aqty) = $sth->fetchrow_array) {
558 &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
563 qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
565 my @values = ($qty * ($form->{sellprice} - $sellprice),
566 $qty * ($form->{weight} - $weight), conv_i($id));
567 do_query($form, $dbh, $query, @values);
569 $main::lxdebug->leave_sub();
572 sub retrieve_assemblies {
573 $main::lxdebug->enter_sub();
575 my ($self, $myconfig, $form) = @_;
577 # connect to database
578 my $dbh = $form->dbconnect($myconfig);
580 my $where = qq|NOT p.obsolete|;
583 if ($form->{partnumber}) {
584 $where .= qq| AND (p.partnumber ILIKE ?)|;
585 push(@values, '%' . $form->{partnumber} . '%');
588 if ($form->{description}) {
589 $where .= qq| AND (p.description ILIKE ?)|;
590 push(@values, '%' . $form->{description} . '%');
593 # retrieve assembly items
595 qq|SELECT p.id, p.partnumber, p.description,
596 p.bin, p.onhand, p.rop,
597 (SELECT sum(p2.inventory_accno_id)
598 FROM parts p2, assembly a
599 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
601 WHERE NOT p.obsolete AND p.assembly $where|;
603 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
607 $main::lxdebug->leave_sub();
611 $main::lxdebug->enter_sub();
613 my ($self, $myconfig, $form) = @_;
614 my @values = (conv_i($form->{id}));
615 # connect to database, turn off AutoCommit
616 my $dbh = $form->dbconnect_noauto($myconfig);
618 my %columns = ( "assembly" => "id", "parts" => "id" );
620 for my $table (qw(prices partstax makemodel inventory assembly translation parts)) {
621 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
622 do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
626 my $rc = $dbh->commit;
629 $main::lxdebug->leave_sub();
635 $main::lxdebug->enter_sub();
637 my ($self, $myconfig, $form) = @_;
639 my $i = $form->{assembly_rows};
641 my $where = qq|1 = 1|;
644 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
646 while (my ($column, $table) = each(%columns)) {
647 next unless ($form->{"${column}_$i"});
648 $where .= qq| AND ${table}.${column} ILIKE ?|;
649 push(@values, '%' . $form->{"${column}_$i"} . '%');
653 $where .= qq| AND NOT (p.id = ?)|;
654 push(@values, conv_i($form->{id}));
657 # Search for part ID overrides all other criteria.
658 if ($form->{"id_${i}"}) {
659 $where = qq|p.id = ?|;
660 @values = ($form->{"id_${i}"});
663 if ($form->{partnumber}) {
664 $where .= qq| ORDER BY p.partnumber|;
666 $where .= qq| ORDER BY p.description|;
669 # connect to database
670 my $dbh = $form->dbconnect($myconfig);
673 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
674 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
675 p.price_factor_id, pfac.factor AS price_factor
677 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
678 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
680 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
684 $main::lxdebug->leave_sub();
689 # Warning, deep magic ahead.
690 # This function gets all parts from the database according to the filters specified
693 # sort revers - sorting field + direction
696 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
697 # partnumber ean description partsgroup microfiche drawing
700 # 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
703 # itemstatus = active | onhand | short | obsolete | orphaned
704 # searchitems = part | assembly | service
707 # make model - makemodel
708 # serialnumber transdatefrom transdateto - invoice/orderitems
711 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
712 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
713 # l_soldtotal - aggreg join to display total of sold quantity
714 # onhand - as above, but masking the simple itemstatus results (doh!)
715 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
716 # l_serialnumber - belonges to serialnumber filter
717 # l_deliverydate - displays deliverydate is sold etc. flags are active
718 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
721 # onhand - as above, but masking the simple itemstatus results (doh!)
723 # search by overrides of description
725 # disabled sanity checks and changes:
726 # - searchitems = assembly will no longer disable bought
727 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
728 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
729 # - itemstatus = obsolete will no longer disable onhand, short
730 # - allow sorting by ean
731 # - serialnumber filter also works if l_serialnumber isn't ticked
732 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
735 $main::lxdebug->enter_sub();
737 my ($self, $myconfig, $form) = @_;
738 my $dbh = $form->get_standard_dbh($myconfig);
740 $form->{parts} = +{ };
741 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
743 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
744 my @project_filters = qw(projectnumber projectdescription);
745 my @makemodel_filters = qw(make model);
746 my @invoice_oi_filters = qw(serialnumber soldtotal);
747 my @apoe_filters = qw(transdate);
748 my @like_filters = (@simple_filters, @invoice_oi_filters);
749 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
750 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit bin rop image));
751 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
752 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
753 my @deliverydate_flags = qw(deliverydate);
754 # my @other_flags = qw(onhand); # ToDO: implement these
755 # my @inactive_flags = qw(l_subtotal short l_linetotal);
757 my @select_tokens = qw(id factor);
758 my @where_tokens = qw(1=1);
759 my @group_tokens = ();
761 my %joins_needed = ();
764 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
765 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
766 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
769 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
770 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
771 ) AS ioi ON ioi.parts_id = p.id|,
774 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
775 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
776 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
777 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
780 SELECT id, name, 'customer' AS cv FROM customer UNION
781 SELECT id, name, 'vendor' AS cv FROM vendor
782 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
783 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
784 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
786 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
789 deliverydate => 'apoe.', serialnumber => 'ioi.',
790 transdate => 'apoe.', trans_id => 'ioi.',
791 module => 'apoe.', name => 'cv.',
792 ordnumber => 'apoe.', make => 'mm.',
793 quonumber => 'apoe.', model => 'mm.',
794 invnumber => 'apoe.', partsgroup => 'pg.',
795 lastcost => 'p.', , soldtotal => ' ',
796 factor => 'pfac.', projectnumber => 'pj.',
797 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
800 serialnumber => 'ioi.',
801 quotation => 'apoe.',
807 # if the join condition in these blocks are met, the column
808 # of the scecified table will gently override (coalesce actually) the original value
809 # use it to conditionally coalesce values from subtables
810 my @column_override = (
811 # column name, prefix, joins_needed, nick name (in case column is named like another)
812 [ 'description', 'ioi.', 'invoice_oi' ],
813 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
814 [ 'transdate', 'apoe.', 'apoe' ],
815 [ 'unit', 'ioi.', 'invoice_oi' ],
816 [ 'sellprice', 'ioi.', 'invoice_oi' ],
819 # careful with renames. these are HARD, and any filters done on the original column will break
820 my %renamed_columns = (
821 'factor' => 'price_factor',
822 'SUM(ioi.qty)' => 'soldtotal',
823 'ioi.id' => 'ioi_id',
825 'projectdescription' => 'projectdescription',
829 projectdescription => 'description',
832 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
833 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
836 my $make_token_builder = sub {
837 my $joins_needed = shift;
839 my ($nick, $alias) = @_;
840 my ($col) = $real_column{$nick} || $nick;
841 my @coalesce_tokens =
842 map { ($_->[1] || 'p.') . $_->[0] }
843 grep { !$_->[2] || $joins_needed->{$_->[2]} }
844 grep { ($_->[3] || $_->[0]) eq $nick }
845 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
847 my $coalesce = scalar @coalesce_tokens > 1;
849 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
850 : shift @coalesce_tokens)
851 . ($alias && ($coalesce || $renamed_columns{$nick})
852 ? " AS " . ($renamed_columns{$nick} || $nick)
857 #===== switches and simple filters ========#
859 # special case transdate
860 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
861 $form->{"l_transdate"} = 1;
862 push @select_tokens, 'transdate';
863 for (qw(transdatefrom transdateto)) {
864 next unless $form->{$_};
865 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
866 push @bind_vars, $form->{$_};
870 if ($form->{"partsgroup_id"}) {
871 $form->{"l_partsgroup"} = '1'; # show the column
872 push @where_tokens, "pg.id = ?";
873 push @bind_vars, $form->{"partsgroup_id"};
876 foreach (@like_filters) {
877 next unless $form->{$_};
878 $form->{"l_$_"} = '1'; # show the column
879 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
880 push @bind_vars, "%$form->{$_}%";
883 foreach (@simple_l_switches) {
884 next unless $form->{"l_$_"};
885 push @select_tokens, $_;
888 for ($form->{searchitems}) {
889 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
890 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
891 push @where_tokens, 'NOT p.assembly' if /service/;
892 push @where_tokens, ' p.assembly' if /assembly/;
895 for ($form->{itemstatus}) {
896 push @where_tokens, 'p.id NOT IN
897 (SELECT DISTINCT parts_id FROM invoice UNION
898 SELECT DISTINCT parts_id FROM assembly UNION
899 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
900 push @where_tokens, 'p.onhand = 0' if /orphaned/;
901 push @where_tokens, 'NOT p.obsolete' if /active/;
902 push @where_tokens, ' p.obsolete', if /obsolete/;
903 push @where_tokens, 'p.onhand > 0', if /onhand/;
904 push @where_tokens, 'p.onhand < p.rop', if /short/;
907 my $q_assembly_lastcost =
908 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
910 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
911 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
912 WHERE (a_lc.id = p.id)) AS lastcost|;
913 $table_prefix{$q_assembly_lastcost} = ' ';
915 # special case makemodel search
916 # all_parts is based upon the assumption that every parameter is named like the column it represents
917 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
918 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
920 push @where_tokens, 'mv.name ILIKE ?';
921 push @bind_vars, "%$form->{make}%";
923 if ($form->{model}) {
924 push @where_tokens, 'mm.model ILIKE ?';
925 push @bind_vars, "%$form->{model}%";
928 # special case: sorting by partnumber
929 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
930 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
931 # ToDO: implement proper functional sorting
932 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
933 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
934 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
935 # if $form->{sort} eq 'partnumber';
937 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
940 $limit_clause = " LIMIT 100" if $form->{top100};
941 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
943 #=== joins and complicated filters ========#
945 my $bsooqr = any { $form->{$_} } @oe_flags;
946 my @bsooqr_tokens = ();
948 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
949 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
950 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
951 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
952 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
953 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
954 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
955 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
956 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
957 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
959 $joins_needed{partsgroup} = 1;
960 $joins_needed{pfac} = 1;
961 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
962 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
963 $joins_needed{mv} = 1 if $joins_needed{makemodel};
964 $joins_needed{cv} = 1 if $bsooqr;
965 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
966 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
968 # special case for description search.
969 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
970 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
971 # find the old entries in of @where_tokens and @bind_vars, and adjust them
972 if ($joins_needed{invoice_oi}) {
973 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
974 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
975 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
976 splice @bind_vars, $bi, 0, $bind_vars[$bi];
981 # now the master trick: soldtotal.
982 if ($form->{l_soldtotal}) {
983 push @where_tokens, 'NOT ioi.qty = 0';
984 push @group_tokens, @select_tokens;
985 map { s/.*\sAS\s+//si } @group_tokens;
986 push @select_tokens, 'SUM(ioi.qty)';
989 #============= build query ================#
991 my $token_builder = $make_token_builder->(\%joins_needed);
993 my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
994 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
995 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
996 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
998 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
999 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
1000 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
1001 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
1003 my %oe_flag_to_cvar = (
1004 bought => 'invoice',
1006 onorder => 'orderitems',
1007 ordered => 'orderitems',
1008 rfq => 'orderitems',
1009 quoted => 'orderitems',
1012 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
1014 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1016 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1020 $where_clause .= qq| AND ($cvar_where)|;
1021 push @bind_vars, @cvar_values;
1024 my $query = <<" SQL";
1025 SELECT DISTINCT $select_clause
1034 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1036 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1038 # fix qty sign in ap. those are saved negative
1039 if ($bsooqr && $form->{bought}) {
1040 for my $row (@{ $form->{parts} }) {
1041 $row->{qty} *= -1 if $row->{module} eq 'ir';
1045 # post processing for assembly parts lists (bom)
1046 # for each part get the assembly parts and add them into the partlist.
1048 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1050 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1051 p.unit, p.bin, p.notes,
1052 p.sellprice, p.listprice, p.lastcost,
1053 p.rop, p.weight, p.priceupdate,
1054 p.image, p.drawing, p.microfiche,
1057 INNER JOIN assembly a ON (p.id = a.parts_id)
1060 my $sth = prepare_query($form, $dbh, $query);
1062 foreach my $item (@{ $form->{parts} }) {
1063 push(@assemblies, $item);
1064 do_statement($form, $sth, $query, conv_i($item->{id}));
1066 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1067 $ref->{assemblyitem} = 1;
1068 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1069 push(@assemblies, $ref);
1074 # copy assemblies to $form->{parts}
1075 $form->{parts} = \@assemblies;
1078 if ($form->{l_pricegroups} ) {
1080 SELECT parts_id, price, pricegroup_id
1085 my $sth = prepare_query($form, $dbh, $query);
1087 foreach my $part (@{ $form->{parts} }) {
1088 do_statement($form, $sth, $query, conv_i($part->{id}));
1090 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1091 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1098 $main::lxdebug->leave_sub();
1100 return wantarray ? @{ $form->{parts} } : $form->{parts};
1103 sub _create_filter_for_priceupdate {
1104 $main::lxdebug->enter_sub();
1107 my $myconfig = \%main::myconfig;
1108 my $form = $main::form;
1111 my $where = '1 = 1';
1113 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1115 $column =~ s/.*\.//;
1116 next unless ($form->{$column});
1118 $where .= qq| AND $item ILIKE ?|;
1119 push(@where_values, '%' . $form->{$column} . '%');
1122 foreach my $item (qw(description serialnumber)) {
1123 next unless ($form->{$item});
1125 $where .= qq| AND (${item} ILIKE ?)|;
1126 push(@where_values, '%' . $form->{$item} . '%');
1130 # items which were never bought, sold or on an order
1131 if ($form->{itemstatus} eq 'orphaned') {
1133 qq| AND (p.onhand = 0)
1136 SELECT DISTINCT parts_id FROM invoice
1138 SELECT DISTINCT parts_id FROM assembly
1140 SELECT DISTINCT parts_id FROM orderitems
1143 } elsif ($form->{itemstatus} eq 'active') {
1144 $where .= qq| AND p.obsolete = '0'|;
1146 } elsif ($form->{itemstatus} eq 'obsolete') {
1147 $where .= qq| AND p.obsolete = '1'|;
1149 } elsif ($form->{itemstatus} eq 'onhand') {
1150 $where .= qq| AND p.onhand > 0|;
1152 } elsif ($form->{itemstatus} eq 'short') {
1153 $where .= qq| AND p.onhand < p.rop|;
1157 foreach my $column (qw(make model)) {
1158 next unless ($form->{$column});
1159 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1160 push(@where_values, '%' . $form->{$column} . '%');
1163 $main::lxdebug->leave_sub();
1165 return ($where, @where_values);
1168 sub get_num_matches_for_priceupdate {
1169 $main::lxdebug->enter_sub();
1173 my $myconfig = \%main::myconfig;
1174 my $form = $main::form;
1176 my $dbh = $form->get_standard_dbh($myconfig);
1178 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1180 my $num_updated = 0;
1183 for my $column (qw(sellprice listprice)) {
1184 next if ($form->{$column} eq "");
1192 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1194 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1195 $num_updated += $result if (0 <= $result);
1204 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1205 WHERE $where) AND (pricegroup_id = ?)|;
1206 my $sth = prepare_query($form, $dbh, $query);
1208 for my $i (1 .. $form->{price_rows}) {
1209 next if ($form->{"price_$i"} eq "");
1211 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1212 $num_updated += $result if (0 <= $result);
1216 $main::lxdebug->leave_sub();
1218 return $num_updated;
1222 $main::lxdebug->enter_sub();
1224 my ($self, $myconfig, $form) = @_;
1226 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1227 my $num_updated = 0;
1229 # connect to database
1230 my $dbh = $form->dbconnect_noauto($myconfig);
1232 for my $column (qw(sellprice listprice)) {
1233 next if ($form->{$column} eq "");
1235 my $value = $form->parse_amount($myconfig, $form->{$column});
1238 if ($form->{"${column}_type"} eq "percent") {
1239 $value = ($value / 100) + 1;
1244 qq|UPDATE parts SET $column = $column $operator ?
1248 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1250 my $result = do_query($form, $dbh, $query, $value, @where_values);
1251 $num_updated += $result if (0 <= $result);
1255 qq|UPDATE prices SET price = price + ?
1259 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1260 WHERE $where) AND (pricegroup_id = ?)|;
1261 my $sth_add = prepare_query($form, $dbh, $q_add);
1264 qq|UPDATE prices SET price = price * ?
1268 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1269 WHERE $where) AND (pricegroup_id = ?)|;
1270 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1272 for my $i (1 .. $form->{price_rows}) {
1273 next if ($form->{"price_$i"} eq "");
1275 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1278 if ($form->{"pricegroup_type_$i"} eq "percent") {
1279 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1281 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1284 $num_updated += $result if (0 <= $result);
1288 $sth_multiply->finish();
1290 my $rc= $dbh->commit;
1293 $main::lxdebug->leave_sub();
1295 return $num_updated;
1299 $main::lxdebug->enter_sub();
1301 my ($self, $module, $myconfig, $form) = @_;
1303 # connect to database
1304 my $dbh = $form->dbconnect($myconfig);
1306 my @values = ('%' . $module . '%');
1311 qq|SELECT c.accno, c.description, c.link, c.id,
1312 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1313 FROM chart c, parts p
1314 WHERE (c.link LIKE ?) AND (p.id = ?)
1316 push(@values, conv_i($form->{id}));
1320 qq|SELECT c.accno, c.description, c.link, c.id,
1321 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1322 FROM chart c, defaults d
1327 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1328 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1329 foreach my $key (split(/:/, $ref->{link})) {
1330 if ($key =~ /\Q$module\E/) {
1331 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1332 || ($ref->{id} eq $ref->{income_accno_id})
1333 || ($ref->{id} eq $ref->{expense_accno_id})) {
1334 push @{ $form->{"${module}_links"}{$key} },
1335 { accno => $ref->{accno},
1336 description => $ref->{description},
1337 selected => "selected" };
1338 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1340 push @{ $form->{"${module}_links"}{$key} },
1341 { accno => $ref->{accno},
1342 description => $ref->{description},
1350 # get buchungsgruppen
1351 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1354 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1357 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1361 $main::lxdebug->leave_sub();
1364 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1366 $main::lxdebug->enter_sub();
1368 my ($self, $myconfig, $form, $sortorder) = @_;
1369 my $dbh = $form->dbconnect($myconfig);
1370 my $order = qq| p.partnumber|;
1371 my $where = qq|1 = 1|;
1374 if ($sortorder eq "all") {
1375 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1376 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1378 } elsif ($sortorder eq "partnumber") {
1379 $where .= qq| AND (partnumber ILIKE ?)|;
1380 push(@values, '%' . $form->{partnumber} . '%');
1382 } elsif ($sortorder eq "description") {
1383 $where .= qq| AND (description ILIKE ?)|;
1384 push(@values, '%' . $form->{description} . '%');
1385 $order = "description";
1390 qq|SELECT id, partnumber, description, unit, sellprice
1392 WHERE $where ORDER BY $order|;
1394 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1397 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1398 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1403 $form->{"id_$j"} = $ref->{id};
1404 $form->{"partnumber_$j"} = $ref->{partnumber};
1405 $form->{"description_$j"} = $ref->{description};
1406 $form->{"unit_$j"} = $ref->{unit};
1407 $form->{"sellprice_$j"} = $ref->{sellprice};
1408 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1414 $main::lxdebug->leave_sub();
1419 # gets sum of sold part with part_id
1421 $main::lxdebug->enter_sub();
1423 my ($dbh, $id) = @_;
1425 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1426 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1429 $main::lxdebug->leave_sub();
1432 } #end get_soldtotal
1434 sub retrieve_languages {
1435 $main::lxdebug->enter_sub();
1437 my ($self, $myconfig, $form) = @_;
1439 # connect to database
1440 my $dbh = $form->dbconnect($myconfig);
1446 if ($form->{language_values} ne "") {
1448 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1450 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1451 ORDER BY lower(l.description)|;
1452 @values = (conv_i($form->{id}));
1455 $query = qq|SELECT id, description
1457 ORDER BY lower(description)|;
1460 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1464 $main::lxdebug->leave_sub();
1469 sub follow_account_chain {
1470 $main::lxdebug->enter_sub(2);
1472 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1474 my @visited_accno_ids = ($accno_id);
1478 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1479 map { $_->{id} => $_ }
1480 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1481 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1483 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1484 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1488 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1489 last unless ($ref && $ref->{"is_valid"} &&
1490 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1491 $accno_id = $ref->{"new_chart_id"};
1492 $accno = $ref->{"accno"};
1493 push(@visited_accno_ids, $accno_id);
1496 $main::lxdebug->leave_sub(2);
1498 return ($accno_id, $accno);
1501 sub retrieve_accounts {
1502 $main::lxdebug->enter_sub;
1505 my $myconfig = shift;
1507 my $dbh = $form->get_standard_dbh;
1508 my %args = @_; # index => part_id
1510 $form->{taxzone_id} *= 1;
1512 return unless grep $_, values %args; # shortfuse if no part_id supplied
1514 # transdate madness.
1516 if ($form->{type} eq "invoice") {
1517 if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1518 $transdate = $form->{invdate};
1520 $transdate = $form->{deliverydate};
1522 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
1523 # if credit_note has a deliverydate, use this instead of invdate
1524 # useful for credit_notes of invoices from an old period with different tax
1525 # if there is no deliverydate then invdate is used, old default (see next elsif)
1526 $transdate = $form->{deliverydate};
1527 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1528 $transdate = $form->{invdate};
1530 $transdate = $form->{transdate};
1533 if ($transdate eq "") {
1534 $transdate = DateTime->today_local->to_lxoffice;
1536 $transdate = $dbh->quote($transdate);
1539 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1541 my @part_ids = grep { $_ } values %args;
1542 my $in = join ',', ('?') x @part_ids;
1544 my %accno_by_part = map { $_->{id} => $_ }
1545 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1547 p.id, p.inventory_accno_id AS is_part,
1548 bg.inventory_accno_id,
1549 bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
1550 bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
1551 c1.accno AS inventory_accno,
1552 c2.accno AS income_accno,
1553 c3.accno AS expense_accno
1555 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1556 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1557 LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
1558 LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
1562 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1563 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1565 LEFT JOIN chart c ON c.id = t.chart_id
1569 WHERE tk.chart_id = ? AND startdate <= ?
1570 ORDER BY startdate DESC LIMIT 1)
1573 while (my ($index => $part_id) = each %args) {
1574 my $ref = $accno_by_part{$part_id} or next;
1576 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1579 for my $type (qw(inventory income expense)) {
1580 next unless $ref->{"${type}_accno_id"};
1581 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1582 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1585 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1587 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1588 $ref = $sth_tax->fetchrow_hashref or next;
1590 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1591 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1593 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1598 $::lxdebug->leave_sub;
1601 sub get_basic_part_info {
1602 $main::lxdebug->enter_sub();
1607 Common::check_params(\%params, qw(id));
1609 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1612 $main::lxdebug->leave_sub();
1616 my $myconfig = \%main::myconfig;
1617 my $form = $main::form;
1619 my $dbh = $form->get_standard_dbh($myconfig);
1621 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1623 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1625 if ('' eq ref $params{id}) {
1626 $info = $info->[0] || { };
1628 $main::lxdebug->leave_sub();
1632 my %info_map = map { $_->{id} => $_ } @{ $info };
1634 $main::lxdebug->leave_sub();
1639 sub prepare_parts_for_printing {
1640 $main::lxdebug->enter_sub();
1645 my $myconfig = \%main::myconfig;
1646 my $form = $main::form;
1648 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1650 my $prefix = $params{prefix} || 'id_';
1651 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1653 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1656 $main::lxdebug->leave_sub();
1660 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1661 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1663 LEFT JOIN vendor v ON (mm.make = v.id)
1664 WHERE mm.parts_id IN ($placeholders)|;
1668 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1670 while (my $ref = $sth->fetchrow_hashref()) {
1671 $makemodel{$ref->{parts_id}} ||= [];
1672 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1677 my @columns = qw(ean image microfiche drawing weight);
1679 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1681 WHERE id IN ($placeholders)|;
1683 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1685 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1687 foreach my $i (1 .. $rowcount) {
1688 my $id = $form->{"${prefix}${i}"};
1692 foreach (@columns) {
1693 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1696 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1697 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1699 next if (!$makemodel{$id});
1701 foreach my $ref (@{ $makemodel{$id} }) {
1702 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1706 $main::lxdebug->leave_sub();