1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
31 # Inventory Control backend
33 #======================================================================
38 use List::MoreUtils qw(all any uniq);
48 $main::lxdebug->enter_sub();
50 my ($self, $myconfig, $form) = @_;
53 my $dbh = $form->get_standard_dbh;
59 c1.accno AS inventory_accno,
60 c2.accno AS income_accno,
61 c3.accno AS expense_accno,
64 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
65 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
66 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
67 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
69 my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
71 # copy to $form variables
72 map { $form->{$_} = $ref->{$_} } (keys %{$ref});
76 # part or service item
77 $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
78 if ($form->{assembly}) {
79 $form->{item} = 'assembly';
81 # retrieve assembly items
83 qq|SELECT p.id, p.partnumber, p.description,
84 p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
85 pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
87 JOIN assembly a ON (a.parts_id = p.id)
88 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
89 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
92 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
94 $form->{assembly_rows} = 0;
95 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
96 $form->{assembly_rows}++;
97 foreach my $key (keys %{$ref}) {
98 $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
105 # setup accno hash for <option checked> {amount} is used in create_links
106 $form->{amount}{IC} = $form->{inventory_accno};
107 $form->{amount}{IC_income} = $form->{income_accno};
108 $form->{amount}{IC_sale} = $form->{income_accno};
109 $form->{amount}{IC_expense} = $form->{expense_accno};
110 $form->{amount}{IC_cogs} = $form->{expense_accno};
114 SELECT pg.pricegroup, pg.id AS pricegroup_id, COALESCE(pr.price, 0) AS price
116 LEFT JOIN prices pr ON (pr.pricegroup_id = pg.id) AND (pr.parts_id = ?)
117 ORDER BY lower(pg.pricegroup)
121 foreach $ref (selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}))) {
122 $form->{"${_}_${row}"} = $ref->{$_} for qw(pricegroup_id pricegroup price);
125 $form->{price_rows} = $row - 1;
128 if ($form->{makemodel}) {
130 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
131 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
132 my @values = ($form->{id});
133 $sth = $dbh->prepare($query);
134 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
138 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
139 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
144 $form->{makemodel_rows} = $i - 1;
149 $query = qq|SELECT language_id, translation, longdescription
152 $form->{translations} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
155 my @referencing_tables = qw(invoice orderitems inventory);
156 my %column_map = ( );
157 my $parts_id = conv_i($form->{id});
159 $form->{orphaned} = 1;
161 foreach my $table (@referencing_tables) {
162 my $column = $column_map{$table} || 'parts_id';
163 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
164 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
167 $form->{orphaned} = 0;
172 $form->{"unit_changeable"} = $form->{orphaned};
174 Common::webdav_folder($form) if $::lx_office_conf{features}{webdav};
176 $main::lxdebug->leave_sub();
179 sub get_pricegroups {
180 $main::lxdebug->enter_sub();
182 my ($self, $myconfig, $form) = @_;
184 my $dbh = $form->get_standard_dbh;
187 my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
188 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
191 foreach my $pg (@{ $pricegroups }) {
192 $form->{"klass_$i"} = "$pg->{id}";
193 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
194 $form->{"pricegroup_id_$i"} = "$pg->{id}";
195 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
200 $form->{price_rows} = $i - 1;
202 $main::lxdebug->leave_sub();
207 sub retrieve_buchungsgruppen {
208 $main::lxdebug->enter_sub();
210 my ($self, $myconfig, $form) = @_;
214 my $dbh = $form->get_standard_dbh;
216 # get buchungsgruppen
217 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
218 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
220 $main::lxdebug->leave_sub();
224 $main::lxdebug->enter_sub();
226 my ($self, $myconfig, $form) = @_;
228 # connect to database, turn off AutoCommit
229 my $dbh = $form->get_standard_dbh;
232 # make up a unique handle and store in partnumber field
233 # then retrieve the record based on the unique handle to get the id
234 # replace the partnumber field with the actual variable
235 # add records for makemodel
237 # if there is a $form->{id} then replace the old entry
238 # delete all makemodel entries and add the new ones
240 # undo amount formatting
241 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
242 qw(rop weight listprice sellprice gv lastcost);
244 my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
246 $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
250 my $priceupdate = ', priceupdate = current_date';
253 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
254 if (!$trans_number->is_unique) {
255 $::lxdebug->leave_sub;
260 $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
261 my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
263 # if item is part of an assembly adjust all assemblies
264 $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
265 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
266 while (my ($id, $qty) = $sth->fetchrow_array) {
267 &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
271 # delete makemodel records
272 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
274 if ($form->{item} eq 'assembly') {
275 # delete assembly records
276 do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
279 # delete translations
280 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
282 # Check whether or not the prices have changed. If they haven't
283 # then 'priceupdate' should not be updated.
284 my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
285 $priceupdate = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
288 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, save => 1);
290 if ($form->{partnumber} && !$trans_number->is_unique) {
291 $::lxdebug->leave_sub;
295 $form->{partnumber} ||= $trans_number->create_unique;
297 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
298 do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit});
300 $form->{orphaned} = 1;
302 my $partsgroup_id = undef;
304 if ($form->{partsgroup}) {
305 (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
308 my ($subq_inventory, $subq_expense, $subq_income);
309 if ($form->{"item"} eq "part") {
311 qq|(SELECT bg.inventory_accno_id
312 FROM buchungsgruppen bg
313 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
315 $subq_inventory = "NULL";
318 if ($form->{"item"} ne "assembly") {
320 qq|(SELECT bg.expense_accno_id_0
321 FROM buchungsgruppen bg
322 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
324 $subq_expense = "NULL";
327 normalize_text_blocks();
346 buchungsgruppen_id = ?,
348 inventory_accno_id = $subq_inventory,
349 income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
350 expense_accno_id = $subq_expense,
359 not_discountable = ?,
365 @values = ($form->{partnumber},
366 $form->{description},
367 $makemodel ? 't' : 'f',
368 $form->{assembly} ? 't' : 'f',
377 conv_i($form->{warehouse_id}),
378 conv_i($form->{bin_id}),
379 conv_i($form->{buchungsgruppen_id}),
380 conv_i($form->{payment_id}),
381 conv_i($form->{buchungsgruppen_id}),
382 $form->{obsolete} ? 't' : 'f',
385 $form->{shop} ? 't' : 'f',
389 $form->{has_sernumber} ? 't' : 'f',
390 $form->{not_discountable} ? 't' : 'f',
392 conv_i($partsgroup_id),
393 conv_i($form->{price_factor_id}),
396 do_query($form, $dbh, $query, @values);
398 # delete translation records
399 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
401 my @translations = grep { $_->{language_id} && $_->{translation} } @{ $form->{translations} || [] };
403 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
404 VALUES ( ?, ?, ?, ? )|;
405 $sth = $dbh->prepare($query);
407 foreach my $translation (@translations) {
408 do_statement($form, $sth, $query, conv_i($form->{id}), conv_i($translation->{language_id}), $translation->{translation}, $translation->{longdescription});
414 # delete price records
415 do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
417 $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) VALUES(?, ?, ?)|;
418 $sth = prepare_query($form, $dbh, $query);
420 # insert price records only if different to sellprice
421 for my $i (1 .. $form->{price_rows}) {
422 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
423 next unless $price && ($price != $form->{sellprice});
425 @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
426 do_statement($form, $sth, $query, @values);
431 # insert makemodel records
434 for my $i (1 .. $form->{makemodel_rows}) {
435 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
437 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
438 if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
440 if ($form->{"lastupdate_$i"} eq "") {
441 $lastupdate = 'now()';
443 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
446 $lastupdate = 'now()';
448 $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
449 qq|VALUES (?, ?, ?, ?, ?, ?)|;
450 @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
452 do_query($form, $dbh, $query, @values);
456 # add assembly records
457 if ($form->{item} eq 'assembly') {
458 # check additional assembly row
459 my $i = $form->{assembly_rows};
460 # if last row is not empty add them
461 if ($form->{"partnumber_$i"} ne "") {
462 $query = qq|SELECT id FROM parts WHERE partnumber = ?|;
463 my ($partid) = selectrow_query($form, $dbh, $query,$form->{"partnumber_$i"} );
465 $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
466 $form->{"id_$i"} = $partid;
467 $form->{"bom_$i"} = 0;
468 $form->{assembly_rows}++;
471 $::form->error($::locale->text("uncorrect partnumber ").$form->{"partnumber_$i"});
475 for my $i (1 .. $form->{assembly_rows}) {
476 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
478 if ($form->{"qty_$i"} != 0) {
479 $form->{"bom_$i"} *= 1;
480 $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
481 qq|VALUES (?, ?, ?, ?)|;
482 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
483 do_query($form, $dbh, $query, @values);
489 my $shippingdate = "$a[5]-$a[4]-$a[3]";
491 $form->get_employee($dbh);
495 #set expense_accno=inventory_accno if they are different => bilanz
497 ($form->{expense_accno} != $form->{inventory_accno})
498 ? $form->{inventory_accno}
499 : $form->{expense_accno};
501 # get tax rates and description
503 ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
505 qq|SELECT c.accno, c.description, t.rate, t.taxnumber
507 WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
509 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
511 $form->{taxaccount} = "";
512 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
513 $form->{taxaccount} .= "$ptr->{accno} ";
514 if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
515 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
516 $form->{"$ptr->{accno}_description"} = $ptr->{description};
517 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
518 $form->{taxaccount2} .= " $ptr->{accno} ";
522 CVar->save_custom_variables(dbh => $dbh,
524 trans_id => $form->{id},
529 my $rc = $dbh->commit;
531 $main::lxdebug->leave_sub();
536 sub update_assembly {
537 $main::lxdebug->enter_sub();
539 my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
541 my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
542 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
544 while (my ($pid, $aqty) = $sth->fetchrow_array) {
545 &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
550 qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
552 my @values = ($qty * ($form->{sellprice} - $sellprice),
553 $qty * ($form->{weight} - $weight), conv_i($id));
554 do_query($form, $dbh, $query, @values);
556 $main::lxdebug->leave_sub();
559 sub retrieve_assemblies {
560 $main::lxdebug->enter_sub();
562 my ($self, $myconfig, $form) = @_;
564 # connect to database
565 my $dbh = $form->get_standard_dbh;
567 my $where = qq|NOT p.obsolete|;
570 if ($form->{partnumber}) {
571 $where .= qq| AND (p.partnumber ILIKE ?)|;
572 push(@values, '%' . $form->{partnumber} . '%');
575 if ($form->{description}) {
576 $where .= qq| AND (p.description ILIKE ?)|;
577 push(@values, '%' . $form->{description} . '%');
580 # retrieve assembly items
582 qq|SELECT p.id, p.partnumber, p.description,
584 (SELECT sum(p2.inventory_accno_id)
585 FROM parts p2, assembly a
586 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
588 WHERE NOT p.obsolete AND p.assembly $where|;
590 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
592 $main::lxdebug->leave_sub();
596 $main::lxdebug->enter_sub();
598 my ($self, $myconfig, $form) = @_;
599 my @values = (conv_i($form->{id}));
600 # connect to database, turn off AutoCommit
601 my $dbh = $form->get_standard_dbh;
603 my %columns = ( "assembly" => "id", "parts" => "id" );
605 for my $table (qw(prices makemodel inventory assembly translation parts)) {
606 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
607 do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
611 my $rc = $dbh->commit;
613 $main::lxdebug->leave_sub();
619 $main::lxdebug->enter_sub();
621 my ($self, $myconfig, $form) = @_;
623 my $i = $form->{assembly_rows};
625 my $where = qq|1 = 1|;
628 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
630 while (my ($column, $table) = each(%columns)) {
631 next unless ($form->{"${column}_$i"});
632 $where .= qq| AND ${table}.${column} ILIKE ?|;
633 push(@values, '%' . $form->{"${column}_$i"} . '%');
637 $where .= qq| AND NOT (p.id = ?)|;
638 push(@values, conv_i($form->{id}));
641 # Search for part ID overrides all other criteria.
642 if ($form->{"id_${i}"}) {
643 $where = qq|p.id = ?|;
644 @values = ($form->{"id_${i}"});
647 if ($form->{partnumber}) {
648 $where .= qq| ORDER BY p.partnumber|;
650 $where .= qq| ORDER BY p.description|;
653 # connect to database
654 my $dbh = $form->get_standard_dbh;
657 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
658 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
659 p.price_factor_id, pfac.factor AS price_factor
661 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
662 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
664 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
666 $main::lxdebug->leave_sub();
671 # Warning, deep magic ahead.
672 # This function gets all parts from the database according to the filters specified
675 # sort revers - sorting field + direction
678 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
679 # partnumber ean description partsgroup microfiche drawing
682 # 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
685 # itemstatus = active | onhand | short | obsolete | orphaned
686 # searchitems = part | assembly | service
689 # make model - makemodel
690 # serialnumber transdatefrom transdateto - invoice/orderitems
693 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
694 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
695 # l_soldtotal - aggreg join to display total of sold quantity
696 # onhand - as above, but masking the simple itemstatus results (doh!)
697 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
698 # l_serialnumber - belonges to serialnumber filter
699 # l_deliverydate - displays deliverydate is sold etc. flags are active
700 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
703 # onhand - as above, but masking the simple itemstatus results (doh!)
705 # search by overrides of description
707 # disabled sanity checks and changes:
708 # - searchitems = assembly will no longer disable bought
709 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
710 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
711 # - itemstatus = obsolete will no longer disable onhand, short
712 # - allow sorting by ean
713 # - serialnumber filter also works if l_serialnumber isn't ticked
714 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
717 $main::lxdebug->enter_sub();
719 my ($self, $myconfig, $form) = @_;
720 my $dbh = $form->get_standard_dbh($myconfig);
722 $form->{parts} = +{ };
723 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
725 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
726 my @project_filters = qw(projectnumber projectdescription);
727 my @makemodel_filters = qw(make model);
728 my @invoice_oi_filters = qw(serialnumber soldtotal);
729 my @apoe_filters = qw(transdate);
730 my @like_filters = (@simple_filters, @invoice_oi_filters);
731 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
732 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image));
733 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
734 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
735 my @deliverydate_flags = qw(deliverydate);
736 # my @other_flags = qw(onhand); # ToDO: implement these
737 # my @inactive_flags = qw(l_subtotal short l_linetotal);
739 my @select_tokens = qw(id factor);
740 my @where_tokens = qw(1=1);
741 my @group_tokens = ();
743 my %joins_needed = ();
746 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
747 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
748 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
751 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
752 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
753 ) AS ioi ON ioi.parts_id = p.id|,
756 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
757 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
758 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
759 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
762 SELECT id, name, 'customer' AS cv FROM customer UNION
763 SELECT id, name, 'vendor' AS cv FROM vendor
764 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
765 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
766 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
768 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
771 deliverydate => 'apoe.', serialnumber => 'ioi.',
772 transdate => 'apoe.', trans_id => 'ioi.',
773 module => 'apoe.', name => 'cv.',
774 ordnumber => 'apoe.', make => 'mm.',
775 quonumber => 'apoe.', model => 'mm.',
776 invnumber => 'apoe.', partsgroup => 'pg.',
777 lastcost => 'p.', , soldtotal => ' ',
778 factor => 'pfac.', projectnumber => 'pj.',
779 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
782 serialnumber => 'ioi.',
783 quotation => 'apoe.',
789 # if the join condition in these blocks are met, the column
790 # of the scecified table will gently override (coalesce actually) the original value
791 # use it to conditionally coalesce values from subtables
792 my @column_override = (
793 # column name, prefix, joins_needed, nick name (in case column is named like another)
794 [ 'description', 'ioi.', 'invoice_oi' ],
795 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
796 [ 'transdate', 'apoe.', 'apoe' ],
797 [ 'unit', 'ioi.', 'invoice_oi' ],
798 [ 'sellprice', 'ioi.', 'invoice_oi' ],
801 # careful with renames. these are HARD, and any filters done on the original column will break
802 my %renamed_columns = (
803 'factor' => 'price_factor',
804 'SUM(ioi.qty)' => 'soldtotal',
805 'ioi.id' => 'ioi_id',
807 'projectdescription' => 'projectdescription',
811 projectdescription => 'description',
814 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
815 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
818 my $make_token_builder = sub {
819 my $joins_needed = shift;
821 my ($nick, $alias) = @_;
822 my ($col) = $real_column{$nick} || $nick;
823 my @coalesce_tokens =
824 map { ($_->[1] || 'p.') . $_->[0] }
825 grep { !$_->[2] || $joins_needed->{$_->[2]} }
826 grep { ($_->[3] || $_->[0]) eq $nick }
827 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
829 my $coalesce = scalar @coalesce_tokens > 1;
831 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
832 : shift @coalesce_tokens)
833 . ($alias && ($coalesce || $renamed_columns{$nick})
834 ? " AS " . ($renamed_columns{$nick} || $nick)
839 #===== switches and simple filters ========#
841 # special case transdate
842 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
843 $form->{"l_transdate"} = 1;
844 push @select_tokens, 'transdate';
845 for (qw(transdatefrom transdateto)) {
846 next unless $form->{$_};
847 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
848 push @bind_vars, $form->{$_};
852 if ($form->{"partsgroup_id"}) {
853 $form->{"l_partsgroup"} = '1'; # show the column
854 push @where_tokens, "pg.id = ?";
855 push @bind_vars, $form->{"partsgroup_id"};
858 foreach (@like_filters) {
859 next unless $form->{$_};
860 $form->{"l_$_"} = '1'; # show the column
861 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
862 push @bind_vars, "%$form->{$_}%";
865 foreach (@simple_l_switches) {
866 next unless $form->{"l_$_"};
867 push @select_tokens, $_;
870 for ($form->{searchitems}) {
871 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
872 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
873 push @where_tokens, 'NOT p.assembly' if /service/;
874 push @where_tokens, ' p.assembly' if /assembly/;
877 for ($form->{itemstatus}) {
878 push @where_tokens, 'p.id NOT IN
879 (SELECT DISTINCT parts_id FROM invoice UNION
880 SELECT DISTINCT parts_id FROM assembly UNION
881 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
882 push @where_tokens, 'p.onhand = 0' if /orphaned/;
883 push @where_tokens, 'NOT p.obsolete' if /active/;
884 push @where_tokens, ' p.obsolete', if /obsolete/;
885 push @where_tokens, 'p.onhand > 0', if /onhand/;
886 push @where_tokens, 'p.onhand < p.rop', if /short/;
889 my $q_assembly_lastcost =
890 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
892 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
893 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
894 WHERE (a_lc.id = p.id)) AS lastcost|;
895 $table_prefix{$q_assembly_lastcost} = ' ';
897 # special case makemodel search
898 # all_parts is based upon the assumption that every parameter is named like the column it represents
899 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
900 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
902 push @where_tokens, 'mv.name ILIKE ?';
903 push @bind_vars, "%$form->{make}%";
905 if ($form->{model}) {
906 push @where_tokens, 'mm.model ILIKE ?';
907 push @bind_vars, "%$form->{model}%";
910 # special case: sorting by partnumber
911 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
912 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
913 # ToDO: implement proper functional sorting
914 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
915 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
916 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
917 # if $form->{sort} eq 'partnumber';
919 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
922 $limit_clause = " LIMIT 100" if $form->{top100};
923 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
925 #=== joins and complicated filters ========#
927 my $bsooqr = any { $form->{$_} } @oe_flags;
928 my @bsooqr_tokens = ();
930 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
931 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
932 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
933 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
934 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
935 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
936 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
937 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
938 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
939 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
941 $joins_needed{partsgroup} = 1;
942 $joins_needed{pfac} = 1;
943 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
944 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
945 $joins_needed{mv} = 1 if $joins_needed{makemodel};
946 $joins_needed{cv} = 1 if $bsooqr;
947 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
948 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
950 # special case for description search.
951 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
952 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
953 # find the old entries in of @where_tokens and @bind_vars, and adjust them
954 if ($joins_needed{invoice_oi}) {
955 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
956 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
957 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
958 splice @bind_vars, $bi, 0, $bind_vars[$bi];
963 # now the master trick: soldtotal.
964 if ($form->{l_soldtotal}) {
965 push @where_tokens, 'NOT ioi.qty = 0';
966 push @group_tokens, @select_tokens;
967 map { s/.*\sAS\s+//si } @group_tokens;
968 push @select_tokens, 'SUM(ioi.qty)';
971 #============= build query ================#
973 my $token_builder = $make_token_builder->(\%joins_needed);
975 my @sort_cols = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
976 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
977 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
978 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
980 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
981 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
982 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
983 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
985 my %oe_flag_to_cvar = (
988 onorder => 'orderitems',
989 ordered => 'orderitems',
991 quoted => 'orderitems',
994 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
996 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
998 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1002 $where_clause .= qq| AND ($cvar_where)|;
1003 push @bind_vars, @cvar_values;
1006 my $query = <<" SQL";
1007 SELECT DISTINCT $select_clause
1016 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1018 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1020 # fix qty sign in ap. those are saved negative
1021 if ($bsooqr && $form->{bought}) {
1022 for my $row (@{ $form->{parts} }) {
1023 $row->{qty} *= -1 if $row->{module} eq 'ir';
1027 # post processing for assembly parts lists (bom)
1028 # for each part get the assembly parts and add them into the partlist.
1030 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1032 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1034 p.sellprice, p.listprice, p.lastcost,
1035 p.rop, p.weight, p.priceupdate,
1036 p.image, p.drawing, p.microfiche,
1039 INNER JOIN assembly a ON (p.id = a.parts_id)
1042 my $sth = prepare_query($form, $dbh, $query);
1044 foreach my $item (@{ $form->{parts} }) {
1045 push(@assemblies, $item);
1046 do_statement($form, $sth, $query, conv_i($item->{id}));
1048 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1049 $ref->{assemblyitem} = 1;
1050 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1051 push(@assemblies, $ref);
1056 # copy assemblies to $form->{parts}
1057 $form->{parts} = \@assemblies;
1060 if ($form->{l_pricegroups} ) {
1062 SELECT parts_id, price, pricegroup_id
1067 my $sth = prepare_query($form, $dbh, $query);
1069 foreach my $part (@{ $form->{parts} }) {
1070 do_statement($form, $sth, $query, conv_i($part->{id}));
1072 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1073 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1080 $main::lxdebug->leave_sub();
1082 return wantarray ? @{ $form->{parts} } : $form->{parts};
1085 sub _create_filter_for_priceupdate {
1086 $main::lxdebug->enter_sub();
1089 my $myconfig = \%main::myconfig;
1090 my $form = $main::form;
1093 my $where = '1 = 1';
1095 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1097 $column =~ s/.*\.//;
1098 next unless ($form->{$column});
1100 $where .= qq| AND $item ILIKE ?|;
1101 push(@where_values, '%' . $form->{$column} . '%');
1104 foreach my $item (qw(description serialnumber)) {
1105 next unless ($form->{$item});
1107 $where .= qq| AND (${item} ILIKE ?)|;
1108 push(@where_values, '%' . $form->{$item} . '%');
1112 # items which were never bought, sold or on an order
1113 if ($form->{itemstatus} eq 'orphaned') {
1115 qq| AND (p.onhand = 0)
1118 SELECT DISTINCT parts_id FROM invoice
1120 SELECT DISTINCT parts_id FROM assembly
1122 SELECT DISTINCT parts_id FROM orderitems
1125 } elsif ($form->{itemstatus} eq 'active') {
1126 $where .= qq| AND p.obsolete = '0'|;
1128 } elsif ($form->{itemstatus} eq 'obsolete') {
1129 $where .= qq| AND p.obsolete = '1'|;
1131 } elsif ($form->{itemstatus} eq 'onhand') {
1132 $where .= qq| AND p.onhand > 0|;
1134 } elsif ($form->{itemstatus} eq 'short') {
1135 $where .= qq| AND p.onhand < p.rop|;
1139 foreach my $column (qw(make model)) {
1140 next unless ($form->{$column});
1141 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1142 push(@where_values, '%' . $form->{$column} . '%');
1145 $main::lxdebug->leave_sub();
1147 return ($where, @where_values);
1150 sub get_num_matches_for_priceupdate {
1151 $main::lxdebug->enter_sub();
1155 my $myconfig = \%main::myconfig;
1156 my $form = $main::form;
1158 my $dbh = $form->get_standard_dbh($myconfig);
1160 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1162 my $num_updated = 0;
1165 for my $column (qw(sellprice listprice)) {
1166 next if ($form->{$column} eq "");
1174 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1176 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1177 $num_updated += $result if (0 <= $result);
1186 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1187 WHERE $where) AND (pricegroup_id = ?)|;
1188 my $sth = prepare_query($form, $dbh, $query);
1190 for my $i (1 .. $form->{price_rows}) {
1191 next if ($form->{"price_$i"} eq "");
1193 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1194 $num_updated += $result if (0 <= $result);
1198 $main::lxdebug->leave_sub();
1200 return $num_updated;
1204 $main::lxdebug->enter_sub();
1206 my ($self, $myconfig, $form) = @_;
1208 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1209 my $num_updated = 0;
1211 # connect to database
1212 my $dbh = $form->get_standard_dbh;
1214 for my $column (qw(sellprice listprice)) {
1215 next if ($form->{$column} eq "");
1217 my $value = $form->parse_amount($myconfig, $form->{$column});
1220 if ($form->{"${column}_type"} eq "percent") {
1221 $value = ($value / 100) + 1;
1226 qq|UPDATE parts SET $column = $column $operator ?
1230 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1232 my $result = do_query($form, $dbh, $query, $value, @where_values);
1233 $num_updated += $result if (0 <= $result);
1237 qq|UPDATE prices SET price = price + ?
1241 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1242 WHERE $where) AND (pricegroup_id = ?)|;
1243 my $sth_add = prepare_query($form, $dbh, $q_add);
1246 qq|UPDATE prices SET price = price * ?
1250 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1251 WHERE $where) AND (pricegroup_id = ?)|;
1252 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1254 for my $i (1 .. $form->{price_rows}) {
1255 next if ($form->{"price_$i"} eq "");
1257 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1260 if ($form->{"pricegroup_type_$i"} eq "percent") {
1261 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1263 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1266 $num_updated += $result if (0 <= $result);
1270 $sth_multiply->finish();
1272 my $rc= $dbh->commit;
1274 $main::lxdebug->leave_sub();
1276 return $num_updated;
1280 $main::lxdebug->enter_sub();
1282 my ($self, $module, $myconfig, $form) = @_;
1284 # connect to database
1285 my $dbh = $form->get_standard_dbh;
1287 my @values = ('%' . $module . '%');
1292 qq|SELECT c.accno, c.description, c.link, c.id,
1293 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1294 FROM chart c, parts p
1295 WHERE (c.link LIKE ?) AND (p.id = ?)
1297 push(@values, conv_i($form->{id}));
1301 qq|SELECT c.accno, c.description, c.link, c.id,
1302 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1303 FROM chart c, defaults d
1308 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1309 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1310 foreach my $key (split(/:/, $ref->{link})) {
1311 if ($key =~ /\Q$module\E/) {
1312 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1313 || ($ref->{id} eq $ref->{income_accno_id})
1314 || ($ref->{id} eq $ref->{expense_accno_id})) {
1315 push @{ $form->{"${module}_links"}{$key} },
1316 { accno => $ref->{accno},
1317 description => $ref->{description},
1318 selected => "selected" };
1319 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1321 push @{ $form->{"${module}_links"}{$key} },
1322 { accno => $ref->{accno},
1323 description => $ref->{description},
1331 # get buchungsgruppen
1332 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1335 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1338 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1341 $main::lxdebug->leave_sub();
1344 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1346 $main::lxdebug->enter_sub();
1348 my ($self, $myconfig, $form, $sortorder) = @_;
1349 my $dbh = $form->get_standard_dbh;
1350 my $order = qq| p.partnumber|;
1351 my $where = qq|1 = 1|;
1354 if ($sortorder eq "all") {
1355 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1356 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1358 } elsif ($sortorder eq "partnumber") {
1359 $where .= qq| AND (partnumber ILIKE ?)|;
1360 push(@values, '%' . $form->{partnumber} . '%');
1362 } elsif ($sortorder eq "description") {
1363 $where .= qq| AND (description ILIKE ?)|;
1364 push(@values, '%' . $form->{description} . '%');
1365 $order = "description";
1370 qq|SELECT id, partnumber, description, unit, sellprice
1372 WHERE $where ORDER BY $order|;
1374 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1377 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1378 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1383 $form->{"id_$j"} = $ref->{id};
1384 $form->{"partnumber_$j"} = $ref->{partnumber};
1385 $form->{"description_$j"} = $ref->{description};
1386 $form->{"unit_$j"} = $ref->{unit};
1387 $form->{"sellprice_$j"} = $ref->{sellprice};
1388 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1393 $main::lxdebug->leave_sub();
1398 # gets sum of sold part with part_id
1400 $main::lxdebug->enter_sub();
1402 my ($dbh, $id) = @_;
1404 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1405 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1408 $main::lxdebug->leave_sub();
1411 } #end get_soldtotal
1413 sub retrieve_languages {
1414 $main::lxdebug->enter_sub();
1416 my ($self, $myconfig, $form) = @_;
1418 # connect to database
1419 my $dbh = $form->get_standard_dbh;
1425 if ($form->{language_values} ne "") {
1427 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1429 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1430 ORDER BY lower(l.description)|;
1431 @values = (conv_i($form->{id}));
1434 $query = qq|SELECT id, description
1436 ORDER BY lower(description)|;
1439 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1441 $main::lxdebug->leave_sub();
1446 sub follow_account_chain {
1447 $main::lxdebug->enter_sub(2);
1449 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1451 my @visited_accno_ids = ($accno_id);
1455 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1456 map { $_->{id} => $_ }
1457 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1458 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1460 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1461 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1465 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1466 last unless ($ref && $ref->{"is_valid"} &&
1467 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1468 $accno_id = $ref->{"new_chart_id"};
1469 $accno = $ref->{"accno"};
1470 push(@visited_accno_ids, $accno_id);
1473 $main::lxdebug->leave_sub(2);
1475 return ($accno_id, $accno);
1478 sub retrieve_accounts {
1479 $main::lxdebug->enter_sub;
1482 my $myconfig = shift;
1484 my $dbh = $form->get_standard_dbh;
1485 my %args = @_; # index => part_id
1487 $form->{taxzone_id} *= 1;
1489 return unless grep $_, values %args; # shortfuse if no part_id supplied
1491 # transdate madness.
1493 if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
1494 # use deliverydate for sales and purchase invoice, if it exists
1495 # also use deliverydate for credit notes
1496 if (!$form->{deliverydate}) {
1497 $transdate = $form->{invdate};
1499 $transdate = $form->{deliverydate};
1501 } elsif ($form->{script} eq 'ir.pl') {
1502 # when a purchase invoice is opened from the report of purchase invoices
1503 # $form->{type} isn't set, but $form->{script} is, not sure why this is or
1504 # whether this distinction matters in some other scenario. Otherwise one
1505 # could probably take out this elsif and add a
1506 # " or $form->{script} eq 'ir.pl' "
1507 # to the above if-statement
1508 if (!$form->{deliverydate}) {
1509 $transdate = $form->{invdate};
1511 $transdate = $form->{deliverydate};
1513 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
1514 # if credit_note has a deliverydate, use this instead of invdate
1515 # useful for credit_notes of invoices from an old period with different tax
1516 # if there is no deliverydate then invdate is used, old default (see next elsif)
1517 # Falls hier der Stichtag für Steuern anders bestimmt wird,
1518 # entsprechend auch bei Taxkeys.pm anpassen
1519 $transdate = $form->{deliverydate};
1520 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1521 $transdate = $form->{invdate};
1523 $transdate = $form->{transdate};
1526 if ($transdate eq "") {
1527 $transdate = DateTime->today_local->to_lxoffice;
1529 $transdate = $dbh->quote($transdate);
1532 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1534 my @part_ids = grep { $_ } values %args;
1535 my $in = join ',', ('?') x @part_ids;
1537 my %accno_by_part = map { $_->{id} => $_ }
1538 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1540 p.id, p.inventory_accno_id AS is_part,
1541 bg.inventory_accno_id,
1542 bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
1543 bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
1544 c1.accno AS inventory_accno,
1545 c2.accno AS income_accno,
1546 c3.accno AS expense_accno
1548 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1549 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1550 LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
1551 LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
1555 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1556 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1558 LEFT JOIN chart c ON c.id = t.chart_id
1562 WHERE tk.chart_id = ? AND startdate <= ?
1563 ORDER BY startdate DESC LIMIT 1)
1566 while (my ($index => $part_id) = each %args) {
1567 my $ref = $accno_by_part{$part_id} or next;
1569 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1572 for my $type (qw(inventory income expense)) {
1573 next unless $ref->{"${type}_accno_id"};
1574 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1575 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1578 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1580 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1581 $ref = $sth_tax->fetchrow_hashref or next;
1583 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1584 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1586 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1591 $::lxdebug->leave_sub;
1594 sub get_basic_part_info {
1595 $main::lxdebug->enter_sub();
1600 Common::check_params(\%params, qw(id));
1602 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1605 $main::lxdebug->leave_sub();
1609 my $myconfig = \%main::myconfig;
1610 my $form = $main::form;
1612 my $dbh = $form->get_standard_dbh($myconfig);
1614 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1616 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1618 if ('' eq ref $params{id}) {
1619 $info = $info->[0] || { };
1621 $main::lxdebug->leave_sub();
1625 my %info_map = map { $_->{id} => $_ } @{ $info };
1627 $main::lxdebug->leave_sub();
1632 sub prepare_parts_for_printing {
1633 $main::lxdebug->enter_sub();
1638 my $myconfig = $params{myconfig} || \%main::myconfig;
1639 my $form = $params{form} || $main::form;
1641 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1643 my $prefix = $params{prefix} || 'id_';
1644 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1646 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1649 $main::lxdebug->leave_sub();
1653 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1654 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1656 LEFT JOIN vendor v ON (mm.make = v.id)
1657 WHERE mm.parts_id IN ($placeholders)|;
1661 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1663 while (my $ref = $sth->fetchrow_hashref()) {
1664 $makemodel{$ref->{parts_id}} ||= [];
1665 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1670 my @columns = qw(ean image microfiche drawing weight);
1672 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1674 WHERE id IN ($placeholders)|;
1676 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1678 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1680 foreach my $i (1 .. $rowcount) {
1681 my $id = $form->{"${prefix}${i}"};
1685 foreach (@columns) {
1686 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1689 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1690 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1692 next if (!$makemodel{$id});
1694 foreach my $ref (@{ $makemodel{$id} }) {
1695 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1699 $main::lxdebug->leave_sub();
1702 sub normalize_text_blocks {
1703 $main::lxdebug->enter_sub();
1708 my $form = $params{form} || $main::form;
1710 # check if feature is enabled (select normalize_part_descriptions from defaults)
1711 return unless ($::instance_conf->get_normalize_part_descriptions);
1713 foreach (qw(description notes)) {
1714 $form->{$_} =~ s/\s+$//s;
1715 $form->{$_} =~ s/^\s+//s;
1716 $form->{$_} =~ s/ {2,}/ /g;
1718 $main::lxdebug->leave_sub();