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->get_standard_dbh;
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)});
160 my @referencing_tables = qw(invoice orderitems inventory);
161 my %column_map = ( );
162 my $parts_id = conv_i($form->{id});
164 $form->{orphaned} = 1;
166 foreach my $table (@referencing_tables) {
167 my $column = $column_map{$table} || 'parts_id';
168 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
169 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
172 $form->{orphaned} = 0;
177 $form->{"unit_changeable"} = $form->{orphaned};
179 Common::webdav_folder($form) if $::lx_office_conf{features}{webdav};
181 $main::lxdebug->leave_sub();
184 sub get_pricegroups {
185 $main::lxdebug->enter_sub();
187 my ($self, $myconfig, $form) = @_;
189 my $dbh = $form->get_standard_dbh;
192 my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
193 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
196 foreach my $pg (@{ $pricegroups }) {
197 $form->{"klass_$i"} = "$pg->{id}";
198 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
199 $form->{"pricegroup_id_$i"} = "$pg->{id}";
200 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
205 $form->{price_rows} = $i - 1;
207 $main::lxdebug->leave_sub();
212 sub retrieve_buchungsgruppen {
213 $main::lxdebug->enter_sub();
215 my ($self, $myconfig, $form) = @_;
219 my $dbh = $form->get_standard_dbh;
221 # get buchungsgruppen
222 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
223 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
225 $main::lxdebug->leave_sub();
229 $main::lxdebug->enter_sub();
231 my ($self, $myconfig, $form) = @_;
233 # connect to database, turn off AutoCommit
234 my $dbh = $form->get_standard_dbh;
237 # make up a unique handle and store in partnumber field
238 # then retrieve the record based on the unique handle to get the id
239 # replace the partnumber field with the actual variable
240 # add records for makemodel
242 # if there is a $form->{id} then replace the old entry
243 # delete all makemodel entries and add the new ones
245 # undo amount formatting
246 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
247 qw(rop weight listprice sellprice gv lastcost);
249 my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
251 $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
255 my $priceupdate = ', priceupdate = current_date';
258 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
259 if (!$trans_number->is_unique) {
260 $::lxdebug->leave_sub;
265 $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
266 my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
268 # if item is part of an assembly adjust all assemblies
269 $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
270 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
271 while (my ($id, $qty) = $sth->fetchrow_array) {
272 &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
276 # delete makemodel records
277 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
279 if ($form->{item} eq 'assembly') {
280 # delete assembly records
281 do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
284 # delete translations
285 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
287 # Check whether or not the prices have changed. If they haven't
288 # then 'priceupdate' should not be updated.
289 my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
290 $priceupdate = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
293 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, save => 1);
295 if ($form->{partnumber} && !$trans_number->is_unique) {
296 $::lxdebug->leave_sub;
300 $form->{partnumber} ||= $trans_number->create_unique;
302 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
303 do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit});
305 $form->{orphaned} = 1;
307 my $partsgroup_id = undef;
309 if ($form->{partsgroup}) {
310 (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
313 my ($subq_inventory, $subq_expense, $subq_income);
314 if ($form->{"item"} eq "part") {
316 qq|(SELECT bg.inventory_accno_id
317 FROM buchungsgruppen bg
318 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
320 $subq_inventory = "NULL";
323 if ($form->{"item"} ne "assembly") {
325 qq|(SELECT bg.expense_accno_id_0
326 FROM buchungsgruppen bg
327 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
329 $subq_expense = "NULL";
349 buchungsgruppen_id = ?,
351 inventory_accno_id = $subq_inventory,
352 income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
353 expense_accno_id = $subq_expense,
362 not_discountable = ?,
368 @values = ($form->{partnumber},
369 $form->{description},
370 $makemodel ? 't' : 'f',
371 $form->{assembly} ? 't' : 'f',
380 conv_i($form->{warehouse_id}),
381 conv_i($form->{bin_id}),
382 conv_i($form->{buchungsgruppen_id}),
383 conv_i($form->{payment_id}),
384 conv_i($form->{buchungsgruppen_id}),
385 $form->{obsolete} ? 't' : 'f',
388 $form->{shop} ? 't' : 'f',
392 $form->{has_sernumber} ? 't' : 'f',
393 $form->{not_discountable} ? 't' : 'f',
395 conv_i($partsgroup_id),
396 conv_i($form->{price_factor_id}),
399 do_query($form, $dbh, $query, @values);
401 # delete translation records
402 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
404 if ($form->{language_values} ne "") {
405 foreach my $item (split(/---\+\+\+---/, $form->{language_values})) {
406 my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
407 if ($translation ne "") {
408 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
409 VALUES ( ?, ?, ?, ? )|;
410 @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
411 do_query($form, $dbh, $query, @values);
416 # delete price records
417 do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
419 $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) VALUES(?, ?, ?)|;
420 $sth = prepare_query($form, $dbh, $query);
422 # insert price records only if different to sellprice
423 for my $i (1 .. $form->{price_rows}) {
424 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
425 next unless $price && ($price != $form->{sellprice});
427 @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
428 do_statement($form, $sth, $query, @values);
433 # insert makemodel records
436 for my $i (1 .. $form->{makemodel_rows}) {
437 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
439 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
440 if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
442 if ($form->{"lastupdate_$i"} eq "") {
443 $lastupdate = 'now()';
445 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
448 $lastupdate = 'now()';
450 $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
451 qq|VALUES (?, ?, ?, ?, ?, ?)|;
452 @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
454 do_query($form, $dbh, $query, @values);
458 # add assembly records
459 if ($form->{item} eq 'assembly') {
461 for my $i (1 .. $form->{assembly_rows}) {
462 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
464 if ($form->{"qty_$i"} != 0) {
465 $form->{"bom_$i"} *= 1;
466 $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
467 qq|VALUES (?, ?, ?, ?)|;
468 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
469 do_query($form, $dbh, $query, @values);
476 my $shippingdate = "$a[5]-$a[4]-$a[3]";
478 $form->get_employee($dbh);
482 #set expense_accno=inventory_accno if they are different => bilanz
484 ($form->{expense_accno} != $form->{inventory_accno})
485 ? $form->{inventory_accno}
486 : $form->{expense_accno};
488 # get tax rates and description
490 ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
492 qq|SELECT c.accno, c.description, t.rate, t.taxnumber
494 WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
496 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
498 $form->{taxaccount} = "";
499 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
500 $form->{taxaccount} .= "$ptr->{accno} ";
501 if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
502 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
503 $form->{"$ptr->{accno}_description"} = $ptr->{description};
504 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
505 $form->{taxaccount2} .= " $ptr->{accno} ";
509 CVar->save_custom_variables(dbh => $dbh,
511 trans_id => $form->{id},
516 my $rc = $dbh->commit;
518 $main::lxdebug->leave_sub();
523 sub update_assembly {
524 $main::lxdebug->enter_sub();
526 my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
528 my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
529 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
531 while (my ($pid, $aqty) = $sth->fetchrow_array) {
532 &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
537 qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
539 my @values = ($qty * ($form->{sellprice} - $sellprice),
540 $qty * ($form->{weight} - $weight), conv_i($id));
541 do_query($form, $dbh, $query, @values);
543 $main::lxdebug->leave_sub();
546 sub retrieve_assemblies {
547 $main::lxdebug->enter_sub();
549 my ($self, $myconfig, $form) = @_;
551 # connect to database
552 my $dbh = $form->get_standard_dbh;
554 my $where = qq|NOT p.obsolete|;
557 if ($form->{partnumber}) {
558 $where .= qq| AND (p.partnumber ILIKE ?)|;
559 push(@values, '%' . $form->{partnumber} . '%');
562 if ($form->{description}) {
563 $where .= qq| AND (p.description ILIKE ?)|;
564 push(@values, '%' . $form->{description} . '%');
567 # retrieve assembly items
569 qq|SELECT p.id, p.partnumber, p.description,
571 (SELECT sum(p2.inventory_accno_id)
572 FROM parts p2, assembly a
573 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
575 WHERE NOT p.obsolete AND p.assembly $where|;
577 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
579 $main::lxdebug->leave_sub();
583 $main::lxdebug->enter_sub();
585 my ($self, $myconfig, $form) = @_;
586 my @values = (conv_i($form->{id}));
587 # connect to database, turn off AutoCommit
588 my $dbh = $form->get_standard_dbh;
590 my %columns = ( "assembly" => "id", "parts" => "id" );
592 for my $table (qw(prices makemodel inventory assembly translation parts)) {
593 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
594 do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
598 my $rc = $dbh->commit;
600 $main::lxdebug->leave_sub();
606 $main::lxdebug->enter_sub();
608 my ($self, $myconfig, $form) = @_;
610 my $i = $form->{assembly_rows};
612 my $where = qq|1 = 1|;
615 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
617 while (my ($column, $table) = each(%columns)) {
618 next unless ($form->{"${column}_$i"});
619 $where .= qq| AND ${table}.${column} ILIKE ?|;
620 push(@values, '%' . $form->{"${column}_$i"} . '%');
624 $where .= qq| AND NOT (p.id = ?)|;
625 push(@values, conv_i($form->{id}));
628 # Search for part ID overrides all other criteria.
629 if ($form->{"id_${i}"}) {
630 $where = qq|p.id = ?|;
631 @values = ($form->{"id_${i}"});
634 if ($form->{partnumber}) {
635 $where .= qq| ORDER BY p.partnumber|;
637 $where .= qq| ORDER BY p.description|;
640 # connect to database
641 my $dbh = $form->get_standard_dbh;
644 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
645 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
646 p.price_factor_id, pfac.factor AS price_factor
648 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
649 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
651 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
653 $main::lxdebug->leave_sub();
658 # Warning, deep magic ahead.
659 # This function gets all parts from the database according to the filters specified
662 # sort revers - sorting field + direction
665 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
666 # partnumber ean description partsgroup microfiche drawing
669 # l_partnumber l_description l_listprice l_sellprice l_lastcost l_priceupdate l_weight l_unit l_rop l_image l_drawing l_microfiche l_partsgroup
672 # itemstatus = active | onhand | short | obsolete | orphaned
673 # searchitems = part | assembly | service
676 # make model - makemodel
677 # serialnumber transdatefrom transdateto - invoice/orderitems
680 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
681 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
682 # l_soldtotal - aggreg join to display total of sold quantity
683 # onhand - as above, but masking the simple itemstatus results (doh!)
684 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
685 # l_serialnumber - belonges to serialnumber filter
686 # l_deliverydate - displays deliverydate is sold etc. flags are active
687 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
690 # onhand - as above, but masking the simple itemstatus results (doh!)
692 # search by overrides of description
694 # disabled sanity checks and changes:
695 # - searchitems = assembly will no longer disable bought
696 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
697 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
698 # - itemstatus = obsolete will no longer disable onhand, short
699 # - allow sorting by ean
700 # - serialnumber filter also works if l_serialnumber isn't ticked
701 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
704 $main::lxdebug->enter_sub();
706 my ($self, $myconfig, $form) = @_;
707 my $dbh = $form->get_standard_dbh($myconfig);
709 $form->{parts} = +{ };
710 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
712 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
713 my @project_filters = qw(projectnumber projectdescription);
714 my @makemodel_filters = qw(make model);
715 my @invoice_oi_filters = qw(serialnumber soldtotal);
716 my @apoe_filters = qw(transdate);
717 my @like_filters = (@simple_filters, @invoice_oi_filters);
718 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
719 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image));
720 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
721 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
722 my @deliverydate_flags = qw(deliverydate);
723 # my @other_flags = qw(onhand); # ToDO: implement these
724 # my @inactive_flags = qw(l_subtotal short l_linetotal);
726 my @select_tokens = qw(id factor);
727 my @where_tokens = qw(1=1);
728 my @group_tokens = ();
730 my %joins_needed = ();
733 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
734 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
735 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
738 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
739 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
740 ) AS ioi ON ioi.parts_id = p.id|,
743 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
744 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
745 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
746 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
749 SELECT id, name, 'customer' AS cv FROM customer UNION
750 SELECT id, name, 'vendor' AS cv FROM vendor
751 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
752 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
753 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
755 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
758 deliverydate => 'apoe.', serialnumber => 'ioi.',
759 transdate => 'apoe.', trans_id => 'ioi.',
760 module => 'apoe.', name => 'cv.',
761 ordnumber => 'apoe.', make => 'mm.',
762 quonumber => 'apoe.', model => 'mm.',
763 invnumber => 'apoe.', partsgroup => 'pg.',
764 lastcost => 'p.', , soldtotal => ' ',
765 factor => 'pfac.', projectnumber => 'pj.',
766 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
769 serialnumber => 'ioi.',
770 quotation => 'apoe.',
776 # if the join condition in these blocks are met, the column
777 # of the scecified table will gently override (coalesce actually) the original value
778 # use it to conditionally coalesce values from subtables
779 my @column_override = (
780 # column name, prefix, joins_needed, nick name (in case column is named like another)
781 [ 'description', 'ioi.', 'invoice_oi' ],
782 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
783 [ 'transdate', 'apoe.', 'apoe' ],
784 [ 'unit', 'ioi.', 'invoice_oi' ],
785 [ 'sellprice', 'ioi.', 'invoice_oi' ],
788 # careful with renames. these are HARD, and any filters done on the original column will break
789 my %renamed_columns = (
790 'factor' => 'price_factor',
791 'SUM(ioi.qty)' => 'soldtotal',
792 'ioi.id' => 'ioi_id',
794 'projectdescription' => 'projectdescription',
798 projectdescription => 'description',
801 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
802 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
805 my $make_token_builder = sub {
806 my $joins_needed = shift;
808 my ($nick, $alias) = @_;
809 my ($col) = $real_column{$nick} || $nick;
810 my @coalesce_tokens =
811 map { ($_->[1] || 'p.') . $_->[0] }
812 grep { !$_->[2] || $joins_needed->{$_->[2]} }
813 grep { ($_->[3] || $_->[0]) eq $nick }
814 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
816 my $coalesce = scalar @coalesce_tokens > 1;
818 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
819 : shift @coalesce_tokens)
820 . ($alias && ($coalesce || $renamed_columns{$nick})
821 ? " AS " . ($renamed_columns{$nick} || $nick)
826 #===== switches and simple filters ========#
828 # special case transdate
829 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
830 $form->{"l_transdate"} = 1;
831 push @select_tokens, 'transdate';
832 for (qw(transdatefrom transdateto)) {
833 next unless $form->{$_};
834 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
835 push @bind_vars, $form->{$_};
839 if ($form->{"partsgroup_id"}) {
840 $form->{"l_partsgroup"} = '1'; # show the column
841 push @where_tokens, "pg.id = ?";
842 push @bind_vars, $form->{"partsgroup_id"};
845 foreach (@like_filters) {
846 next unless $form->{$_};
847 $form->{"l_$_"} = '1'; # show the column
848 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
849 push @bind_vars, "%$form->{$_}%";
852 foreach (@simple_l_switches) {
853 next unless $form->{"l_$_"};
854 push @select_tokens, $_;
857 for ($form->{searchitems}) {
858 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
859 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
860 push @where_tokens, 'NOT p.assembly' if /service/;
861 push @where_tokens, ' p.assembly' if /assembly/;
864 for ($form->{itemstatus}) {
865 push @where_tokens, 'p.id NOT IN
866 (SELECT DISTINCT parts_id FROM invoice UNION
867 SELECT DISTINCT parts_id FROM assembly UNION
868 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
869 push @where_tokens, 'p.onhand = 0' if /orphaned/;
870 push @where_tokens, 'NOT p.obsolete' if /active/;
871 push @where_tokens, ' p.obsolete', if /obsolete/;
872 push @where_tokens, 'p.onhand > 0', if /onhand/;
873 push @where_tokens, 'p.onhand < p.rop', if /short/;
876 my $q_assembly_lastcost =
877 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
879 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
880 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
881 WHERE (a_lc.id = p.id)) AS lastcost|;
882 $table_prefix{$q_assembly_lastcost} = ' ';
884 # special case makemodel search
885 # all_parts is based upon the assumption that every parameter is named like the column it represents
886 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
887 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
889 push @where_tokens, 'mv.name ILIKE ?';
890 push @bind_vars, "%$form->{make}%";
892 if ($form->{model}) {
893 push @where_tokens, 'mm.model ILIKE ?';
894 push @bind_vars, "%$form->{model}%";
897 # special case: sorting by partnumber
898 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
899 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
900 # ToDO: implement proper functional sorting
901 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
902 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
903 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
904 # if $form->{sort} eq 'partnumber';
906 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
909 $limit_clause = " LIMIT 100" if $form->{top100};
910 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
912 #=== joins and complicated filters ========#
914 my $bsooqr = any { $form->{$_} } @oe_flags;
915 my @bsooqr_tokens = ();
917 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
918 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
919 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
920 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
921 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
922 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
923 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
924 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
925 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
926 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
928 $joins_needed{partsgroup} = 1;
929 $joins_needed{pfac} = 1;
930 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
931 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
932 $joins_needed{mv} = 1 if $joins_needed{makemodel};
933 $joins_needed{cv} = 1 if $bsooqr;
934 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
935 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
937 # special case for description search.
938 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
939 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
940 # find the old entries in of @where_tokens and @bind_vars, and adjust them
941 if ($joins_needed{invoice_oi}) {
942 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
943 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
944 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
945 splice @bind_vars, $bi, 0, $bind_vars[$bi];
950 # now the master trick: soldtotal.
951 if ($form->{l_soldtotal}) {
952 push @where_tokens, 'NOT ioi.qty = 0';
953 push @group_tokens, @select_tokens;
954 map { s/.*\sAS\s+//si } @group_tokens;
955 push @select_tokens, 'SUM(ioi.qty)';
958 #============= build query ================#
960 my $token_builder = $make_token_builder->(\%joins_needed);
962 my @sort_cols = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
963 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
964 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
965 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
967 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
968 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
969 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
970 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
972 my %oe_flag_to_cvar = (
975 onorder => 'orderitems',
976 ordered => 'orderitems',
978 quoted => 'orderitems',
981 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
983 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
985 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
989 $where_clause .= qq| AND ($cvar_where)|;
990 push @bind_vars, @cvar_values;
993 my $query = <<" SQL";
994 SELECT DISTINCT $select_clause
1003 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1005 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1007 # fix qty sign in ap. those are saved negative
1008 if ($bsooqr && $form->{bought}) {
1009 for my $row (@{ $form->{parts} }) {
1010 $row->{qty} *= -1 if $row->{module} eq 'ir';
1014 # post processing for assembly parts lists (bom)
1015 # for each part get the assembly parts and add them into the partlist.
1017 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1019 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1021 p.sellprice, p.listprice, p.lastcost,
1022 p.rop, p.weight, p.priceupdate,
1023 p.image, p.drawing, p.microfiche,
1026 INNER JOIN assembly a ON (p.id = a.parts_id)
1029 my $sth = prepare_query($form, $dbh, $query);
1031 foreach my $item (@{ $form->{parts} }) {
1032 push(@assemblies, $item);
1033 do_statement($form, $sth, $query, conv_i($item->{id}));
1035 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1036 $ref->{assemblyitem} = 1;
1037 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1038 push(@assemblies, $ref);
1043 # copy assemblies to $form->{parts}
1044 $form->{parts} = \@assemblies;
1047 if ($form->{l_pricegroups} ) {
1049 SELECT parts_id, price, pricegroup_id
1054 my $sth = prepare_query($form, $dbh, $query);
1056 foreach my $part (@{ $form->{parts} }) {
1057 do_statement($form, $sth, $query, conv_i($part->{id}));
1059 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1060 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1067 $main::lxdebug->leave_sub();
1069 return wantarray ? @{ $form->{parts} } : $form->{parts};
1072 sub _create_filter_for_priceupdate {
1073 $main::lxdebug->enter_sub();
1076 my $myconfig = \%main::myconfig;
1077 my $form = $main::form;
1080 my $where = '1 = 1';
1082 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1084 $column =~ s/.*\.//;
1085 next unless ($form->{$column});
1087 $where .= qq| AND $item ILIKE ?|;
1088 push(@where_values, '%' . $form->{$column} . '%');
1091 foreach my $item (qw(description serialnumber)) {
1092 next unless ($form->{$item});
1094 $where .= qq| AND (${item} ILIKE ?)|;
1095 push(@where_values, '%' . $form->{$item} . '%');
1099 # items which were never bought, sold or on an order
1100 if ($form->{itemstatus} eq 'orphaned') {
1102 qq| AND (p.onhand = 0)
1105 SELECT DISTINCT parts_id FROM invoice
1107 SELECT DISTINCT parts_id FROM assembly
1109 SELECT DISTINCT parts_id FROM orderitems
1112 } elsif ($form->{itemstatus} eq 'active') {
1113 $where .= qq| AND p.obsolete = '0'|;
1115 } elsif ($form->{itemstatus} eq 'obsolete') {
1116 $where .= qq| AND p.obsolete = '1'|;
1118 } elsif ($form->{itemstatus} eq 'onhand') {
1119 $where .= qq| AND p.onhand > 0|;
1121 } elsif ($form->{itemstatus} eq 'short') {
1122 $where .= qq| AND p.onhand < p.rop|;
1126 foreach my $column (qw(make model)) {
1127 next unless ($form->{$column});
1128 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1129 push(@where_values, '%' . $form->{$column} . '%');
1132 $main::lxdebug->leave_sub();
1134 return ($where, @where_values);
1137 sub get_num_matches_for_priceupdate {
1138 $main::lxdebug->enter_sub();
1142 my $myconfig = \%main::myconfig;
1143 my $form = $main::form;
1145 my $dbh = $form->get_standard_dbh($myconfig);
1147 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1149 my $num_updated = 0;
1152 for my $column (qw(sellprice listprice)) {
1153 next if ($form->{$column} eq "");
1161 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1163 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1164 $num_updated += $result if (0 <= $result);
1173 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1174 WHERE $where) AND (pricegroup_id = ?)|;
1175 my $sth = prepare_query($form, $dbh, $query);
1177 for my $i (1 .. $form->{price_rows}) {
1178 next if ($form->{"price_$i"} eq "");
1180 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1181 $num_updated += $result if (0 <= $result);
1185 $main::lxdebug->leave_sub();
1187 return $num_updated;
1191 $main::lxdebug->enter_sub();
1193 my ($self, $myconfig, $form) = @_;
1195 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1196 my $num_updated = 0;
1198 # connect to database
1199 my $dbh = $form->get_standard_dbh;
1201 for my $column (qw(sellprice listprice)) {
1202 next if ($form->{$column} eq "");
1204 my $value = $form->parse_amount($myconfig, $form->{$column});
1207 if ($form->{"${column}_type"} eq "percent") {
1208 $value = ($value / 100) + 1;
1213 qq|UPDATE parts SET $column = $column $operator ?
1217 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1219 my $result = do_query($form, $dbh, $query, $value, @where_values);
1220 $num_updated += $result if (0 <= $result);
1224 qq|UPDATE prices SET price = price + ?
1228 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1229 WHERE $where) AND (pricegroup_id = ?)|;
1230 my $sth_add = prepare_query($form, $dbh, $q_add);
1233 qq|UPDATE prices SET price = price * ?
1237 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1238 WHERE $where) AND (pricegroup_id = ?)|;
1239 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1241 for my $i (1 .. $form->{price_rows}) {
1242 next if ($form->{"price_$i"} eq "");
1244 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1247 if ($form->{"pricegroup_type_$i"} eq "percent") {
1248 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1250 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1253 $num_updated += $result if (0 <= $result);
1257 $sth_multiply->finish();
1259 my $rc= $dbh->commit;
1261 $main::lxdebug->leave_sub();
1263 return $num_updated;
1267 $main::lxdebug->enter_sub();
1269 my ($self, $module, $myconfig, $form) = @_;
1271 # connect to database
1272 my $dbh = $form->get_standard_dbh;
1274 my @values = ('%' . $module . '%');
1279 qq|SELECT c.accno, c.description, c.link, c.id,
1280 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1281 FROM chart c, parts p
1282 WHERE (c.link LIKE ?) AND (p.id = ?)
1284 push(@values, conv_i($form->{id}));
1288 qq|SELECT c.accno, c.description, c.link, c.id,
1289 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1290 FROM chart c, defaults d
1295 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1296 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1297 foreach my $key (split(/:/, $ref->{link})) {
1298 if ($key =~ /\Q$module\E/) {
1299 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1300 || ($ref->{id} eq $ref->{income_accno_id})
1301 || ($ref->{id} eq $ref->{expense_accno_id})) {
1302 push @{ $form->{"${module}_links"}{$key} },
1303 { accno => $ref->{accno},
1304 description => $ref->{description},
1305 selected => "selected" };
1306 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1308 push @{ $form->{"${module}_links"}{$key} },
1309 { accno => $ref->{accno},
1310 description => $ref->{description},
1318 # get buchungsgruppen
1319 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1322 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1325 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1328 $main::lxdebug->leave_sub();
1331 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1333 $main::lxdebug->enter_sub();
1335 my ($self, $myconfig, $form, $sortorder) = @_;
1336 my $dbh = $form->get_standard_dbh;
1337 my $order = qq| p.partnumber|;
1338 my $where = qq|1 = 1|;
1341 if ($sortorder eq "all") {
1342 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1343 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1345 } elsif ($sortorder eq "partnumber") {
1346 $where .= qq| AND (partnumber ILIKE ?)|;
1347 push(@values, '%' . $form->{partnumber} . '%');
1349 } elsif ($sortorder eq "description") {
1350 $where .= qq| AND (description ILIKE ?)|;
1351 push(@values, '%' . $form->{description} . '%');
1352 $order = "description";
1357 qq|SELECT id, partnumber, description, unit, sellprice
1359 WHERE $where ORDER BY $order|;
1361 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1364 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1365 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1370 $form->{"id_$j"} = $ref->{id};
1371 $form->{"partnumber_$j"} = $ref->{partnumber};
1372 $form->{"description_$j"} = $ref->{description};
1373 $form->{"unit_$j"} = $ref->{unit};
1374 $form->{"sellprice_$j"} = $ref->{sellprice};
1375 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1380 $main::lxdebug->leave_sub();
1385 # gets sum of sold part with part_id
1387 $main::lxdebug->enter_sub();
1389 my ($dbh, $id) = @_;
1391 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1392 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1395 $main::lxdebug->leave_sub();
1398 } #end get_soldtotal
1400 sub retrieve_languages {
1401 $main::lxdebug->enter_sub();
1403 my ($self, $myconfig, $form) = @_;
1405 # connect to database
1406 my $dbh = $form->get_standard_dbh;
1412 if ($form->{language_values} ne "") {
1414 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1416 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1417 ORDER BY lower(l.description)|;
1418 @values = (conv_i($form->{id}));
1421 $query = qq|SELECT id, description
1423 ORDER BY lower(description)|;
1426 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1428 $main::lxdebug->leave_sub();
1433 sub follow_account_chain {
1434 $main::lxdebug->enter_sub(2);
1436 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1438 my @visited_accno_ids = ($accno_id);
1442 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1443 map { $_->{id} => $_ }
1444 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1445 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1447 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1448 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1452 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1453 last unless ($ref && $ref->{"is_valid"} &&
1454 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1455 $accno_id = $ref->{"new_chart_id"};
1456 $accno = $ref->{"accno"};
1457 push(@visited_accno_ids, $accno_id);
1460 $main::lxdebug->leave_sub(2);
1462 return ($accno_id, $accno);
1465 sub retrieve_accounts {
1466 $main::lxdebug->enter_sub;
1469 my $myconfig = shift;
1471 my $dbh = $form->get_standard_dbh;
1472 my %args = @_; # index => part_id
1474 $form->{taxzone_id} *= 1;
1476 return unless grep $_, values %args; # shortfuse if no part_id supplied
1478 # transdate madness.
1480 if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
1481 # use deliverydate for sales and purchase invoice, if it exists
1482 # also use deliverydate for credit notes
1483 if (!$form->{deliverydate}) {
1484 $transdate = $form->{invdate};
1486 $transdate = $form->{deliverydate};
1488 } elsif ($form->{script} eq 'ir.pl') {
1489 # when a purchase invoice is opened from the report of purchase invoices
1490 # $form->{type} isn't set, but $form->{script} is, not sure why this is or
1491 # whether this distinction matters in some other scenario. Otherwise one
1492 # could probably take out this elsif and add a
1493 # " or $form->{script} eq 'ir.pl' "
1494 # to the above if-statement
1495 if (!$form->{deliverydate}) {
1496 $transdate = $form->{invdate};
1498 $transdate = $form->{deliverydate};
1500 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
1501 # if credit_note has a deliverydate, use this instead of invdate
1502 # useful for credit_notes of invoices from an old period with different tax
1503 # if there is no deliverydate then invdate is used, old default (see next elsif)
1504 # Falls hier der Stichtag für Steuern anders bestimmt wird,
1505 # entsprechend auch bei Taxkeys.pm anpassen
1506 $transdate = $form->{deliverydate};
1507 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1508 $transdate = $form->{invdate};
1510 $transdate = $form->{transdate};
1513 if ($transdate eq "") {
1514 $transdate = DateTime->today_local->to_lxoffice;
1516 $transdate = $dbh->quote($transdate);
1519 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1521 my @part_ids = grep { $_ } values %args;
1522 my $in = join ',', ('?') x @part_ids;
1524 my %accno_by_part = map { $_->{id} => $_ }
1525 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1527 p.id, p.inventory_accno_id AS is_part,
1528 bg.inventory_accno_id,
1529 bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
1530 bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
1531 c1.accno AS inventory_accno,
1532 c2.accno AS income_accno,
1533 c3.accno AS expense_accno
1535 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1536 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1537 LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
1538 LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
1542 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1543 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1545 LEFT JOIN chart c ON c.id = t.chart_id
1549 WHERE tk.chart_id = ? AND startdate <= ?
1550 ORDER BY startdate DESC LIMIT 1)
1553 while (my ($index => $part_id) = each %args) {
1554 my $ref = $accno_by_part{$part_id} or next;
1556 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1559 for my $type (qw(inventory income expense)) {
1560 next unless $ref->{"${type}_accno_id"};
1561 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1562 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1565 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1567 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1568 $ref = $sth_tax->fetchrow_hashref or next;
1570 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1571 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1573 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1578 $::lxdebug->leave_sub;
1581 sub get_basic_part_info {
1582 $main::lxdebug->enter_sub();
1587 Common::check_params(\%params, qw(id));
1589 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1592 $main::lxdebug->leave_sub();
1596 my $myconfig = \%main::myconfig;
1597 my $form = $main::form;
1599 my $dbh = $form->get_standard_dbh($myconfig);
1601 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1603 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1605 if ('' eq ref $params{id}) {
1606 $info = $info->[0] || { };
1608 $main::lxdebug->leave_sub();
1612 my %info_map = map { $_->{id} => $_ } @{ $info };
1614 $main::lxdebug->leave_sub();
1619 sub prepare_parts_for_printing {
1620 $main::lxdebug->enter_sub();
1625 my $myconfig = $params{myconfig} || \%main::myconfig;
1626 my $form = $params{form} || $main::form;
1628 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1630 my $prefix = $params{prefix} || 'id_';
1631 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1633 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1636 $main::lxdebug->leave_sub();
1640 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1641 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1643 LEFT JOIN vendor v ON (mm.make = v.id)
1644 WHERE mm.parts_id IN ($placeholders)|;
1648 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1650 while (my $ref = $sth->fetchrow_hashref()) {
1651 $makemodel{$ref->{parts_id}} ||= [];
1652 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1657 my @columns = qw(ean image microfiche drawing weight);
1659 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1661 WHERE id IN ($placeholders)|;
1663 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1665 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1667 foreach my $i (1 .. $rowcount) {
1668 my $id = $form->{"${prefix}${i}"};
1672 foreach (@columns) {
1673 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1676 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1677 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1679 next if (!$makemodel{$id});
1681 foreach my $ref (@{ $makemodel{$id} }) {
1682 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1686 $main::lxdebug->leave_sub();