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});
77 # part or service item
78 $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
79 if ($form->{assembly}) {
80 $form->{item} = 'assembly';
82 # retrieve assembly items
84 qq|SELECT p.id, p.partnumber, p.description,
85 p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
86 pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
88 JOIN assembly a ON (a.parts_id = p.id)
89 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
90 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
93 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
95 $form->{assembly_rows} = 0;
96 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
97 $form->{assembly_rows}++;
98 foreach my $key (keys %{$ref}) {
99 $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
106 # setup accno hash for <option checked> {amount} is used in create_links
107 $form->{amount}{IC} = $form->{inventory_accno};
108 $form->{amount}{IC_income} = $form->{income_accno};
109 $form->{amount}{IC_sale} = $form->{income_accno};
110 $form->{amount}{IC_expense} = $form->{expense_accno};
111 $form->{amount}{IC_cogs} = $form->{expense_accno};
115 SELECT pg.pricegroup, pg.id AS pricegroup_id, COALESCE(pr.price, 0) AS price
117 LEFT JOIN prices pr ON (pr.pricegroup_id = pg.id) AND (pr.parts_id = ?)
118 ORDER BY lower(pg.pricegroup)
122 foreach $ref (selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}))) {
123 $form->{"${_}_${row}"} = $ref->{$_} for qw(pricegroup_id pricegroup price);
126 $form->{price_rows} = $row - 1;
129 if ($form->{makemodel}) {
131 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
132 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
133 my @values = ($form->{id});
134 $sth = $dbh->prepare($query);
135 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
139 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
140 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
145 $form->{makemodel_rows} = $i - 1;
150 $query = qq|SELECT language_id, translation, longdescription
153 $form->{translations} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
156 my @referencing_tables = qw(invoice orderitems inventory);
157 my %column_map = ( );
158 my $parts_id = conv_i($form->{id});
160 $form->{orphaned} = 1;
162 foreach my $table (@referencing_tables) {
163 my $column = $column_map{$table} || 'parts_id';
164 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
165 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
168 $form->{orphaned} = 0;
173 $form->{"unit_changeable"} = $form->{orphaned};
175 Common::webdav_folder($form) if $::lx_office_conf{features}{webdav};
177 $main::lxdebug->leave_sub();
180 sub get_pricegroups {
181 $main::lxdebug->enter_sub();
183 my ($self, $myconfig, $form) = @_;
185 my $dbh = $form->get_standard_dbh;
188 my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
189 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
192 foreach my $pg (@{ $pricegroups }) {
193 $form->{"klass_$i"} = "$pg->{id}";
194 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
195 $form->{"pricegroup_id_$i"} = "$pg->{id}";
196 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
201 $form->{price_rows} = $i - 1;
203 $main::lxdebug->leave_sub();
208 sub retrieve_buchungsgruppen {
209 $main::lxdebug->enter_sub();
211 my ($self, $myconfig, $form) = @_;
215 my $dbh = $form->get_standard_dbh;
217 # get buchungsgruppen
218 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
219 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
221 $main::lxdebug->leave_sub();
225 $main::lxdebug->enter_sub();
227 my ($self, $myconfig, $form) = @_;
229 # connect to database, turn off AutoCommit
230 my $dbh = $form->get_standard_dbh;
231 my $restricter = SL::HTML::Restrict->create;
234 # make up a unique handle and store in partnumber field
235 # then retrieve the record based on the unique handle to get the id
236 # replace the partnumber field with the actual variable
237 # add records for makemodel
239 # if there is a $form->{id} then replace the old entry
240 # delete all makemodel entries and add the new ones
242 # undo amount formatting
243 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
244 qw(rop weight listprice sellprice gv lastcost);
246 my $makemodel = ($form->{make_1} || $form->{model_1} || ($form->{makemodel_rows} > 1)) ? 1 : 0;
248 $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
252 my $priceupdate = ', priceupdate = current_date';
255 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
256 if (!$trans_number->is_unique) {
257 $::lxdebug->leave_sub;
262 $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
263 my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
265 # if item is part of an assembly adjust all assemblies
266 $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
267 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
268 while (my ($id, $qty) = $sth->fetchrow_array) {
269 &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
273 # delete makemodel records
274 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
276 if ($form->{item} eq 'assembly') {
277 # delete assembly records
278 do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
281 # delete translations
282 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
284 # Check whether or not the prices have changed. If they haven't
285 # then 'priceupdate' should not be updated.
286 my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
287 $priceupdate = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
290 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, save => 1);
292 if ($form->{partnumber} && !$trans_number->is_unique) {
293 $::lxdebug->leave_sub;
297 $form->{partnumber} ||= $trans_number->create_unique;
299 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
300 do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit});
302 $form->{orphaned} = 1;
304 my $partsgroup_id = undef;
306 if ($form->{partsgroup}) {
307 (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
310 my ($subq_inventory, $subq_expense, $subq_income);
311 if ($form->{"item"} eq "part") {
313 qq|(SELECT bg.inventory_accno_id
314 FROM buchungsgruppen bg
315 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
317 $subq_inventory = "NULL";
320 if ($form->{"item"} ne "assembly") {
322 qq|(SELECT tc.expense_accno_id
323 FROM taxzone_charts tc
324 WHERE tc.buchungsgruppen_id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq| and tc.taxzone_id = 0)|;
326 $subq_expense = "NULL";
329 normalize_text_blocks();
348 buchungsgruppen_id = ?,
350 inventory_accno_id = $subq_inventory,
351 income_accno_id = (SELECT tc.income_accno_id FROM taxzone_charts tc WHERE tc.taxzone_id = 0 and tc.buchungsgruppen_id = ?),
352 expense_accno_id = $subq_expense,
361 not_discountable = ?,
367 @values = ($form->{partnumber},
368 $form->{description},
369 $makemodel ? 't' : 'f',
370 $form->{assembly} ? 't' : 'f',
376 $restricter->process($form->{notes}),
379 conv_i($form->{warehouse_id}),
380 conv_i($form->{bin_id}),
381 conv_i($form->{buchungsgruppen_id}),
382 conv_i($form->{payment_id}),
383 conv_i($form->{buchungsgruppen_id}),
384 $form->{obsolete} ? 't' : 'f',
387 $form->{shop} ? 't' : 'f',
391 $form->{has_sernumber} ? 't' : 'f',
392 $form->{not_discountable} ? 't' : 'f',
394 conv_i($partsgroup_id),
395 conv_i($form->{price_factor_id}),
398 do_query($form, $dbh, $query, @values);
400 # delete translation records
401 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
403 my @translations = grep { $_->{language_id} && $_->{translation} } @{ $form->{translations} || [] };
405 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
406 VALUES ( ?, ?, ?, ? )|;
407 $sth = $dbh->prepare($query);
409 foreach my $translation (@translations) {
410 do_statement($form, $sth, $query, conv_i($form->{id}), conv_i($translation->{language_id}), $translation->{translation}, $restricter->process($translation->{longdescription}));
416 # delete price records
417 do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
419 $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) VALUES(?, ?, ?)|;
420 $sth = prepare_query($form, $dbh, $query);
422 for my $i (1 .. $form->{price_rows}) {
423 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
426 @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
427 do_statement($form, $sth, $query, @values);
432 # insert makemodel records
435 for my $i (1 .. $form->{makemodel_rows}) {
436 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
438 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
439 if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
441 if ($form->{"lastupdate_$i"} eq "") {
442 $lastupdate = 'now()';
444 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
447 $lastupdate = 'now()';
449 $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
450 qq|VALUES (?, ?, ?, ?, ?, ?)|;
451 @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
453 do_query($form, $dbh, $query, @values);
457 # add assembly records
458 if ($form->{item} eq 'assembly') {
459 # check additional assembly row
460 my $i = $form->{assembly_rows};
461 # if last row is not empty add them
462 if ($form->{"partnumber_$i"} ne "") {
463 $query = qq|SELECT id FROM parts WHERE partnumber = ?|;
464 my ($partid) = selectrow_query($form, $dbh, $query,$form->{"partnumber_$i"} );
466 $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
467 $form->{"id_$i"} = $partid;
468 $form->{"bom_$i"} = 0;
469 $form->{assembly_rows}++;
472 $::form->error($::locale->text("uncorrect partnumber ").$form->{"partnumber_$i"});
476 for my $i (1 .. $form->{assembly_rows}) {
477 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
479 if ($form->{"qty_$i"} != 0) {
480 $form->{"bom_$i"} *= 1;
481 $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
482 qq|VALUES (?, ?, ?, ?)|;
483 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
484 do_query($form, $dbh, $query, @values);
490 my $shippingdate = "$a[5]-$a[4]-$a[3]";
492 $form->get_employee($dbh);
496 #set expense_accno=inventory_accno if they are different => bilanz
498 ($form->{expense_accno} != $form->{inventory_accno})
499 ? $form->{inventory_accno}
500 : $form->{expense_accno};
502 # get tax rates and description
504 ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
506 qq|SELECT c.accno, c.description, t.rate, t.taxnumber
508 WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
510 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
512 $form->{taxaccount} = "";
513 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
514 $form->{taxaccount} .= "$ptr->{accno} ";
515 if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
516 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
517 $form->{"$ptr->{accno}_description"} = $ptr->{description};
518 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
519 $form->{taxaccount2} .= " $ptr->{accno} ";
523 CVar->save_custom_variables(dbh => $dbh,
525 trans_id => $form->{id},
530 my $rc = $dbh->commit;
532 $main::lxdebug->leave_sub();
537 sub update_assembly {
538 $main::lxdebug->enter_sub();
540 my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
542 my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
543 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
545 while (my ($pid, $aqty) = $sth->fetchrow_array) {
546 &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
551 qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
553 my @values = ($qty * ($form->{sellprice} - $sellprice),
554 $qty * ($form->{weight} - $weight), conv_i($id));
555 do_query($form, $dbh, $query, @values);
557 $main::lxdebug->leave_sub();
560 sub retrieve_assemblies {
561 $main::lxdebug->enter_sub();
563 my ($self, $myconfig, $form) = @_;
565 # connect to database
566 my $dbh = $form->get_standard_dbh;
568 my $where = qq|NOT p.obsolete|;
571 if ($form->{partnumber}) {
572 $where .= qq| AND (p.partnumber ILIKE ?)|;
573 push(@values, '%' . $form->{partnumber} . '%');
576 if ($form->{description}) {
577 $where .= qq| AND (p.description ILIKE ?)|;
578 push(@values, '%' . $form->{description} . '%');
581 # retrieve assembly items
583 qq|SELECT p.id, p.partnumber, p.description,
585 (SELECT sum(p2.inventory_accno_id)
586 FROM parts p2, assembly a
587 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
589 WHERE NOT p.obsolete AND p.assembly $where|;
591 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
593 $main::lxdebug->leave_sub();
597 $main::lxdebug->enter_sub();
599 my ($self, $myconfig, $form) = @_;
600 my @values = (conv_i($form->{id}));
601 # connect to database, turn off AutoCommit
602 my $dbh = $form->get_standard_dbh;
604 my %columns = ( "assembly" => "id", "parts" => "id" );
606 for my $table (qw(prices makemodel inventory assembly translation parts)) {
607 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
608 do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
612 my $rc = $dbh->commit;
614 $main::lxdebug->leave_sub();
620 $main::lxdebug->enter_sub();
622 my ($self, $myconfig, $form) = @_;
624 my $i = $form->{assembly_rows};
626 my $where = qq|1 = 1|;
629 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
631 while (my ($column, $table) = each(%columns)) {
632 next unless ($form->{"${column}_$i"});
633 $where .= qq| AND ${table}.${column} ILIKE ?|;
634 push(@values, '%' . $form->{"${column}_$i"} . '%');
638 $where .= qq| AND NOT (p.id = ?)|;
639 push(@values, conv_i($form->{id}));
642 # Search for part ID overrides all other criteria.
643 if ($form->{"id_${i}"}) {
644 $where = qq|p.id = ?|;
645 @values = ($form->{"id_${i}"});
648 if ($form->{partnumber}) {
649 $where .= qq| ORDER BY p.partnumber|;
651 $where .= qq| ORDER BY p.description|;
654 # connect to database
655 my $dbh = $form->get_standard_dbh;
658 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
659 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
660 p.price_factor_id, pfac.factor AS price_factor
662 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
663 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
665 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
667 $main::lxdebug->leave_sub();
672 # Warning, deep magic ahead.
673 # This function gets all parts from the database according to the filters specified
676 # sort revers - sorting field + direction
679 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
680 # partnumber ean description partsgroup microfiche drawing
683 # 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
686 # itemstatus = active | onhand | short | obsolete | orphaned
687 # searchitems = part | assembly | service
690 # make model - makemodel
691 # serialnumber transdatefrom transdateto - invoice/orderitems
694 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
695 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
696 # l_soldtotal - aggreg join to display total of sold quantity
697 # onhand - as above, but masking the simple itemstatus results (doh!)
698 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
699 # l_serialnumber - belonges to serialnumber filter
700 # l_deliverydate - displays deliverydate is sold etc. flags are active
701 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
704 # onhand - as above, but masking the simple itemstatus results (doh!)
706 # search by overrides of description
708 # disabled sanity checks and changes:
709 # - searchitems = assembly will no longer disable bought
710 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
711 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
712 # - itemstatus = obsolete will no longer disable onhand, short
713 # - allow sorting by ean
714 # - serialnumber filter also works if l_serialnumber isn't ticked
715 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
718 $main::lxdebug->enter_sub();
720 my ($self, $myconfig, $form) = @_;
721 my $dbh = $form->get_standard_dbh($myconfig);
723 $form->{parts} = +{ };
724 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
726 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
727 my @project_filters = qw(projectnumber projectdescription);
728 my @makemodel_filters = qw(make model);
729 my @invoice_oi_filters = qw(serialnumber soldtotal);
730 my @apoe_filters = qw(transdate);
731 my @like_filters = (@simple_filters, @invoice_oi_filters);
732 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
733 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image));
734 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
735 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
736 my @deliverydate_flags = qw(deliverydate);
737 # my @other_flags = qw(onhand); # ToDO: implement these
738 # my @inactive_flags = qw(l_subtotal short l_linetotal);
740 my @select_tokens = qw(id factor);
741 my @where_tokens = qw(1=1);
742 my @group_tokens = ();
744 my %joins_needed = ();
747 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
748 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
749 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
752 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
753 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
754 ) AS ioi ON ioi.parts_id = p.id|,
757 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
758 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
759 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
760 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
763 SELECT id, name, 'customer' AS cv FROM customer UNION
764 SELECT id, name, 'vendor' AS cv FROM vendor
765 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
766 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
767 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
769 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
772 deliverydate => 'apoe.', serialnumber => 'ioi.',
773 transdate => 'apoe.', trans_id => 'ioi.',
774 module => 'apoe.', name => 'cv.',
775 ordnumber => 'apoe.', make => 'mm.',
776 quonumber => 'apoe.', model => 'mm.',
777 invnumber => 'apoe.', partsgroup => 'pg.',
778 lastcost => 'p.', , soldtotal => ' ',
779 factor => 'pfac.', projectnumber => 'pj.',
780 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
783 serialnumber => 'ioi.',
784 quotation => 'apoe.',
790 # if the join condition in these blocks are met, the column
791 # of the scecified table will gently override (coalesce actually) the original value
792 # use it to conditionally coalesce values from subtables
793 my @column_override = (
794 # column name, prefix, joins_needed, nick name (in case column is named like another)
795 [ 'description', 'ioi.', 'invoice_oi' ],
796 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
797 [ 'transdate', 'apoe.', 'apoe' ],
798 [ 'unit', 'ioi.', 'invoice_oi' ],
799 [ 'sellprice', 'ioi.', 'invoice_oi' ],
802 # careful with renames. these are HARD, and any filters done on the original column will break
803 my %renamed_columns = (
804 'factor' => 'price_factor',
805 'SUM(ioi.qty)' => 'soldtotal',
806 'ioi.id' => 'ioi_id',
808 'projectdescription' => 'projectdescription',
812 projectdescription => 'description',
815 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
816 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
819 my $make_token_builder = sub {
820 my $joins_needed = shift;
822 my ($nick, $alias) = @_;
823 my ($col) = $real_column{$nick} || $nick;
824 my @coalesce_tokens =
825 map { ($_->[1] || 'p.') . $_->[0] }
826 grep { !$_->[2] || $joins_needed->{$_->[2]} }
827 grep { ($_->[3] || $_->[0]) eq $nick }
828 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
830 my $coalesce = scalar @coalesce_tokens > 1;
832 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
833 : shift @coalesce_tokens)
834 . ($alias && ($coalesce || $renamed_columns{$nick})
835 ? " AS " . ($renamed_columns{$nick} || $nick)
840 #===== switches and simple filters ========#
842 # special case transdate
843 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
844 $form->{"l_transdate"} = 1;
845 push @select_tokens, 'transdate';
846 for (qw(transdatefrom transdateto)) {
847 next unless $form->{$_};
848 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
849 push @bind_vars, $form->{$_};
853 if ($form->{"partsgroup_id"}) {
854 $form->{"l_partsgroup"} = '1'; # show the column
855 push @where_tokens, "pg.id = ?";
856 push @bind_vars, $form->{"partsgroup_id"};
859 foreach (@like_filters) {
860 next unless $form->{$_};
861 $form->{"l_$_"} = '1'; # show the column
862 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
863 push @bind_vars, "%$form->{$_}%";
866 foreach (@simple_l_switches) {
867 next unless $form->{"l_$_"};
868 push @select_tokens, $_;
871 for ($form->{searchitems}) {
872 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
873 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
874 push @where_tokens, 'NOT p.assembly' if /service/;
875 push @where_tokens, ' p.assembly' if /assembly/;
878 for ($form->{itemstatus}) {
879 push @where_tokens, 'p.id NOT IN
880 (SELECT DISTINCT parts_id FROM invoice UNION
881 SELECT DISTINCT parts_id FROM assembly UNION
882 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
883 push @where_tokens, 'p.onhand = 0' if /orphaned/;
884 push @where_tokens, 'NOT p.obsolete' if /active/;
885 push @where_tokens, ' p.obsolete', if /obsolete/;
886 push @where_tokens, 'p.onhand > 0', if /onhand/;
887 push @where_tokens, 'p.onhand < p.rop', if /short/;
890 my $q_assembly_lastcost =
891 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
893 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
894 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
895 WHERE (a_lc.id = p.id)) AS lastcost|;
896 $table_prefix{$q_assembly_lastcost} = ' ';
898 # special case makemodel search
899 # all_parts is based upon the assumption that every parameter is named like the column it represents
900 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
901 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
903 push @where_tokens, 'mv.name ILIKE ?';
904 push @bind_vars, "%$form->{make}%";
906 if ($form->{model}) {
907 push @where_tokens, 'mm.model ILIKE ?';
908 push @bind_vars, "%$form->{model}%";
911 # special case: sorting by partnumber
912 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
913 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
914 # ToDO: implement proper functional sorting
915 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
916 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
917 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
918 # if $form->{sort} eq 'partnumber';
920 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
923 $limit_clause = " LIMIT 100" if $form->{top100};
924 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
926 #=== joins and complicated filters ========#
928 my $bsooqr = any { $form->{$_} } @oe_flags;
929 my @bsooqr_tokens = ();
931 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
932 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
933 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
934 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
935 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
936 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
937 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
938 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
939 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
940 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
942 $joins_needed{partsgroup} = 1;
943 $joins_needed{pfac} = 1;
944 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
945 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
946 $joins_needed{mv} = 1 if $joins_needed{makemodel};
947 $joins_needed{cv} = 1 if $bsooqr;
948 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
949 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
951 # special case for description search.
952 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
953 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
954 # find the old entries in of @where_tokens and @bind_vars, and adjust them
955 if ($joins_needed{invoice_oi}) {
956 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
957 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
958 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
959 splice @bind_vars, $bi, 0, $bind_vars[$bi];
964 # now the master trick: soldtotal.
965 if ($form->{l_soldtotal}) {
966 push @where_tokens, 'NOT ioi.qty = 0';
967 push @group_tokens, @select_tokens;
968 map { s/.*\sAS\s+//si } @group_tokens;
969 push @select_tokens, 'SUM(ioi.qty)';
972 #============= build query ================#
974 my $token_builder = $make_token_builder->(\%joins_needed);
976 my @sort_cols = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
977 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
978 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
979 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
981 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
982 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
983 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
984 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
986 my %oe_flag_to_cvar = (
989 onorder => 'orderitems',
990 ordered => 'orderitems',
992 quoted => 'orderitems',
995 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
997 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
999 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1003 $where_clause .= qq| AND ($cvar_where)|;
1004 push @bind_vars, @cvar_values;
1007 my $query = <<" SQL";
1008 SELECT DISTINCT $select_clause
1017 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1019 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1021 # fix qty sign in ap. those are saved negative
1022 if ($bsooqr && $form->{bought}) {
1023 for my $row (@{ $form->{parts} }) {
1024 $row->{qty} *= -1 if $row->{module} eq 'ir';
1028 # post processing for assembly parts lists (bom)
1029 # for each part get the assembly parts and add them into the partlist.
1031 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1033 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1035 p.sellprice, p.listprice, p.lastcost,
1036 p.rop, p.weight, p.priceupdate,
1037 p.image, p.drawing, p.microfiche,
1040 INNER JOIN assembly a ON (p.id = a.parts_id)
1043 my $sth = prepare_query($form, $dbh, $query);
1045 foreach my $item (@{ $form->{parts} }) {
1046 push(@assemblies, $item);
1047 do_statement($form, $sth, $query, conv_i($item->{id}));
1049 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1050 $ref->{assemblyitem} = 1;
1051 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1052 push(@assemblies, $ref);
1057 # copy assemblies to $form->{parts}
1058 $form->{parts} = \@assemblies;
1061 if ($form->{l_pricegroups} ) {
1063 SELECT parts_id, price, pricegroup_id
1068 my $sth = prepare_query($form, $dbh, $query);
1070 foreach my $part (@{ $form->{parts} }) {
1071 do_statement($form, $sth, $query, conv_i($part->{id}));
1073 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1074 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1081 $main::lxdebug->leave_sub();
1083 return @{ $form->{parts} };
1086 sub _create_filter_for_priceupdate {
1087 $main::lxdebug->enter_sub();
1090 my $myconfig = \%main::myconfig;
1091 my $form = $main::form;
1094 my $where = '1 = 1';
1096 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1098 $column =~ s/.*\.//;
1099 next unless ($form->{$column});
1101 $where .= qq| AND $item ILIKE ?|;
1102 push(@where_values, '%' . $form->{$column} . '%');
1105 foreach my $item (qw(description serialnumber)) {
1106 next unless ($form->{$item});
1108 $where .= qq| AND (${item} ILIKE ?)|;
1109 push(@where_values, '%' . $form->{$item} . '%');
1113 # items which were never bought, sold or on an order
1114 if ($form->{itemstatus} eq 'orphaned') {
1116 qq| AND (p.onhand = 0)
1119 SELECT DISTINCT parts_id FROM invoice
1121 SELECT DISTINCT parts_id FROM assembly
1123 SELECT DISTINCT parts_id FROM orderitems
1126 } elsif ($form->{itemstatus} eq 'active') {
1127 $where .= qq| AND p.obsolete = '0'|;
1129 } elsif ($form->{itemstatus} eq 'obsolete') {
1130 $where .= qq| AND p.obsolete = '1'|;
1132 } elsif ($form->{itemstatus} eq 'onhand') {
1133 $where .= qq| AND p.onhand > 0|;
1135 } elsif ($form->{itemstatus} eq 'short') {
1136 $where .= qq| AND p.onhand < p.rop|;
1140 foreach my $column (qw(make model)) {
1141 next unless ($form->{$column});
1142 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1143 push(@where_values, '%' . $form->{$column} . '%');
1146 $main::lxdebug->leave_sub();
1148 return ($where, @where_values);
1151 sub get_num_matches_for_priceupdate {
1152 $main::lxdebug->enter_sub();
1156 my $myconfig = \%main::myconfig;
1157 my $form = $main::form;
1159 my $dbh = $form->get_standard_dbh($myconfig);
1161 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1163 my $num_updated = 0;
1166 for my $column (qw(sellprice listprice)) {
1167 next if ($form->{$column} eq "");
1175 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1177 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1178 $num_updated += $result if (0 <= $result);
1187 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1188 WHERE $where) AND (pricegroup_id = ?)|;
1189 my $sth = prepare_query($form, $dbh, $query);
1191 for my $i (1 .. $form->{price_rows}) {
1192 next if ($form->{"price_$i"} eq "");
1194 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1195 $num_updated += $result if (0 <= $result);
1199 $main::lxdebug->leave_sub();
1201 return $num_updated;
1205 $main::lxdebug->enter_sub();
1207 my ($self, $myconfig, $form) = @_;
1209 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1210 my $num_updated = 0;
1212 # connect to database
1213 my $dbh = $form->get_standard_dbh;
1215 for my $column (qw(sellprice listprice)) {
1216 next if ($form->{$column} eq "");
1218 my $value = $form->parse_amount($myconfig, $form->{$column});
1221 if ($form->{"${column}_type"} eq "percent") {
1222 $value = ($value / 100) + 1;
1227 qq|UPDATE parts SET $column = $column $operator ?
1231 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1233 my $result = do_query($form, $dbh, $query, $value, @where_values);
1234 $num_updated += $result if (0 <= $result);
1238 qq|UPDATE prices SET price = price + ?
1242 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1243 WHERE $where) AND (pricegroup_id = ?)|;
1244 my $sth_add = prepare_query($form, $dbh, $q_add);
1247 qq|UPDATE prices SET price = price * ?
1251 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1252 WHERE $where) AND (pricegroup_id = ?)|;
1253 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1255 for my $i (1 .. $form->{price_rows}) {
1256 next if ($form->{"price_$i"} eq "");
1258 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1261 if ($form->{"pricegroup_type_$i"} eq "percent") {
1262 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1264 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1267 $num_updated += $result if (0 <= $result);
1271 $sth_multiply->finish();
1273 my $rc= $dbh->commit;
1275 $main::lxdebug->leave_sub();
1277 return $num_updated;
1281 $main::lxdebug->enter_sub();
1283 my ($self, $module, $myconfig, $form) = @_;
1285 # connect to database
1286 my $dbh = $form->get_standard_dbh;
1288 my @values = ('%' . $module . '%');
1293 qq|SELECT c.accno, c.description, c.link, c.id,
1294 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1295 FROM chart c, parts p
1296 WHERE (c.link LIKE ?) AND (p.id = ?)
1298 push(@values, conv_i($form->{id}));
1302 qq|SELECT c.accno, c.description, c.link, c.id,
1303 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1304 FROM chart c, defaults d
1309 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1310 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1311 foreach my $key (split(/:/, $ref->{link})) {
1312 if ($key =~ /\Q$module\E/) {
1313 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1314 || ($ref->{id} eq $ref->{income_accno_id})
1315 || ($ref->{id} eq $ref->{expense_accno_id})) {
1316 push @{ $form->{"${module}_links"}{$key} },
1317 { accno => $ref->{accno},
1318 description => $ref->{description},
1319 selected => "selected" };
1320 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1322 push @{ $form->{"${module}_links"}{$key} },
1323 { accno => $ref->{accno},
1324 description => $ref->{description},
1332 # get buchungsgruppen
1333 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1336 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1339 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1342 $main::lxdebug->leave_sub();
1345 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1347 $main::lxdebug->enter_sub();
1349 my ($self, $myconfig, $form, $sortorder) = @_;
1350 my $dbh = $form->get_standard_dbh;
1351 my $order = qq| p.partnumber|;
1352 my $where = qq|1 = 1|;
1355 if ($sortorder eq "all") {
1356 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1357 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1359 } elsif ($sortorder eq "partnumber") {
1360 $where .= qq| AND (partnumber ILIKE ?)|;
1361 push(@values, '%' . $form->{partnumber} . '%');
1363 } elsif ($sortorder eq "description") {
1364 $where .= qq| AND (description ILIKE ?)|;
1365 push(@values, '%' . $form->{description} . '%');
1366 $order = "description";
1371 qq|SELECT id, partnumber, description, unit, sellprice
1373 WHERE $where ORDER BY $order|;
1375 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1378 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1379 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1384 $form->{"id_$j"} = $ref->{id};
1385 $form->{"partnumber_$j"} = $ref->{partnumber};
1386 $form->{"description_$j"} = $ref->{description};
1387 $form->{"unit_$j"} = $ref->{unit};
1388 $form->{"sellprice_$j"} = $ref->{sellprice};
1389 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1394 $main::lxdebug->leave_sub();
1399 # gets sum of sold part with part_id
1401 $main::lxdebug->enter_sub();
1403 my ($dbh, $id) = @_;
1405 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1406 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1409 $main::lxdebug->leave_sub();
1412 } #end get_soldtotal
1414 sub retrieve_languages {
1415 $main::lxdebug->enter_sub();
1417 my ($self, $myconfig, $form) = @_;
1419 # connect to database
1420 my $dbh = $form->get_standard_dbh;
1426 if ($form->{language_values} ne "") {
1428 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1430 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1431 ORDER BY lower(l.description)|;
1432 @values = (conv_i($form->{id}));
1435 $query = qq|SELECT id, description
1437 ORDER BY lower(description)|;
1440 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1442 $main::lxdebug->leave_sub();
1447 sub follow_account_chain {
1448 $main::lxdebug->enter_sub(2);
1450 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1452 my @visited_accno_ids = ($accno_id);
1456 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1457 map { $_->{id} => $_ }
1458 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1459 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1461 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1462 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1466 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1467 last unless ($ref && $ref->{"is_valid"} &&
1468 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1469 $accno_id = $ref->{"new_chart_id"};
1470 $accno = $ref->{"accno"};
1471 push(@visited_accno_ids, $accno_id);
1474 $main::lxdebug->leave_sub(2);
1476 return ($accno_id, $accno);
1479 sub retrieve_accounts {
1480 $main::lxdebug->enter_sub;
1483 my $myconfig = shift;
1485 my $dbh = $form->get_standard_dbh;
1486 my %args = @_; # index => part_id
1488 $form->{taxzone_id} *= 1;
1490 return unless grep $_, values %args; # shortfuse if no part_id supplied
1492 # transdate madness.
1494 if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
1495 # use deliverydate for sales and purchase invoice, if it exists
1496 # also use deliverydate for credit notes
1497 if (!$form->{deliverydate}) {
1498 $transdate = $form->{invdate};
1500 $transdate = $form->{deliverydate};
1502 } elsif ($form->{script} eq 'ir.pl') {
1503 # when a purchase invoice is opened from the report of purchase invoices
1504 # $form->{type} isn't set, but $form->{script} is, not sure why this is or
1505 # whether this distinction matters in some other scenario. Otherwise one
1506 # could probably take out this elsif and add a
1507 # " or $form->{script} eq 'ir.pl' "
1508 # to the above if-statement
1509 if (!$form->{deliverydate}) {
1510 $transdate = $form->{invdate};
1512 $transdate = $form->{deliverydate};
1514 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
1515 # if credit_note has a deliverydate, use this instead of invdate
1516 # useful for credit_notes of invoices from an old period with different tax
1517 # if there is no deliverydate then invdate is used, old default (see next elsif)
1518 # Falls hier der Stichtag für Steuern anders bestimmt wird,
1519 # entsprechend auch bei Taxkeys.pm anpassen
1520 $transdate = $form->{deliverydate};
1521 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1522 $transdate = $form->{invdate};
1524 $transdate = $form->{transdate};
1527 if ($transdate eq "") {
1528 $transdate = DateTime->today_local->to_lxoffice;
1530 $transdate = $dbh->quote($transdate);
1533 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1535 my @part_ids = grep { $_ } values %args;
1536 my $in = join ',', ('?') x @part_ids;
1538 my %accno_by_part = map { $_->{id} => $_ }
1539 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1541 p.id, p.inventory_accno_id AS is_part,
1542 bg.inventory_accno_id,
1543 tc.income_accno_id AS income_accno_id,
1544 tc.expense_accno_id AS expense_accno_id,
1545 c1.accno AS inventory_accno,
1546 c2.accno AS income_accno,
1547 c3.accno AS expense_accno
1549 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1550 LEFT JOIN taxzone_charts tc on bg.id = tc.buchungsgruppen_id
1551 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1552 LEFT JOIN chart c2 ON tc.income_accno_id = c2.id
1553 LEFT JOIN chart c3 ON tc.expense_accno_id = c3.id
1555 tc.taxzone_id = '$form->{taxzone_id}'
1560 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1561 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1563 LEFT JOIN chart c ON c.id = t.chart_id
1567 WHERE tk.chart_id = ? AND startdate <= ?
1568 ORDER BY startdate DESC LIMIT 1)
1571 while (my ($index => $part_id) = each %args) {
1572 my $ref = $accno_by_part{$part_id} or next;
1574 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1577 for my $type (qw(inventory income expense)) {
1578 next unless $ref->{"${type}_accno_id"};
1579 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1580 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1583 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1585 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1586 $ref = $sth_tax->fetchrow_hashref or next;
1588 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1589 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1591 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1596 $::lxdebug->leave_sub;
1599 sub get_basic_part_info {
1600 $main::lxdebug->enter_sub();
1605 Common::check_params(\%params, qw(id));
1607 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1610 $main::lxdebug->leave_sub();
1614 my $myconfig = \%main::myconfig;
1615 my $form = $main::form;
1617 my $dbh = $form->get_standard_dbh($myconfig);
1619 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1621 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1623 if ('' eq ref $params{id}) {
1624 $info = $info->[0] || { };
1626 $main::lxdebug->leave_sub();
1630 my %info_map = map { $_->{id} => $_ } @{ $info };
1632 $main::lxdebug->leave_sub();
1637 sub prepare_parts_for_printing {
1638 $main::lxdebug->enter_sub();
1643 my $myconfig = $params{myconfig} || \%main::myconfig;
1644 my $form = $params{form} || $main::form;
1646 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1648 my $prefix = $params{prefix} || 'id_';
1649 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1651 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1654 $main::lxdebug->leave_sub();
1658 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1659 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1661 LEFT JOIN vendor v ON (mm.make = v.id)
1662 WHERE mm.parts_id IN ($placeholders)|;
1666 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1668 while (my $ref = $sth->fetchrow_hashref()) {
1669 $makemodel{$ref->{parts_id}} ||= [];
1670 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1675 my @columns = qw(ean image microfiche drawing weight);
1677 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1679 WHERE id IN ($placeholders)|;
1681 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1683 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1685 foreach my $i (1 .. $rowcount) {
1686 my $id = $form->{"${prefix}${i}"};
1690 foreach (@columns) {
1691 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1694 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1695 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1697 next if (!$makemodel{$id});
1699 foreach my $ref (@{ $makemodel{$id} }) {
1700 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1704 my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
1705 my %parts_by_id = map { $_->id => $_ } @$parts;
1707 for my $i (1..$rowcount) {
1708 my $id = $form->{"${prefix}${i}"};
1711 push @{ $form->{TEMPLATE_ARRAYS}{part_type} }, $parts_by_id{$id}->type;
1714 $main::lxdebug->leave_sub();
1717 sub normalize_text_blocks {
1718 $main::lxdebug->enter_sub();
1723 my $form = $params{form} || $main::form;
1725 # check if feature is enabled (select normalize_part_descriptions from defaults)
1726 return unless ($::instance_conf->get_normalize_part_descriptions);
1728 foreach (qw(description notes)) {
1729 $form->{$_} =~ s/\s+$//s;
1730 $form->{$_} =~ s/^\s+//s;
1731 $form->{$_} =~ s/ {2,}/ /g;
1733 $main::lxdebug->leave_sub();