1 package SL::Controller::CustomerVendor;
 
   4 use parent qw(SL::Controller::Base);
 
   6 use List::MoreUtils qw(any);
 
  10 use SL::Helper::Flash;
 
  11 use SL::Locale::String;
 
  12 use SL::Util qw(trim);
 
  16 use SL::Controller::Helper::GetModels;
 
  17 use SL::Controller::Helper::ReportGenerator;
 
  18 use SL::Controller::Helper::ParseFilter;
 
  23 use SL::DB::ContactDepartment;
 
  24 use SL::DB::ContactTitle;
 
  30 use SL::DB::PaymentTerm;
 
  31 use SL::DB::Pricegroup;
 
  35 use SL::DB::FollowUpLink;
 
  39 use SL::DB::PurchaseInvoice;
 
  44 use Rose::Object::MakeMethods::Generic (
 
  45   scalar                  => [ qw(user_has_edit_rights) ],
 
  46   'scalar --get_set_init' => [ qw(customer_models vendor_models zugferd_settings) ],
 
  50 __PACKAGE__->run_before(
 
  54     'save_and_ap_transaction',
 
  55     'save_and_ar_transaction',
 
  64     'delete_additional_billing_address',
 
  68 __PACKAGE__->run_before(
 
  69   '_load_customer_vendor',
 
  75     'ajaj_get_additional_billing_address',
 
  81 # make sure this comes after _load_customer_vendor
 
  82 __PACKAGE__->run_before('_check_auth');
 
  84 __PACKAGE__->run_before(
 
  85   '_create_customer_vendor',
 
  91 __PACKAGE__->run_before('normalize_name');
 
  93 my @ADDITIONAL_BILLING_ADDRESS_COLUMNS = qw(name department_1 department_2 contact street zipcode city country gln email phone fax default_address);
 
 100   if ($self->{cv}->is_customer) {
 
 101     $self->{cv}->assign_attributes(hourly_rate => $::instance_conf->get_customer_hourly_rate);
 
 102     $self->{cv}->salesman_id(SL::DB::Manager::Employee->current->id) if !$::auth->assert('customer_vendor_all_edit', 1);
 
 106     'customer_vendor/form',
 
 107     title => ($self->is_vendor() ? $::locale->text('Add Vendor') : $::locale->text('Add Customer')),
 
 108     %{$self->{template_args}}
 
 115   $self->_pre_render();
 
 117     'customer_vendor/form',
 
 118     title => ($self->is_vendor() ? $::locale->text('Edit Vendor') : $::locale->text('Edit Customer')),
 
 119     %{$self->{template_args}}
 
 126   if ($::request->type eq 'json') {
 
 131       $cv_hash          = $self->{cv}->as_tree;
 
 132       $cv_hash->{cvars} = $self->{cv}->cvar_as_hashref;
 
 135     $self->render(\ SL::JSON::to_json($cv_hash), { layout => 0, type => 'json', process => 0 });
 
 139 sub _check_ustid_taxnumber_unique {
 
 143   if ($self->is_vendor()) {
 
 144     %cfg = (should_check  => $::instance_conf->get_vendor_ustid_taxnummer_unique,
 
 145             manager_class => 'SL::DB::Manager::Vendor',
 
 146             err_ustid     => t8('A vendor with the same VAT ID already exists.'),
 
 147             err_taxnumber => t8('A vendor with the same taxnumber already exists.'),
 
 150   } elsif ($self->is_customer()) {
 
 151     %cfg = (should_check  => $::instance_conf->get_customer_ustid_taxnummer_unique,
 
 152             manager_class => 'SL::DB::Manager::Customer',
 
 153             err_ustid     => t8('A customer with the same VAT ID already exists.'),
 
 154             err_taxnumber => t8('A customer with the same taxnumber already exists.'),
 
 163   if ($cfg{should_check}) {
 
 164     my $do_clean_taxnumber = sub { my $n = $_[0]; $n //= ''; $n =~ s{[[:space:].-]+}{}g; return $n};
 
 166     my $clean_ustid     = SL::VATIDNr->clean($self->{cv}->ustid);
 
 167     my $clean_taxnumber = $do_clean_taxnumber->($self->{cv}->taxnumber);
 
 169     if (!($clean_ustid || $clean_taxnumber)) {
 
 170       return t8('VAT ID and/or taxnumber must be given.');
 
 173       my $clean_number = $clean_ustid;
 
 175         my $entries = $cfg{manager_class}->get_all(query => ['!id' => $self->{cv}->id, '!ustid' => undef, '!ustid' => ''], select => ['ustid'], distinct => 1);
 
 176         if (any { $clean_number eq SL::VATIDNr->clean($_->ustid) } @$entries) {
 
 177           push @errors, $cfg{err_ustid};
 
 181       $clean_number = $clean_taxnumber;
 
 183         my $entries = $cfg{manager_class}->get_all(query => ['!id' => $self->{cv}->id, '!taxnumber' => undef, '!taxnumber' => ''], select => ['taxnumber'], distinct => 1);
 
 184         if (any { $clean_number eq $do_clean_taxnumber->($_->taxnumber) } @$entries) {
 
 185           push @errors, $cfg{err_taxnumber};
 
 191   return join "\n", @errors if @errors;
 
 198   my @errors = $self->{cv}->validate;
 
 200     flash('error', @errors);
 
 201     $self->_pre_render();
 
 203       'customer_vendor/form',
 
 204       title => ($self->is_vendor() ? t8('Edit Vendor') : t8('Edit Customer')),
 
 205       %{$self->{template_args}}
 
 207     $::dispatcher->end_request;
 
 210   $self->{cv}->greeting(trim $self->{cv}->greeting);
 
 211   my $save_greeting           = $self->{cv}->greeting
 
 212     && $::instance_conf->get_vc_greetings_use_textfield
 
 213     && SL::DB::Manager::Greeting->get_all_count(where => [description => $self->{cv}->greeting]) == 0;
 
 215   $self->{contact}->cp_title(trim($self->{contact}->cp_title));
 
 216   my $save_contact_title      = $self->{contact}->cp_title
 
 217     && $::instance_conf->get_contact_titles_use_textfield
 
 218     && SL::DB::Manager::ContactTitle->get_all_count(where => [description => $self->{contact}->cp_title]) == 0;
 
 220   $self->{contact}->cp_abteilung(trim($self->{contact}->cp_abteilung));
 
 221   my $save_contact_department = $self->{contact}->cp_abteilung
 
 222     && $::instance_conf->get_contact_departments_use_textfield
 
 223     && SL::DB::Manager::ContactDepartment->get_all_count(where => [description => $self->{contact}->cp_abteilung]) == 0;
 
 225   my $db = $self->{cv}->db;
 
 227   $db->with_transaction(sub {
 
 229     if ( $self->is_vendor() ) {
 
 230       if ( $self->{cv}->vendornumber ) {
 
 231         $cvs_by_nr = SL::DB::Manager::Vendor->get_all(query => [vendornumber => $self->{cv}->vendornumber]);
 
 234       if ( $self->{cv}->customernumber ) {
 
 235         $cvs_by_nr = SL::DB::Manager::Customer->get_all(query => [customernumber => $self->{cv}->customernumber]);
 
 239     foreach my $entry (@{$cvs_by_nr}) {
 
 240       if( $entry->id != $self->{cv}->id ) {
 
 242           $self->is_vendor() ? $::locale->text('This vendor number is already in use.') : $::locale->text('This customer number is already in use.');
 
 244         $::form->error($msg);
 
 248     my $ustid_taxnumber_error = $self->_check_ustid_taxnumber_unique;
 
 249     $::form->error($ustid_taxnumber_error) if $ustid_taxnumber_error;
 
 251     $self->{cv}->save(cascade => 1);
 
 253     SL::DB::Greeting->new(description => $self->{cv}->greeting)->save if $save_greeting;
 
 255     $self->{contact}->cp_cv_id($self->{cv}->id);
 
 256     if( $self->{contact}->cp_name ne '' || $self->{contact}->cp_givenname ne '' ) {
 
 257       SL::DB::ContactTitle     ->new(description => $self->{contact}->cp_title)    ->save if $save_contact_title;
 
 258       SL::DB::ContactDepartment->new(description => $self->{contact}->cp_abteilung)->save if $save_contact_department;
 
 260       $self->{contact}->save(cascade => 1);
 
 263     if( $self->{note}->subject ne '' && $self->{note}->body ne '' ) {
 
 265       if ( !$self->{note_followup}->follow_up_date ) {
 
 266         $::form->error($::locale->text('Date missing!'));
 
 269       $self->{note}->trans_id($self->{cv}->id);
 
 270       $self->{note}->save();
 
 272       $self->{note_followup}->save();
 
 274       $self->{note_followup_link}->follow_up_id($self->{note_followup}->id);
 
 275       $self->{note_followup_link}->trans_id($self->{cv}->id);
 
 276       $self->{note_followup_link}->save();
 
 278       SL::Helper::Flash::flash_later('info', $::locale->text('Follow-Up saved.'));
 
 281     $self->{shipto}->trans_id($self->{cv}->id);
 
 282     if(any { $self->{shipto}->$_ ne '' } qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax shiptoemail)) {
 
 283       $self->{shipto}->save(cascade => 1);
 
 286     if ($self->is_customer && any { $self->{additional_billing_address}->$_ ne '' } grep { $_ ne 'default_address' } @ADDITIONAL_BILLING_ADDRESS_COLUMNS) {
 
 287       $self->{additional_billing_address}->customer_id($self->{cv}->id);
 
 288       $self->{additional_billing_address}->save(cascade => 1);
 
 290       # Make sure only one address per customer has "default address" set.
 
 291       if ($self->{additional_billing_address}->default_address) {
 
 292         SL::DB::Manager::AdditionalBillingAddress->update_all(
 
 293           set   => { default_address => 0, },
 
 295             customer_id => $self->{cv}->id,
 
 296             '!id'       => $self->{additional_billing_address}->id,
 
 301     my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
 
 302     SL::DB::History->new(
 
 303       trans_id => $self->{cv}->id,
 
 304       snumbers => $snumbers,
 
 305       employee_id => SL::DB::Manager::Employee->current->id,
 
 309     if ( $::form->{delete_notes} ) {
 
 310       foreach my $note_id (@{ $::form->{delete_notes} }) {
 
 311         my $note = SL::DB::Note->new(id => $note_id)->load();
 
 312         if ( $note->follow_up ) {
 
 313           if ( $note->follow_up->follow_up_link ) {
 
 314             $note->follow_up->follow_up_link->delete(cascade => 'delete');
 
 316           $note->follow_up->delete(cascade => 'delete');
 
 318         $note->delete(cascade => 'delete');
 
 323   }) || die($db->error);
 
 332   my @redirect_params = (
 
 334     id     => $self->{cv}->id,
 
 335     db     => ($self->is_vendor() ? 'vendor' : 'customer'),
 
 338   if ( $self->{contact}->cp_id ) {
 
 339     push(@redirect_params, contact_id => $self->{contact}->cp_id);
 
 342   if ( $self->{shipto}->shipto_id ) {
 
 343     push(@redirect_params, shipto_id => $self->{shipto}->shipto_id);
 
 346   if ( $self->is_customer && $self->{additional_billing_address}->id ) {
 
 347     push(@redirect_params, additional_billing_address_id => $self->{additional_billing_address}->id);
 
 350   $self->redirect_to(@redirect_params);
 
 353 sub action_save_and_close {
 
 358   my $msg = $self->is_vendor() ? $::locale->text('Vendor saved') : $::locale->text('Customer saved');
 
 359   $::form->redirect($msg);
 
 363   my ($self, $script) = @_;
 
 365   $::auth->assert('gl_transactions | ap_transactions | ar_transactions'.
 
 366                     '| invoice_edit         | vendor_invoice_edit | ' .
 
 367                  ' request_quotation_edit | sales_quotation_edit | sales_order_edit    | purchase_order_edit');
 
 371   my $name = $::form->escape($self->{cv}->name, 1);
 
 372   my $db = $self->is_vendor() ? 'vendor' : 'customer';
 
 375   if ($::instance_conf->get_feature_experimental_order && 'oe.pl' eq $script) {
 
 376     $script = 'controller.pl';
 
 377     $action = 'Order/' . $action;
 
 380   my $url = $self->url_for(
 
 381     controller => $script,
 
 384     $db .'_id' => $self->{cv}->id,
 
 386     type       => $::form->{type},
 
 387     callback   => $::form->{callback},
 
 390   print $::form->redirect_header($url);
 
 393 sub action_save_and_ar_transaction {
 
 396   $main::auth->assert('ar_transactions');
 
 398   $self->_transaction('ar.pl');
 
 401 sub action_save_and_ap_transaction {
 
 404   $main::auth->assert('ap_transactions');
 
 406   $self->_transaction('ap.pl');
 
 409 sub action_save_and_invoice {
 
 412   if ( $self->is_vendor() ) {
 
 413     $::auth->assert('vendor_invoice_edit');
 
 415     $::auth->assert('invoice_edit');
 
 418   $::form->{type} = 'invoice';
 
 419   $self->_transaction($self->is_vendor() ? 'ir.pl' : 'is.pl');
 
 422 sub action_save_and_order {
 
 425   if ( $self->is_vendor() ) {
 
 426     $::auth->assert('purchase_order_edit');
 
 428     $::auth->assert('sales_order_edit');
 
 431   $::form->{type} = $self->is_vendor() ? 'purchase_order' : 'sales_order';
 
 432   $self->_transaction('oe.pl');
 
 435 sub action_save_and_rfq {
 
 438   $::auth->assert('request_quotation_edit');
 
 440   $::form->{type} = 'request_quotation';
 
 441   $self->_transaction('oe.pl');
 
 444 sub action_save_and_quotation {
 
 447   $::auth->assert('sales_quotation_edit');
 
 449   $::form->{type} = 'sales_quotation';
 
 450   $self->_transaction('oe.pl');
 
 456   my $db = $self->{cv}->db;
 
 458   if( !$self->is_orphaned() ) {
 
 459     $self->action_edit();
 
 462     $db->with_transaction(sub {
 
 463       $self->{cv}->delete(cascade => 1);
 
 465       my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
 
 466       SL::DB::History->new(
 
 467         trans_id => $self->{cv}->id,
 
 468         snumbers => $snumbers,
 
 469         employee_id => SL::DB::Manager::Employee->current->id,
 
 470         addition => 'DELETED',
 
 472     }) || die($db->error);
 
 474     my $msg = $self->is_vendor() ? $::locale->text('Vendor deleted!') : $::locale->text('Customer deleted!');
 
 475     $::form->redirect($msg);
 
 481 sub action_delete_contact {
 
 484   my $db = $self->{contact}->db;
 
 486   if ( !$self->{contact}->cp_id ) {
 
 487     SL::Helper::Flash::flash('error', $::locale->text('No contact selected to delete'));
 
 490     $db->with_transaction(sub {
 
 491       if ( $self->{contact}->used ) {
 
 492         $self->{contact}->detach();
 
 493         $self->{contact}->save();
 
 494         SL::Helper::Flash::flash('info', $::locale->text('Contact is in use and was flagged invalid.'));
 
 496         $self->{contact}->delete(cascade => 1);
 
 497         SL::Helper::Flash::flash('info', $::locale->text('Contact deleted.'));
 
 501     }) || die($db->error);
 
 503     $self->{contact} = $self->_new_contact_object;
 
 506   $self->action_edit();
 
 509 sub action_delete_shipto {
 
 512   my $db = $self->{shipto}->db;
 
 514   if ( !$self->{shipto}->shipto_id ) {
 
 515     SL::Helper::Flash::flash('error', $::locale->text('No shipto selected to delete'));
 
 518     $db->with_transaction(sub {
 
 519       if ( $self->{shipto}->used ) {
 
 520         $self->{shipto}->detach();
 
 521         $self->{shipto}->save(cascade => 1);
 
 522         SL::Helper::Flash::flash('info', $::locale->text('Shipto is in use and was flagged invalid.'));
 
 524         $self->{shipto}->delete(cascade => 1);
 
 525         SL::Helper::Flash::flash('info', $::locale->text('Shipto deleted.'));
 
 529     }) || die($db->error);
 
 531     $self->{shipto} = SL::DB::Shipto->new();
 
 534   $self->action_edit();
 
 537 sub action_delete_additional_billing_address {
 
 540   my $db = $self->{additional_billing_address}->db;
 
 542   if ( !$self->{additional_billing_address}->id ) {
 
 543     SL::Helper::Flash::flash('error', $::locale->text('No address selected to delete'));
 
 545     $db->with_transaction(sub {
 
 546       if ( $self->{additional_billing_address}->used ) {
 
 547         $self->{additional_billing_address}->detach;
 
 548         $self->{additional_billing_address}->save(cascade => 1);
 
 549         SL::Helper::Flash::flash('info', $::locale->text('Address is in use and was flagged invalid.'));
 
 551         $self->{additional_billing_address}->delete(cascade => 1);
 
 552         SL::Helper::Flash::flash('info', $::locale->text('Address deleted.'));
 
 556     }) || die($db->error);
 
 558     $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new;
 
 568     controller => 'ct.pl',
 
 570     db => $self->is_vendor() ? 'vendor' : 'customer',
 
 573   if ( $::form->{callback} ) {
 
 574     push(@url_params, callback => $::form->{callback});
 
 577   $self->redirect_to(@url_params);
 
 581 sub action_search_contact {
 
 584   my $url = 'ct.pl?action=search_contact&db=customer';
 
 586   if ( $::form->{callback} ) {
 
 587     $url .= '&callback='. $::form->escape($::form->{callback});
 
 590   print $::form->redirect_header($url);
 
 593 sub action_get_delivery {
 
 596   $::auth->assert('sales_all_edit')    if $self->is_customer();
 
 597   $::auth->assert('purchase_all_edit') if $self->is_vendor();
 
 599   my $dbh = $::form->get_standard_dbh();
 
 601   my ($arap, $db, $qty_sign);
 
 602   if ( $self->is_vendor() ) {
 
 605     $qty_sign = ' * -1 AS qty';
 
 612   my $where = ' WHERE 1=1';
 
 615   if ( !$self->is_vendor() && $::form->{shipto_id} && $::form->{shipto_id} ne 'all' ) {
 
 616     $where .= " AND ${arap}.shipto_id = ?";
 
 617     push(@values, $::form->{shipto_id});
 
 619     $where .= " AND ${arap}.${db}_id = ?";
 
 620     push(@values, $::form->{id});
 
 623   if ( $::form->{delivery_from} ) {
 
 624     $where .= " AND ${arap}.transdate >= ?";
 
 625     push(@values, conv_date($::form->{delivery_from}));
 
 628   if ( $::form->{delivery_to} ) {
 
 629     $where .= " AND ${arap}.transdate <= ?";
 
 630     push(@values, conv_date($::form->{delivery_to}));
 
 649       ON ". ($arap eq 'ar' ? '(ar.shipto_id = s.shipto_id) ' : '(ap.id = s.trans_id) ') ."
 
 652        ON ${arap}.id = i.trans_id
 
 658        ON (oe.ordnumber = ${arap}.ordnumber AND NOT ${arap}.ordnumber = ''
 
 659            AND ". ($arap eq 'ar' ? 'oe.customer_id IS NOT NULL' : 'oe.vendor_id IS NOT NULL') ." )
 
 662      ORDER BY ${arap}.transdate DESC LIMIT 15";
 
 664   $self->{delivery} = selectall_hashref_query($::form, $dbh, $query, @values);
 
 666   $self->render('customer_vendor/get_delivery', { layout => 0 });
 
 669 sub action_ajaj_get_shipto {
 
 676         my $name = 'shipto'. $_;
 
 677         $name => $self->{shipto}->$name;
 
 679       qw(_id name department_1 department_2 street zipcode city gln country contact phone fax email)
 
 683   $data->{shipto_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{shipto}->cvars_by_config);
 
 685   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
 
 688 sub action_ajaj_get_additional_billing_address {
 
 692     additional_billing_address => {
 
 693       map { ($_ => $self->{additional_billing_address}->$_) } ('id', @ADDITIONAL_BILLING_ADDRESS_COLUMNS)
 
 697   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
 
 700 sub action_ajaj_get_contact {
 
 708         my $name = 'cp_'. $_;
 
 710         if ( $_ eq 'birthday' && $self->{contact}->$name ) {
 
 711           $name => $self->{contact}->$name->to_lxoffice;
 
 713           $name => $self->{contact}->$name;
 
 717         id gender abteilung title position givenname name email phone1 phone2 fax mobile1 mobile2
 
 718         satphone satfax project street zipcode city privatphone privatemail birthday main
 
 723   $data->{contact_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{contact}->cvars_by_config);
 
 725   # avoid two or more main_cp
 
 726   my $has_main_cp = grep { $_->cp_main == 1 } @{ $self->{cv}->contacts };
 
 727   $data->{contact}->{disable_cp_main} = 1 if ($has_main_cp && !$data->{contact}->{cp_main});
 
 729   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
 
 732 sub action_ajaj_autocomplete {
 
 733   my ($self, %params) = @_;
 
 735   my ($model, $manager, $number, $matches);
 
 737   # first see if this is customer or vendor picking
 
 738   if ($::form->{type} eq 'customer') {
 
 739      $model   = $self->customer_models;
 
 740      $manager = 'SL::DB::Manager::Customer';
 
 741      $number  = 'customernumber';
 
 742   } elsif ($::form->{type} eq 'vendor')  {
 
 743      $model   = $self->vendor_models;
 
 744      $manager = 'SL::DB::Manager::Vendor';
 
 745      $number  = 'vendornumber';
 
 747      die "unknown type $::form->{type}";
 
 750   # if someone types something, and hits enter, assume he entered the full name.
 
 751   # if something matches, treat that as the sole match
 
 752   # unfortunately get_models can't do more than one per package atm, so we do it
 
 753   # the oldfashioned way.
 
 754   if ($::form->{prefer_exact}) {
 
 756     if (1 == scalar @{ $exact_matches = $manager->get_all(
 
 760           name    => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
 
 761           $number => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
 
 766       $matches = $exact_matches;
 
 770   $matches //= $model->get;
 
 774      value       => $_->displayable_name,
 
 775      label       => $_->displayable_name,
 
 777      $number     => $_->$number,
 
 779      type        => $::form->{type},
 
 780      cvars       => { map { ($_->config->name => { value => $_->value_as_text, is_valid => $_->is_valid }) } @{ $_->cvars_by_config } },
 
 784   $self->render(\ SL::JSON::to_json(\@hashes), { layout => 0, type => 'json', process => 0 });
 
 787 sub action_test_page {
 
 788   $_[0]->render('customer_vendor/test_page');
 
 791 sub action_ajax_list_prices {
 
 792   my ($self, %params) = @_;
 
 794   my $report   = SL::ReportGenerator->new(\%::myconfig, $::form);
 
 795   my @columns  = qw(partnumber description price);
 
 796   my @visible  = qw(partnumber description price);
 
 797   my @sortable = qw(partnumber description price);
 
 800     partnumber  => { text => $::locale->text('Part Number'),      sub => sub { $_[0]->parts->partnumber  } },
 
 801     description => { text => $::locale->text('Part Description'), sub => sub { $_[0]->parts->description } },
 
 802     price       => { text => $::locale->text('Price'),            sub => sub { $::form->format_amount(\%::myconfig, $_[0]->price, 2) }, align => 'right' },
 
 805   $::form->{sort_by}  ||= 'partnumber';
 
 806   $::form->{sort_dir} //= 1;
 
 808   for my $col (@sortable) {
 
 809     $column_defs{$col}{link} = $self->url_for(
 
 810       action   => 'ajax_list_prices',
 
 811       callback => $::form->{callback},
 
 813       id       => $self->{cv}->id,
 
 815       sort_dir => ($::form->{sort_by} eq $col ? 1 - $::form->{sort_dir} : $::form->{sort_dir})
 
 819   map { $column_defs{$_}{visible} = 1 } @visible;
 
 822   $pricegroup = $self->{cv}->pricegroup->pricegroup if $self->{cv}->pricegroup;
 
 824   $report->set_columns(%column_defs);
 
 825   $report->set_column_order(@columns);
 
 826   $report->set_options(allow_pdf_export => 0, allow_csv_export => 0);
 
 827   $report->set_sort_indicator($::form->{sort_by}, $::form->{sort_dir});
 
 828   $report->set_export_options(@{ $params{report_generator_export_options} || [] });
 
 829   $report->set_options(
 
 830     %{ $params{report_generator_options} || {} },
 
 831     output_format        => 'HTML',
 
 832     top_info_text        => $::locale->text('Pricegroup') . ': ' . $pricegroup,
 
 833     title                => $::locale->text('Price List'),
 
 836   my $sort_param = $::form->{sort_by} eq 'price'       ? 'price'             :
 
 837                    $::form->{sort_by} eq 'description' ? 'parts.description' :
 
 839   $sort_param .= ' ' . ($::form->{sort_dir} ? 'ASC' : 'DESC');
 
 840   my $prices = SL::DB::Manager::Price->get_all(where        => [ pricegroup_id => $self->{cv}->pricegroup_id ],
 
 841                                                sort_by      => $sort_param,
 
 842                                                with_objects => 'parts');
 
 844   $self->report_generator_list_objects(report => $report, objects => $prices, layout => 0, header => 0);
 
 848   return $::form->{db} eq 'vendor';
 
 852   return $::form->{db} eq 'customer';
 
 858   if ( defined($self->{_is_orphaned}) ) {
 
 859     return $self->{_is_orphaned};
 
 862   my $arap      = $self->is_vendor ? 'ap' : 'ar';
 
 865   my $cv = $self->is_vendor ? 'vendor' : 'customer';
 
 869     FROM '. $arap .' AS a
 
 870     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
 
 877     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
 
 883     FROM delivery_orders a
 
 884     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
 
 888   if ( $self->is_vendor ) {
 
 891       SELECT 1 FROM makemodel mm WHERE mm.make = ?';
 
 895   my ($dummy) = selectrow_query($::form, $::form->get_standard_dbh(), $query, (conv_i($self->{cv}->id)) x $num_args);
 
 897   return $self->{_is_orphaned} = !$dummy;
 
 900 sub _copy_form_to_cvars {
 
 901   my ($self, %params) = @_;
 
 903   foreach my $cvar (@{ $params{target}->cvars_by_config }) {
 
 904     my $value = $params{source}->{$cvar->config->name};
 
 905     $value    = $::form->parse_amount(\%::myconfig, $value) if $cvar->config->type eq 'number';
 
 907     $cvar->value($value);
 
 911 sub _instantiate_args {
 
 914   my $curr_employee = SL::DB::Manager::Employee->current;
 
 916   if ( $::form->{cv}->{id} ) {
 
 917     if ( $self->is_vendor() ) {
 
 918       $self->{cv} = SL::DB::Vendor->new(id => $::form->{cv}->{id})->load();
 
 920       $self->{cv} = SL::DB::Customer->new(id => $::form->{cv}->{id})->load();
 
 923     $self->{cv} = $self->_new_customer_vendor_object;
 
 925   $self->{cv}->assign_attributes(%{$::form->{cv}});
 
 927   if ( $self->is_customer() && $::form->{cv}->{taxincluded_checked} eq '' ) {
 
 928     $self->{cv}->taxincluded_checked(undef);
 
 931   $self->{cv}->hourly_rate($::instance_conf->get_customer_hourly_rate) if $self->is_customer && !$self->{cv}->hourly_rate;
 
 933   if ( $::form->{note}->{id} ) {
 
 934     $self->{note} = SL::DB::Note->new(id => $::form->{note}->{id})->load();
 
 935     $self->{note_followup} = $self->{note}->follow_up;
 
 936     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
 
 938     $self->{note} = SL::DB::Note->new();
 
 939     $self->{note_followup} = SL::DB::FollowUp->new();
 
 940     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
 
 943   $self->{note}->assign_attributes(%{$::form->{note}});
 
 944   $self->{note}->created_by($curr_employee->id);
 
 945   $self->{note}->trans_module('ct');
 
 947   $self->{note_followup}->assign_attributes(%{$::form->{note_followup}});
 
 948   $self->{note_followup}->note($self->{note});
 
 949   $self->{note_followup}->created_by($curr_employee->id);
 
 951   $self->{note_followup_link}->trans_type($self->is_vendor() ? 'vendor' : 'customer');
 
 952   $self->{note_followup_link}->trans_info($self->{cv}->name);
 
 954   if ( $::form->{shipto}->{shipto_id} ) {
 
 955     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto}->{shipto_id})->load();
 
 957     $self->{shipto} = SL::DB::Shipto->new();
 
 959   $self->{shipto}->assign_attributes(%{$::form->{shipto}});
 
 960   $self->{shipto}->module('CT');
 
 962   if ($self->is_customer) {
 
 963     if ( $::form->{additional_billing_address}->{id} ) {
 
 964       $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new(id => $::form->{additional_billing_address}->{id})->load;
 
 966       $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new;
 
 968     $self->{additional_billing_address}->assign_attributes(%{ $::form->{additional_billing_address} });
 
 971   if ( $::form->{contact}->{cp_id} ) {
 
 972     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact}->{cp_id})->load();
 
 974     $self->{contact} = $self->_new_contact_object;
 
 976   $self->{contact}->assign_attributes(%{$::form->{contact}});
 
 978   $self->_copy_form_to_cvars(target => $self->{cv},      source => $::form->{cv_cvars});
 
 979   $self->_copy_form_to_cvars(target => $self->{contact}, source => $::form->{contact_cvars});
 
 980   $self->_copy_form_to_cvars(target => $self->{shipto},  source => $::form->{shipto_cvars});
 
 983 sub _load_customer_vendor {
 
 986   if ( $self->is_vendor() ) {
 
 987     $self->{cv} = SL::DB::Vendor->new(id => $::form->{id})->load();
 
 989     $self->{cv} = SL::DB::Customer->new(id => $::form->{id})->load();
 
 992   if ( $::form->{note_id} ) {
 
 993     $self->{note} = SL::DB::Note->new(id => $::form->{note_id})->load();
 
 994     $self->{note_followup} = $self->{note}->follow_up;
 
 995     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
 
 997     $self->{note} = SL::DB::Note->new();
 
 998     $self->{note_followup} = SL::DB::FollowUp->new();
 
 999     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
 
1002   if ( $::form->{shipto_id} ) {
 
1003     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto_id})->load();
 
1005     if ( $self->{shipto}->trans_id != $self->{cv}->id ) {
 
1006       die($::locale->text('Error'));
 
1009     $self->{shipto} = SL::DB::Shipto->new();
 
1012   if ($self->is_customer) {
 
1013     if ( $::form->{additional_billing_address_id} ) {
 
1014       $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new(id => $::form->{additional_billing_address_id})->load;
 
1015       die($::locale->text('Error')) if $self->{additional_billing_address}->customer_id != $self->{cv}->id;
 
1018       $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new;
 
1022   if ( $::form->{contact_id} ) {
 
1023     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact_id})->load();
 
1025     if ( $self->{contact}->cp_cv_id != $self->{cv}->id ) {
 
1026       die($::locale->text('Error'));
 
1029     $self->{contact} = $self->_new_contact_object;
 
1033 sub _may_access_action {
 
1034   my ($self, $action)   = @_;
 
1036   my $is_new            = !$self->{cv} || !$self->{cv}->id;
 
1037   my $is_own_customer   = !$is_new
 
1038                        && $self->{cv}->is_customer
 
1039                        && (SL::DB::Manager::Employee->current->id == $self->{cv}->salesman_id);
 
1040   my $has_edit_rights   = $::auth->assert('customer_vendor_all_edit', 1);
 
1041   $has_edit_rights    ||= $::auth->assert('customer_vendor_edit',     1) && ($is_new || $is_own_customer);
 
1042   my $needs_edit_rights = $action =~ m{^(?:add|save|delete|update)};
 
1044   $self->user_has_edit_rights($has_edit_rights);
 
1046   return 1 if $has_edit_rights;
 
1047   return 0 if $needs_edit_rights;
 
1052   my ($self, $action) = @_;
 
1054   if (!$self->_may_access_action($action)) {
 
1055     $::auth->deny_access;
 
1059 sub _create_customer_vendor {
 
1062   $self->{cv} = $self->_new_customer_vendor_object;
 
1063   $self->{cv}->currency_id($::instance_conf->get_currency_id());
 
1065   $self->{note} = SL::DB::Note->new();
 
1067   $self->{note_followup} = SL::DB::FollowUp->new();
 
1069   $self->{shipto} = SL::DB::Shipto->new();
 
1070   $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new if $self->is_customer;
 
1072   $self->{contact} = $self->_new_contact_object;
 
1078   my $dbh = $::form->get_standard_dbh();
 
1082   $self->{all_business} = SL::DB::Manager::Business->get_all();
 
1084   $self->{all_employees} = SL::DB::Manager::Employee->get_all(query => [ deleted => 0 ]);
 
1086   $self->{all_greetings} = SL::DB::Manager::Greeting->get_all_sorted();
 
1087   if ($self->{cv}->id && $self->{cv}->greeting && !grep {$self->{cv}->greeting eq $_->description} @{$self->{all_greetings}}) {
 
1088     unshift @{$self->{all_greetings}}, (SL::DB::Greeting->new(description => $self->{cv}->greeting));
 
1091   $self->{all_contact_titles} = SL::DB::Manager::ContactTitle->get_all_sorted();
 
1092   foreach my $contact (@{ $self->{cv}->contacts }) {
 
1093     if ($contact->cp_title && !grep {$contact->cp_title eq $_->description} @{$self->{all_contact_titles}}) {
 
1094       unshift @{$self->{all_contact_titles}}, (SL::DB::ContactTitle->new(description => $contact->cp_title));
 
1098   $self->{all_contact_departments} = SL::DB::Manager::ContactDepartment->get_all_sorted();
 
1099   foreach my $contact (@{ $self->{cv}->contacts }) {
 
1100     if ($contact->cp_abteilung && !grep {$contact->cp_abteilung eq $_->description} @{$self->{all_contact_departments}}) {
 
1101       unshift @{$self->{all_contact_departments}}, (SL::DB::ContactDepartment->new(description => $contact->cp_abteilung));
 
1105   $self->{all_currencies} = SL::DB::Manager::Currency->get_all();
 
1107   $self->{all_languages} = SL::DB::Manager::Language->get_all();
 
1109   $self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all_sorted();
 
1111   if ( $::instance_conf->get_vertreter() ) {
 
1116     my $business_ids = [
 
1119         selectall_hashref_query($::form, $dbh, $query)
 
1123     if ( $business_ids->[0] ) {
 
1124       $self->{all_salesman_customers} = SL::DB::Manager::Customer->get_all(query => [business_id => $business_ids]);
 
1126       $self->{all_salesman_customers} = [];
 
1129     $self->{all_salesmen} = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $self->{cv}->salesman_id,  deleted => 0 ] ]);
 
1132   $self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id       => $self->{cv}->payment_id,
 
1135   $self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_all();
 
1137   if ($self->{cv}->is_customer) {
 
1138     $self->{all_pricegroups} = SL::DB::Manager::Pricegroup->get_all_sorted(query => [ or => [ id => $self->{cv}->pricegroup_id, obsolete => 0 ] ]);
 
1141   $self->{contacts} = $self->{cv}->contacts;
 
1142   $self->{contacts} ||= [];
 
1144   $self->{shiptos} = $self->{cv}->shipto;
 
1145   $self->{shiptos} ||= [];
 
1147   if ($self->is_customer) {
 
1148     $self->{additional_billing_addresses} = $self->{cv}->additional_billing_addresses;
 
1149     $self->{additional_billing_addresses} ||= [];
 
1152   $self->{notes} = SL::DB::Manager::Note->get_all(
 
1154       trans_id => $self->{cv}->id,
 
1155       trans_module => 'ct',
 
1157     with_objects => ['follow_up'],
 
1160   if ( $self->is_vendor()) {
 
1161     $self->{open_items} = SL::DB::Manager::PurchaseInvoice->get_all_count(
 
1163         vendor_id => $self->{cv}->id,
 
1164         paid => {lt_sql => 'amount'},
 
1168     $self->{open_items} = SL::DB::Manager::Invoice->get_all_count(
 
1170         customer_id => $self->{cv}->id,
 
1171         paid => {lt_sql => 'amount'},
 
1176   if ( $self->is_vendor() ) {
 
1177     $self->{open_orders} = SL::DB::Manager::Order->get_all_count(
 
1179         vendor_id => $self->{cv}->id,
 
1184     $self->{open_orders} = SL::DB::Manager::Order->get_all_count(
 
1186         customer_id => $self->{cv}->id,
 
1192   if ($self->{cv}->number && $::instance_conf->get_webdav) {
 
1193     my $webdav = SL::Webdav->new(
 
1194       type     => $self->is_customer ? 'customer'
 
1195                 : $self->is_vendor   ? 'vendor'
 
1197       number   => $self->{cv}->number,
 
1199     my @all_objects = $webdav->get_all_objects;
 
1200     @{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
 
1202                                                     link => File::Spec->catfile($_->full_filedescriptor),
 
1206   $self->{template_args} ||= {};
 
1208   $::request->{layout}->add_javascripts("$_.js") for qw (kivi.CustomerVendor kivi.File kivi.CustomerVendorTurnover ckeditor/ckeditor ckeditor/adapters/jquery);
 
1210   $self->_setup_form_action_bar;
 
1213 sub _setup_form_action_bar {
 
1216   my $no_rights = $self->user_has_edit_rights ? undef
 
1217                 : $self->{cv}->is_customer    ? t8("You don't have the rights to edit this customer.")
 
1218                 :                               t8("You don't have the rights to edit this vendor.");
 
1220   for my $bar ($::request->layout->get('actionbar')) {
 
1225           submit    => [ '#form', { action => "CustomerVendor/save" } ],
 
1226           checks    => [ 'check_taxzone_and_ustid' ],
 
1227           accesskey => 'enter',
 
1228           disabled  => $no_rights,
 
1231           t8('Save and Close'),
 
1232           submit => [ '#form', { action => "CustomerVendor/save_and_close" } ],
 
1233           checks => [ 'check_taxzone_and_ustid' ],
 
1234           disabled => $no_rights,
 
1236       ], # end of combobox "Save"
 
1239         action => [ t8('Workflow') ],
 
1241           t8('Save and AP Transaction'),
 
1242           submit => [ '#form', { action => "CustomerVendor/save_and_ap_transaction" } ],
 
1243           checks => [ 'check_taxzone_and_ustid' ],
 
1244           disabled => $no_rights,
 
1245         ]) x !!$self->is_vendor,
 
1247           t8('Save and AR Transaction'),
 
1248           submit => [ '#form', { action => "CustomerVendor/save_and_ar_transaction" } ],
 
1249           checks => [ 'check_taxzone_and_ustid' ],
 
1250           disabled => $no_rights,
 
1251         ]) x !$self->is_vendor,
 
1253           t8('Save and Invoice'),
 
1254           submit => [ '#form', { action => "CustomerVendor/save_and_invoice" } ],
 
1255           checks => [ 'check_taxzone_and_ustid' ],
 
1256           disabled => $no_rights,
 
1259           t8('Save and Order'),
 
1260           submit => [ '#form', { action => "CustomerVendor/save_and_order" } ],
 
1261           checks => [ 'check_taxzone_and_ustid' ],
 
1262           disabled => $no_rights,
 
1266           submit => [ '#form', { action => "CustomerVendor/save_and_rfq" } ],
 
1267           checks => [ 'check_taxzone_and_ustid' ],
 
1268           disabled => $no_rights,
 
1269         ]) x !!$self->is_vendor,
 
1271           t8('Save and Quotation'),
 
1272           submit => [ '#form', { action => "CustomerVendor/save_and_quotation" } ],
 
1273           checks => [ 'check_taxzone_and_ustid' ],
 
1274           disabled => $no_rights,
 
1275         ]) x !$self->is_vendor,
 
1276       ], # end of combobox "Workflow"
 
1280         submit   => [ '#form', { action => "CustomerVendor/delete" } ],
 
1281         confirm  => t8('Do you really want to delete this object?'),
 
1282         disabled => !$self->{cv}->id    ? t8('This object has not been saved yet.')
 
1283                   : !$self->is_orphaned ? t8('This object has already been used.')
 
1291         call     => [ 'kivi.CustomerVendor.showHistoryWindow', $self->{cv}->id ],
 
1292         disabled => !$self->{cv}->id ? t8('This object has not been saved yet.') : undef,
 
1298 sub _prepare_cvar_configs_for_ajaj {
 
1299   my ($self, $cvars) = @_;
 
1304       my $result = { type => $cvar->config->type };
 
1306       if ($cvar->config->type eq 'number') {
 
1307         $result->{value} = $::form->format_amount(\%::myconfig, $cvar->value, -2);
 
1309       } elsif ($result->{type} eq 'date') {
 
1310         $result->{value} = $cvar->value ? $cvar->value->to_kivitendo : undef;
 
1312       } elsif ($result->{type} =~ m{customer|vendor|part}) {
 
1313         my $object       = $cvar->value;
 
1314         my $method       = $result->{type} eq 'part' ? 'description' : 'name';
 
1316         $result->{id}    = int($cvar->number_value) || undef;
 
1317         $result->{value} = $object ? $object->$method // '' : '';
 
1320         $result->{value} = $cvar->value;
 
1323       ( $cvar->config->name => $result )
 
1325     } grep { $_->is_valid } @{ $cvars }
 
1329 sub normalize_name {
 
1332   # check if feature is enabled (select normalize_vc_names from defaults)
 
1333   return unless ($::instance_conf->get_normalize_vc_names);
 
1335   return unless $self->{cv};
 
1336   my $name = $self->{cv}->name;
 
1340   $self->{cv}->name($name);
 
1343 sub home_address_for_google_maps {
 
1346   my $address = $::instance_conf->get_address // '';
 
1347   $address    =~ s{^\s+|\s+$|\r+}{}g;
 
1348   $address    =~ s{\n+}{,}g;
 
1349   $address    =~ s{\s+}{ }g;
 
1354 sub init_customer_models {
 
1357   SL::Controller::Helper::GetModels->new(
 
1358     controller   => $self,
 
1359     model        => 'Customer',
 
1362         by => 'customernumber',
 
1365       customernumber => t8('Customer Number'),
 
1370 sub init_vendor_models {
 
1373   SL::Controller::Helper::GetModels->new(
 
1374     controller => $self,
 
1378         by => 'vendornumber',
 
1381       vendornumber => t8('Vendor Number'),
 
1386 sub init_zugferd_settings {
 
1388     [ -1, t8('Use settings from client configuration') ],
 
1389     @SL::ZUGFeRD::customer_settings,
 
1393 sub _new_customer_vendor_object {
 
1396   my $class  = 'SL::DB::' . ($self->is_vendor ? 'Vendor' : 'Customer');
 
1397   my $object = $class->new(
 
1400     custom_variables => [],
 
1403   $object->additional_billing_addresses([]) if $self->is_customer;
 
1408 sub _new_contact_object {
 
1411   return SL::DB::Contact->new(custom_variables => []);