1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
31 # Inventory Control backend
33 #======================================================================
38 use List::MoreUtils qw(all any uniq);
47 $main::lxdebug->enter_sub();
49 my ($self, $myconfig, $form) = @_;
52 my $dbh = $form->dbconnect($myconfig);
58 c1.accno AS inventory_accno,
59 c2.accno AS income_accno,
60 c3.accno AS expense_accno,
63 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
64 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
65 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
66 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
68 my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
70 # copy to $form variables
71 map { $form->{$_} = $ref->{$_} } (keys %{$ref});
75 # part or service item
76 $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
77 if ($form->{assembly}) {
78 $form->{item} = 'assembly';
80 # retrieve assembly items
82 qq|SELECT p.id, p.partnumber, p.description,
83 p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
84 pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
86 JOIN assembly a ON (a.parts_id = p.id)
87 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
88 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
91 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
93 $form->{assembly_rows} = 0;
94 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
95 $form->{assembly_rows}++;
96 foreach my $key (keys %{$ref}) {
97 $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
104 # setup accno hash for <option checked> {amount} is used in create_links
105 $form->{amount}{IC} = $form->{inventory_accno};
106 $form->{amount}{IC_income} = $form->{income_accno};
107 $form->{amount}{IC_sale} = $form->{income_accno};
108 $form->{amount}{IC_expense} = $form->{expense_accno};
109 $form->{amount}{IC_cogs} = $form->{expense_accno};
111 my @pricegroups = ();
112 my @pricegroups_not_used = ();
116 qq|SELECT p.parts_id, p.pricegroup_id, p.price,
117 (SELECT pg.pricegroup
119 WHERE pg.id = p.pricegroup_id) AS pricegroup
122 ORDER BY pricegroup|;
123 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
127 while (($form->{"klass_$i"}, $form->{"pricegroup_id_$i"},
128 $form->{"price_$i"}, $form->{"pricegroup_$i"})
129 = $sth->fetchrow_array()) {
130 push @pricegroups, $form->{"pricegroup_id_$i"};
137 $query = qq|SELECT id, pricegroup FROM pricegroup|;
138 $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
140 #find not used pricegroups
141 while (my $tmp = pop(@{ $form->{PRICEGROUPS} })) {
143 foreach my $item (@pricegroups) {
144 if ($item eq $tmp->{id}) {
149 push(@pricegroups_not_used, $tmp) unless ($in_use);
152 # if not used pricegroups are avaible
153 if (@pricegroups_not_used) {
155 foreach my $name (@pricegroups_not_used) {
156 $form->{"klass_$i"} = "$name->{id}";
157 $form->{"pricegroup_id_$i"} = "$name->{id}";
158 $form->{"pricegroup_$i"} = "$name->{pricegroup}";
164 $form->{price_rows} = $i - 1;
166 unless ($form->{item} eq 'service') {
169 if ($form->{makemodel}) {
171 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
172 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
173 my @values = ($form->{id});
174 $sth = $dbh->prepare($query);
175 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
179 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
180 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
185 $form->{makemodel_rows} = $i - 1;
191 $form->{language_values} = "";
192 $query = qq|SELECT language_id, translation, longdescription
195 my $trq = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
196 while (my $tr = $trq->fetchrow_hashref("NAME_lc")) {
197 $form->{language_values} .= "---+++---" . join('--++--', @{$tr}{qw(language_id translation longdescription)});
201 # now get accno for taxes
204 FROM chart c, partstax pt
205 WHERE (pt.chart_id = c.id) AND (pt.parts_id = ?)|;
206 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
207 while (my ($key) = $sth->fetchrow_array) {
208 $form->{amount}{$key} = $key;
214 my @referencing_tables = qw(invoice orderitems inventory rmaitems);
215 my %column_map = ( );
216 my $parts_id = conv_i($form->{id});
218 $form->{orphaned} = 1;
220 foreach my $table (@referencing_tables) {
221 my $column = $column_map{$table} || 'parts_id';
222 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
223 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
226 $form->{orphaned} = 0;
231 $form->{"unit_changeable"} = $form->{orphaned};
235 $main::lxdebug->leave_sub();
238 sub get_pricegroups {
239 $main::lxdebug->enter_sub();
241 my ($self, $myconfig, $form) = @_;
243 my $dbh = $form->dbconnect($myconfig);
246 my $query = qq|SELECT id, pricegroup FROM pricegroup|;
247 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
250 foreach my $pg (@{ $pricegroups }) {
251 $form->{"klass_$i"} = "$pg->{id}";
252 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
253 $form->{"pricegroup_id_$i"} = "$pg->{id}";
254 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
259 $form->{price_rows} = $i - 1;
263 $main::lxdebug->leave_sub();
268 sub retrieve_buchungsgruppen {
269 $main::lxdebug->enter_sub();
271 my ($self, $myconfig, $form) = @_;
275 my $dbh = $form->dbconnect($myconfig);
277 # get buchungsgruppen
278 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
279 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
281 $main::lxdebug->leave_sub();
285 $main::lxdebug->enter_sub();
287 my ($self, $myconfig, $form) = @_;
289 # connect to database, turn off AutoCommit
290 my $dbh = $form->dbconnect_noauto($myconfig);
293 # make up a unique handle and store in partnumber field
294 # then retrieve the record based on the unique handle to get the id
295 # replace the partnumber field with the actual variable
296 # add records for makemodel
298 # if there is a $form->{id} then replace the old entry
299 # delete all makemodel entries and add the new ones
301 # undo amount formatting
302 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
303 qw(rop weight listprice sellprice gv lastcost);
305 my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
307 $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
311 my $priceupdate = ', priceupdate = current_date';
316 $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
317 my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
319 # if item is part of an assembly adjust all assemblies
320 $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
321 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
322 while (my ($id, $qty) = $sth->fetchrow_array) {
323 &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
327 if ($form->{item} ne 'service') {
328 # delete makemodel records
329 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
332 if ($form->{item} eq 'assembly') {
333 # delete assembly records
334 do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
338 do_query($form, $dbh, qq|DELETE FROM partstax WHERE parts_id = ?|, conv_i($form->{id}));
340 # delete translations
341 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
343 # Check whether or not the prices have changed. If they haven't
344 # then 'priceupdate' should not be updated.
345 my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
346 $priceupdate = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
349 my ($count) = selectrow_query($form, $dbh, qq|SELECT COUNT(*) FROM parts WHERE partnumber = ?|, $form->{partnumber});
351 $main::lxdebug->leave_sub();
355 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
356 do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, '', '')|, $form->{id});
358 $form->{orphaned} = 1;
359 if ($form->{partnumber} eq "" && $form->{"item"} eq "service") {
360 $form->{partnumber} = $form->update_defaults($myconfig, "servicenumber");
362 if ($form->{partnumber} eq "" && $form->{"item"} ne "service") {
363 $form->{partnumber} = $form->update_defaults($myconfig, "articlenumber");
367 my $partsgroup_id = 0;
369 if ($form->{partsgroup}) {
370 (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
373 my ($subq_inventory, $subq_expense, $subq_income);
374 if ($form->{"item"} eq "part") {
376 qq|(SELECT bg.inventory_accno_id
377 FROM buchungsgruppen bg
378 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
380 $subq_inventory = "NULL";
383 if ($form->{"item"} ne "assembly") {
385 qq|(SELECT bg.expense_accno_id_0
386 FROM buchungsgruppen bg
387 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
389 $subq_expense = "NULL";
408 buchungsgruppen_id = ?,
410 inventory_accno_id = $subq_inventory,
411 income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
412 expense_accno_id = $subq_expense,
421 not_discountable = ?,
427 @values = ($form->{partnumber},
428 $form->{description},
429 $makemodel ? 't' : 'f',
430 $form->{assembly} ? 't' : 'f',
440 conv_i($form->{buchungsgruppen_id}),
441 conv_i($form->{payment_id}),
442 conv_i($form->{buchungsgruppen_id}),
443 $form->{obsolete} ? 't' : 'f',
446 $form->{shop} ? 't' : 'f',
450 $form->{has_sernumber} ? 't' : 'f',
451 $form->{not_discountable} ? 't' : 'f',
453 conv_i($partsgroup_id),
454 conv_i($form->{price_factor_id}),
457 do_query($form, $dbh, $query, @values);
459 # delete translation records
460 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
462 if ($form->{language_values} ne "") {
463 foreach my $item (split(/---\+\+\+---/, $form->{language_values})) {
464 my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
465 if ($translation ne "") {
466 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
467 VALUES ( ?, ?, ?, ? )|;
468 @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
469 do_query($form, $dbh, $query, @values);
474 # delete price records
475 do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
477 # insert price records only if different to sellprice
478 for my $i (1 .. $form->{price_rows}) {
479 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
481 $form->{"price_$i"} = $form->{sellprice};
485 || $form->{"klass_$i"}
486 || $form->{"pricegroup_id_$i"})
487 and $price != $form->{sellprice}
489 #$klass = $form->parse_amount($myconfig, $form->{"klass_$i"});
490 $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) | .
492 @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
493 do_query($form, $dbh, $query, @values);
497 # insert makemodel records
498 unless ($form->{item} eq 'service') {
501 for my $i (1 .. $form->{makemodel_rows}) {
502 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
504 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
505 if ($value == $form->{"old_lastcost_$i"})
507 $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);
521 foreach my $item (split(/ /, $form->{taxaccounts})) {
522 if ($form->{"IC_tax_$item"}) {
524 qq|INSERT INTO partstax (parts_id, chart_id)
525 VALUES (?, (SELECT id FROM chart WHERE accno = ?))|;
526 @values = (conv_i($form->{id}), $item);
527 do_query($form, $dbh, $query, @values);
531 # add assembly records
532 if ($form->{item} eq 'assembly') {
534 for my $i (1 .. $form->{assembly_rows}) {
535 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
537 if ($form->{"qty_$i"} != 0) {
538 $form->{"bom_$i"} *= 1;
539 $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
540 qq|VALUES (?, ?, ?, ?)|;
541 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
542 do_query($form, $dbh, $query, @values);
549 my $shippingdate = "$a[5]-$a[4]-$a[3]";
551 $form->get_employee($dbh);
555 #set expense_accno=inventory_accno if they are different => bilanz
557 ($form->{expense_accno} != $form->{inventory_accno})
558 ? $form->{inventory_accno}
559 : $form->{expense_accno};
561 # get tax rates and description
563 ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
565 qq|SELECT c.accno, c.description, t.rate, t.taxnumber
567 WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
569 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
571 $form->{taxaccount} = "";
572 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
573 $form->{taxaccount} .= "$ptr->{accno} ";
574 if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
575 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
576 $form->{"$ptr->{accno}_description"} = $ptr->{description};
577 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
578 $form->{taxaccount2} .= " $ptr->{accno} ";
582 CVar->save_custom_variables('dbh' => $dbh,
584 'trans_id' => $form->{id},
585 'variables' => $form);
588 my $rc = $dbh->commit;
591 $main::lxdebug->leave_sub();
596 sub update_assembly {
597 $main::lxdebug->enter_sub();
599 my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
601 my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
602 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
604 while (my ($pid, $aqty) = $sth->fetchrow_array) {
605 &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
610 qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
612 my @values = ($qty * ($form->{sellprice} - $sellprice),
613 $qty * ($form->{weight} - $weight), conv_i($id));
614 do_query($form, $dbh, $query, @values);
616 $main::lxdebug->leave_sub();
619 sub retrieve_assemblies {
620 $main::lxdebug->enter_sub();
622 my ($self, $myconfig, $form) = @_;
624 # connect to database
625 my $dbh = $form->dbconnect($myconfig);
627 my $where = qq|NOT p.obsolete|;
630 if ($form->{partnumber}) {
631 $where .= qq| AND (p.partnumber ILIKE ?)|;
632 push(@values, '%' . $form->{partnumber} . '%');
635 if ($form->{description}) {
636 $where .= qq| AND (p.description ILIKE ?)|;
637 push(@values, '%' . $form->{description} . '%');
640 # retrieve assembly items
642 qq|SELECT p.id, p.partnumber, p.description,
643 p.bin, p.onhand, p.rop,
644 (SELECT sum(p2.inventory_accno_id)
645 FROM parts p2, assembly a
646 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
648 WHERE NOT p.obsolete AND p.assembly $where|;
650 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
654 $main::lxdebug->leave_sub();
658 $main::lxdebug->enter_sub();
660 my ($self, $myconfig, $form) = @_;
661 my @values = (conv_i($form->{id}));
662 # connect to database, turn off AutoCommit
663 my $dbh = $form->dbconnect_noauto($myconfig);
665 my %columns = ( "assembly" => "id", "parts" => "id" );
667 for my $table (qw(prices partstax makemodel inventory assembly license translation parts)) {
668 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
669 do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
673 my $rc = $dbh->commit;
676 $main::lxdebug->leave_sub();
682 $main::lxdebug->enter_sub();
684 my ($self, $myconfig, $form) = @_;
686 my $i = $form->{assembly_rows};
688 my $where = qq|1 = 1|;
691 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
693 while (my ($column, $table) = each(%columns)) {
694 next unless ($form->{"${column}_$i"});
695 $where .= qq| AND ${table}.${column} ILIKE ?|;
696 push(@values, '%' . $form->{"${column}_$i"} . '%');
700 $where .= qq| AND NOT (p.id = ?)|;
701 push(@values, conv_i($form->{id}));
704 if ($form->{partnumber}) {
705 $where .= qq| ORDER BY p.partnumber|;
707 $where .= qq| ORDER BY p.description|;
710 # connect to database
711 my $dbh = $form->dbconnect($myconfig);
714 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
715 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
716 p.price_factor_id, pfac.factor AS price_factor
718 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
719 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
721 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
725 $main::lxdebug->leave_sub();
730 # Warning, deep magic ahead.
731 # This function gets all parts from the database according to the filters specified
734 # sort revers - sorting field + direction
737 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
738 # partnumber ean description partsgroup microfiche drawing
741 # 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
744 # itemstatus = active | onhand | short | obsolete | orphaned
745 # searchitems = part | assembly | service
748 # make model - makemodel
749 # serialnumber transdatefrom transdateto - invoice/orderitems
752 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
753 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
754 # l_soldtotal - aggreg join to display total of sold quantity
755 # onhand - as above, but masking the simple itemstatus results (doh!)
756 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
757 # l_serialnumber - belonges to serialnumber filter
758 # l_deliverydate - displays deliverydate is sold etc. flags are active
759 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
762 # onhand - as above, but masking the simple itemstatus results (doh!)
764 # search by overrides of description
766 # disabled sanity checks and changes:
767 # - searchitems = assembly will no longer disable bought
768 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
769 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
770 # - itemstatus = obsolete will no longer disable onhand, short
771 # - allow sorting by ean
772 # - serialnumber filter also works if l_serialnumber isn't ticked
773 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
776 $main::lxdebug->enter_sub();
778 my ($self, $myconfig, $form) = @_;
779 my $dbh = $form->get_standard_dbh($myconfig);
781 $form->{parts} = +{ };
782 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
784 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
785 my @makemodel_filters = qw(make model);
786 my @invoice_oi_filters = qw(serialnumber soldtotal);
787 my @apoe_filters = qw(transdate);
788 my @like_filters = (@simple_filters, @makemodel_filters, @invoice_oi_filters);
789 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, qw(serialnumber));
790 my @simple_l_switches = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
791 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
792 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
793 my @deliverydate_flags = qw(deliverydate);
794 # my @other_flags = qw(onhand); # ToDO: implement these
795 # my @inactive_flags = qw(l_subtotal short l_linetotal);
797 my @select_tokens = qw(id factor);
798 my @where_tokens = qw(1=1);
799 my @group_tokens = ();
801 my %joins_needed = ();
804 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
805 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
806 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
809 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, id FROM invoice UNION
810 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, id FROM orderitems
811 ) AS ioi ON ioi.parts_id = p.id|,
814 SELECT id, transdate, 'ir' AS module, ordnumber, quonumber, invnumber, FALSE AS quotation, NULL AS customer_id, vendor_id, NULL AS deliverydate, 'invoice' AS ioi FROM ap UNION
815 SELECT id, transdate, 'is' AS module, ordnumber, quonumber, invnumber, FALSE AS quotation, customer_id, NULL AS vendor_id, deliverydate, 'invoice' AS ioi FROM ar UNION
816 SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber, quotation, customer_id, vendor_id, reqdate AS deliverydate, 'orderitems' AS ioi FROM oe
817 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
820 SELECT id, name, 'customer' AS cv FROM customer UNION
821 SELECT id, name, 'vendor' AS cv FROM vendor
822 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
824 my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac);
827 deliverydate => 'apoe.', serialnumber => 'ioi.',
828 transdate => 'apoe.', trans_id => 'ioi.',
829 module => 'apoe.', name => 'cv.',
830 ordnumber => 'apoe.', make => 'mm.',
831 quonumber => 'apoe.', model => 'mm.',
832 invnumber => 'apoe.', partsgroup => 'pg.',
833 lastcost => 'p.', , soldtotal => ' ',
835 'SUM(ioi.qty)' => ' ',
838 serialnumber => 'ioi.',
839 quotation => 'apoe.',
845 # if the join condition in these blocks are met, the column
846 # of the scecified table will gently override (coalesce actually) the original value
847 # use it to conditionally coalesce values from subtables
848 my @column_override = (
849 # column name, prefix, joins_needed
850 [ 'description', 'ioi.', 'invoice_oi' ],
851 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
852 [ 'transdate', 'apoe.', 'apoe' ],
853 [ 'unit', 'ioi.', 'invoice_oi' ],
854 [ 'sellprice', 'ioi.', 'invoice_oi' ],
857 # careful with renames. these are HARD, and any filters done on the original column will break
858 my %renamed_columns = (
859 'factor' => 'price_factor',
860 'SUM(ioi.qty)' => 'soldtotal',
861 'ioi.id' => 'ioi_id',
865 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
866 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
869 my $make_token_builder = sub {
870 my $joins_needed = shift;
872 my ($col, $alias) = @_;
873 my @coalesce_tokens =
874 map { ($_->[1] || 'p.') . $_->[0] }
875 grep { !$_->[2] || $joins_needed->{$_->[2]} }
876 grep { $_->[0] eq $col }
877 @column_override, [ $col, $table_prefix{$col} ];
879 my $coalesce = scalar @coalesce_tokens > 1;
881 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
882 : shift @coalesce_tokens)
883 . ($alias && ($coalesce || $renamed_columns{$col})
884 ? " AS " . ($renamed_columns{$col} || $col)
889 #===== switches and simple filters ========#
891 # special case transdate
892 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
893 $form->{"l_transdate"} = 1;
894 push @select_tokens, 'transdate';
895 for (qw(transdatefrom transdateto)) {
896 next unless $form->{$_};
897 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
898 push @bind_vars, $form->{$_};
902 foreach (@like_filters) {
903 next unless $form->{$_};
904 $form->{"l_$_"} = '1'; # show the column
905 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
906 push @bind_vars, "%$form->{$_}%";
909 foreach (@simple_l_switches) {
910 next unless $form->{"l_$_"};
911 push @select_tokens, $_;
914 for ($form->{searchitems}) {
915 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
916 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
917 push @where_tokens, 'NOT p.assembly' if /service/;
918 push @where_tokens, ' p.assembly' if /assembly/;
921 for ($form->{itemstatus}) {
922 push @where_tokens, 'p.id NOT IN
923 (SELECT DISTINCT parts_id FROM invoice UNION
924 SELECT DISTINCT parts_id FROM assembly UNION
925 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
926 push @where_tokens, 'p.onhand = 0' if /orphaned/;
927 push @where_tokens, 'NOT p.obsolete' if /active/;
928 push @where_tokens, ' p.obsolete', if /obsolete/;
929 push @where_tokens, 'p.onhand > 0', if /onhand/;
930 push @where_tokens, 'p.onhand < p.rop', if /short/;
933 my $q_assembly_lastcost =
934 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
936 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
937 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
938 WHERE (a_lc.id = p.id)) AS lastcost|;
939 $table_prefix{$q_assembly_lastcost} = ' ';
941 # special case: sorting by partnumber
942 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
943 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
944 # ToDO: implement proper functional sorting
945 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
946 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
947 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
948 # if $form->{sort} eq 'partnumber';
950 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
953 $limit_clause = " LIMIT 100" if $form->{top100};
954 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
956 #=== joins and complicated filters ========#
958 my $bsooqr = any { $form->{$_} } @oe_flags;
959 my @bsooqr_tokens = ();
961 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
962 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
963 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
964 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
965 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
966 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
967 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
968 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
969 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
970 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
972 $joins_needed{partsgroup} = 1;
973 $joins_needed{pfac} = 1;
974 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
975 $joins_needed{cv} = 1 if $bsooqr;
976 $joins_needed{apoe} = 1 if $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
977 $joins_needed{invoice_oi} = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
979 # in bsoorq, use qtys instead of onhand
980 if ($joins_needed{invoice_oi}) {
981 $renamed_columns{onhand} = 'onhand_before_bsooqr';
982 $renamed_columns{qty} = 'onhand';
985 # special case for description search.
986 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
987 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
988 # find the old entries in of @where_tokens and @bind_vars, and adjust them
989 if ($joins_needed{invoice_oi}) {
990 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
991 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
992 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
993 splice @bind_vars, $bi, 0, $bind_vars[$bi];
998 # now the master trick: soldtotal.
999 if ($form->{l_soldtotal}) {
1000 push @where_tokens, 'NOT ioi.qty = 0';
1001 push @group_tokens, @select_tokens;
1002 map { s/.*\sAS\s+//si } @group_tokens;
1003 push @select_tokens, 'SUM(ioi.qty)';
1006 #============= build query ================#
1008 my $token_builder = $make_token_builder->(\%joins_needed);
1010 my @sort_cols = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
1011 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
1012 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
1013 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
1015 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
1016 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
1017 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
1018 my $group_clause = ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens if scalar @group_tokens;
1020 my %oe_flag_to_cvar = (
1021 bought => 'invoice',
1023 onorder => 'orderitems',
1024 ordered => 'orderitems',
1025 rfq => 'orderitems',
1026 quoted => 'orderitems',
1029 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
1031 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1033 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1037 $where_clause .= qq| AND ($cvar_where)|;
1038 push @bind_vars, @cvar_values;
1041 my $query = <<" SQL";
1042 SELECT DISTINCT $select_clause
1051 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1053 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1055 # post processing for assembly parts lists (bom)
1056 # for each part get the assembly parts and add them into the partlist.
1058 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1060 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1062 p.sellprice, p.listprice, p.lastcost,
1063 p.rop, p.weight, p.priceupdate,
1064 p.image, p.drawing, p.microfiche,
1067 INNER JOIN assembly a ON (p.id = a.parts_id)
1070 my $sth = prepare_query($form, $dbh, $query);
1072 foreach my $item (@{ $form->{parts} }) {
1073 push(@assemblies, $item);
1074 do_statement($form, $sth, $query, conv_i($item->{id}));
1076 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1077 $ref->{assemblyitem} = 1;
1078 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1079 push(@assemblies, $ref);
1084 # copy assemblies to $form->{parts}
1085 $form->{parts} = \@assemblies;
1088 $main::lxdebug->leave_sub();
1090 return wantarray ? @{ $form->{parts} } : $form->{parts};
1093 sub _create_filter_for_priceupdate {
1094 $main::lxdebug->enter_sub();
1097 my $myconfig = \%main::myconfig;
1098 my $form = $main::form;
1101 my $where = '1 = 1';
1103 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1105 $column =~ s/.*\.//;
1106 next unless ($form->{$column});
1108 $where .= qq| AND $item ILIKE ?|;
1109 push(@where_values, '%' . $form->{$column} . '%');
1112 foreach my $item (qw(description serialnumber)) {
1113 next unless ($form->{$item});
1115 $where .= qq| AND (${item} ILIKE ?)|;
1116 push(@where_values, '%' . $form->{$item} . '%');
1120 # items which were never bought, sold or on an order
1121 if ($form->{itemstatus} eq 'orphaned') {
1123 qq| AND (p.onhand = 0)
1126 SELECT DISTINCT parts_id FROM invoice
1128 SELECT DISTINCT parts_id FROM assembly
1130 SELECT DISTINCT parts_id FROM orderitems
1133 } elsif ($form->{itemstatus} eq 'active') {
1134 $where .= qq| AND p.obsolete = '0'|;
1136 } elsif ($form->{itemstatus} eq 'obsolete') {
1137 $where .= qq| AND p.obsolete = '1'|;
1139 } elsif ($form->{itemstatus} eq 'onhand') {
1140 $where .= qq| AND p.onhand > 0|;
1142 } elsif ($form->{itemstatus} eq 'short') {
1143 $where .= qq| AND p.onhand < p.rop|;
1147 foreach my $column (qw(make model)) {
1148 next unless ($form->{$column});
1149 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1150 push(@where_values, '%' . $form->{$column} . '%');
1153 $main::lxdebug->leave_sub();
1155 return ($where, @where_values);
1158 sub get_num_matches_for_priceupdate {
1159 $main::lxdebug->enter_sub();
1163 my $myconfig = \%main::myconfig;
1164 my $form = $main::form;
1166 my $dbh = $form->get_standard_dbh($myconfig);
1168 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1170 my $num_updated = 0;
1173 for my $column (qw(sellprice listprice)) {
1174 next if ($form->{$column} eq "");
1182 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1184 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1185 $num_updated += $result if (0 <= $result);
1194 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1195 WHERE $where) AND (pricegroup_id = ?)|;
1196 my $sth = prepare_query($form, $dbh, $query);
1198 for my $i (1 .. $form->{price_rows}) {
1199 next if ($form->{"price_$i"} eq "");
1201 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1202 $num_updated += $result if (0 <= $result);
1206 $main::lxdebug->leave_sub();
1208 return $num_updated;
1212 $main::lxdebug->enter_sub();
1214 my ($self, $myconfig, $form) = @_;
1216 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1217 my $num_updated = 0;
1219 # connect to database
1220 my $dbh = $form->dbconnect_noauto($myconfig);
1222 for my $column (qw(sellprice listprice)) {
1223 next if ($form->{$column} eq "");
1225 my $value = $form->parse_amount($myconfig, $form->{$column});
1228 if ($form->{"${column}_type"} eq "percent") {
1229 $value = ($value / 100) + 1;
1234 qq|UPDATE parts SET $column = $column $operator ?
1238 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1240 my $result = do_query($form, $dbh, $query, $value, @where_values);
1241 $num_updated += $result if (0 <= $result);
1245 qq|UPDATE prices SET price = price + ?
1249 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1250 WHERE $where) AND (pricegroup_id = ?)|;
1251 my $sth_add = prepare_query($form, $dbh, $q_add);
1254 qq|UPDATE prices SET price = price * ?
1258 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1259 WHERE $where) AND (pricegroup_id = ?)|;
1260 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1262 for my $i (1 .. $form->{price_rows}) {
1263 next if ($form->{"price_$i"} eq "");
1265 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1268 if ($form->{"pricegroup_type_$i"} eq "percent") {
1269 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1271 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1274 $num_updated += $result if (0 <= $result);
1278 $sth_multiply->finish();
1280 my $rc= $dbh->commit;
1283 $main::lxdebug->leave_sub();
1285 return $num_updated;
1289 $main::lxdebug->enter_sub();
1291 my ($self, $module, $myconfig, $form) = @_;
1293 # connect to database
1294 my $dbh = $form->dbconnect($myconfig);
1296 my @values = ('%' . $module . '%');
1301 qq|SELECT c.accno, c.description, c.link, c.id,
1302 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1303 FROM chart c, parts p
1304 WHERE (c.link LIKE ?) AND (p.id = ?)
1306 push(@values, conv_i($form->{id}));
1310 qq|SELECT c.accno, c.description, c.link, c.id,
1311 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1312 FROM chart c, defaults d
1317 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1318 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1319 foreach my $key (split(/:/, $ref->{link})) {
1320 if ($key =~ /\Q$module\E/) {
1321 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1322 || ($ref->{id} eq $ref->{income_accno_id})
1323 || ($ref->{id} eq $ref->{expense_accno_id})) {
1324 push @{ $form->{"${module}_links"}{$key} },
1325 { accno => $ref->{accno},
1326 description => $ref->{description},
1327 selected => "selected" };
1328 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1330 push @{ $form->{"${module}_links"}{$key} },
1331 { accno => $ref->{accno},
1332 description => $ref->{description},
1340 # get buchungsgruppen
1341 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1344 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1347 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1351 $main::lxdebug->leave_sub();
1354 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1356 $main::lxdebug->enter_sub();
1358 my ($self, $myconfig, $form, $sortorder) = @_;
1359 my $dbh = $form->dbconnect($myconfig);
1360 my $order = qq| p.partnumber|;
1361 my $where = qq|1 = 1|;
1364 if ($sortorder eq "all") {
1365 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1366 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1368 } elsif ($sortorder eq "partnumber") {
1369 $where .= qq| AND (partnumber ILIKE ?)|;
1370 push(@values, '%' . $form->{partnumber} . '%');
1372 } elsif ($sortorder eq "description") {
1373 $where .= qq| AND (description ILIKE ?)|;
1374 push(@values, '%' . $form->{description} . '%');
1375 $order = "description";
1380 qq|SELECT id, partnumber, description, unit, sellprice
1382 WHERE $where ORDER BY $order|;
1384 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1387 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1388 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1393 $form->{"id_$j"} = $ref->{id};
1394 $form->{"partnumber_$j"} = $ref->{partnumber};
1395 $form->{"description_$j"} = $ref->{description};
1396 $form->{"unit_$j"} = $ref->{unit};
1397 $form->{"sellprice_$j"} = $ref->{sellprice};
1398 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1404 $main::lxdebug->leave_sub();
1409 # gets sum of sold part with part_id
1411 $main::lxdebug->enter_sub();
1413 my ($dbh, $id) = @_;
1415 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1416 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1419 $main::lxdebug->leave_sub();
1422 } #end get_soldtotal
1424 sub retrieve_languages {
1425 $main::lxdebug->enter_sub();
1427 my ($self, $myconfig, $form) = @_;
1429 # connect to database
1430 my $dbh = $form->dbconnect($myconfig);
1436 if ($form->{language_values} ne "") {
1438 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1440 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1441 ORDER BY lower(l.description)|;
1442 @values = (conv_i($form->{id}));
1445 $query = qq|SELECT id, description
1447 ORDER BY lower(description)|;
1450 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1454 $main::lxdebug->leave_sub();
1459 sub follow_account_chain {
1460 $main::lxdebug->enter_sub(2);
1462 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1464 my @visited_accno_ids = ($accno_id);
1468 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1469 map { $_->{id} => $_ }
1470 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1471 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1473 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1474 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1478 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1479 last unless ($ref && $ref->{"is_valid"} &&
1480 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1481 $accno_id = $ref->{"new_chart_id"};
1482 $accno = $ref->{"accno"};
1483 push(@visited_accno_ids, $accno_id);
1486 $main::lxdebug->leave_sub(2);
1488 return ($accno_id, $accno);
1491 sub retrieve_accounts {
1492 $main::lxdebug->enter_sub;
1495 my $myconfig = shift;
1497 my $dbh = $form->get_standard_dbh;
1498 my %args = @_; # index => part_id
1500 $form->{taxzone_id} *= 1;
1502 return unless grep $_, values %args; # shortfuse if no part_id supplied
1504 # transdate madness.
1506 if ($form->{type} eq "invoice") {
1507 if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1508 $transdate = $form->{invdate};
1510 $transdate = $form->{deliverydate};
1512 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1513 $transdate = $form->{invdate};
1515 $transdate = $form->{transdate};
1518 if ($transdate eq "") {
1519 $transdate = "current_date";
1521 $transdate = $dbh->quote($transdate);
1524 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1526 my @part_ids = grep { $_ } values %args;
1527 my $in = join ',', ('?') x @part_ids;
1529 my %accno_by_part = map { $_->{id} => $_ }
1530 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1532 p.id, p.inventory_accno_id AS is_part,
1533 bg.inventory_accno_id,
1534 bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
1535 bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
1536 c1.accno AS inventory_accno,
1537 c2.accno AS income_accno,
1538 c3.accno AS expense_accno
1540 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1541 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1542 LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
1543 LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
1547 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1548 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1550 LEFT JOIN chart c ON c.id = t.chart_id
1554 WHERE tk.chart_id = ? AND startdate <= ?
1555 ORDER BY startdate DESC LIMIT 1)
1558 while (my ($index => $part_id) = each %args) {
1559 my $ref = $accno_by_part{$part_id} or next;
1561 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1564 for my $type (qw(inventory income expense)) {
1565 next unless $ref->{"${type}_accno_id"};
1566 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1567 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1570 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1572 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1573 $ref = $sth_tax->fetchrow_hashref or next;
1575 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1576 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1578 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1583 $::lxdebug->leave_sub;
1586 sub get_basic_part_info {
1587 $main::lxdebug->enter_sub();
1592 Common::check_params(\%params, qw(id));
1594 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1597 $main::lxdebug->leave_sub();
1601 my $myconfig = \%main::myconfig;
1602 my $form = $main::form;
1604 my $dbh = $form->get_standard_dbh($myconfig);
1606 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1608 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1610 if ('' eq ref $params{id}) {
1611 $info = $info->[0] || { };
1613 $main::lxdebug->leave_sub();
1617 my %info_map = map { $_->{id} => $_ } @{ $info };
1619 $main::lxdebug->leave_sub();
1624 sub prepare_parts_for_printing {
1625 $main::lxdebug->enter_sub();
1630 my $myconfig = \%main::myconfig;
1631 my $form = $main::form;
1633 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1635 my $prefix = $params{prefix} || 'id_';
1636 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1638 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1641 $main::lxdebug->leave_sub();
1645 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1646 my $query = qq|SELECT mm.parts_id, mm.model, v.name AS make
1648 LEFT JOIN vendor v ON (mm.make = v.id)
1649 WHERE mm.parts_id IN ($placeholders)|;
1653 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1655 while (my $ref = $sth->fetchrow_hashref()) {
1656 $makemodel{$ref->{parts_id}} ||= [];
1657 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1662 my @columns = qw(ean image microfiche drawing weight);
1664 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1666 WHERE id IN ($placeholders)|;
1668 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1670 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1672 foreach my $i (1 .. $rowcount) {
1673 my $id = $form->{"${prefix}${i}"};
1677 foreach (@columns) {
1678 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1681 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1682 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1684 next if (!$makemodel{$id});
1686 foreach my $ref (@{ $makemodel{$id} }) {
1687 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1691 $main::lxdebug->leave_sub();