X-Git-Url: http://wagnertech.de/git?a=blobdiff_plain;f=SL%2FIR.pm;h=3d8ee363728f89e4d90f1b8906e01b6093c3c2cc;hb=f05bd96b031d7d4ffaf4804704684ae929a0890a;hp=1dde56f74cd29d79e23776a489dea94d650998ae;hpb=2f6a11fb5314d652152e0514bf5e5bf2735dc8fe;p=kivitendo-erp.git diff --git a/SL/IR.pm b/SL/IR.pm index 1dde56f74..3d8ee3637 100644 --- a/SL/IR.pm +++ b/SL/IR.pm @@ -25,7 +25,8 @@ # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software -# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1335, USA. #====================================================================== # # Inventory received module @@ -40,6 +41,7 @@ use SL::Common; use SL::CVar; use SL::DATEV qw(:CONSTANTS); use SL::DBUtils; +use SL::DB::Draft; use SL::DO; use SL::GenericTranslations; use SL::HTML::Restrict; @@ -47,17 +49,31 @@ use SL::IO; use SL::MoreCommon; use SL::DB::Default; use SL::DB::TaxZone; +use SL::DB::MakeModel; +use SL::DB; +use SL::Presenter::Part qw(type_abbreviation classification_abbreviation); use List::Util qw(min); use strict; +use constant PCLASS_OK => 0; +use constant PCLASS_NOTFORSALE => 1; +use constant PCLASS_NOTFORPURCHASE => 2; sub post_invoice { + my ($self, $myconfig, $form, $provided_dbh, %params) = @_; $main::lxdebug->enter_sub(); - my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_; + my $rc = SL::DB->client->with_transaction(\&_post_invoice, $self, $myconfig, $form, $provided_dbh, %params); - # connect to database, turn off autocommit - my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig); + $::lxdebug->leave_sub; + return $rc; +} + +sub _post_invoice { + my ($self, $myconfig, $form, $provided_dbh, %params) = @_; + + my $payments_only = $params{payments_only}; + my $dbh = $provided_dbh || SL::DB->client->dbh; my $restricter = SL::HTML::Restrict->create; $form->{defaultcurrency} = $form->get_default_currency($myconfig); @@ -102,9 +118,12 @@ sub post_invoice { my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} }; my $price_factor; + my @processed_invoice_ids; for my $i (1 .. $form->{rowcount}) { next unless $form->{"id_$i"}; + my $position = $i; + $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"}); $form->{"qty_$i"} *= -1 if $form->{storno}; @@ -144,17 +163,8 @@ sub post_invoice { map { $taxrate += $form->{"${_}_rate"} } @taxaccounts; $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1; - ##################################################################### - # das ist aus IS.pm kopiert. schlimm. jb 7.10.2009 - # ich würde mir wünschen, dass diese vier stellen zusammengefasst werden - # ... vier stellen = (einkauf + verkauf) * (maske + backend) - # ansonsten stolpert man immer wieder viermal statt einmal heftig - # und auch das undo discount formatting ist nicht besonders wartungsfreundlich - - # keine ahnung wofür das in IS.pm gemacht wird: - # my ($dec) = ($fxsellprice =~ /\.(\d+)/); - # $dec = length $dec; - # my $decimalplaces = ($dec > 2) ? $dec : 2; + # copied from IS.pm, with some changes (no decimalplaces corrections here etc) + # TODO maybe use PriceTaxCalculation or something like this for backends (IR.pm / IS.pm) # undo discount formatting $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100; @@ -234,17 +244,17 @@ sub post_invoice { ORDER BY transdate|; # ORDER BY transdate guarantees FIFO -# sold two items without having bought them yet, example result of query: -# id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate -# ---+-----+-----------+----------+--------------------+------------------+------------ -# 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05 + # sold two items without having bought them yet, example result of query: + # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate + # ---+-----+-----------+----------+--------------------+------------------+------------ + # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05 -# base_qty + allocated > 0 if article has already been sold but not bought yet + # base_qty + allocated > 0 if article has already been sold but not bought yet -# select qty,allocated,base_qty,sellprice from invoice where trans_id = 9; -# qty | allocated | base_qty | sellprice -# -----+-----------+----------+------------ -# 2 | 0 | 2 | 1000.00000 + # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9; + # qty | allocated | base_qty | sellprice + # -----+-----------+----------+------------ + # 2 | 0 | 2 | 1000.00000 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"})); @@ -259,7 +269,7 @@ sub post_invoice { if ($ref->{allocated} < 0) { -# we have an entry for it already, adjust amount + # we have an entry for it already, adjust amount $form->update_balance($dbh, "acc_trans", "amount", qq| (trans_id = $ref->{trans_id}) AND (chart_id = $ref->{inventory_accno_id}) @@ -292,7 +302,7 @@ sub post_invoice { $ref->{inventory_accno_id}); do_query($form, $dbh, $query, @values); -# add expense + # add expense $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM taxkeys @@ -375,30 +385,67 @@ sub post_invoice { next if $payments_only; - # save detail record in invoice table - my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('invoiceid')|); + CVar->get_non_editable_ic_cvars(form => $form, + dbh => $dbh, + row => $i, + sub_module => 'invoice', + may_converted_from => ['delivery_order_items', 'orderitems', 'invoice']); + + if (!$form->{"invoice_id_$i"}) { + # there is no persistent id, therefore create one with all necessary constraints + my $q_invoice_id = qq|SELECT nextval('invoiceid')|; + my $h_invoice_id = prepare_query($form, $dbh, $q_invoice_id); + do_statement($form, $h_invoice_id, $q_invoice_id); + $form->{"invoice_id_$i"} = $h_invoice_id->fetchrow_array(); + my $q_create_invoice_id = qq|INSERT INTO invoice (id, trans_id, position, parts_id) values (?, ?, ?, ?)|; + do_query($form, $dbh, $q_create_invoice_id, conv_i($form->{"invoice_id_$i"}), + conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"})); + $h_invoice_id->finish(); + } - $query = - qq|INSERT INTO invoice (id, trans_id, parts_id, description, longdescription, qty, base_qty, - sellprice, fxsellprice, discount, allocated, unit, deliverydate, - project_id, serialnumber, price_factor_id, price_factor, marge_price_factor) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|; - @values = ($invoice_id, conv_i($form->{id}), conv_i($form->{"id_$i"}), + # save detail record in invoice table + $query = <{id}), conv_i($position), conv_i($form->{"id_$i"}), $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"} * -1, $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated, $form->{"unit_$i"}, conv_date($form->{deliverydate}), conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"}, - conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"})); + conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}), + $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"}, + conv_i($form->{"invoice_id_$i"})); do_query($form, $dbh, $query, @values); + push @processed_invoice_ids, $form->{"invoice_id_$i"}; CVar->save_custom_variables(module => 'IC', sub_module => 'invoice', - trans_id => $invoice_id, + trans_id => $form->{"invoice_id_$i"}, configs => $ic_cvar_configs, variables => $form, name_prefix => 'ic_', name_postfix => "_$i", dbh => $dbh); + + # link previous items with invoice items See IS.pm (no credit note -> no invoice item) + foreach (qw(delivery_order_items orderitems invoice)) { + if (!$form->{useasnew} && $form->{"converted_from_${_}_id_$i"}) { + RecordLinks->create_links('dbh' => $dbh, + 'mode' => 'ids', + 'from_table' => $_, + 'from_ids' => $form->{"converted_from_${_}_id_$i"}, + 'to_table' => 'invoice', + 'to_id' => $form->{"invoice_id_$i"}, + ); + } + delete $form->{"converted_from_${_}_id_$i"}; + } } $h_item_unit->finish(); @@ -502,6 +549,7 @@ sub post_invoice { if ($form->{currency} ne $defaultcurrency) && !$exchangerate; # record acc_trans transactions + my $taxdate = $form->{tax_point} || $form->{deliverydate} || $form->{invdate}; foreach my $trans_id (keys %{ $form->{amount} }) { foreach my $accno (keys %{ $form->{amount}{$trans_id} }) { $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2); @@ -528,7 +576,7 @@ sub post_invoice { ORDER BY startdate DESC LIMIT 1), (SELECT link FROM chart WHERE accno = ?))|; @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno}, - conv_date($form->{invdate}), $accno, conv_date($form->{invdate}), $project_id, $accno, conv_date($form->{invdate}), $accno); + conv_date($form->{invdate}), $accno, conv_date($taxdate), $project_id, $accno, conv_date($taxdate), $accno); do_query($form, $dbh, $query, @values); } } @@ -545,6 +593,8 @@ sub post_invoice { $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0; + my %already_cleared = %{ $params{already_cleared} // {} }; + # record payments and offsetting AP for my $i (1 .. $form->{paidaccounts}) { if ($form->{"acc_trans_id_$i"} @@ -561,9 +611,16 @@ sub post_invoice { $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1; + my $new_cleared = !$form->{"acc_trans_id_$i"} ? 'f' + : !$already_cleared{$form->{"acc_trans_id_$i"}} ? 'f' + : $already_cleared{$form->{"acc_trans_id_$i"}}->{amount} != $form->{"paid_$i"} ? 'f' + : $already_cleared{$form->{"acc_trans_id_$i"}}->{accno} != $accno ? 'f' + : $already_cleared{$form->{"acc_trans_id_$i"}}->{cleared} ? 't' + : 'f'; + # record AP if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) { - $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link) + $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, cleared, tax_id, chart_link) VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, (SELECT taxkey_id FROM taxkeys @@ -572,7 +629,7 @@ sub post_invoice { WHERE accno = ?) AND startdate <= ? ORDER BY startdate DESC LIMIT 1), - ?, + ?, ?, (SELECT tax_id FROM taxkeys WHERE chart_id= (SELECT id @@ -582,7 +639,7 @@ sub post_invoice { ORDER BY startdate DESC LIMIT 1), (SELECT link FROM chart WHERE accno = ?))|; @values = (conv_i($form->{id}), $form->{AP}, $amount, - $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP}); + $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $new_cleared, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP}); do_query($form, $dbh, $query, @values); } @@ -590,7 +647,7 @@ sub post_invoice { my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig)); $query = - qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, tax_id, chart_link) + qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, cleared, tax_id, chart_link) VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?, (SELECT taxkey_id FROM taxkeys @@ -598,7 +655,7 @@ sub post_invoice { FROM chart WHERE accno = ?) AND startdate <= ? ORDER BY startdate DESC LIMIT 1), - ?, + ?, ?, (SELECT tax_id FROM taxkeys WHERE chart_id= (SELECT id @@ -607,7 +664,7 @@ sub post_invoice { ORDER BY startdate DESC LIMIT 1), (SELECT link FROM chart WHERE accno = ?))|; @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"}, - $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $accno, conv_date($form->{"datepaid_$i"}), $accno); + $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $new_cleared, $accno, conv_date($form->{"datepaid_$i"}), $accno); do_query($form, $dbh, $query, @values); $exchangerate = 0; @@ -659,13 +716,8 @@ sub post_invoice { if ($payments_only) { $query = qq|UPDATE ap SET paid = ? WHERE id = ?|; do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id})); + $form->new_lastmtime('ap'); - if (!$provided_dbh) { - $dbh->commit(); - $dbh->disconnect(); - } - - $main::lxdebug->leave_sub(); return; } @@ -675,32 +727,29 @@ sub post_invoice { my $taxzone_id = $form->{taxzone_id} * 1; $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id); - # Seit neuestem wird die department_id schon übergeben UND $form->department nicht mehr - # korrekt zusammengebaut. Sehr wahrscheinlich beim Umstieg auf T8 kaputt gegangen - # Ich lass den Code von 2005 erstmal noch stehen ;-) jb 03-2011 - # copy & paste von IS.pm - if (!$form->{department_id}){ - $form->{department_id} = (split /--/, $form->{department})[1]; - } $form->{invnumber} = $form->{id} unless $form->{invnumber}; # save AP record $query = qq|UPDATE ap SET - invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?, - orddate = ?, quodate = ?, vendor_id = ?, amount = ?, - netamount = ?, paid = ?, duedate = ?, - invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?, - intnotes = ?, storno_id = ?, storno = ?, + invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?, + orddate = ?, quodate = ?, vendor_id = ?, amount = ?, + netamount = ?, paid = ?, duedate = ?, deliverydate = ?, + invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?, + intnotes = ?, storno_id = ?, storno = ?, tax_point = ?, cp_id = ?, employee_id = ?, department_id = ?, delivery_term_id = ?, + payment_id = ?, transaction_description = ?, + currency_id = (SELECT id FROM currencies WHERE name = ?), globalproject_id = ?, direct_debit = ? WHERE id = ?|; @values = ( $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}), conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount, - $netamount, $form->{paid}, conv_date($form->{duedate}), - '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f', - $form->{intnotes}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f', + $netamount, $form->{paid}, conv_date($form->{duedate}), conv_date($form->{deliverydate}), + '1', $taxzone_id, $restricter->process($form->{notes}), $form->{taxincluded} ? 't' : 'f', + $form->{intnotes}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f', conv_date($form->{tax_point}), conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}), conv_i($form->{delivery_term_id}), + conv_i($form->{payment_id}), $form->{transaction_description}, + $form->{"currency"}, conv_i($form->{globalproject_id}), $form->{direct_debit} ? 't' : 'f', conv_i($form->{id}) @@ -721,6 +770,7 @@ sub post_invoice { do_query($form, $dbh, $query, conv_i($form->{id})); } + $form->new_lastmtime('ap'); $form->{name} = $form->{vendor}; $form->{name} =~ s/--\Q$form->{vendor_id}\E//; @@ -733,15 +783,19 @@ sub post_invoice { Common::webdav_folder($form); - # Link this record to the records it was created from. - RecordLinks->create_links('dbh' => $dbh, - 'mode' => 'ids', - 'from_table' => 'oe', - 'from_ids' => $form->{convert_from_oe_ids}, - 'to_table' => 'ap', - 'to_id' => $form->{id}, - ); - delete $form->{convert_from_oe_ids}; + # Link this record to the records it was created from order or invoice (storno) + foreach (qw(oe ap)) { + if ($form->{"convert_from_${_}_ids"}) { + RecordLinks->create_links('dbh' => $dbh, + 'mode' => 'ids', + 'from_table' => $_, + 'from_ids' => $form->{"convert_from_${_}_ids"}, + 'to_table' => 'ap', + 'to_id' => $form->{id}, + ); + delete $form->{"convert_from_${_}_ids"}; + } + } my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids}; if (scalar @convert_from_do_ids) { @@ -762,37 +816,36 @@ sub post_invoice { 'arap_id' => $form->{id}, 'table' => 'ap',); + # search for orphaned invoice items + $query = sprintf 'SELECT id FROM invoice WHERE trans_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_invoice_ids; + @values = (conv_i($form->{id}), map { conv_i($_) } @processed_invoice_ids); + my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values); + if (scalar @orphaned_ids) { + # clean up invoice items + $query = sprintf 'DELETE FROM invoice WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids; + do_query($form, $dbh, $query, @orphaned_ids); + } + + if ($form->{draft_id}) { + SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]); + } + # safety check datev export if ($::instance_conf->get_datev_check_on_purchase_invoice) { - my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef; - $transdate ||= DateTime->today; my $datev = SL::DATEV->new( - exporttype => DATEV_ET_BUCHUNGEN, - format => DATEV_FORMAT_KNE, dbh => $dbh, - from => $transdate, - to => $transdate, trans_id => $form->{id}, ); - $datev->export; + $datev->generate_datev_data; if ($datev->errors) { - $dbh->rollback; die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors; } } - my $rc = 1; - if (!$provided_dbh) { - $rc = $dbh->commit(); - $dbh->disconnect(); - } - - $main::lxdebug->leave_sub(); - - return $rc; + return 1; } sub reverse_invoice { @@ -802,7 +855,7 @@ sub reverse_invoice { # reverse inventory items my $query = - qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice + qq|SELECT i.parts_id, p.part_type, i.qty, i.allocated, i.sellprice FROM invoice i, parts p WHERE (i.parts_id = p.id) AND (i.trans_id = ?)|; @@ -813,7 +866,7 @@ sub reverse_invoice { while (my $ref = $sth->fetchrow_hashref("NAME_lc")) { $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2); - next unless $ref->{inventory_accno_id}; + next unless $ref->{part_type} eq 'part'; # if $ref->{allocated} > 0 than we sold that many items next if ($ref->{allocated} <= 0); @@ -839,17 +892,20 @@ sub reverse_invoice { #adjust allocated $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty); - $form->update_balance($dbh, "acc_trans", "amount", - qq| (trans_id = $pthref->{trans_id}) - AND (chart_id = $ref->{expense_accno_id}) - AND (transdate = '$pthref->{transdate}')|, - $amount); + if ( $::instance_conf->get_inventory_system eq 'perpetual' ) { - $form->update_balance($dbh, "acc_trans", "amount", - qq| (trans_id = $pthref->{trans_id}) - AND (chart_id = $ref->{inventory_accno_id}) - AND (transdate = '$pthref->{transdate}')|, - $amount * -1); + $form->update_balance($dbh, "acc_trans", "amount", + qq| (trans_id = $pthref->{trans_id}) + AND (chart_id = $ref->{expense_accno_id}) + AND (transdate = '$pthref->{transdate}')|, + $amount); + + $form->update_balance($dbh, "acc_trans", "amount", + qq| (trans_id = $pthref->{trans_id}) + AND (chart_id = $ref->{inventory_accno_id}) + AND (transdate = '$pthref->{transdate}')|, + $amount * -1); + } last if (($ref->{allocated} -= $qty) <= 0); } @@ -863,10 +919,6 @@ sub reverse_invoice { $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|; do_query($form, $dbh, $query, $id); - # delete invoice entries - $query = qq|DELETE FROM invoice WHERE trans_id = ?|; - do_query($form, $dbh, $query, $id); - $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|; do_query($form, $dbh, $query, $id); @@ -879,24 +931,30 @@ sub delete_invoice { my ($self, $myconfig, $form) = @_; my $query; # connect to database - my $dbh = $form->dbconnect_noauto($myconfig); + my $dbh = SL::DB->client->dbh; - &reverse_invoice($dbh, $form); + SL::DB->client->with_transaction(sub{ - # delete zero entries - $query = qq|DELETE FROM acc_trans WHERE amount = 0|; - do_query($form, $dbh, $query); + &reverse_invoice($dbh, $form); - # delete AP record - $query = qq|DELETE FROM ap WHERE id = ?|; - do_query($form, $dbh, $query, conv_i($form->{id})); + my @values = (conv_i($form->{id})); - my $rc = $dbh->commit; - $dbh->disconnect; + # delete zero entries + # wtf? use case for this? + $query = qq|DELETE FROM acc_trans WHERE amount = 0|; + do_query($form, $dbh, $query); - $main::lxdebug->leave_sub(); - return $rc; + my @queries = ( + qq|DELETE FROM invoice WHERE trans_id = ?|, + qq|DELETE FROM ap WHERE id = ?|, + ); + + map { do_query($form, $dbh, $_, @values) } @queries; + 1; + }) or do { die SL::DB->client->error }; + + return 1; } sub retrieve_invoice { @@ -905,7 +963,7 @@ sub retrieve_invoice { my ($self, $myconfig, $form) = @_; # connect to database - my $dbh = $form->dbconnect($myconfig); + my $dbh = SL::DB->client->dbh; my ($query, $sth, $ref, $q_invdate); @@ -937,7 +995,6 @@ sub retrieve_invoice { map { $form->{$_} = $ref->{$_} } keys %$ref; if (!$form->{id}) { - $dbh->disconnect(); $main::lxdebug->leave_sub(); return; @@ -945,14 +1002,17 @@ sub retrieve_invoice { # retrieve invoice $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate, - orddate, quodate, globalproject_id, + orddate, quodate, deliverydate, tax_point, globalproject_id, ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate, + mtime, itime, intnotes, (SELECT cu.name FROM currencies cu WHERE cu.id=ap.currency_id) AS currency, direct_debit, - delivery_term_id + payment_id, delivery_term_id, transaction_description FROM ap WHERE id = ?|; $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id})); map { $form->{$_} = $ref->{$_} } keys %$ref; + $form->{mtime} = $form->{itime} if !$form->{mtime}; + $form->{lastmtime} = $form->{mtime}; $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell"); @@ -962,7 +1022,7 @@ sub retrieve_invoice { delete $ref->{id}; map { $form->{$_} = $ref->{$_} } keys %$ref; - my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date"; + my $transdate = $form->{tax_point} ? $dbh->quote($form->{tax_point}) :$form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date"; my $taxzone_id = $form->{taxzone_id} * 1; $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id); @@ -976,8 +1036,9 @@ sub retrieve_invoice { i.id AS invoice_id, i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber, - i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount, - p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, pr.projectnumber, pg.partsgroup + i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount, i.active_price_source, i.active_discount_source, + p.partnumber, p.part_type, pr.projectnumber, pg.partsgroup + ,p.classification_id FROM invoice i JOIN parts p ON (i.parts_id = p.id) @@ -989,7 +1050,7 @@ sub retrieve_invoice { WHERE i.trans_id = ? - ORDER BY i.id|; + ORDER BY i.position|; $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id})); while (my $ref = $sth->fetchrow_hashref("NAME_lc")) { @@ -1000,10 +1061,8 @@ sub retrieve_invoice { trans_id => $ref->{invoice_id}, ); map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars }; - delete $ref->{invoice_id}; - map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"}; - delete($ref->{"part_inventory_accno_id"}); + map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_type"} eq 'part'; foreach my $type (qw(inventory income expense)) { while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) { @@ -1015,7 +1074,9 @@ sub retrieve_invoice { # get tax rates and description my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno}; $query = - qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t + qq|SELECT c.accno, t.taxdescription, t.rate, t.id as tax_id, + c.accno as taxnumber -- taxnumber is same as accno, but still accessed as taxnumber in code + FROM tax t LEFT JOIN chart c ON (c.id = t.chart_id) WHERE t.id in (SELECT tk.tax_id FROM taxkeys tk @@ -1040,6 +1101,7 @@ sub retrieve_invoice { $form->{"$ptr->{accno}_rate"} = $ptr->{rate}; $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription}; $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber}; + $form->{"$ptr->{accno}_tax_id"} = $ptr->{tax_id}; $form->{taxaccounts} .= "$ptr->{accno} "; } @@ -1053,8 +1115,6 @@ sub retrieve_invoice { Common::webdav_folder($form); - $dbh->disconnect(); - $main::lxdebug->leave_sub(); } @@ -1066,7 +1126,7 @@ sub get_vendor { $params = $form unless defined $params && ref $params eq "HASH"; # connect to database - my $dbh = $form->dbconnect($myconfig); + my $dbh = SL::DB->client->dbh; my $dateformat = $myconfig->{dateformat}; $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/; @@ -1093,11 +1153,11 @@ sub get_vendor { my $query = qq|SELECT v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount, - v.creditlimit, v.terms, v.notes AS intnotes, + v.creditlimit, v.notes AS intnotes, v.email, v.cc, v.bcc, v.language_id, v.payment_id, v.delivery_term_id, v.street, v.zipcode, v.city, v.country, v.taxzone_id, cu.name AS curr, v.direct_debit, $duedate + COALESCE(pt.terms_netto, 0) AS duedate, - b.description AS business + b.discount AS tradediscount, b.description AS business FROM vendor v LEFT JOIN business b ON (b.id = v.business_id) LEFT JOIN payment_terms pt ON (v.payment_id = pt.id) @@ -1129,45 +1189,6 @@ sub get_vendor { } $sth->finish(); - if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) { - # setup last accounts used - $query = - qq|SELECT c.id, c.accno, c.description, c.link, c.category - FROM chart c - JOIN acc_trans ac ON (ac.chart_id = c.id) - JOIN ap a ON (a.id = ac.trans_id) - WHERE (a.vendor_id = ?) - AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%'))) - AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|; - my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid); - - my $i = 0; - for $ref (@$refs) { - if ($ref->{category} eq 'E') { - $i++; - my ($tax_id, $rate); - if ($params->{initial_transdate}) { - my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk - LEFT JOIN tax t ON (tk.tax_id = t.id) - WHERE (tk.chart_id = ?) AND (startdate <= ?) - ORDER BY tk.startdate DESC - LIMIT 1|; - ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate}); - $params->{"taxchart_$i"} = "${tax_id}--${rate}"; - } - - $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id"; - } - - if ($ref->{category} eq 'L') { - $params->{APselected} = $params->{AP_1} = $ref->{accno}; - } - } - $params->{rowcount} = $i if ($i && !$params->{type}); - } - - $dbh->disconnect(); - $main::lxdebug->leave_sub(); } @@ -1176,20 +1197,19 @@ sub retrieve_item { my ($self, $myconfig, $form) = @_; - # connect to database - my $dbh = $form->dbconnect($myconfig); + my $dbh = SL::DB->client->dbh; my $i = $form->{rowcount}; # don't include assemblies or obsolete parts - my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'"; + my $where = "NOT p.part_type = 'assembly' AND NOT p.obsolete = '1'"; my @values; foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) { my $field = (split m{\.}, $table_column)[1]; next unless $form->{"${field}_${i}"}; $where .= " AND lower(${table_column}) LIKE lower(?)"; - push @values, '%' . $form->{"${field}_${i}"} . '%'; + push @values, like($form->{"${field}_${i}"}); } my (%mm_by_id); @@ -1203,7 +1223,7 @@ sub retrieve_item { LEFT JOIN parts ON parts.id = parts_id WHERE NOT parts.obsolete AND model ILIKE ? AND (make IS NULL OR make = ?); |; - my $mm_results = selectall_hashref_query($::form, $dbh, $mm_query, '%' . $form->{"partnumber_$i"} . '%', $::form->{vendor_id}); + my $mm_results = selectall_hashref_query($::form, $dbh, $mm_query, like($form->{"partnumber_$i"}), $::form->{vendor_id}); my @mm_ids = map { $_->{parts_id} } @$mm_results; push @{$mm_by_id{ $_->{parts_id} } ||= []}, $_ for @$mm_results; @@ -1240,10 +1260,11 @@ sub retrieve_item { my $query = qq|SELECT p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice, - p.unit, p.assembly, p.onhand, p.formel, + p.unit, p.part_type, p.onhand, p.formel, p.notes AS partnotes, p.notes AS longdescription, p.not_discountable, - p.inventory_accno_id, p.price_factor_id, + p.price_factor_id, p.ean, + p.classification_id, pfac.factor AS price_factor, @@ -1259,6 +1280,7 @@ sub retrieve_item { c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid, + pt.used_for_purchase AS used_for_purchase, pg.partsgroup FROM parts p @@ -1275,6 +1297,7 @@ sub retrieve_item { FROM taxzone_charts tc WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id) LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id) + LEFT JOIN part_classifications pt ON (pt.id = p.classification_id) LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id) WHERE $where|; my $sth = prepare_execute_query($form, $dbh, $query, @values); @@ -1293,6 +1316,7 @@ sub retrieve_item { map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries; $form->{item_list} = []; + my $has_wrong_pclass = PCLASS_OK; while (my $ref = $sth->fetchrow_hashref("NAME_lc")) { if ($mm_by_id{$ref->{id}}) { @@ -1300,10 +1324,16 @@ sub retrieve_item { push @{ $ref->{matches} ||= [] }, $::locale->text('Model') . ': ' . join ', ', map { $_->{model} } @{ $mm_by_id{$ref->{id}} }; } - if ($ref->{ean} eq $::form->{"partnumber_$i"}) { + if (($::form->{"partnumber_$i"} ne '') && ($ref->{ean} eq $::form->{"partnumber_$i"})) { push @{ $ref->{matches} ||= [] }, $::locale->text('EAN') . ': ' . $ref->{ean}; } + $ref->{type_and_classific} = type_abbreviation($ref->{part_type}) . + classification_abbreviation($ref->{classification_id}); + if (! $ref->{used_for_purchase} ) { + $has_wrong_pclass = PCLASS_NOTFORPURCHASE; + next; + } # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das # Buchungskonto also aus dem Ergebnis rausgenommen werden. @@ -1315,7 +1345,7 @@ sub retrieve_item { # get tax rates and description my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno}; $query = - qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber + qq|SELECT c.accno, t.taxdescription, t.rate, c.accno as taxnumber, t.id as tax_id FROM tax t LEFT JOIN chart c on (c.id = t.chart_id) WHERE t.id IN @@ -1346,6 +1376,7 @@ sub retrieve_item { $form->{"$ptr->{accno}_rate"} = $ptr->{rate}; $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription}; $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber}; + $form->{"$ptr->{accno}_tax_id"} = $ptr->{tax_id}; $form->{taxaccounts} .= "$ptr->{accno} "; } @@ -1365,7 +1396,6 @@ sub retrieve_item { chop $ref->{taxaccounts}; $ref->{onhand} *= 1; - push @{ $form->{item_list} }, $ref; } @@ -1373,17 +1403,18 @@ sub retrieve_item { $sth->finish(); $_->[1]->finish for @translation_queries; + $form->{is_wrong_pclass} = $has_wrong_pclass; + $form->{NOTFORSALE} = PCLASS_NOTFORSALE; + $form->{NOTFORPURCHASE} = PCLASS_NOTFORPURCHASE; foreach my $item (@{ $form->{item_list} }) { my $custom_variables = CVar->get_custom_variables(module => 'IC', trans_id => $item->{id}, dbh => $dbh, ); - + $form->{is_wrong_pclass} = PCLASS_OK; # one correct type map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables }; } - $dbh->disconnect(); - $main::lxdebug->leave_sub(); } @@ -1392,8 +1423,7 @@ sub vendor_details { my ($self, $myconfig, $form, @wanted_vars) = @_; - # connect to database - my $dbh = $form->dbconnect($myconfig); + my $dbh = SL::DB->client->dbh; my @values; @@ -1418,8 +1448,8 @@ sub vendor_details { LIMIT 1|; my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values); - # remove id and taxincluded before copy back - delete @$ref{qw(id taxincluded)}; + # remove id,notes (double of vendornotes) and taxincluded before copy back + delete @$ref{qw(id taxincluded notes)}; @wanted_vars = grep({ $_ } @wanted_vars); if (scalar(@wanted_vars) > 0) { @@ -1435,12 +1465,17 @@ sub vendor_details { 'trans_id' => $form->{vendor_id}); map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables }; + if ($form->{cp_id}) { + $custom_variables = CVar->get_custom_variables(dbh => $dbh, + module => 'Contacts', + trans_id => $form->{cp_id}); + $form->{"cp_cvar_$_->{name}"} = $_->{value} for @{ $custom_variables }; + } + $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh, 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'), 'allow_fallback' => 1); - $dbh->disconnect(); - $main::lxdebug->leave_sub(); } @@ -1449,8 +1484,7 @@ sub item_links { my ($self, $myconfig, $form) = @_; - # connect to database - my $dbh = $form->dbconnect($myconfig); + my $dbh = SL::DB->client->dbh; my $query = qq|SELECT accno, description, link @@ -1470,8 +1504,6 @@ sub item_links { } $sth->finish(); - $dbh->disconnect(); - $main::lxdebug->leave_sub(); } @@ -1515,17 +1547,33 @@ sub _delete_payments { } sub post_payment { + my ($self, $myconfig, $form, $locale) = @_; $main::lxdebug->enter_sub(); + my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale); + + $::lxdebug->leave_sub; + return $rc; +} + +sub _post_payment { my ($self, $myconfig, $form, $locale) = @_; - # connect to database, turn off autocommit - my $dbh = $form->dbconnect_noauto($myconfig); + my $dbh = SL::DB->client->dbh; my (%payments, $old_form, $row, $item, $query, %keep_vars); $old_form = save_form(); + $query = <{id}); + # Delete all entries in acc_trans from prior payments. if (SL::DB::Default->get->payments_changeable != 0) { $self->_delete_payments($form, $dbh); @@ -1572,16 +1620,11 @@ sub post_payment { ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id})); # Post the new payments. - $self->post_invoice($myconfig, $form, $dbh, 1); + $self->post_invoice($myconfig, $form, $dbh, payments_only => 1, already_cleared => \%already_cleared); restore_form($old_form); - my $rc = $dbh->commit(); - $dbh->disconnect(); - - $main::lxdebug->leave_sub(); - - return $rc; + return 1; } sub get_duedate { @@ -1609,5 +1652,4 @@ sub get_duedate { return $duedate; } - 1;