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., 51 Franklin Street, Fifth Floor, Boston,
30 #======================================================================
32 # Inventory Control backend
34 #======================================================================
39 use List::MoreUtils qw(all any uniq);
44 use SL::HTML::Restrict;
46 use SL::Util qw(trim);
48 use SL::Presenter::Part qw(type_abbreviation classification_abbreviation separate_abbreviation);
53 sub retrieve_buchungsgruppen {
54 $main::lxdebug->enter_sub();
56 my ($self, $myconfig, $form) = @_;
60 my $dbh = $form->get_standard_dbh;
63 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
64 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
66 $main::lxdebug->leave_sub();
70 $main::lxdebug->enter_sub();
72 my ($self, $myconfig, $form) = @_;
74 my $i = $form->{assembly_rows};
76 my $where = qq|1 = 1|;
79 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
81 while (my ($column, $table) = each(%columns)) {
82 next unless ($form->{"${column}_$i"});
83 $where .= qq| AND ${table}.${column} ILIKE ?|;
84 push(@values, like($form->{"${column}_$i"}));
88 $where .= qq| AND NOT (p.id = ?)|;
89 push(@values, conv_i($form->{id}));
92 # Search for part ID overrides all other criteria.
93 if ($form->{"id_${i}"}) {
94 $where = qq|p.id = ?|;
95 @values = ($form->{"id_${i}"});
98 if ($form->{partnumber}) {
99 $where .= qq| ORDER BY p.partnumber|;
101 $where .= qq| ORDER BY p.description|;
105 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
107 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
108 p.price_factor_id, pfac.factor AS price_factor, p.notes as longdescription
110 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
111 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
113 $form->{item_list} = selectall_hashref_query($form, SL::DB->client->dbh, $query, @values);
115 $main::lxdebug->leave_sub();
120 # Warning, deep magic ahead.
121 # This function gets all parts from the database according to the filters specified
124 # sort revers - sorting field + direction
127 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
128 # partnumber ean description partsgroup microfiche drawing
131 # 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
135 # itemstatus = active | onhand | short | obsolete | orphaned
136 # searchitems = part | assembly | service
139 # make model - makemodel
140 # serialnumber transdatefrom transdateto - invoice/orderitems
141 # warehouse - warehouse
145 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
146 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
147 # l_soldtotal - aggreg join to display total of sold quantity
148 # onhand - as above, but masking the simple itemstatus results (doh!)
149 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
150 # l_serialnumber - belonges to serialnumber filter
151 # l_deliverydate - displays deliverydate is sold etc. flags are active
152 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
155 # onhand - as above, but masking the simple itemstatus results (doh!)
157 # search by overrides of description
158 # soldtotal drops option default warehouse and bin
159 # soldtotal can not work if there are no documents checked
161 # disabled sanity checks and changes:
162 # - searchitems = assembly will no longer disable bought
163 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
164 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
165 # - itemstatus = obsolete will no longer disable onhand, short
166 # - allow sorting by ean
167 # - serialnumber filter also works if l_serialnumber isn't ticked
168 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
171 $main::lxdebug->enter_sub();
173 my ($self, $myconfig, $form) = @_;
174 my $dbh = $form->get_standard_dbh($myconfig);
176 # sanity backend check
177 croak "Cannot combine soldtotal with default bin or default warehouse" if ($form->{l_soldtotal} && ($form->{l_bin} || $form->{l_warehouse}));
179 $form->{parts} = +{ };
180 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
182 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
183 my @project_filters = qw(projectnumber projectdescription);
184 my @makemodel_filters = qw(make model);
185 my @invoice_oi_filters = qw(serialnumber soldtotal);
186 my @apoe_filters = qw(transdate);
187 my @like_filters = (@simple_filters, @invoice_oi_filters);
188 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
189 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image shop insertdate));
190 my %no_simple_l_switches = (warehouse => 'wh.description as warehouse', bin => 'bin.description as bin');
191 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
192 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
193 my @deliverydate_flags = qw(deliverydate);
194 # my @other_flags = qw(onhand); # ToDO: implement these
195 # my @inactive_flags = qw(l_subtotal short l_linetotal);
197 my @select_tokens = qw(id factor part_type classification_id);
198 my @where_tokens = qw(1=1);
199 my @group_tokens = ();
201 my %joins_needed = ();
204 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
205 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
206 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
209 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
210 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
211 ) AS ioi ON ioi.parts_id = p.id|,
214 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
215 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
216 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
217 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
220 SELECT id, name, 'customer' AS cv FROM customer UNION
221 SELECT id, name, 'vendor' AS cv FROM vendor
222 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
223 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
224 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
225 warehouse => 'LEFT JOIN warehouse AS wh ON wh.id = p.warehouse_id',
226 bin => 'LEFT JOIN bin ON bin.id = p.bin_id',
228 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project warehouse bin);
231 deliverydate => 'apoe.', serialnumber => 'ioi.',
232 transdate => 'apoe.', trans_id => 'ioi.',
233 module => 'apoe.', name => 'cv.',
234 ordnumber => 'apoe.', make => 'mm.',
235 quonumber => 'apoe.', model => 'mm.',
236 invnumber => 'apoe.', partsgroup => 'pg.',
237 lastcost => 'p.', , soldtotal => ' ',
238 factor => 'pfac.', projectnumber => 'pj.',
239 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
242 serialnumber => 'ioi.',
243 quotation => 'apoe.',
249 # if the join condition in these blocks are met, the column
250 # of the specified table will gently override (coalesce actually) the original value
251 # use it to conditionally coalesce values from subtables
252 my @column_override = (
253 # column name, prefix, joins_needed, nick name (in case column is named like another)
254 [ 'description', 'ioi.', 'invoice_oi' ],
255 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
256 [ 'transdate', 'apoe.', 'apoe' ],
257 [ 'unit', 'ioi.', 'invoice_oi' ],
258 [ 'sellprice', 'ioi.', 'invoice_oi' ],
261 # careful with renames. these are HARD, and any filters done on the original column will break
262 my %renamed_columns = (
263 'factor' => 'price_factor',
264 'SUM(ioi.qty)' => 'soldtotal',
265 'ioi.id' => 'ioi_id',
267 'projectdescription' => 'projectdescription',
268 'insertdate' => 'insertdate',
272 projectdescription => 'description',
273 insertdate => 'itime::DATE',
276 if ($form->{l_assembly} && $form->{l_lastcost}) {
277 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
280 my $make_token_builder = sub {
281 my $joins_needed = shift;
283 my ($nick, $alias) = @_;
284 my ($col) = $real_column{$nick} || $nick;
285 my @coalesce_tokens =
286 map { ($_->[1] || 'p.') . $_->[0] }
287 grep { !$_->[2] || $joins_needed->{$_->[2]} }
288 grep { ($_->[3] || $_->[0]) eq $nick }
289 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
291 my $coalesce = scalar @coalesce_tokens > 1;
293 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
294 : shift @coalesce_tokens)
295 . ($alias && ($coalesce || $renamed_columns{$nick})
296 ? " AS " . ($renamed_columns{$nick} || $nick)
301 #===== switches and simple filters ========#
303 # special case transdate
304 if (grep { trim($form->{$_}) } qw(transdatefrom transdateto)) {
305 $form->{"l_transdate"} = 1;
306 push @select_tokens, 'transdate';
307 for (qw(transdatefrom transdateto)) {
308 my $value = trim($form->{$_});
310 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
311 push @bind_vars, $value;
315 # special case smart search
317 $form->{"l_$_"} = 1 for qw(partnumber description unit sellprice lastcost linetotal);
318 $form->{l_service} = 1 if $form->{searchitems} eq 'service' || $form->{searchitems} eq '';
319 $form->{l_assembly} = 1 if $form->{searchitems} eq 'assembly' || $form->{searchitems} eq '';
320 $form->{l_part} = 1 if $form->{searchitems} eq 'part' || $form->{searchitems} eq '';
321 $form->{l_assortment} = 1 if $form->{searchitems} eq 'assortment' || $form->{searchitems} eq '';
322 push @where_tokens, "p.partnumber ILIKE ? OR p.description ILIKE ?";
323 push @bind_vars, (like($form->{all})) x 2;
326 # special case insertdate
327 if (grep { trim($form->{$_}) } qw(insertdatefrom insertdateto)) {
328 $form->{"l_insertdate"} = 1;
329 push @select_tokens, 'insertdate';
331 my $token_builder = $make_token_builder->();
332 my $token = $token_builder->('insertdate');
334 for (qw(insertdatefrom insertdateto)) {
335 my $value = trim($form->{$_});
337 push @where_tokens, sprintf "$token %s ?", /from$/ ? '>=' : '<=';
338 push @bind_vars, $value;
342 if ($form->{"partsgroup_id"}) {
343 $form->{"l_partsgroup"} = '1'; # show the column
344 push @where_tokens, "pg.id = ?";
345 push @bind_vars, $form->{"partsgroup_id"};
348 if ($form->{shop} ne '') {
349 $form->{l_shop} = '1'; # show the column
350 if ($form->{shop} eq '0' || $form->{shop} eq 'f') {
351 push @where_tokens, 'NOT p.shop';
354 push @where_tokens, 'p.shop';
358 foreach (@like_filters) {
359 next unless $form->{$_};
360 $form->{"l_$_"} = '1'; # show the column
361 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
362 push @bind_vars, like($form->{$_});
365 foreach (@simple_l_switches) {
366 next unless $form->{"l_$_"};
367 push @select_tokens, $_;
370 # Oder Bedingungen fuer Ware Dienstleistung Erzeugnis:
371 if ($form->{l_part} || $form->{l_assembly} || $form->{l_service} || $form->{l_assortment}) {
373 push @or_tokens, "p.part_type = 'service'" if $form->{l_service};
374 push @or_tokens, "p.part_type = 'assembly'" if $form->{l_assembly};
375 push @or_tokens, "p.part_type = 'part'" if $form->{l_part};
376 push @or_tokens, "p.part_type = 'assortment'" if $form->{l_assortment};
377 push @where_tokens, join ' OR ', map { "($_)" } @or_tokens;
381 push @where_tokens, q|'F' = 'T'|;
384 if ( $form->{classification_id} > 0 ) {
385 push @where_tokens, "p.classification_id = ?";
386 push @bind_vars, $form->{classification_id};
389 for ($form->{itemstatus}) {
390 push @where_tokens, 'p.id NOT IN
391 (SELECT DISTINCT parts_id FROM invoice UNION
392 SELECT DISTINCT parts_id FROM assembly UNION
393 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
394 push @where_tokens, 'p.onhand = 0' if /orphaned/;
395 push @where_tokens, 'NOT p.obsolete' if /active/;
396 push @where_tokens, ' p.obsolete', if /obsolete/;
397 push @where_tokens, 'p.onhand > 0', if /onhand/;
398 push @where_tokens, 'p.onhand < p.rop', if /short/;
401 my $q_assembly_lastcost =
402 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
404 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
405 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
406 WHERE (a_lc.id = p.id)) AS lastcost|;
407 $table_prefix{$q_assembly_lastcost} = ' ';
409 # special case makemodel search
410 # all_parts is based upon the assumption that every parameter is named like the column it represents
411 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
412 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
414 push @where_tokens, 'mv.name ILIKE ?';
415 push @bind_vars, like($form->{make});
417 if ($form->{model}) {
418 push @where_tokens, 'mm.model ILIKE ?';
419 push @bind_vars, like($form->{model});
422 # special case: sorting by partnumber
423 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
424 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
425 # ToDO: implement proper functional sorting
426 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
427 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
428 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
429 # if $form->{sort} eq 'partnumber';
431 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
434 $limit_clause = " LIMIT 100" if $form->{top100};
435 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
437 #=== joins and complicated filters ========#
439 my $bsooqr = any { $form->{$_} } @oe_flags;
440 my @bsooqr_tokens = ();
442 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
443 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
444 push @select_tokens, $q_assembly_lastcost if $form->{l_assembly} && $form->{l_lastcost};
445 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
446 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
447 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
448 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
449 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
450 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
451 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
453 $joins_needed{partsgroup} = 1;
454 $joins_needed{pfac} = 1;
455 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
456 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
457 $joins_needed{mv} = 1 if $joins_needed{makemodel};
458 $joins_needed{cv} = 1 if $bsooqr;
459 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
460 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
461 $joins_needed{bin} = 1 if $form->{l_bin};
462 $joins_needed{warehouse} = 1 if $form->{l_warehouse};
464 # special case for description search.
465 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
466 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
467 # find the old entries in of @where_tokens and @bind_vars, and adjust them
468 if ($joins_needed{invoice_oi}) {
469 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
470 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
471 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
472 splice @bind_vars, $bi, 0, $bind_vars[$bi];
477 # now the master trick: soldtotal.
478 if ($form->{l_soldtotal}) {
479 push @where_tokens, 'NOT ioi.qty = 0';
480 push @group_tokens, @select_tokens;
481 map { s/.*\sAS\s+//si } @group_tokens;
482 push @select_tokens, 'SUM(ioi.qty)';
485 #============= build query ================#
487 my $token_builder = $make_token_builder->(\%joins_needed);
489 my @sort_cols = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate insertdate shop));
490 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
491 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
492 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
494 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
495 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
496 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
497 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
499 # key of %no_simple_l_switch is the logical l_switch.
500 # the assigned value is the 'not so simple
502 my $no_simple_select_clause;
503 foreach my $no_simple_l_switch (keys %no_simple_l_switches) {
504 next unless $form->{"l_${no_simple_l_switch}"};
505 $no_simple_select_clause .= ', '. $no_simple_l_switches{$no_simple_l_switch};
507 $select_clause .= $no_simple_select_clause;
509 my %oe_flag_to_cvar = (
512 onorder => 'orderitems',
513 ordered => 'orderitems',
515 quoted => 'orderitems',
518 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
520 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
522 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
526 $where_clause .= qq| AND ($cvar_where)|;
527 push @bind_vars, @cvar_values;
530 my $query = <<" SQL";
531 SELECT DISTINCT $select_clause
540 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
542 map { $_->{onhand} *= 1 } @{ $form->{parts} };
544 # fix qty sign in ap. those are saved negative
545 if ($bsooqr && $form->{bought}) {
546 for my $row (@{ $form->{parts} }) {
547 $row->{qty} *= -1 if $row->{module} eq 'ir';
551 # post processing for assembly parts lists (bom)
552 # for each part get the assembly parts and add them into the partlist.
554 if ($form->{l_assembly} && $form->{bom}) {
556 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
557 p.unit, p.notes, p.itime::DATE as insertdate,
558 p.sellprice, p.listprice, p.lastcost,
559 p.rop, p.weight, p.priceupdate,
560 p.image, p.drawing, p.microfiche,
563 INNER JOIN assembly a ON (p.id = a.parts_id)
566 my $sth = prepare_query($form, $dbh, $query);
568 foreach my $item (@{ $form->{parts} }) {
569 push(@assemblies, $item);
570 do_statement($form, $sth, $query, conv_i($item->{id}));
572 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
573 $ref->{assemblyitem} = 1;
574 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
575 push(@assemblies, $ref);
580 # copy assemblies to $form->{parts}
581 $form->{parts} = \@assemblies;
584 if ($form->{l_pricegroups} ) {
586 SELECT parts_id, price, pricegroup_id
591 my $sth = prepare_query($form, $dbh, $query);
593 foreach my $part (@{ $form->{parts} }) {
594 do_statement($form, $sth, $query, conv_i($part->{id}));
596 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
597 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
603 $main::lxdebug->leave_sub();
605 return $form->{parts};
608 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
610 $main::lxdebug->enter_sub();
612 my ($self, $myconfig, $form, $sortorder) = @_;
613 my $dbh = $form->get_standard_dbh;
614 my $order = qq| p.partnumber|;
615 my $where = qq|1 = 1|;
618 if ($sortorder eq "all") {
619 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
620 push(@values, like($form->{partnumber}), like($form->{description}));
622 } elsif ($sortorder eq "partnumber") {
623 $where .= qq| AND (partnumber ILIKE ?)|;
624 push(@values, like($form->{partnumber}));
626 } elsif ($sortorder eq "description") {
627 $where .= qq| AND (description ILIKE ?)|;
628 push(@values, like($form->{description}));
629 $order = "description";
634 qq|SELECT id, partnumber, description, unit, sellprice,
637 WHERE $where ORDER BY $order|;
639 my $sth = prepare_execute_query($form, $dbh, $query, @values);
642 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
643 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
648 $form->{"type_and_classific_$j"} = type_abbreviation($ref->{part_type}).
649 classification_abbreviation($ref->{classification_id});
650 $form->{"id_$j"} = $ref->{id};
651 $form->{"partnumber_$j"} = $ref->{partnumber};
652 $form->{"description_$j"} = $ref->{description};
653 $form->{"unit_$j"} = $ref->{unit};
654 $form->{"sellprice_$j"} = $ref->{sellprice};
655 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
660 $main::lxdebug->leave_sub();
665 # gets sum of sold part with part_id
667 $main::lxdebug->enter_sub();
671 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
672 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
675 $main::lxdebug->leave_sub();
680 sub follow_account_chain {
681 $main::lxdebug->enter_sub(2);
683 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
685 my @visited_accno_ids = ($accno_id);
689 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
690 map { $_->{id} => $_ }
691 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
692 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
694 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
695 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
699 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
700 last unless ($ref && $ref->{"is_valid"} &&
701 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
702 $accno_id = $ref->{"new_chart_id"};
703 $accno = $ref->{"accno"};
704 push(@visited_accno_ids, $accno_id);
707 $main::lxdebug->leave_sub(2);
709 return ($accno_id, $accno);
712 sub retrieve_accounts {
713 $main::lxdebug->enter_sub;
716 my $myconfig = shift;
718 my $dbh = $form->get_standard_dbh;
719 my %args = @_; # index => part_id
721 $form->{taxzone_id} *= 1;
723 return unless grep $_, values %args; # shortfuse if no part_id supplied
727 if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
728 # use deliverydate for sales and purchase invoice, if it exists
729 # also use deliverydate for credit notes
730 if (!$form->{deliverydate}) {
731 $transdate = $form->{invdate};
733 $transdate = $form->{deliverydate};
735 } elsif ($form->{script} eq 'ir.pl') {
736 # when a purchase invoice is opened from the report of purchase invoices
737 # $form->{type} isn't set, but $form->{script} is, not sure why this is or
738 # whether this distinction matters in some other scenario. Otherwise one
739 # could probably take out this elsif and add a
740 # " or $form->{script} eq 'ir.pl' "
741 # to the above if-statement
742 if (!$form->{deliverydate}) {
743 $transdate = $form->{invdate};
745 $transdate = $form->{deliverydate};
747 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
748 # if credit_note has a deliverydate, use this instead of invdate
749 # useful for credit_notes of invoices from an old period with different tax
750 # if there is no deliverydate then invdate is used, old default (see next elsif)
751 # Falls hier der Stichtag für Steuern anders bestimmt wird,
752 # entsprechend auch bei Taxkeys.pm anpassen
753 $transdate = $form->{deliverydate};
754 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
755 $transdate = $form->{invdate};
757 $transdate = $form->{transdate};
760 if ($transdate eq "") {
761 $transdate = DateTime->today_local->to_lxoffice;
763 $transdate = $dbh->quote($transdate);
766 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
768 my @part_ids = grep { $_ } values %args;
769 my $in = join ',', ('?') x @part_ids;
771 my %accno_by_part = map { $_->{id} => $_ }
772 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
775 bg.inventory_accno_id,
776 tc.income_accno_id AS income_accno_id,
777 tc.expense_accno_id AS expense_accno_id,
778 c1.accno AS inventory_accno,
779 c2.accno AS income_accno,
780 c3.accno AS expense_accno
782 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
783 LEFT JOIN taxzone_charts tc on bg.id = tc.buchungsgruppen_id
784 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
785 LEFT JOIN chart c2 ON tc.income_accno_id = c2.id
786 LEFT JOIN chart c3 ON tc.expense_accno_id = c3.id
788 tc.taxzone_id = '$form->{taxzone_id}'
793 my $query_tax = <<SQL;
794 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
796 LEFT JOIN chart c ON c.id = t.chart_id
800 WHERE tk.chart_id = ? AND startdate <= ?
801 ORDER BY startdate DESC LIMIT 1)
803 my $sth_tax = prepare_query($::form, $dbh, $query_tax);
805 while (my ($index => $part_id) = each %args) {
806 my $ref = $accno_by_part{$part_id} or next;
808 $ref->{"inventory_accno_id"} = undef unless $ref->{"part_type"} eq 'part';
811 for my $type (qw(inventory income expense)) {
812 next unless $ref->{"${type}_accno_id"};
813 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
814 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
817 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
819 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate)) || $::form->dberror($query_tax);
820 $ref = $sth_tax->fetchrow_hashref or next;
822 $form->{"taxaccounts_$index"} = $ref->{"accno"};
823 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
825 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
830 $::lxdebug->leave_sub;
833 sub get_basic_part_info {
834 $main::lxdebug->enter_sub();
839 Common::check_params(\%params, qw(id));
841 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
844 $main::lxdebug->leave_sub();
848 my $myconfig = \%main::myconfig;
849 my $form = $main::form;
851 my $dbh = $form->get_standard_dbh($myconfig);
853 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
855 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
857 if ('' eq ref $params{id}) {
858 $info = $info->[0] || { };
860 $main::lxdebug->leave_sub();
864 my %info_map = map { $_->{id} => $_ } @{ $info };
866 $main::lxdebug->leave_sub();
871 sub prepare_parts_for_printing {
872 $main::lxdebug->enter_sub();
877 my $myconfig = $params{myconfig} || \%main::myconfig;
878 my $form = $params{form} || $main::form;
880 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
882 my $prefix = $params{prefix} || 'id_';
883 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
885 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
888 $main::lxdebug->leave_sub();
892 my $placeholders = join ', ', ('?') x scalar(@part_ids);
893 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
895 LEFT JOIN vendor v ON (mm.make = v.id)
896 WHERE mm.parts_id IN ($placeholders)|;
900 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
902 while (my $ref = $sth->fetchrow_hashref()) {
903 $makemodel{$ref->{parts_id}} ||= [];
904 push @{ $makemodel{$ref->{parts_id}} }, $ref;
909 my @columns = qw(ean image microfiche drawing);
911 $query = qq|SELECT id, | . join(', ', @columns) . qq|
913 WHERE id IN ($placeholders)|;
915 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
918 map { $template_arrays{$_} = [] } (qw(make model), @columns);
920 foreach my $i (1 .. $rowcount) {
921 my $id = $form->{"${prefix}${i}"};
926 push @{ $template_arrays{$_} }, $data{$id}->{$_};
929 push @{ $template_arrays{make} }, [];
930 push @{ $template_arrays{model} }, [];
932 next if (!$makemodel{$id});
934 foreach my $ref (@{ $makemodel{$id} }) {
935 map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(make model);
939 my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
940 my %parts_by_id = map { $_->id => $_ } @$parts;
942 for my $i (1..$rowcount) {
943 my $id = $form->{"${prefix}${i}"};
945 my $prt = $parts_by_id{$id};
946 my $type_abbr = type_abbreviation($prt->part_type);
947 push @{ $template_arrays{part_type} }, $prt->part_type;
948 push @{ $template_arrays{part_abbreviation} }, $type_abbr;
949 push @{ $template_arrays{type_and_classific}}, $type_abbr . classification_abbreviation($prt->classification_id);
950 push @{ $template_arrays{separate} }, separate_abbreviation($prt->classification_id);
953 $main::lxdebug->leave_sub();
954 return %template_arrays;