1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
31 # Inventory Control backend
33 #======================================================================
38 use List::MoreUtils qw(all any uniq);
48 $main::lxdebug->enter_sub();
50 my ($self, $myconfig, $form) = @_;
53 my $dbh = $form->dbconnect($myconfig);
59 c1.accno AS inventory_accno,
60 c2.accno AS income_accno,
61 c3.accno AS expense_accno,
64 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
65 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
66 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
67 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
69 my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
71 # copy to $form variables
72 map { $form->{$_} = $ref->{$_} } (keys %{$ref});
76 # part or service item
77 $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
78 if ($form->{assembly}) {
79 $form->{item} = 'assembly';
81 # retrieve assembly items
83 qq|SELECT p.id, p.partnumber, p.description,
84 p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
85 pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
87 JOIN assembly a ON (a.parts_id = p.id)
88 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
89 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
92 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
94 $form->{assembly_rows} = 0;
95 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
96 $form->{assembly_rows}++;
97 foreach my $key (keys %{$ref}) {
98 $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
105 # setup accno hash for <option checked> {amount} is used in create_links
106 $form->{amount}{IC} = $form->{inventory_accno};
107 $form->{amount}{IC_income} = $form->{income_accno};
108 $form->{amount}{IC_sale} = $form->{income_accno};
109 $form->{amount}{IC_expense} = $form->{expense_accno};
110 $form->{amount}{IC_cogs} = $form->{expense_accno};
114 SELECT pg.pricegroup, pg.id AS pricegroup_id, COALESCE(pr.price, 0) AS price
116 LEFT JOIN prices pr ON (pr.pricegroup_id = pg.id) AND (pr.parts_id = ?)
117 ORDER BY lower(pg.pricegroup)
121 foreach $ref (selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}))) {
122 $form->{"${_}_${row}"} = $ref->{$_} for qw(pricegroup_id pricegroup price);
125 $form->{price_rows} = $row - 1;
128 if ($form->{makemodel}) {
130 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
131 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
132 my @values = ($form->{id});
133 $sth = $dbh->prepare($query);
134 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
138 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
139 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
144 $form->{makemodel_rows} = $i - 1;
149 $form->{language_values} = "";
150 $query = qq|SELECT language_id, translation, longdescription
153 my $trq = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
154 while (my $tr = $trq->fetchrow_hashref("NAME_lc")) {
155 $form->{language_values} .= "---+++---" . join('--++--', @{$tr}{qw(language_id translation longdescription)});
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};
181 $main::lxdebug->leave_sub();
184 sub get_pricegroups {
185 $main::lxdebug->enter_sub();
187 my ($self, $myconfig, $form) = @_;
189 my $dbh = $form->dbconnect($myconfig);
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;
209 $main::lxdebug->leave_sub();
214 sub retrieve_buchungsgruppen {
215 $main::lxdebug->enter_sub();
217 my ($self, $myconfig, $form) = @_;
221 my $dbh = $form->dbconnect($myconfig);
223 # get buchungsgruppen
224 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
225 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
227 $main::lxdebug->leave_sub();
231 $main::lxdebug->enter_sub();
233 my ($self, $myconfig, $form) = @_;
235 # connect to database, turn off AutoCommit
236 my $dbh = $form->get_standard_dbh;
239 # make up a unique handle and store in partnumber field
240 # then retrieve the record based on the unique handle to get the id
241 # replace the partnumber field with the actual variable
242 # add records for makemodel
244 # if there is a $form->{id} then replace the old entry
245 # delete all makemodel entries and add the new ones
247 # undo amount formatting
248 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
249 qw(rop weight listprice sellprice gv lastcost);
251 my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
253 $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
257 my $priceupdate = ', priceupdate = current_date';
260 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
261 if (!$trans_number->is_unique) {
262 $::lxdebug->leave_sub;
267 $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
268 my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
270 # if item is part of an assembly adjust all assemblies
271 $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
272 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
273 while (my ($id, $qty) = $sth->fetchrow_array) {
274 &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
278 # delete makemodel records
279 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
281 if ($form->{item} eq 'assembly') {
282 # delete assembly records
283 do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
286 # delete translations
287 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
289 # Check whether or not the prices have changed. If they haven't
290 # then 'priceupdate' should not be updated.
291 my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
292 $priceupdate = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
295 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, save => 1);
297 if ($form->{partnumber} && !$trans_number->is_unique) {
298 $::lxdebug->leave_sub;
302 $form->{partnumber} ||= $trans_number->create_unique;
304 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
305 do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit});
307 $form->{orphaned} = 1;
309 my $partsgroup_id = undef;
311 if ($form->{partsgroup}) {
312 (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
315 my ($subq_inventory, $subq_expense, $subq_income);
316 if ($form->{"item"} eq "part") {
318 qq|(SELECT bg.inventory_accno_id
319 FROM buchungsgruppen bg
320 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
322 $subq_inventory = "NULL";
325 if ($form->{"item"} ne "assembly") {
327 qq|(SELECT bg.expense_accno_id_0
328 FROM buchungsgruppen bg
329 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
331 $subq_expense = "NULL";
351 buchungsgruppen_id = ?,
353 inventory_accno_id = $subq_inventory,
354 income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
355 expense_accno_id = $subq_expense,
364 not_discountable = ?,
370 @values = ($form->{partnumber},
371 $form->{description},
372 $makemodel ? 't' : 'f',
373 $form->{assembly} ? 't' : 'f',
382 conv_i($form->{warehouse_id}),
383 conv_i($form->{bin_id}),
384 conv_i($form->{buchungsgruppen_id}),
385 conv_i($form->{payment_id}),
386 conv_i($form->{buchungsgruppen_id}),
387 $form->{obsolete} ? 't' : 'f',
390 $form->{shop} ? 't' : 'f',
394 $form->{has_sernumber} ? 't' : 'f',
395 $form->{not_discountable} ? 't' : 'f',
397 conv_i($partsgroup_id),
398 conv_i($form->{price_factor_id}),
401 do_query($form, $dbh, $query, @values);
403 # delete translation records
404 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
406 if ($form->{language_values} ne "") {
407 foreach my $item (split(/---\+\+\+---/, $form->{language_values})) {
408 my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
409 if ($translation ne "") {
410 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
411 VALUES ( ?, ?, ?, ? )|;
412 @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
413 do_query($form, $dbh, $query, @values);
418 # delete price records
419 do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
421 $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) VALUES(?, ?, ?)|;
422 $sth = prepare_query($form, $dbh, $query);
424 # insert price records only if different to sellprice
425 for my $i (1 .. $form->{price_rows}) {
426 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
427 next unless $price && ($price != $form->{sellprice});
429 @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
430 do_statement($form, $sth, $query, @values);
435 # insert makemodel records
438 for my $i (1 .. $form->{makemodel_rows}) {
439 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
441 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
442 if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
444 if ($form->{"lastupdate_$i"} eq "") {
445 $lastupdate = 'now()';
447 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
450 $lastupdate = 'now()';
452 $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
453 qq|VALUES (?, ?, ?, ?, ?, ?)|;
454 @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
456 do_query($form, $dbh, $query, @values);
460 # add assembly records
461 if ($form->{item} eq 'assembly') {
463 for my $i (1 .. $form->{assembly_rows}) {
464 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
466 if ($form->{"qty_$i"} != 0) {
467 $form->{"bom_$i"} *= 1;
468 $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
469 qq|VALUES (?, ?, ?, ?)|;
470 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
471 do_query($form, $dbh, $query, @values);
478 my $shippingdate = "$a[5]-$a[4]-$a[3]";
480 $form->get_employee($dbh);
484 #set expense_accno=inventory_accno if they are different => bilanz
486 ($form->{expense_accno} != $form->{inventory_accno})
487 ? $form->{inventory_accno}
488 : $form->{expense_accno};
490 # get tax rates and description
492 ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
494 qq|SELECT c.accno, c.description, t.rate, t.taxnumber
496 WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
498 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
500 $form->{taxaccount} = "";
501 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
502 $form->{taxaccount} .= "$ptr->{accno} ";
503 if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
504 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
505 $form->{"$ptr->{accno}_description"} = $ptr->{description};
506 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
507 $form->{taxaccount2} .= " $ptr->{accno} ";
511 CVar->save_custom_variables(dbh => $dbh,
513 trans_id => $form->{id},
518 my $rc = $dbh->commit;
520 $main::lxdebug->leave_sub();
525 sub update_assembly {
526 $main::lxdebug->enter_sub();
528 my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
530 my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
531 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
533 while (my ($pid, $aqty) = $sth->fetchrow_array) {
534 &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
539 qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
541 my @values = ($qty * ($form->{sellprice} - $sellprice),
542 $qty * ($form->{weight} - $weight), conv_i($id));
543 do_query($form, $dbh, $query, @values);
545 $main::lxdebug->leave_sub();
548 sub retrieve_assemblies {
549 $main::lxdebug->enter_sub();
551 my ($self, $myconfig, $form) = @_;
553 # connect to database
554 my $dbh = $form->dbconnect($myconfig);
556 my $where = qq|NOT p.obsolete|;
559 if ($form->{partnumber}) {
560 $where .= qq| AND (p.partnumber ILIKE ?)|;
561 push(@values, '%' . $form->{partnumber} . '%');
564 if ($form->{description}) {
565 $where .= qq| AND (p.description ILIKE ?)|;
566 push(@values, '%' . $form->{description} . '%');
569 # retrieve assembly items
571 qq|SELECT p.id, p.partnumber, p.description,
573 (SELECT sum(p2.inventory_accno_id)
574 FROM parts p2, assembly a
575 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
577 WHERE NOT p.obsolete AND p.assembly $where|;
579 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
583 $main::lxdebug->leave_sub();
587 $main::lxdebug->enter_sub();
589 my ($self, $myconfig, $form) = @_;
590 my @values = (conv_i($form->{id}));
591 # connect to database, turn off AutoCommit
592 my $dbh = $form->dbconnect_noauto($myconfig);
594 my %columns = ( "assembly" => "id", "parts" => "id" );
596 for my $table (qw(prices makemodel inventory assembly translation parts)) {
597 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
598 do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
602 my $rc = $dbh->commit;
605 $main::lxdebug->leave_sub();
611 $main::lxdebug->enter_sub();
613 my ($self, $myconfig, $form) = @_;
615 my $i = $form->{assembly_rows};
617 my $where = qq|1 = 1|;
620 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
622 while (my ($column, $table) = each(%columns)) {
623 next unless ($form->{"${column}_$i"});
624 $where .= qq| AND ${table}.${column} ILIKE ?|;
625 push(@values, '%' . $form->{"${column}_$i"} . '%');
629 $where .= qq| AND NOT (p.id = ?)|;
630 push(@values, conv_i($form->{id}));
633 # Search for part ID overrides all other criteria.
634 if ($form->{"id_${i}"}) {
635 $where = qq|p.id = ?|;
636 @values = ($form->{"id_${i}"});
639 if ($form->{partnumber}) {
640 $where .= qq| ORDER BY p.partnumber|;
642 $where .= qq| ORDER BY p.description|;
645 # connect to database
646 my $dbh = $form->dbconnect($myconfig);
649 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
650 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
651 p.price_factor_id, pfac.factor AS price_factor
653 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
654 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
656 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
660 $main::lxdebug->leave_sub();
665 # Warning, deep magic ahead.
666 # This function gets all parts from the database according to the filters specified
669 # sort revers - sorting field + direction
672 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
673 # partnumber ean description partsgroup microfiche drawing
676 # 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
679 # itemstatus = active | onhand | short | obsolete | orphaned
680 # searchitems = part | assembly | service
683 # make model - makemodel
684 # serialnumber transdatefrom transdateto - invoice/orderitems
687 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
688 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
689 # l_soldtotal - aggreg join to display total of sold quantity
690 # onhand - as above, but masking the simple itemstatus results (doh!)
691 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
692 # l_serialnumber - belonges to serialnumber filter
693 # l_deliverydate - displays deliverydate is sold etc. flags are active
694 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
697 # onhand - as above, but masking the simple itemstatus results (doh!)
699 # search by overrides of description
701 # disabled sanity checks and changes:
702 # - searchitems = assembly will no longer disable bought
703 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
704 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
705 # - itemstatus = obsolete will no longer disable onhand, short
706 # - allow sorting by ean
707 # - serialnumber filter also works if l_serialnumber isn't ticked
708 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
711 $main::lxdebug->enter_sub();
713 my ($self, $myconfig, $form) = @_;
714 my $dbh = $form->get_standard_dbh($myconfig);
716 $form->{parts} = +{ };
717 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
719 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
720 my @project_filters = qw(projectnumber projectdescription);
721 my @makemodel_filters = qw(make model);
722 my @invoice_oi_filters = qw(serialnumber soldtotal);
723 my @apoe_filters = qw(transdate);
724 my @like_filters = (@simple_filters, @invoice_oi_filters);
725 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
726 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image));
727 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
728 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
729 my @deliverydate_flags = qw(deliverydate);
730 # my @other_flags = qw(onhand); # ToDO: implement these
731 # my @inactive_flags = qw(l_subtotal short l_linetotal);
733 my @select_tokens = qw(id factor);
734 my @where_tokens = qw(1=1);
735 my @group_tokens = ();
737 my %joins_needed = ();
740 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
741 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
742 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
745 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
746 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
747 ) AS ioi ON ioi.parts_id = p.id|,
750 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
751 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
752 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
753 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
756 SELECT id, name, 'customer' AS cv FROM customer UNION
757 SELECT id, name, 'vendor' AS cv FROM vendor
758 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
759 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
760 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
762 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
765 deliverydate => 'apoe.', serialnumber => 'ioi.',
766 transdate => 'apoe.', trans_id => 'ioi.',
767 module => 'apoe.', name => 'cv.',
768 ordnumber => 'apoe.', make => 'mm.',
769 quonumber => 'apoe.', model => 'mm.',
770 invnumber => 'apoe.', partsgroup => 'pg.',
771 lastcost => 'p.', , soldtotal => ' ',
772 factor => 'pfac.', projectnumber => 'pj.',
773 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
776 serialnumber => 'ioi.',
777 quotation => 'apoe.',
783 # if the join condition in these blocks are met, the column
784 # of the scecified table will gently override (coalesce actually) the original value
785 # use it to conditionally coalesce values from subtables
786 my @column_override = (
787 # column name, prefix, joins_needed, nick name (in case column is named like another)
788 [ 'description', 'ioi.', 'invoice_oi' ],
789 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
790 [ 'transdate', 'apoe.', 'apoe' ],
791 [ 'unit', 'ioi.', 'invoice_oi' ],
792 [ 'sellprice', 'ioi.', 'invoice_oi' ],
795 # careful with renames. these are HARD, and any filters done on the original column will break
796 my %renamed_columns = (
797 'factor' => 'price_factor',
798 'SUM(ioi.qty)' => 'soldtotal',
799 'ioi.id' => 'ioi_id',
801 'projectdescription' => 'projectdescription',
805 projectdescription => 'description',
808 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
809 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
812 my $make_token_builder = sub {
813 my $joins_needed = shift;
815 my ($nick, $alias) = @_;
816 my ($col) = $real_column{$nick} || $nick;
817 my @coalesce_tokens =
818 map { ($_->[1] || 'p.') . $_->[0] }
819 grep { !$_->[2] || $joins_needed->{$_->[2]} }
820 grep { ($_->[3] || $_->[0]) eq $nick }
821 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
823 my $coalesce = scalar @coalesce_tokens > 1;
825 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
826 : shift @coalesce_tokens)
827 . ($alias && ($coalesce || $renamed_columns{$nick})
828 ? " AS " . ($renamed_columns{$nick} || $nick)
833 #===== switches and simple filters ========#
835 # special case transdate
836 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
837 $form->{"l_transdate"} = 1;
838 push @select_tokens, 'transdate';
839 for (qw(transdatefrom transdateto)) {
840 next unless $form->{$_};
841 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
842 push @bind_vars, $form->{$_};
846 if ($form->{"partsgroup_id"}) {
847 $form->{"l_partsgroup"} = '1'; # show the column
848 push @where_tokens, "pg.id = ?";
849 push @bind_vars, $form->{"partsgroup_id"};
852 foreach (@like_filters) {
853 next unless $form->{$_};
854 $form->{"l_$_"} = '1'; # show the column
855 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
856 push @bind_vars, "%$form->{$_}%";
859 foreach (@simple_l_switches) {
860 next unless $form->{"l_$_"};
861 push @select_tokens, $_;
864 for ($form->{searchitems}) {
865 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
866 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
867 push @where_tokens, 'NOT p.assembly' if /service/;
868 push @where_tokens, ' p.assembly' if /assembly/;
871 for ($form->{itemstatus}) {
872 push @where_tokens, 'p.id NOT IN
873 (SELECT DISTINCT parts_id FROM invoice UNION
874 SELECT DISTINCT parts_id FROM assembly UNION
875 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
876 push @where_tokens, 'p.onhand = 0' if /orphaned/;
877 push @where_tokens, 'NOT p.obsolete' if /active/;
878 push @where_tokens, ' p.obsolete', if /obsolete/;
879 push @where_tokens, 'p.onhand > 0', if /onhand/;
880 push @where_tokens, 'p.onhand < p.rop', if /short/;
883 my $q_assembly_lastcost =
884 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
886 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
887 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
888 WHERE (a_lc.id = p.id)) AS lastcost|;
889 $table_prefix{$q_assembly_lastcost} = ' ';
891 # special case makemodel search
892 # all_parts is based upon the assumption that every parameter is named like the column it represents
893 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
894 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
896 push @where_tokens, 'mv.name ILIKE ?';
897 push @bind_vars, "%$form->{make}%";
899 if ($form->{model}) {
900 push @where_tokens, 'mm.model ILIKE ?';
901 push @bind_vars, "%$form->{model}%";
904 # special case: sorting by partnumber
905 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
906 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
907 # ToDO: implement proper functional sorting
908 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
909 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
910 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
911 # if $form->{sort} eq 'partnumber';
913 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
916 $limit_clause = " LIMIT 100" if $form->{top100};
917 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
919 #=== joins and complicated filters ========#
921 my $bsooqr = any { $form->{$_} } @oe_flags;
922 my @bsooqr_tokens = ();
924 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
925 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
926 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
927 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
928 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
929 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
930 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
931 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
932 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
933 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
935 $joins_needed{partsgroup} = 1;
936 $joins_needed{pfac} = 1;
937 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
938 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
939 $joins_needed{mv} = 1 if $joins_needed{makemodel};
940 $joins_needed{cv} = 1 if $bsooqr;
941 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
942 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
944 # special case for description search.
945 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
946 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
947 # find the old entries in of @where_tokens and @bind_vars, and adjust them
948 if ($joins_needed{invoice_oi}) {
949 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
950 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
951 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
952 splice @bind_vars, $bi, 0, $bind_vars[$bi];
957 # now the master trick: soldtotal.
958 if ($form->{l_soldtotal}) {
959 push @where_tokens, 'NOT ioi.qty = 0';
960 push @group_tokens, @select_tokens;
961 map { s/.*\sAS\s+//si } @group_tokens;
962 push @select_tokens, 'SUM(ioi.qty)';
965 #============= build query ================#
967 my $token_builder = $make_token_builder->(\%joins_needed);
969 my @sort_cols = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
970 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
971 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
972 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
974 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
975 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
976 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
977 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
979 my %oe_flag_to_cvar = (
982 onorder => 'orderitems',
983 ordered => 'orderitems',
985 quoted => 'orderitems',
988 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
990 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
992 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
996 $where_clause .= qq| AND ($cvar_where)|;
997 push @bind_vars, @cvar_values;
1000 my $query = <<" SQL";
1001 SELECT DISTINCT $select_clause
1010 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1012 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1014 # fix qty sign in ap. those are saved negative
1015 if ($bsooqr && $form->{bought}) {
1016 for my $row (@{ $form->{parts} }) {
1017 $row->{qty} *= -1 if $row->{module} eq 'ir';
1021 # post processing for assembly parts lists (bom)
1022 # for each part get the assembly parts and add them into the partlist.
1024 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1026 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1028 p.sellprice, p.listprice, p.lastcost,
1029 p.rop, p.weight, p.priceupdate,
1030 p.image, p.drawing, p.microfiche,
1033 INNER JOIN assembly a ON (p.id = a.parts_id)
1036 my $sth = prepare_query($form, $dbh, $query);
1038 foreach my $item (@{ $form->{parts} }) {
1039 push(@assemblies, $item);
1040 do_statement($form, $sth, $query, conv_i($item->{id}));
1042 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1043 $ref->{assemblyitem} = 1;
1044 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1045 push(@assemblies, $ref);
1050 # copy assemblies to $form->{parts}
1051 $form->{parts} = \@assemblies;
1054 if ($form->{l_pricegroups} ) {
1056 SELECT parts_id, price, pricegroup_id
1061 my $sth = prepare_query($form, $dbh, $query);
1063 foreach my $part (@{ $form->{parts} }) {
1064 do_statement($form, $sth, $query, conv_i($part->{id}));
1066 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1067 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1074 $main::lxdebug->leave_sub();
1076 return wantarray ? @{ $form->{parts} } : $form->{parts};
1079 sub _create_filter_for_priceupdate {
1080 $main::lxdebug->enter_sub();
1083 my $myconfig = \%main::myconfig;
1084 my $form = $main::form;
1087 my $where = '1 = 1';
1089 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1091 $column =~ s/.*\.//;
1092 next unless ($form->{$column});
1094 $where .= qq| AND $item ILIKE ?|;
1095 push(@where_values, '%' . $form->{$column} . '%');
1098 foreach my $item (qw(description serialnumber)) {
1099 next unless ($form->{$item});
1101 $where .= qq| AND (${item} ILIKE ?)|;
1102 push(@where_values, '%' . $form->{$item} . '%');
1106 # items which were never bought, sold or on an order
1107 if ($form->{itemstatus} eq 'orphaned') {
1109 qq| AND (p.onhand = 0)
1112 SELECT DISTINCT parts_id FROM invoice
1114 SELECT DISTINCT parts_id FROM assembly
1116 SELECT DISTINCT parts_id FROM orderitems
1119 } elsif ($form->{itemstatus} eq 'active') {
1120 $where .= qq| AND p.obsolete = '0'|;
1122 } elsif ($form->{itemstatus} eq 'obsolete') {
1123 $where .= qq| AND p.obsolete = '1'|;
1125 } elsif ($form->{itemstatus} eq 'onhand') {
1126 $where .= qq| AND p.onhand > 0|;
1128 } elsif ($form->{itemstatus} eq 'short') {
1129 $where .= qq| AND p.onhand < p.rop|;
1133 foreach my $column (qw(make model)) {
1134 next unless ($form->{$column});
1135 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1136 push(@where_values, '%' . $form->{$column} . '%');
1139 $main::lxdebug->leave_sub();
1141 return ($where, @where_values);
1144 sub get_num_matches_for_priceupdate {
1145 $main::lxdebug->enter_sub();
1149 my $myconfig = \%main::myconfig;
1150 my $form = $main::form;
1152 my $dbh = $form->get_standard_dbh($myconfig);
1154 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1156 my $num_updated = 0;
1159 for my $column (qw(sellprice listprice)) {
1160 next if ($form->{$column} eq "");
1168 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1170 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1171 $num_updated += $result if (0 <= $result);
1180 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1181 WHERE $where) AND (pricegroup_id = ?)|;
1182 my $sth = prepare_query($form, $dbh, $query);
1184 for my $i (1 .. $form->{price_rows}) {
1185 next if ($form->{"price_$i"} eq "");
1187 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1188 $num_updated += $result if (0 <= $result);
1192 $main::lxdebug->leave_sub();
1194 return $num_updated;
1198 $main::lxdebug->enter_sub();
1200 my ($self, $myconfig, $form) = @_;
1202 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1203 my $num_updated = 0;
1205 # connect to database
1206 my $dbh = $form->dbconnect_noauto($myconfig);
1208 for my $column (qw(sellprice listprice)) {
1209 next if ($form->{$column} eq "");
1211 my $value = $form->parse_amount($myconfig, $form->{$column});
1214 if ($form->{"${column}_type"} eq "percent") {
1215 $value = ($value / 100) + 1;
1220 qq|UPDATE parts SET $column = $column $operator ?
1224 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1226 my $result = do_query($form, $dbh, $query, $value, @where_values);
1227 $num_updated += $result if (0 <= $result);
1231 qq|UPDATE prices SET price = price + ?
1235 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1236 WHERE $where) AND (pricegroup_id = ?)|;
1237 my $sth_add = prepare_query($form, $dbh, $q_add);
1240 qq|UPDATE prices SET price = price * ?
1244 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1245 WHERE $where) AND (pricegroup_id = ?)|;
1246 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1248 for my $i (1 .. $form->{price_rows}) {
1249 next if ($form->{"price_$i"} eq "");
1251 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1254 if ($form->{"pricegroup_type_$i"} eq "percent") {
1255 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1257 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1260 $num_updated += $result if (0 <= $result);
1264 $sth_multiply->finish();
1266 my $rc= $dbh->commit;
1269 $main::lxdebug->leave_sub();
1271 return $num_updated;
1275 $main::lxdebug->enter_sub();
1277 my ($self, $module, $myconfig, $form) = @_;
1279 # connect to database
1280 my $dbh = $form->dbconnect($myconfig);
1282 my @values = ('%' . $module . '%');
1287 qq|SELECT c.accno, c.description, c.link, c.id,
1288 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1289 FROM chart c, parts p
1290 WHERE (c.link LIKE ?) AND (p.id = ?)
1292 push(@values, conv_i($form->{id}));
1296 qq|SELECT c.accno, c.description, c.link, c.id,
1297 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1298 FROM chart c, defaults d
1303 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1304 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1305 foreach my $key (split(/:/, $ref->{link})) {
1306 if ($key =~ /\Q$module\E/) {
1307 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1308 || ($ref->{id} eq $ref->{income_accno_id})
1309 || ($ref->{id} eq $ref->{expense_accno_id})) {
1310 push @{ $form->{"${module}_links"}{$key} },
1311 { accno => $ref->{accno},
1312 description => $ref->{description},
1313 selected => "selected" };
1314 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1316 push @{ $form->{"${module}_links"}{$key} },
1317 { accno => $ref->{accno},
1318 description => $ref->{description},
1326 # get buchungsgruppen
1327 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1330 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1333 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1337 $main::lxdebug->leave_sub();
1340 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1342 $main::lxdebug->enter_sub();
1344 my ($self, $myconfig, $form, $sortorder) = @_;
1345 my $dbh = $form->dbconnect($myconfig);
1346 my $order = qq| p.partnumber|;
1347 my $where = qq|1 = 1|;
1350 if ($sortorder eq "all") {
1351 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1352 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1354 } elsif ($sortorder eq "partnumber") {
1355 $where .= qq| AND (partnumber ILIKE ?)|;
1356 push(@values, '%' . $form->{partnumber} . '%');
1358 } elsif ($sortorder eq "description") {
1359 $where .= qq| AND (description ILIKE ?)|;
1360 push(@values, '%' . $form->{description} . '%');
1361 $order = "description";
1366 qq|SELECT id, partnumber, description, unit, sellprice
1368 WHERE $where ORDER BY $order|;
1370 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1373 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1374 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1379 $form->{"id_$j"} = $ref->{id};
1380 $form->{"partnumber_$j"} = $ref->{partnumber};
1381 $form->{"description_$j"} = $ref->{description};
1382 $form->{"unit_$j"} = $ref->{unit};
1383 $form->{"sellprice_$j"} = $ref->{sellprice};
1384 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1390 $main::lxdebug->leave_sub();
1395 # gets sum of sold part with part_id
1397 $main::lxdebug->enter_sub();
1399 my ($dbh, $id) = @_;
1401 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1402 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1405 $main::lxdebug->leave_sub();
1408 } #end get_soldtotal
1410 sub retrieve_languages {
1411 $main::lxdebug->enter_sub();
1413 my ($self, $myconfig, $form) = @_;
1415 # connect to database
1416 my $dbh = $form->dbconnect($myconfig);
1422 if ($form->{language_values} ne "") {
1424 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1426 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1427 ORDER BY lower(l.description)|;
1428 @values = (conv_i($form->{id}));
1431 $query = qq|SELECT id, description
1433 ORDER BY lower(description)|;
1436 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1440 $main::lxdebug->leave_sub();
1445 sub follow_account_chain {
1446 $main::lxdebug->enter_sub(2);
1448 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1450 my @visited_accno_ids = ($accno_id);
1454 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1455 map { $_->{id} => $_ }
1456 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1457 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1459 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1460 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1464 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1465 last unless ($ref && $ref->{"is_valid"} &&
1466 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1467 $accno_id = $ref->{"new_chart_id"};
1468 $accno = $ref->{"accno"};
1469 push(@visited_accno_ids, $accno_id);
1472 $main::lxdebug->leave_sub(2);
1474 return ($accno_id, $accno);
1477 sub retrieve_accounts {
1478 $main::lxdebug->enter_sub;
1481 my $myconfig = shift;
1483 my $dbh = $form->get_standard_dbh;
1484 my %args = @_; # index => part_id
1486 $form->{taxzone_id} *= 1;
1488 return unless grep $_, values %args; # shortfuse if no part_id supplied
1490 # transdate madness.
1492 if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
1493 # use deliverydate for sales and purchase invoice, if it exists
1494 # also use deliverydate for credit notes
1495 if (!$form->{deliverydate}) {
1496 $transdate = $form->{invdate};
1498 $transdate = $form->{deliverydate};
1500 } elsif ($form->{script} eq 'ir.pl') {
1501 # when a purchase invoice is opened from the report of purchase invoices
1502 # $form->{type} isn't set, but $form->{script} is, not sure why this is or
1503 # whether this distinction matters in some other scenario. Otherwise one
1504 # could probably take out this elsif and add a
1505 # " or $form->{script} eq 'ir.pl' "
1506 # to the above if-statement
1507 if (!$form->{deliverydate}) {
1508 $transdate = $form->{invdate};
1510 $transdate = $form->{deliverydate};
1512 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
1513 # if credit_note has a deliverydate, use this instead of invdate
1514 # useful for credit_notes of invoices from an old period with different tax
1515 # if there is no deliverydate then invdate is used, old default (see next elsif)
1516 # Falls hier der Stichtag für Steuern anders bestimmt wird,
1517 # entsprechend auch bei Taxkeys.pm anpassen
1518 $transdate = $form->{deliverydate};
1519 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1520 $transdate = $form->{invdate};
1522 $transdate = $form->{transdate};
1525 if ($transdate eq "") {
1526 $transdate = DateTime->today_local->to_lxoffice;
1528 $transdate = $dbh->quote($transdate);
1531 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1533 my @part_ids = grep { $_ } values %args;
1534 my $in = join ',', ('?') x @part_ids;
1536 my %accno_by_part = map { $_->{id} => $_ }
1537 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1539 p.id, p.inventory_accno_id AS is_part,
1540 bg.inventory_accno_id,
1541 bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
1542 bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
1543 c1.accno AS inventory_accno,
1544 c2.accno AS income_accno,
1545 c3.accno AS expense_accno
1547 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1548 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1549 LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
1550 LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
1554 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1555 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1557 LEFT JOIN chart c ON c.id = t.chart_id
1561 WHERE tk.chart_id = ? AND startdate <= ?
1562 ORDER BY startdate DESC LIMIT 1)
1565 while (my ($index => $part_id) = each %args) {
1566 my $ref = $accno_by_part{$part_id} or next;
1568 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1571 for my $type (qw(inventory income expense)) {
1572 next unless $ref->{"${type}_accno_id"};
1573 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1574 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1577 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1579 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1580 $ref = $sth_tax->fetchrow_hashref or next;
1582 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1583 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1585 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1590 $::lxdebug->leave_sub;
1593 sub get_basic_part_info {
1594 $main::lxdebug->enter_sub();
1599 Common::check_params(\%params, qw(id));
1601 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1604 $main::lxdebug->leave_sub();
1608 my $myconfig = \%main::myconfig;
1609 my $form = $main::form;
1611 my $dbh = $form->get_standard_dbh($myconfig);
1613 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1615 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1617 if ('' eq ref $params{id}) {
1618 $info = $info->[0] || { };
1620 $main::lxdebug->leave_sub();
1624 my %info_map = map { $_->{id} => $_ } @{ $info };
1626 $main::lxdebug->leave_sub();
1631 sub prepare_parts_for_printing {
1632 $main::lxdebug->enter_sub();
1637 my $myconfig = $params{myconfig} || \%main::myconfig;
1638 my $form = $params{form} || $main::form;
1640 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1642 my $prefix = $params{prefix} || 'id_';
1643 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1645 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1648 $main::lxdebug->leave_sub();
1652 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1653 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1655 LEFT JOIN vendor v ON (mm.make = v.id)
1656 WHERE mm.parts_id IN ($placeholders)|;
1660 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1662 while (my $ref = $sth->fetchrow_hashref()) {
1663 $makemodel{$ref->{parts_id}} ||= [];
1664 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1669 my @columns = qw(ean image microfiche drawing weight);
1671 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1673 WHERE id IN ($placeholders)|;
1675 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1677 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1679 foreach my $i (1 .. $rowcount) {
1680 my $id = $form->{"${prefix}${i}"};
1684 foreach (@columns) {
1685 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1688 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1689 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1691 next if (!$makemodel{$id});
1693 foreach my $ref (@{ $makemodel{$id} }) {
1694 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1698 $main::lxdebug->leave_sub();