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);
43 use SL::HTML::Restrict;
49 $main::lxdebug->enter_sub();
51 my ($self, $myconfig, $form) = @_;
54 my $dbh = $form->get_standard_dbh;
60 c1.accno AS inventory_accno,
61 c2.accno AS income_accno,
62 c3.accno AS expense_accno,
65 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
66 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
67 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
68 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
70 my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
72 # copy to $form variables
73 map { $form->{$_} = $ref->{$_} } (keys %{$ref});
75 $form->{mtime} = $form->{itime} if !$form->{mtime};
76 $form->{lastmtime} = $form->{mtime};
79 # part or service item
80 $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
81 if ($form->{assembly}) {
82 $form->{item} = 'assembly';
84 # retrieve assembly items
86 qq|SELECT p.id, p.partnumber, p.description,
87 p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
88 pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
90 JOIN assembly a ON (a.parts_id = p.id)
91 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
92 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
95 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
97 $form->{assembly_rows} = 0;
98 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
99 $form->{assembly_rows}++;
100 foreach my $key (keys %{$ref}) {
101 $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
108 # setup accno hash for <option checked> {amount} is used in create_links
109 $form->{amount}{IC} = $form->{inventory_accno};
110 $form->{amount}{IC_income} = $form->{income_accno};
111 $form->{amount}{IC_sale} = $form->{income_accno};
112 $form->{amount}{IC_expense} = $form->{expense_accno};
113 $form->{amount}{IC_cogs} = $form->{expense_accno};
117 SELECT pg.pricegroup, pg.id AS pricegroup_id, COALESCE(pr.price, 0) AS price
119 LEFT JOIN prices pr ON (pr.pricegroup_id = pg.id) AND (pr.parts_id = ?)
120 ORDER BY lower(pg.pricegroup)
124 foreach $ref (selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}))) {
125 $form->{"${_}_${row}"} = $ref->{$_} for qw(pricegroup_id pricegroup price);
128 $form->{price_rows} = $row - 1;
131 if ($form->{makemodel}) {
133 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
134 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
135 my @values = ($form->{id});
136 $sth = $dbh->prepare($query);
137 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
141 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
142 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
147 $form->{makemodel_rows} = $i - 1;
152 $query = qq|SELECT language_id, translation, longdescription
155 $form->{translations} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
158 my @referencing_tables = qw(invoice orderitems inventory);
159 my %column_map = ( );
160 my $parts_id = conv_i($form->{id});
162 $form->{orphaned} = 1;
164 foreach my $table (@referencing_tables) {
165 my $column = $column_map{$table} || 'parts_id';
166 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
167 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
170 $form->{orphaned} = 0;
175 $form->{"unit_changeable"} = $form->{orphaned};
177 Common::webdav_folder($form) if $::lx_office_conf{features}{webdav};
179 $main::lxdebug->leave_sub();
182 sub get_pricegroups {
183 $main::lxdebug->enter_sub();
185 my ($self, $myconfig, $form) = @_;
187 my $dbh = $form->get_standard_dbh;
190 my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
191 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
194 foreach my $pg (@{ $pricegroups }) {
195 $form->{"klass_$i"} = "$pg->{id}";
196 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
197 $form->{"pricegroup_id_$i"} = "$pg->{id}";
198 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
203 $form->{price_rows} = $i - 1;
205 $main::lxdebug->leave_sub();
210 sub retrieve_buchungsgruppen {
211 $main::lxdebug->enter_sub();
213 my ($self, $myconfig, $form) = @_;
217 my $dbh = $form->get_standard_dbh;
219 # get buchungsgruppen
220 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
221 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
223 $main::lxdebug->leave_sub();
227 $main::lxdebug->enter_sub();
229 my ($self, $myconfig, $form) = @_;
231 # connect to database, turn off AutoCommit
232 my $dbh = $form->get_standard_dbh;
233 my $restricter = SL::HTML::Restrict->create;
236 # make up a unique handle and store in partnumber field
237 # then retrieve the record based on the unique handle to get the id
238 # replace the partnumber field with the actual variable
239 # add records for makemodel
241 # if there is a $form->{id} then replace the old entry
242 # delete all makemodel entries and add the new ones
244 # undo amount formatting
245 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
246 qw(rop weight listprice sellprice gv lastcost);
248 my $makemodel = ($form->{make_1} || $form->{model_1} || ($form->{makemodel_rows} > 1)) ? 1 : 0;
250 $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
254 my $priceupdate = ', priceupdate = current_date';
257 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
258 if (!$trans_number->is_unique) {
259 $::lxdebug->leave_sub;
264 $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
265 my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
267 # if item is part of an assembly adjust all assemblies
268 $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
269 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
270 while (my ($id, $qty) = $sth->fetchrow_array) {
271 &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
275 # delete makemodel records
276 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
278 if ($form->{item} eq 'assembly') {
279 # delete assembly records
280 do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
283 # delete translations
284 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
286 # Check whether or not the prices have changed. If they haven't
287 # then 'priceupdate' should not be updated.
288 my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
289 $priceupdate = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
292 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, save => 1);
294 if ($form->{partnumber} && !$trans_number->is_unique) {
295 $::lxdebug->leave_sub;
299 $form->{partnumber} ||= $trans_number->create_unique;
301 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
302 do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit});
304 $form->{orphaned} = 1;
306 my $partsgroup_id = undef;
308 if ($form->{partsgroup}) {
309 (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
312 my ($subq_inventory, $subq_expense, $subq_income);
313 if ($form->{"item"} eq "part") {
315 qq|(SELECT bg.inventory_accno_id
316 FROM buchungsgruppen bg
317 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
319 $subq_inventory = "NULL";
322 if ($form->{"item"} ne "assembly") {
324 qq|(SELECT tc.expense_accno_id
325 FROM taxzone_charts tc
326 WHERE tc.buchungsgruppen_id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq| and tc.taxzone_id = 0)|;
328 $subq_expense = "NULL";
331 normalize_text_blocks();
350 buchungsgruppen_id = ?,
352 inventory_accno_id = $subq_inventory,
353 income_accno_id = (SELECT tc.income_accno_id FROM taxzone_charts tc WHERE tc.taxzone_id = 0 and tc.buchungsgruppen_id = ?),
354 expense_accno_id = $subq_expense,
363 not_discountable = ?,
369 @values = ($form->{partnumber},
370 $form->{description},
371 $makemodel ? 't' : 'f',
372 $form->{assembly} ? 't' : 'f',
378 $restricter->process($form->{notes}),
381 conv_i($form->{warehouse_id}),
382 conv_i($form->{bin_id}),
383 conv_i($form->{buchungsgruppen_id}),
384 conv_i($form->{payment_id}),
385 conv_i($form->{buchungsgruppen_id}),
386 $form->{obsolete} ? 't' : 'f',
389 $form->{shop} ? 't' : 'f',
393 $form->{has_sernumber} ? 't' : 'f',
394 $form->{not_discountable} ? 't' : 'f',
396 conv_i($partsgroup_id),
397 conv_i($form->{price_factor_id}),
400 do_query($form, $dbh, $query, @values);
402 # delete translation records
403 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
405 my @translations = grep { $_->{language_id} && $_->{translation} } @{ $form->{translations} || [] };
407 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
408 VALUES ( ?, ?, ?, ? )|;
409 $sth = $dbh->prepare($query);
411 foreach my $translation (@translations) {
412 do_statement($form, $sth, $query, conv_i($form->{id}), conv_i($translation->{language_id}), $translation->{translation}, $restricter->process($translation->{longdescription}));
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 for my $i (1 .. $form->{price_rows}) {
425 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
428 @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
429 do_statement($form, $sth, $query, @values);
434 # insert makemodel records
437 for my $i (1 .. $form->{makemodel_rows}) {
438 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
440 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
441 if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
443 if ($form->{"lastupdate_$i"} eq "") {
444 $lastupdate = 'now()';
446 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
449 $lastupdate = 'now()';
451 $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
452 qq|VALUES (?, ?, ?, ?, ?, ?)|;
453 @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
455 do_query($form, $dbh, $query, @values);
459 # add assembly records
460 if ($form->{item} eq 'assembly') {
461 # check additional assembly row
462 my $i = $form->{assembly_rows};
463 # if last row is not empty add them
464 if ($form->{"partnumber_$i"} ne "") {
465 $query = qq|SELECT id FROM parts WHERE partnumber = ?|;
466 my ($partid) = selectrow_query($form, $dbh, $query,$form->{"partnumber_$i"} );
468 $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
469 $form->{"id_$i"} = $partid;
470 $form->{"bom_$i"} = 0;
471 $form->{assembly_rows}++;
474 $::form->error($::locale->text("uncorrect partnumber ").$form->{"partnumber_$i"});
478 for my $i (1 .. $form->{assembly_rows}) {
479 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
481 if ($form->{"qty_$i"} != 0) {
482 $form->{"bom_$i"} *= 1;
483 $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
484 qq|VALUES (?, ?, ?, ?)|;
485 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
486 do_query($form, $dbh, $query, @values);
492 my $shippingdate = "$a[5]-$a[4]-$a[3]";
494 $form->get_employee($dbh);
498 #set expense_accno=inventory_accno if they are different => bilanz
500 ($form->{expense_accno} != $form->{inventory_accno})
501 ? $form->{inventory_accno}
502 : $form->{expense_accno};
504 # get tax rates and description
506 ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
508 qq|SELECT c.accno, c.description, t.rate, t.taxnumber
510 WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
512 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
514 $form->{taxaccount} = "";
515 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
516 $form->{taxaccount} .= "$ptr->{accno} ";
517 if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
518 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
519 $form->{"$ptr->{accno}_description"} = $ptr->{description};
520 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
521 $form->{taxaccount2} .= " $ptr->{accno} ";
525 CVar->save_custom_variables(dbh => $dbh,
527 trans_id => $form->{id},
531 # Delete saved custom variable values for configs that have been
532 # marked invalid for this part.
534 DELETE FROM custom_variables
535 WHERE (config_id IN (
537 FROM custom_variables_validity val
538 LEFT JOIN custom_variable_configs val_cfg ON (val.config_id = val_cfg.id)
539 WHERE (val_cfg.module = 'IC')
540 AND (val.trans_id = ?)))
543 do_query($form, $dbh, $query, ($form->{id}) x 2);
546 my $rc = $dbh->commit;
548 $main::lxdebug->leave_sub();
553 sub update_assembly {
554 $main::lxdebug->enter_sub();
556 my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
558 my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
559 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
561 while (my ($pid, $aqty) = $sth->fetchrow_array) {
562 &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
567 qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
569 my @values = ($qty * ($form->{sellprice} - $sellprice),
570 $qty * ($form->{weight} - $weight), conv_i($id));
571 do_query($form, $dbh, $query, @values);
573 $main::lxdebug->leave_sub();
576 sub retrieve_assemblies {
577 $main::lxdebug->enter_sub();
579 my ($self, $myconfig, $form) = @_;
581 # connect to database
582 my $dbh = $form->get_standard_dbh;
584 my $where = qq|NOT p.obsolete|;
587 if ($form->{partnumber}) {
588 $where .= qq| AND (p.partnumber ILIKE ?)|;
589 push(@values, '%' . $form->{partnumber} . '%');
592 if ($form->{description}) {
593 $where .= qq| AND (p.description ILIKE ?)|;
594 push(@values, '%' . $form->{description} . '%');
597 # retrieve assembly items
599 qq|SELECT p.id, p.partnumber, p.description,
601 (SELECT sum(p2.inventory_accno_id)
602 FROM parts p2, assembly a
603 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
605 WHERE NOT p.obsolete AND p.assembly $where|;
607 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
609 $main::lxdebug->leave_sub();
613 $main::lxdebug->enter_sub();
615 my ($self, $myconfig, $form) = @_;
616 my @values = (conv_i($form->{id}));
617 # connect to database, turn off AutoCommit
618 my $dbh = $form->get_standard_dbh;
620 my %columns = ( "assembly" => "id", "parts" => "id" );
622 for my $table (qw(prices makemodel inventory assembly translation parts)) {
623 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
624 do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
628 my $rc = $dbh->commit;
630 $main::lxdebug->leave_sub();
636 $main::lxdebug->enter_sub();
638 my ($self, $myconfig, $form) = @_;
640 my $i = $form->{assembly_rows};
642 my $where = qq|1 = 1|;
645 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
647 while (my ($column, $table) = each(%columns)) {
648 next unless ($form->{"${column}_$i"});
649 $where .= qq| AND ${table}.${column} ILIKE ?|;
650 push(@values, '%' . $form->{"${column}_$i"} . '%');
654 $where .= qq| AND NOT (p.id = ?)|;
655 push(@values, conv_i($form->{id}));
658 # Search for part ID overrides all other criteria.
659 if ($form->{"id_${i}"}) {
660 $where = qq|p.id = ?|;
661 @values = ($form->{"id_${i}"});
664 if ($form->{partnumber}) {
665 $where .= qq| ORDER BY p.partnumber|;
667 $where .= qq| ORDER BY p.description|;
670 # connect to database
671 my $dbh = $form->get_standard_dbh;
674 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
675 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
676 p.price_factor_id, pfac.factor AS price_factor, p.notes as longdescription
678 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
679 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
681 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
683 $main::lxdebug->leave_sub();
688 # Warning, deep magic ahead.
689 # This function gets all parts from the database according to the filters specified
692 # sort revers - sorting field + direction
695 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
696 # partnumber ean description partsgroup microfiche drawing
699 # 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
702 # itemstatus = active | onhand | short | obsolete | orphaned
703 # searchitems = part | assembly | service
706 # make model - makemodel
707 # serialnumber transdatefrom transdateto - invoice/orderitems
710 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
711 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
712 # l_soldtotal - aggreg join to display total of sold quantity
713 # onhand - as above, but masking the simple itemstatus results (doh!)
714 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
715 # l_serialnumber - belonges to serialnumber filter
716 # l_deliverydate - displays deliverydate is sold etc. flags are active
717 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
720 # onhand - as above, but masking the simple itemstatus results (doh!)
722 # search by overrides of description
724 # disabled sanity checks and changes:
725 # - searchitems = assembly will no longer disable bought
726 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
727 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
728 # - itemstatus = obsolete will no longer disable onhand, short
729 # - allow sorting by ean
730 # - serialnumber filter also works if l_serialnumber isn't ticked
731 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
734 $main::lxdebug->enter_sub();
736 my ($self, $myconfig, $form) = @_;
737 my $dbh = $form->get_standard_dbh($myconfig);
739 $form->{parts} = +{ };
740 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
742 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
743 my @project_filters = qw(projectnumber projectdescription);
744 my @makemodel_filters = qw(make model);
745 my @invoice_oi_filters = qw(serialnumber soldtotal);
746 my @apoe_filters = qw(transdate);
747 my @like_filters = (@simple_filters, @invoice_oi_filters);
748 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
749 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image shop insertdate));
750 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
751 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
752 my @deliverydate_flags = qw(deliverydate);
753 # my @other_flags = qw(onhand); # ToDO: implement these
754 # my @inactive_flags = qw(l_subtotal short l_linetotal);
756 my @select_tokens = qw(id factor);
757 my @where_tokens = qw(1=1);
758 my @group_tokens = ();
760 my %joins_needed = ();
763 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
764 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
765 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
768 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
769 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
770 ) AS ioi ON ioi.parts_id = p.id|,
773 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
774 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
775 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
776 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
779 SELECT id, name, 'customer' AS cv FROM customer UNION
780 SELECT id, name, 'vendor' AS cv FROM vendor
781 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
782 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
783 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
785 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
788 deliverydate => 'apoe.', serialnumber => 'ioi.',
789 transdate => 'apoe.', trans_id => 'ioi.',
790 module => 'apoe.', name => 'cv.',
791 ordnumber => 'apoe.', make => 'mm.',
792 quonumber => 'apoe.', model => 'mm.',
793 invnumber => 'apoe.', partsgroup => 'pg.',
794 lastcost => 'p.', , soldtotal => ' ',
795 factor => 'pfac.', projectnumber => 'pj.',
796 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
799 serialnumber => 'ioi.',
800 quotation => 'apoe.',
806 # if the join condition in these blocks are met, the column
807 # of the scecified table will gently override (coalesce actually) the original value
808 # use it to conditionally coalesce values from subtables
809 my @column_override = (
810 # column name, prefix, joins_needed, nick name (in case column is named like another)
811 [ 'description', 'ioi.', 'invoice_oi' ],
812 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
813 [ 'transdate', 'apoe.', 'apoe' ],
814 [ 'unit', 'ioi.', 'invoice_oi' ],
815 [ 'sellprice', 'ioi.', 'invoice_oi' ],
818 # careful with renames. these are HARD, and any filters done on the original column will break
819 my %renamed_columns = (
820 'factor' => 'price_factor',
821 'SUM(ioi.qty)' => 'soldtotal',
822 'ioi.id' => 'ioi_id',
824 'projectdescription' => 'projectdescription',
825 'insertdate' => 'insertdate',
829 projectdescription => 'description',
830 insertdate => 'itime::DATE',
833 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
834 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
837 my $make_token_builder = sub {
838 my $joins_needed = shift;
840 my ($nick, $alias) = @_;
841 my ($col) = $real_column{$nick} || $nick;
842 my @coalesce_tokens =
843 map { ($_->[1] || 'p.') . $_->[0] }
844 grep { !$_->[2] || $joins_needed->{$_->[2]} }
845 grep { ($_->[3] || $_->[0]) eq $nick }
846 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
848 my $coalesce = scalar @coalesce_tokens > 1;
850 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
851 : shift @coalesce_tokens)
852 . ($alias && ($coalesce || $renamed_columns{$nick})
853 ? " AS " . ($renamed_columns{$nick} || $nick)
858 #===== switches and simple filters ========#
860 # special case transdate
861 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
862 $form->{"l_transdate"} = 1;
863 push @select_tokens, 'transdate';
864 for (qw(transdatefrom transdateto)) {
865 next unless $form->{$_};
866 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
867 push @bind_vars, $form->{$_};
871 # special case insertdate
872 if (grep { $form->{$_} } qw(insertdatefrom insertdateto)) {
873 $form->{"l_insertdate"} = 1;
874 push @select_tokens, 'insertdate';
876 my $token_builder = $make_token_builder->();
877 my $token = $token_builder->('insertdate');
879 for (qw(insertdatefrom insertdateto)) {
880 next unless $form->{$_};
881 push @where_tokens, sprintf "$token %s ?", /from$/ ? '>=' : '<=';
882 push @bind_vars, $form->{$_};
886 if ($form->{"partsgroup_id"}) {
887 $form->{"l_partsgroup"} = '1'; # show the column
888 push @where_tokens, "pg.id = ?";
889 push @bind_vars, $form->{"partsgroup_id"};
892 if ($form->{shop} ne '') {
893 $form->{l_shop} = '1'; # show the column
894 if ($form->{shop} eq '0' || $form->{shop} eq 'f') {
895 push @where_tokens, 'NOT p.shop';
898 push @where_tokens, 'p.shop';
902 foreach (@like_filters) {
903 next unless $form->{$_};
904 $form->{"l_$_"} = '1'; # show the column
905 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
906 push @bind_vars, "%$form->{$_}%";
909 foreach (@simple_l_switches) {
910 next unless $form->{"l_$_"};
911 push @select_tokens, $_;
914 for ($form->{searchitems}) {
915 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
916 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
917 push @where_tokens, 'NOT p.assembly' if /service/;
918 push @where_tokens, ' p.assembly' if /assembly/;
921 for ($form->{itemstatus}) {
922 push @where_tokens, 'p.id NOT IN
923 (SELECT DISTINCT parts_id FROM invoice UNION
924 SELECT DISTINCT parts_id FROM assembly UNION
925 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
926 push @where_tokens, 'p.onhand = 0' if /orphaned/;
927 push @where_tokens, 'NOT p.obsolete' if /active/;
928 push @where_tokens, ' p.obsolete', if /obsolete/;
929 push @where_tokens, 'p.onhand > 0', if /onhand/;
930 push @where_tokens, 'p.onhand < p.rop', if /short/;
933 my $q_assembly_lastcost =
934 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
936 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
937 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
938 WHERE (a_lc.id = p.id)) AS lastcost|;
939 $table_prefix{$q_assembly_lastcost} = ' ';
941 # special case makemodel search
942 # all_parts is based upon the assumption that every parameter is named like the column it represents
943 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
944 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
946 push @where_tokens, 'mv.name ILIKE ?';
947 push @bind_vars, "%$form->{make}%";
949 if ($form->{model}) {
950 push @where_tokens, 'mm.model ILIKE ?';
951 push @bind_vars, "%$form->{model}%";
954 # special case: sorting by partnumber
955 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
956 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
957 # ToDO: implement proper functional sorting
958 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
959 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
960 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
961 # if $form->{sort} eq 'partnumber';
963 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
966 $limit_clause = " LIMIT 100" if $form->{top100};
967 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
969 #=== joins and complicated filters ========#
971 my $bsooqr = any { $form->{$_} } @oe_flags;
972 my @bsooqr_tokens = ();
974 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
975 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
976 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
977 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
978 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
979 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
980 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
981 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
982 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
983 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
985 $joins_needed{partsgroup} = 1;
986 $joins_needed{pfac} = 1;
987 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
988 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
989 $joins_needed{mv} = 1 if $joins_needed{makemodel};
990 $joins_needed{cv} = 1 if $bsooqr;
991 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
992 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
994 # special case for description search.
995 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
996 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
997 # find the old entries in of @where_tokens and @bind_vars, and adjust them
998 if ($joins_needed{invoice_oi}) {
999 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
1000 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
1001 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
1002 splice @bind_vars, $bi, 0, $bind_vars[$bi];
1007 # now the master trick: soldtotal.
1008 if ($form->{l_soldtotal}) {
1009 push @where_tokens, 'NOT ioi.qty = 0';
1010 push @group_tokens, @select_tokens;
1011 map { s/.*\sAS\s+//si } @group_tokens;
1012 push @select_tokens, 'SUM(ioi.qty)';
1015 #============= build query ================#
1017 my $token_builder = $make_token_builder->(\%joins_needed);
1019 my @sort_cols = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate insertdate shop));
1020 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
1021 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
1022 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
1024 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
1025 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
1026 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
1027 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
1029 my %oe_flag_to_cvar = (
1030 bought => 'invoice',
1032 onorder => 'orderitems',
1033 ordered => 'orderitems',
1034 rfq => 'orderitems',
1035 quoted => 'orderitems',
1038 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
1040 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1042 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1046 $where_clause .= qq| AND ($cvar_where)|;
1047 push @bind_vars, @cvar_values;
1050 my $query = <<" SQL";
1051 SELECT DISTINCT $select_clause
1060 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1062 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1064 # fix qty sign in ap. those are saved negative
1065 if ($bsooqr && $form->{bought}) {
1066 for my $row (@{ $form->{parts} }) {
1067 $row->{qty} *= -1 if $row->{module} eq 'ir';
1071 # post processing for assembly parts lists (bom)
1072 # for each part get the assembly parts and add them into the partlist.
1074 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1076 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1077 p.unit, p.notes, p.itime::DATE as insertdate,
1078 p.sellprice, p.listprice, p.lastcost,
1079 p.rop, p.weight, p.priceupdate,
1080 p.image, p.drawing, p.microfiche,
1083 INNER JOIN assembly a ON (p.id = a.parts_id)
1086 my $sth = prepare_query($form, $dbh, $query);
1088 foreach my $item (@{ $form->{parts} }) {
1089 push(@assemblies, $item);
1090 do_statement($form, $sth, $query, conv_i($item->{id}));
1092 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1093 $ref->{assemblyitem} = 1;
1094 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1095 push(@assemblies, $ref);
1100 # copy assemblies to $form->{parts}
1101 $form->{parts} = \@assemblies;
1104 if ($form->{l_pricegroups} ) {
1106 SELECT parts_id, price, pricegroup_id
1111 my $sth = prepare_query($form, $dbh, $query);
1113 foreach my $part (@{ $form->{parts} }) {
1114 do_statement($form, $sth, $query, conv_i($part->{id}));
1116 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1117 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1124 $main::lxdebug->leave_sub();
1126 return @{ $form->{parts} };
1129 sub _create_filter_for_priceupdate {
1130 $main::lxdebug->enter_sub();
1133 my $myconfig = \%main::myconfig;
1134 my $form = $main::form;
1137 my $where = '1 = 1';
1139 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1141 $column =~ s/.*\.//;
1142 next unless ($form->{$column});
1144 $where .= qq| AND $item ILIKE ?|;
1145 push(@where_values, '%' . $form->{$column} . '%');
1148 foreach my $item (qw(description serialnumber)) {
1149 next unless ($form->{$item});
1151 $where .= qq| AND (${item} ILIKE ?)|;
1152 push(@where_values, '%' . $form->{$item} . '%');
1156 # items which were never bought, sold or on an order
1157 if ($form->{itemstatus} eq 'orphaned') {
1159 qq| AND (p.onhand = 0)
1162 SELECT DISTINCT parts_id FROM invoice
1164 SELECT DISTINCT parts_id FROM assembly
1166 SELECT DISTINCT parts_id FROM orderitems
1169 } elsif ($form->{itemstatus} eq 'active') {
1170 $where .= qq| AND p.obsolete = '0'|;
1172 } elsif ($form->{itemstatus} eq 'obsolete') {
1173 $where .= qq| AND p.obsolete = '1'|;
1175 } elsif ($form->{itemstatus} eq 'onhand') {
1176 $where .= qq| AND p.onhand > 0|;
1178 } elsif ($form->{itemstatus} eq 'short') {
1179 $where .= qq| AND p.onhand < p.rop|;
1183 foreach my $column (qw(make model)) {
1184 next unless ($form->{$column});
1185 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1186 push(@where_values, '%' . $form->{$column} . '%');
1189 $main::lxdebug->leave_sub();
1191 return ($where, @where_values);
1194 sub get_num_matches_for_priceupdate {
1195 $main::lxdebug->enter_sub();
1199 my $myconfig = \%main::myconfig;
1200 my $form = $main::form;
1202 my $dbh = $form->get_standard_dbh($myconfig);
1204 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1206 my $num_updated = 0;
1209 for my $column (qw(sellprice listprice)) {
1210 next if ($form->{$column} eq "");
1218 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1220 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1221 $num_updated += $result if (0 <= $result);
1230 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1231 WHERE $where) AND (pricegroup_id = ?)|;
1232 my $sth = prepare_query($form, $dbh, $query);
1234 for my $i (1 .. $form->{price_rows}) {
1235 next if ($form->{"price_$i"} eq "");
1237 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1238 $num_updated += $result if (0 <= $result);
1242 $main::lxdebug->leave_sub();
1244 return $num_updated;
1248 $main::lxdebug->enter_sub();
1250 my ($self, $myconfig, $form) = @_;
1252 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1253 my $num_updated = 0;
1255 # connect to database
1256 my $dbh = $form->get_standard_dbh;
1258 for my $column (qw(sellprice listprice)) {
1259 next if ($form->{$column} eq "");
1261 my $value = $form->parse_amount($myconfig, $form->{$column});
1264 if ($form->{"${column}_type"} eq "percent") {
1265 $value = ($value / 100) + 1;
1270 qq|UPDATE parts SET $column = $column $operator ?
1274 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1276 my $result = do_query($form, $dbh, $query, $value, @where_values);
1277 $num_updated += $result if (0 <= $result);
1281 qq|UPDATE prices SET price = price + ?
1285 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1286 WHERE $where) AND (pricegroup_id = ?)|;
1287 my $sth_add = prepare_query($form, $dbh, $q_add);
1290 qq|UPDATE prices SET price = price * ?
1294 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1295 WHERE $where) AND (pricegroup_id = ?)|;
1296 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1298 for my $i (1 .. $form->{price_rows}) {
1299 next if ($form->{"price_$i"} eq "");
1301 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1304 if ($form->{"pricegroup_type_$i"} eq "percent") {
1305 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1307 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1310 $num_updated += $result if (0 <= $result);
1314 $sth_multiply->finish();
1316 my $rc= $dbh->commit;
1318 $main::lxdebug->leave_sub();
1320 return $num_updated;
1324 $main::lxdebug->enter_sub();
1326 my ($self, $module, $myconfig, $form) = @_;
1328 # connect to database
1329 my $dbh = $form->get_standard_dbh;
1331 my @values = ('%' . $module . '%');
1336 qq|SELECT c.accno, c.description, c.link, c.id,
1337 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1338 FROM chart c, parts p
1339 WHERE (c.link LIKE ?) AND (p.id = ?)
1341 push(@values, conv_i($form->{id}));
1345 qq|SELECT c.accno, c.description, c.link, c.id,
1346 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1347 FROM chart c, defaults d
1352 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1353 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1354 foreach my $key (split(/:/, $ref->{link})) {
1355 if ($key =~ /\Q$module\E/) {
1356 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1357 || ($ref->{id} eq $ref->{income_accno_id})
1358 || ($ref->{id} eq $ref->{expense_accno_id})) {
1359 push @{ $form->{"${module}_links"}{$key} },
1360 { accno => $ref->{accno},
1361 description => $ref->{description},
1362 selected => "selected" };
1363 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1365 push @{ $form->{"${module}_links"}{$key} },
1366 { accno => $ref->{accno},
1367 description => $ref->{description},
1375 # get buchungsgruppen
1376 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1379 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1382 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1385 $main::lxdebug->leave_sub();
1388 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1390 $main::lxdebug->enter_sub();
1392 my ($self, $myconfig, $form, $sortorder) = @_;
1393 my $dbh = $form->get_standard_dbh;
1394 my $order = qq| p.partnumber|;
1395 my $where = qq|1 = 1|;
1398 if ($sortorder eq "all") {
1399 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1400 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1402 } elsif ($sortorder eq "partnumber") {
1403 $where .= qq| AND (partnumber ILIKE ?)|;
1404 push(@values, '%' . $form->{partnumber} . '%');
1406 } elsif ($sortorder eq "description") {
1407 $where .= qq| AND (description ILIKE ?)|;
1408 push(@values, '%' . $form->{description} . '%');
1409 $order = "description";
1414 qq|SELECT id, partnumber, description, unit, sellprice
1416 WHERE $where ORDER BY $order|;
1418 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1421 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1422 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1427 $form->{"id_$j"} = $ref->{id};
1428 $form->{"partnumber_$j"} = $ref->{partnumber};
1429 $form->{"description_$j"} = $ref->{description};
1430 $form->{"unit_$j"} = $ref->{unit};
1431 $form->{"sellprice_$j"} = $ref->{sellprice};
1432 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1437 $main::lxdebug->leave_sub();
1442 # gets sum of sold part with part_id
1444 $main::lxdebug->enter_sub();
1446 my ($dbh, $id) = @_;
1448 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1449 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1452 $main::lxdebug->leave_sub();
1455 } #end get_soldtotal
1457 sub retrieve_languages {
1458 $main::lxdebug->enter_sub();
1460 my ($self, $myconfig, $form) = @_;
1462 # connect to database
1463 my $dbh = $form->get_standard_dbh;
1469 if ($form->{language_values} ne "") {
1471 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1473 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1474 ORDER BY lower(l.description)|;
1475 @values = (conv_i($form->{id}));
1478 $query = qq|SELECT id, description
1480 ORDER BY lower(description)|;
1483 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1485 $main::lxdebug->leave_sub();
1490 sub follow_account_chain {
1491 $main::lxdebug->enter_sub(2);
1493 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1495 my @visited_accno_ids = ($accno_id);
1499 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1500 map { $_->{id} => $_ }
1501 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1502 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1504 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1505 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1509 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1510 last unless ($ref && $ref->{"is_valid"} &&
1511 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1512 $accno_id = $ref->{"new_chart_id"};
1513 $accno = $ref->{"accno"};
1514 push(@visited_accno_ids, $accno_id);
1517 $main::lxdebug->leave_sub(2);
1519 return ($accno_id, $accno);
1522 sub retrieve_accounts {
1523 $main::lxdebug->enter_sub;
1526 my $myconfig = shift;
1528 my $dbh = $form->get_standard_dbh;
1529 my %args = @_; # index => part_id
1531 $form->{taxzone_id} *= 1;
1533 return unless grep $_, values %args; # shortfuse if no part_id supplied
1535 # transdate madness.
1537 if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
1538 # use deliverydate for sales and purchase invoice, if it exists
1539 # also use deliverydate for credit notes
1540 if (!$form->{deliverydate}) {
1541 $transdate = $form->{invdate};
1543 $transdate = $form->{deliverydate};
1545 } elsif ($form->{script} eq 'ir.pl') {
1546 # when a purchase invoice is opened from the report of purchase invoices
1547 # $form->{type} isn't set, but $form->{script} is, not sure why this is or
1548 # whether this distinction matters in some other scenario. Otherwise one
1549 # could probably take out this elsif and add a
1550 # " or $form->{script} eq 'ir.pl' "
1551 # to the above if-statement
1552 if (!$form->{deliverydate}) {
1553 $transdate = $form->{invdate};
1555 $transdate = $form->{deliverydate};
1557 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
1558 # if credit_note has a deliverydate, use this instead of invdate
1559 # useful for credit_notes of invoices from an old period with different tax
1560 # if there is no deliverydate then invdate is used, old default (see next elsif)
1561 # Falls hier der Stichtag für Steuern anders bestimmt wird,
1562 # entsprechend auch bei Taxkeys.pm anpassen
1563 $transdate = $form->{deliverydate};
1564 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1565 $transdate = $form->{invdate};
1567 $transdate = $form->{transdate};
1570 if ($transdate eq "") {
1571 $transdate = DateTime->today_local->to_lxoffice;
1573 $transdate = $dbh->quote($transdate);
1576 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1578 my @part_ids = grep { $_ } values %args;
1579 my $in = join ',', ('?') x @part_ids;
1581 my %accno_by_part = map { $_->{id} => $_ }
1582 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1584 p.id, p.inventory_accno_id AS is_part,
1585 bg.inventory_accno_id,
1586 tc.income_accno_id AS income_accno_id,
1587 tc.expense_accno_id AS expense_accno_id,
1588 c1.accno AS inventory_accno,
1589 c2.accno AS income_accno,
1590 c3.accno AS expense_accno
1592 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1593 LEFT JOIN taxzone_charts tc on bg.id = tc.buchungsgruppen_id
1594 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1595 LEFT JOIN chart c2 ON tc.income_accno_id = c2.id
1596 LEFT JOIN chart c3 ON tc.expense_accno_id = c3.id
1598 tc.taxzone_id = '$form->{taxzone_id}'
1603 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1604 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1606 LEFT JOIN chart c ON c.id = t.chart_id
1610 WHERE tk.chart_id = ? AND startdate <= ?
1611 ORDER BY startdate DESC LIMIT 1)
1614 while (my ($index => $part_id) = each %args) {
1615 my $ref = $accno_by_part{$part_id} or next;
1617 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1620 for my $type (qw(inventory income expense)) {
1621 next unless $ref->{"${type}_accno_id"};
1622 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1623 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1626 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1628 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1629 $ref = $sth_tax->fetchrow_hashref or next;
1631 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1632 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1634 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1639 $::lxdebug->leave_sub;
1642 sub get_basic_part_info {
1643 $main::lxdebug->enter_sub();
1648 Common::check_params(\%params, qw(id));
1650 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1653 $main::lxdebug->leave_sub();
1657 my $myconfig = \%main::myconfig;
1658 my $form = $main::form;
1660 my $dbh = $form->get_standard_dbh($myconfig);
1662 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1664 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1666 if ('' eq ref $params{id}) {
1667 $info = $info->[0] || { };
1669 $main::lxdebug->leave_sub();
1673 my %info_map = map { $_->{id} => $_ } @{ $info };
1675 $main::lxdebug->leave_sub();
1680 sub prepare_parts_for_printing {
1681 $main::lxdebug->enter_sub();
1686 my $myconfig = $params{myconfig} || \%main::myconfig;
1687 my $form = $params{form} || $main::form;
1689 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1691 my $prefix = $params{prefix} || 'id_';
1692 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1694 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1697 $main::lxdebug->leave_sub();
1701 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1702 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1704 LEFT JOIN vendor v ON (mm.make = v.id)
1705 WHERE mm.parts_id IN ($placeholders)|;
1709 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1711 while (my $ref = $sth->fetchrow_hashref()) {
1712 $makemodel{$ref->{parts_id}} ||= [];
1713 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1718 my @columns = qw(ean image microfiche drawing);
1720 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1722 WHERE id IN ($placeholders)|;
1724 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1726 my %template_arrays;
1727 map { $template_arrays{$_} = [] } (qw(make model), @columns);
1729 foreach my $i (1 .. $rowcount) {
1730 my $id = $form->{"${prefix}${i}"};
1734 foreach (@columns) {
1735 push @{ $template_arrays{$_} }, $data{$id}->{$_};
1738 push @{ $template_arrays{make} }, [];
1739 push @{ $template_arrays{model} }, [];
1741 next if (!$makemodel{$id});
1743 foreach my $ref (@{ $makemodel{$id} }) {
1744 map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(make model);
1748 my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
1749 my %parts_by_id = map { $_->id => $_ } @$parts;
1751 for my $i (1..$rowcount) {
1752 my $id = $form->{"${prefix}${i}"};
1755 push @{ $template_arrays{part_type} }, $parts_by_id{$id}->type;
1758 return %template_arrays;
1759 $main::lxdebug->leave_sub();
1762 sub normalize_text_blocks {
1763 $main::lxdebug->enter_sub();
1768 my $form = $params{form} || $main::form;
1770 # check if feature is enabled (select normalize_part_descriptions from defaults)
1771 return unless ($::instance_conf->get_normalize_part_descriptions);
1773 foreach (qw(description notes)) {
1774 $form->{$_} =~ s/\s+$//s;
1775 $form->{$_} =~ s/^\s+//s;
1776 $form->{$_} =~ s/ {2,}/ /g;
1778 $main::lxdebug->leave_sub();