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;
45 use SL::Util qw(trim);
52 $main::lxdebug->enter_sub();
54 my ($self, $myconfig, $form) = @_;
56 my $dbh = $form->get_standard_dbh;
59 my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
60 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
63 foreach my $pg (@{ $pricegroups }) {
64 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
65 $form->{"pricegroup_id_$i"} = "$pg->{id}";
66 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
71 $form->{price_rows} = $i - 1;
73 $main::lxdebug->leave_sub();
78 sub retrieve_buchungsgruppen {
79 $main::lxdebug->enter_sub();
81 my ($self, $myconfig, $form) = @_;
85 my $dbh = $form->get_standard_dbh;
88 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
89 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
91 $main::lxdebug->leave_sub();
94 sub retrieve_assemblies {
95 $main::lxdebug->enter_sub();
97 my ($self, $myconfig, $form) = @_;
100 my $dbh = $form->get_standard_dbh;
102 my $where = qq|NOT p.obsolete|;
105 if ($form->{partnumber}) {
106 $where .= qq| AND (p.partnumber ILIKE ?)|;
107 push(@values, like($form->{partnumber}));
110 if ($form->{description}) {
111 $where .= qq| AND (p.description ILIKE ?)|;
112 push(@values, like($form->{description}));
115 # retrieve assembly items
117 qq|SELECT p.id, p.partnumber, p.description,
119 (SELECT sum(p2.inventory_accno_id)
120 FROM parts p2, assembly a
121 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
123 WHERE NOT p.obsolete AND p.part_type = 'assembly' $where|;
125 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
127 $main::lxdebug->leave_sub();
131 $main::lxdebug->enter_sub();
133 my ($self, $myconfig, $form) = @_;
135 my $i = $form->{assembly_rows};
137 my $where = qq|1 = 1|;
140 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
142 while (my ($column, $table) = each(%columns)) {
143 next unless ($form->{"${column}_$i"});
144 $where .= qq| AND ${table}.${column} ILIKE ?|;
145 push(@values, like($form->{"${column}_$i"}));
149 $where .= qq| AND NOT (p.id = ?)|;
150 push(@values, conv_i($form->{id}));
153 # Search for part ID overrides all other criteria.
154 if ($form->{"id_${i}"}) {
155 $where = qq|p.id = ?|;
156 @values = ($form->{"id_${i}"});
159 if ($form->{partnumber}) {
160 $where .= qq| ORDER BY p.partnumber|;
162 $where .= qq| ORDER BY p.description|;
166 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
167 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
168 p.price_factor_id, pfac.factor AS price_factor, p.notes as longdescription
170 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
171 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
173 $form->{item_list} = selectall_hashref_query($form, SL::DB->client->dbh, $query, @values);
175 $main::lxdebug->leave_sub();
180 # Warning, deep magic ahead.
181 # This function gets all parts from the database according to the filters specified
184 # sort revers - sorting field + direction
187 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
188 # partnumber ean description partsgroup microfiche drawing
191 # 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
194 # itemstatus = active | onhand | short | obsolete | orphaned
195 # searchitems = part | assembly | service
198 # make model - makemodel
199 # serialnumber transdatefrom transdateto - invoice/orderitems
202 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
203 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
204 # l_soldtotal - aggreg join to display total of sold quantity
205 # onhand - as above, but masking the simple itemstatus results (doh!)
206 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
207 # l_serialnumber - belonges to serialnumber filter
208 # l_deliverydate - displays deliverydate is sold etc. flags are active
209 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
212 # onhand - as above, but masking the simple itemstatus results (doh!)
214 # search by overrides of description
216 # disabled sanity checks and changes:
217 # - searchitems = assembly will no longer disable bought
218 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
219 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
220 # - itemstatus = obsolete will no longer disable onhand, short
221 # - allow sorting by ean
222 # - serialnumber filter also works if l_serialnumber isn't ticked
223 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
226 $main::lxdebug->enter_sub();
228 my ($self, $myconfig, $form) = @_;
229 my $dbh = $form->get_standard_dbh($myconfig);
231 $form->{parts} = +{ };
232 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
234 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
235 my @project_filters = qw(projectnumber projectdescription);
236 my @makemodel_filters = qw(make model);
237 my @invoice_oi_filters = qw(serialnumber soldtotal);
238 my @apoe_filters = qw(transdate);
239 my @like_filters = (@simple_filters, @invoice_oi_filters);
240 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
241 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image shop insertdate));
242 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
243 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
244 my @deliverydate_flags = qw(deliverydate);
245 # my @other_flags = qw(onhand); # ToDO: implement these
246 # my @inactive_flags = qw(l_subtotal short l_linetotal);
248 my @select_tokens = qw(id factor);
249 my @where_tokens = qw(1=1);
250 my @group_tokens = ();
252 my %joins_needed = ();
255 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
256 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
257 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
260 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
261 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
262 ) AS ioi ON ioi.parts_id = p.id|,
265 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
266 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
267 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
268 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
271 SELECT id, name, 'customer' AS cv FROM customer UNION
272 SELECT id, name, 'vendor' AS cv FROM vendor
273 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
274 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
275 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
277 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
280 deliverydate => 'apoe.', serialnumber => 'ioi.',
281 transdate => 'apoe.', trans_id => 'ioi.',
282 module => 'apoe.', name => 'cv.',
283 ordnumber => 'apoe.', make => 'mm.',
284 quonumber => 'apoe.', model => 'mm.',
285 invnumber => 'apoe.', partsgroup => 'pg.',
286 lastcost => 'p.', , soldtotal => ' ',
287 factor => 'pfac.', projectnumber => 'pj.',
288 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
291 serialnumber => 'ioi.',
292 quotation => 'apoe.',
298 # if the join condition in these blocks are met, the column
299 # of the scecified table will gently override (coalesce actually) the original value
300 # use it to conditionally coalesce values from subtables
301 my @column_override = (
302 # column name, prefix, joins_needed, nick name (in case column is named like another)
303 [ 'description', 'ioi.', 'invoice_oi' ],
304 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
305 [ 'transdate', 'apoe.', 'apoe' ],
306 [ 'unit', 'ioi.', 'invoice_oi' ],
307 [ 'sellprice', 'ioi.', 'invoice_oi' ],
310 # careful with renames. these are HARD, and any filters done on the original column will break
311 my %renamed_columns = (
312 'factor' => 'price_factor',
313 'SUM(ioi.qty)' => 'soldtotal',
314 'ioi.id' => 'ioi_id',
316 'projectdescription' => 'projectdescription',
317 'insertdate' => 'insertdate',
321 projectdescription => 'description',
322 insertdate => 'itime::DATE',
325 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
326 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
329 my $make_token_builder = sub {
330 my $joins_needed = shift;
332 my ($nick, $alias) = @_;
333 my ($col) = $real_column{$nick} || $nick;
334 my @coalesce_tokens =
335 map { ($_->[1] || 'p.') . $_->[0] }
336 grep { !$_->[2] || $joins_needed->{$_->[2]} }
337 grep { ($_->[3] || $_->[0]) eq $nick }
338 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
340 my $coalesce = scalar @coalesce_tokens > 1;
342 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
343 : shift @coalesce_tokens)
344 . ($alias && ($coalesce || $renamed_columns{$nick})
345 ? " AS " . ($renamed_columns{$nick} || $nick)
350 #===== switches and simple filters ========#
352 # special case transdate
353 if (grep { trim($form->{$_}) } qw(transdatefrom transdateto)) {
354 $form->{"l_transdate"} = 1;
355 push @select_tokens, 'transdate';
356 for (qw(transdatefrom transdateto)) {
357 my $value = trim($form->{$_});
359 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
360 push @bind_vars, $value;
364 # special case smart search
366 $form->{"l_$_"} = 1 for qw(partnumber description unit sellprice lastcost cvar_packaging linetotal);
367 push @where_tokens, "p.partnumber ILIKE ? OR p.description ILIKE ?";
368 push @bind_vars, (like($form->{all})) x 2;
371 # special case insertdate
372 if (grep { trim($form->{$_}) } qw(insertdatefrom insertdateto)) {
373 $form->{"l_insertdate"} = 1;
374 push @select_tokens, 'insertdate';
376 my $token_builder = $make_token_builder->();
377 my $token = $token_builder->('insertdate');
379 for (qw(insertdatefrom insertdateto)) {
380 my $value = trim($form->{$_});
382 push @where_tokens, sprintf "$token %s ?", /from$/ ? '>=' : '<=';
383 push @bind_vars, $value;
387 if ($form->{"partsgroup_id"}) {
388 $form->{"l_partsgroup"} = '1'; # show the column
389 push @where_tokens, "pg.id = ?";
390 push @bind_vars, $form->{"partsgroup_id"};
393 if ($form->{shop} ne '') {
394 $form->{l_shop} = '1'; # show the column
395 if ($form->{shop} eq '0' || $form->{shop} eq 'f') {
396 push @where_tokens, 'NOT p.shop';
399 push @where_tokens, 'p.shop';
403 foreach (@like_filters) {
404 next unless $form->{$_};
405 $form->{"l_$_"} = '1'; # show the column
406 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
407 push @bind_vars, like($form->{$_});
410 foreach (@simple_l_switches) {
411 next unless $form->{"l_$_"};
412 push @select_tokens, $_;
415 for ($form->{searchitems}) {
416 push @where_tokens, "p.part_type = 'part'" if /part/;
417 push @where_tokens, "p.part_type = 'service'" if /service/;
418 push @where_tokens, "p.part_type = 'assembly'" if /assembly/;
421 for ($form->{itemstatus}) {
422 push @where_tokens, 'p.id NOT IN
423 (SELECT DISTINCT parts_id FROM invoice UNION
424 SELECT DISTINCT parts_id FROM assembly UNION
425 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
426 push @where_tokens, 'p.onhand = 0' if /orphaned/;
427 push @where_tokens, 'NOT p.obsolete' if /active/;
428 push @where_tokens, ' p.obsolete', if /obsolete/;
429 push @where_tokens, 'p.onhand > 0', if /onhand/;
430 push @where_tokens, 'p.onhand < p.rop', if /short/;
433 my $q_assembly_lastcost =
434 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
436 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
437 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
438 WHERE (a_lc.id = p.id)) AS lastcost|;
439 $table_prefix{$q_assembly_lastcost} = ' ';
441 # special case makemodel search
442 # all_parts is based upon the assumption that every parameter is named like the column it represents
443 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
444 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
446 push @where_tokens, 'mv.name ILIKE ?';
447 push @bind_vars, like($form->{make});
449 if ($form->{model}) {
450 push @where_tokens, 'mm.model ILIKE ?';
451 push @bind_vars, like($form->{model});
454 # special case: sorting by partnumber
455 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
456 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
457 # ToDO: implement proper functional sorting
458 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
459 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
460 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
461 # if $form->{sort} eq 'partnumber';
463 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
466 $limit_clause = " LIMIT 100" if $form->{top100};
467 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
469 #=== joins and complicated filters ========#
471 my $bsooqr = any { $form->{$_} } @oe_flags;
472 my @bsooqr_tokens = ();
474 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
475 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
476 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
477 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
478 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
479 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
480 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
481 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
482 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
483 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
485 $joins_needed{partsgroup} = 1;
486 $joins_needed{pfac} = 1;
487 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
488 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
489 $joins_needed{mv} = 1 if $joins_needed{makemodel};
490 $joins_needed{cv} = 1 if $bsooqr;
491 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
492 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
494 # special case for description search.
495 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
496 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
497 # find the old entries in of @where_tokens and @bind_vars, and adjust them
498 if ($joins_needed{invoice_oi}) {
499 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
500 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
501 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
502 splice @bind_vars, $bi, 0, $bind_vars[$bi];
507 # now the master trick: soldtotal.
508 if ($form->{l_soldtotal}) {
509 push @where_tokens, 'NOT ioi.qty = 0';
510 push @group_tokens, @select_tokens;
511 map { s/.*\sAS\s+//si } @group_tokens;
512 push @select_tokens, 'SUM(ioi.qty)';
515 #============= build query ================#
517 my $token_builder = $make_token_builder->(\%joins_needed);
519 my @sort_cols = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate insertdate shop));
520 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
521 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
522 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
524 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
525 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
526 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
527 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
529 my %oe_flag_to_cvar = (
532 onorder => 'orderitems',
533 ordered => 'orderitems',
535 quoted => 'orderitems',
538 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
540 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
542 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
546 $where_clause .= qq| AND ($cvar_where)|;
547 push @bind_vars, @cvar_values;
550 my $query = <<" SQL";
551 SELECT DISTINCT $select_clause
560 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
562 map { $_->{onhand} *= 1 } @{ $form->{parts} };
564 # fix qty sign in ap. those are saved negative
565 if ($bsooqr && $form->{bought}) {
566 for my $row (@{ $form->{parts} }) {
567 $row->{qty} *= -1 if $row->{module} eq 'ir';
571 # post processing for assembly parts lists (bom)
572 # for each part get the assembly parts and add them into the partlist.
574 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
576 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
577 p.unit, p.notes, p.itime::DATE as insertdate,
578 p.sellprice, p.listprice, p.lastcost,
579 p.rop, p.weight, p.priceupdate,
580 p.image, p.drawing, p.microfiche,
583 INNER JOIN assembly a ON (p.id = a.parts_id)
586 my $sth = prepare_query($form, $dbh, $query);
588 foreach my $item (@{ $form->{parts} }) {
589 push(@assemblies, $item);
590 do_statement($form, $sth, $query, conv_i($item->{id}));
592 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
593 $ref->{assemblyitem} = 1;
594 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
595 push(@assemblies, $ref);
600 # copy assemblies to $form->{parts}
601 $form->{parts} = \@assemblies;
604 if ($form->{l_pricegroups} ) {
606 SELECT parts_id, price, pricegroup_id
611 my $sth = prepare_query($form, $dbh, $query);
613 foreach my $part (@{ $form->{parts} }) {
614 do_statement($form, $sth, $query, conv_i($part->{id}));
616 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
617 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
624 $main::lxdebug->leave_sub();
626 return @{ $form->{parts} };
629 sub _create_filter_for_priceupdate {
630 $main::lxdebug->enter_sub();
633 my $myconfig = \%main::myconfig;
634 my $form = $main::form;
639 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
642 next unless ($form->{$column});
644 $where .= qq| AND $item ILIKE ?|;
645 push(@where_values, like($form->{$column}));
648 foreach my $item (qw(description serialnumber)) {
649 next unless ($form->{$item});
651 $where .= qq| AND (${item} ILIKE ?)|;
652 push(@where_values, like($form->{$item}));
656 # items which were never bought, sold or on an order
657 if ($form->{itemstatus} eq 'orphaned') {
659 qq| AND (p.onhand = 0)
662 SELECT DISTINCT parts_id FROM invoice
664 SELECT DISTINCT parts_id FROM assembly
666 SELECT DISTINCT parts_id FROM orderitems
669 } elsif ($form->{itemstatus} eq 'active') {
670 $where .= qq| AND p.obsolete = '0'|;
672 } elsif ($form->{itemstatus} eq 'obsolete') {
673 $where .= qq| AND p.obsolete = '1'|;
675 } elsif ($form->{itemstatus} eq 'onhand') {
676 $where .= qq| AND p.onhand > 0|;
678 } elsif ($form->{itemstatus} eq 'short') {
679 $where .= qq| AND p.onhand < p.rop|;
683 foreach my $column (qw(make model)) {
684 next unless ($form->{$column});
685 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
686 push(@where_values, like($form->{$column}));
689 $main::lxdebug->leave_sub();
691 return ($where, @where_values);
694 sub get_num_matches_for_priceupdate {
695 $main::lxdebug->enter_sub();
699 my $myconfig = \%main::myconfig;
700 my $form = $main::form;
702 my $dbh = $form->get_standard_dbh($myconfig);
704 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
709 for my $column (qw(sellprice listprice)) {
710 next if ($form->{$column} eq "");
718 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
720 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
721 $num_updated += $result if (0 <= $result);
730 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
731 WHERE $where) AND (pricegroup_id = ?)|;
732 my $sth = prepare_query($form, $dbh, $query);
734 for my $i (1 .. $form->{price_rows}) {
735 next if ($form->{"price_$i"} eq "");
737 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
738 $num_updated += $result if (0 <= $result);
742 $main::lxdebug->leave_sub();
748 my ($self, $myconfig, $form) = @_;
749 $main::lxdebug->enter_sub();
751 my $num_updated = SL::DB->client->with_transaction(\&_update_prices, $self, $myconfig, $form);
753 $main::lxdebug->leave_sub();
758 my ($self, $myconfig, $form) = @_;
760 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
763 # connect to database
764 my $dbh = SL::DB->client->dbh;
766 for my $column (qw(sellprice listprice)) {
767 next if ($form->{$column} eq "");
769 my $value = $form->parse_amount($myconfig, $form->{$column});
772 if ($form->{"${column}_type"} eq "percent") {
773 $value = ($value / 100) + 1;
778 qq|UPDATE parts SET $column = $column $operator ?
782 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
784 my $result = do_query($form, $dbh, $query, $value, @where_values);
785 $num_updated += $result if (0 <= $result);
789 qq|UPDATE prices SET price = price + ?
793 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
794 WHERE $where) AND (pricegroup_id = ?)|;
795 my $sth_add = prepare_query($form, $dbh, $q_add);
798 qq|UPDATE prices SET price = price * ?
802 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
803 WHERE $where) AND (pricegroup_id = ?)|;
804 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
806 for my $i (1 .. $form->{price_rows}) {
807 next if ($form->{"price_$i"} eq "");
809 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
812 if ($form->{"pricegroup_type_$i"} eq "percent") {
813 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
815 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
818 $num_updated += $result if (0 <= $result);
822 $sth_multiply->finish();
827 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
829 $main::lxdebug->enter_sub();
831 my ($self, $myconfig, $form, $sortorder) = @_;
832 my $dbh = $form->get_standard_dbh;
833 my $order = qq| p.partnumber|;
834 my $where = qq|1 = 1|;
837 if ($sortorder eq "all") {
838 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
839 push(@values, like($form->{partnumber}), like($form->{description}));
841 } elsif ($sortorder eq "partnumber") {
842 $where .= qq| AND (partnumber ILIKE ?)|;
843 push(@values, like($form->{partnumber}));
845 } elsif ($sortorder eq "description") {
846 $where .= qq| AND (description ILIKE ?)|;
847 push(@values, like($form->{description}));
848 $order = "description";
853 qq|SELECT id, partnumber, description, unit, sellprice
855 WHERE $where ORDER BY $order|;
857 my $sth = prepare_execute_query($form, $dbh, $query, @values);
860 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
861 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
866 $form->{"id_$j"} = $ref->{id};
867 $form->{"partnumber_$j"} = $ref->{partnumber};
868 $form->{"description_$j"} = $ref->{description};
869 $form->{"unit_$j"} = $ref->{unit};
870 $form->{"sellprice_$j"} = $ref->{sellprice};
871 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
876 $main::lxdebug->leave_sub();
881 # gets sum of sold part with part_id
883 $main::lxdebug->enter_sub();
887 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
888 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
891 $main::lxdebug->leave_sub();
896 sub follow_account_chain {
897 $main::lxdebug->enter_sub(2);
899 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
901 my @visited_accno_ids = ($accno_id);
905 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
906 map { $_->{id} => $_ }
907 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
908 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
910 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
911 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
915 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
916 last unless ($ref && $ref->{"is_valid"} &&
917 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
918 $accno_id = $ref->{"new_chart_id"};
919 $accno = $ref->{"accno"};
920 push(@visited_accno_ids, $accno_id);
923 $main::lxdebug->leave_sub(2);
925 return ($accno_id, $accno);
928 sub retrieve_accounts {
929 $main::lxdebug->enter_sub;
932 my $myconfig = shift;
934 my $dbh = $form->get_standard_dbh;
935 my %args = @_; # index => part_id
937 $form->{taxzone_id} *= 1;
939 return unless grep $_, values %args; # shortfuse if no part_id supplied
943 if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
944 # use deliverydate for sales and purchase invoice, if it exists
945 # also use deliverydate for credit notes
946 if (!$form->{deliverydate}) {
947 $transdate = $form->{invdate};
949 $transdate = $form->{deliverydate};
951 } elsif ($form->{script} eq 'ir.pl') {
952 # when a purchase invoice is opened from the report of purchase invoices
953 # $form->{type} isn't set, but $form->{script} is, not sure why this is or
954 # whether this distinction matters in some other scenario. Otherwise one
955 # could probably take out this elsif and add a
956 # " or $form->{script} eq 'ir.pl' "
957 # to the above if-statement
958 if (!$form->{deliverydate}) {
959 $transdate = $form->{invdate};
961 $transdate = $form->{deliverydate};
963 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
964 # if credit_note has a deliverydate, use this instead of invdate
965 # useful for credit_notes of invoices from an old period with different tax
966 # if there is no deliverydate then invdate is used, old default (see next elsif)
967 # Falls hier der Stichtag für Steuern anders bestimmt wird,
968 # entsprechend auch bei Taxkeys.pm anpassen
969 $transdate = $form->{deliverydate};
970 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
971 $transdate = $form->{invdate};
973 $transdate = $form->{transdate};
976 if ($transdate eq "") {
977 $transdate = DateTime->today_local->to_lxoffice;
979 $transdate = $dbh->quote($transdate);
982 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
984 my @part_ids = grep { $_ } values %args;
985 my $in = join ',', ('?') x @part_ids;
987 my %accno_by_part = map { $_->{id} => $_ }
988 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
991 bg.inventory_accno_id,
992 tc.income_accno_id AS income_accno_id,
993 tc.expense_accno_id AS expense_accno_id,
994 c1.accno AS inventory_accno,
995 c2.accno AS income_accno,
996 c3.accno AS expense_accno
998 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
999 LEFT JOIN taxzone_charts tc on bg.id = tc.buchungsgruppen_id
1000 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1001 LEFT JOIN chart c2 ON tc.income_accno_id = c2.id
1002 LEFT JOIN chart c3 ON tc.expense_accno_id = c3.id
1004 tc.taxzone_id = '$form->{taxzone_id}'
1009 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1010 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1012 LEFT JOIN chart c ON c.id = t.chart_id
1016 WHERE tk.chart_id = ? AND startdate <= ?
1017 ORDER BY startdate DESC LIMIT 1)
1020 while (my ($index => $part_id) = each %args) {
1021 my $ref = $accno_by_part{$part_id} or next;
1023 $ref->{"inventory_accno_id"} = undef unless $ref->{"part_type"} eq 'part';
1026 for my $type (qw(inventory income expense)) {
1027 next unless $ref->{"${type}_accno_id"};
1028 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1029 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1032 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1034 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1035 $ref = $sth_tax->fetchrow_hashref or next;
1037 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1038 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1040 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1045 $::lxdebug->leave_sub;
1048 sub get_basic_part_info {
1049 $main::lxdebug->enter_sub();
1054 Common::check_params(\%params, qw(id));
1056 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1059 $main::lxdebug->leave_sub();
1063 my $myconfig = \%main::myconfig;
1064 my $form = $main::form;
1066 my $dbh = $form->get_standard_dbh($myconfig);
1068 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1070 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1072 if ('' eq ref $params{id}) {
1073 $info = $info->[0] || { };
1075 $main::lxdebug->leave_sub();
1079 my %info_map = map { $_->{id} => $_ } @{ $info };
1081 $main::lxdebug->leave_sub();
1086 sub prepare_parts_for_printing {
1087 $main::lxdebug->enter_sub();
1092 my $myconfig = $params{myconfig} || \%main::myconfig;
1093 my $form = $params{form} || $main::form;
1095 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1097 my $prefix = $params{prefix} || 'id_';
1098 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1100 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1103 $main::lxdebug->leave_sub();
1107 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1108 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1110 LEFT JOIN vendor v ON (mm.make = v.id)
1111 WHERE mm.parts_id IN ($placeholders)|;
1115 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1117 while (my $ref = $sth->fetchrow_hashref()) {
1118 $makemodel{$ref->{parts_id}} ||= [];
1119 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1124 my @columns = qw(ean image microfiche drawing);
1126 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1128 WHERE id IN ($placeholders)|;
1130 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1132 my %template_arrays;
1133 map { $template_arrays{$_} = [] } (qw(make model), @columns);
1135 foreach my $i (1 .. $rowcount) {
1136 my $id = $form->{"${prefix}${i}"};
1140 foreach (@columns) {
1141 push @{ $template_arrays{$_} }, $data{$id}->{$_};
1144 push @{ $template_arrays{make} }, [];
1145 push @{ $template_arrays{model} }, [];
1147 next if (!$makemodel{$id});
1149 foreach my $ref (@{ $makemodel{$id} }) {
1150 map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(make model);
1154 my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
1155 my %parts_by_id = map { $_->id => $_ } @$parts;
1157 for my $i (1..$rowcount) {
1158 my $id = $form->{"${prefix}${i}"};
1161 push @{ $template_arrays{part_type} }, $parts_by_id{$id}->type;
1164 return %template_arrays;
1165 $main::lxdebug->leave_sub();
1168 sub normalize_text_blocks {
1169 $main::lxdebug->enter_sub();
1174 my $form = $params{form} || $main::form;
1176 # check if feature is enabled (select normalize_part_descriptions from defaults)
1177 return unless ($::instance_conf->get_normalize_part_descriptions);
1179 foreach (qw(description notes)) {
1180 $form->{$_} =~ s/\s+$//s;
1181 $form->{$_} =~ s/^\s+//s;
1182 $form->{$_} =~ s/ {2,}/ /g;
1184 $main::lxdebug->leave_sub();