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',
67 __PACKAGE__->run_before(
68 '_load_customer_vendor',
79 # make sure this comes after _load_customer_vendor
80 __PACKAGE__->run_before('_check_auth');
82 __PACKAGE__->run_before(
83 '_create_customer_vendor',
89 __PACKAGE__->run_before('normalize_name');
97 if ($self->{cv}->is_customer) {
98 $self->{cv}->assign_attributes(hourly_rate => $::instance_conf->get_customer_hourly_rate);
99 $self->{cv}->salesman_id(SL::DB::Manager::Employee->current->id) if !$::auth->assert('customer_vendor_all_edit', 1);
103 'customer_vendor/form',
104 title => ($self->is_vendor() ? $::locale->text('Add Vendor') : $::locale->text('Add Customer')),
105 %{$self->{template_args}}
112 $self->_pre_render();
114 'customer_vendor/form',
115 title => ($self->is_vendor() ? $::locale->text('Edit Vendor') : $::locale->text('Edit Customer')),
116 %{$self->{template_args}}
123 if ($::request->type eq 'json') {
128 $cv_hash = $self->{cv}->as_tree;
129 $cv_hash->{cvars} = $self->{cv}->cvar_as_hashref;
132 $self->render(\ SL::JSON::to_json($cv_hash), { layout => 0, type => 'json', process => 0 });
136 sub _check_ustid_taxnumber_unique {
140 if ($self->is_vendor()) {
141 %cfg = (should_check => $::instance_conf->get_vendor_ustid_taxnummer_unique,
142 manager_class => 'SL::DB::Manager::Vendor',
143 err_ustid => t8('A vendor with the same VAT ID already exists.'),
144 err_taxnumber => t8('A vendor with the same taxnumber already exists.'),
147 } elsif ($self->is_customer()) {
148 %cfg = (should_check => $::instance_conf->get_customer_ustid_taxnummer_unique,
149 manager_class => 'SL::DB::Manager::Customer',
150 err_ustid => t8('A customer with the same VAT ID already exists.'),
151 err_taxnumber => t8('A customer with the same taxnumber already exists.'),
160 if ($cfg{should_check}) {
161 my $do_clean_taxnumber = sub { my $n = $_[0]; $n //= ''; $n =~ s{[[:space:].-]+}{}g; return $n};
163 my $clean_ustid = SL::VATIDNr->clean($self->{cv}->ustid);
164 my $clean_taxnumber = $do_clean_taxnumber->($self->{cv}->taxnumber);
166 if (!($clean_ustid || $clean_taxnumber)) {
167 return t8('VAT ID and/or taxnumber must be given.');
170 my $clean_number = $clean_ustid;
172 my $entries = $cfg{manager_class}->get_all(query => ['!id' => $self->{cv}->id, '!ustid' => undef, '!ustid' => ''], select => ['ustid'], distinct => 1);
173 if (any { $clean_number eq SL::VATIDNr->clean($_->ustid) } @$entries) {
174 push @errors, $cfg{err_ustid};
178 $clean_number = $clean_taxnumber;
180 my $entries = $cfg{manager_class}->get_all(query => ['!id' => $self->{cv}->id, '!taxnumber' => undef, '!taxnumber' => ''], select => ['taxnumber'], distinct => 1);
181 if (any { $clean_number eq $do_clean_taxnumber->($_->taxnumber) } @$entries) {
182 push @errors, $cfg{err_taxnumber};
188 return join "\n", @errors if @errors;
195 my @errors = $self->{cv}->validate;
197 flash('error', @errors);
198 $self->_pre_render();
200 'customer_vendor/form',
201 title => ($self->is_vendor() ? t8('Edit Vendor') : t8('Edit Customer')),
202 %{$self->{template_args}}
204 $::dispatcher->end_request;
207 $self->{cv}->greeting(trim $self->{cv}->greeting);
208 my $save_greeting = $self->{cv}->greeting
209 && $::instance_conf->get_vc_greetings_use_textfield
210 && SL::DB::Manager::Greeting->get_all_count(where => [description => $self->{cv}->greeting]) == 0;
212 $self->{contact}->cp_title(trim($self->{contact}->cp_title));
213 my $save_contact_title = $self->{contact}->cp_title
214 && $::instance_conf->get_contact_titles_use_textfield
215 && SL::DB::Manager::ContactTitle->get_all_count(where => [description => $self->{contact}->cp_title]) == 0;
217 $self->{contact}->cp_abteilung(trim($self->{contact}->cp_abteilung));
218 my $save_contact_department = $self->{contact}->cp_abteilung
219 && $::instance_conf->get_contact_departments_use_textfield
220 && SL::DB::Manager::ContactDepartment->get_all_count(where => [description => $self->{contact}->cp_abteilung]) == 0;
222 my $db = $self->{cv}->db;
224 $db->with_transaction(sub {
226 if ( $self->is_vendor() ) {
227 if ( $self->{cv}->vendornumber ) {
228 $cvs_by_nr = SL::DB::Manager::Vendor->get_all(query => [vendornumber => $self->{cv}->vendornumber]);
231 if ( $self->{cv}->customernumber ) {
232 $cvs_by_nr = SL::DB::Manager::Customer->get_all(query => [customernumber => $self->{cv}->customernumber]);
236 foreach my $entry (@{$cvs_by_nr}) {
237 if( $entry->id != $self->{cv}->id ) {
239 $self->is_vendor() ? $::locale->text('This vendor number is already in use.') : $::locale->text('This customer number is already in use.');
241 $::form->error($msg);
245 my $ustid_taxnumber_error = $self->_check_ustid_taxnumber_unique;
246 $::form->error($ustid_taxnumber_error) if $ustid_taxnumber_error;
248 $self->{cv}->save(cascade => 1);
250 SL::DB::Greeting->new(description => $self->{cv}->greeting)->save if $save_greeting;
252 $self->{contact}->cp_cv_id($self->{cv}->id);
253 if( $self->{contact}->cp_name ne '' || $self->{contact}->cp_givenname ne '' ) {
254 SL::DB::ContactTitle ->new(description => $self->{contact}->cp_title) ->save if $save_contact_title;
255 SL::DB::ContactDepartment->new(description => $self->{contact}->cp_abteilung)->save if $save_contact_department;
257 $self->{contact}->save(cascade => 1);
260 if( $self->{note}->subject ne '' && $self->{note}->body ne '' ) {
262 if ( !$self->{note_followup}->follow_up_date ) {
263 $::form->error($::locale->text('Date missing!'));
266 $self->{note}->trans_id($self->{cv}->id);
267 $self->{note}->save();
269 $self->{note_followup}->save();
271 $self->{note_followup_link}->follow_up_id($self->{note_followup}->id);
272 $self->{note_followup_link}->trans_id($self->{cv}->id);
273 $self->{note_followup_link}->save();
275 SL::Helper::Flash::flash_later('info', $::locale->text('Follow-Up saved.'));
278 $self->{shipto}->trans_id($self->{cv}->id);
279 if(any { $self->{shipto}->$_ ne '' } qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax shiptoemail)) {
280 $self->{shipto}->save(cascade => 1);
283 my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
284 SL::DB::History->new(
285 trans_id => $self->{cv}->id,
286 snumbers => $snumbers,
287 employee_id => SL::DB::Manager::Employee->current->id,
291 if ( $::form->{delete_notes} ) {
292 foreach my $note_id (@{ $::form->{delete_notes} }) {
293 my $note = SL::DB::Note->new(id => $note_id)->load();
294 if ( $note->follow_up ) {
295 if ( $note->follow_up->follow_up_link ) {
296 $note->follow_up->follow_up_link->delete(cascade => 'delete');
298 $note->follow_up->delete(cascade => 'delete');
300 $note->delete(cascade => 'delete');
305 }) || die($db->error);
314 my @redirect_params = (
316 id => $self->{cv}->id,
317 db => ($self->is_vendor() ? 'vendor' : 'customer'),
320 if ( $self->{contact}->cp_id ) {
321 push(@redirect_params, contact_id => $self->{contact}->cp_id);
324 if ( $self->{shipto}->shipto_id ) {
325 push(@redirect_params, shipto_id => $self->{shipto}->shipto_id);
328 $self->redirect_to(@redirect_params);
331 sub action_save_and_close {
336 my $msg = $self->is_vendor() ? $::locale->text('Vendor saved') : $::locale->text('Customer saved');
337 $::form->redirect($msg);
341 my ($self, $script) = @_;
343 $::auth->assert('gl_transactions | ap_transactions | ar_transactions'.
344 '| invoice_edit | vendor_invoice_edit | ' .
345 ' request_quotation_edit | sales_quotation_edit | sales_order_edit | purchase_order_edit');
349 my $name = $::form->escape($self->{cv}->name, 1);
350 my $db = $self->is_vendor() ? 'vendor' : 'customer';
353 if ($::instance_conf->get_feature_experimental_order && 'oe.pl' eq $script) {
354 $script = 'controller.pl';
355 $action = 'Order/' . $action;
358 my $url = $self->url_for(
359 controller => $script,
362 $db .'_id' => $self->{cv}->id,
364 type => $::form->{type},
365 callback => $::form->{callback},
368 print $::form->redirect_header($url);
371 sub action_save_and_ar_transaction {
374 $main::auth->assert('ar_transactions');
376 $self->_transaction('ar.pl');
379 sub action_save_and_ap_transaction {
382 $main::auth->assert('ap_transactions');
384 $self->_transaction('ap.pl');
387 sub action_save_and_invoice {
390 if ( $self->is_vendor() ) {
391 $::auth->assert('vendor_invoice_edit');
393 $::auth->assert('invoice_edit');
396 $::form->{type} = 'invoice';
397 $self->_transaction($self->is_vendor() ? 'ir.pl' : 'is.pl');
400 sub action_save_and_order {
403 if ( $self->is_vendor() ) {
404 $::auth->assert('purchase_order_edit');
406 $::auth->assert('sales_order_edit');
409 $::form->{type} = $self->is_vendor() ? 'purchase_order' : 'sales_order';
410 $self->_transaction('oe.pl');
413 sub action_save_and_rfq {
416 $::auth->assert('request_quotation_edit');
418 $::form->{type} = 'request_quotation';
419 $self->_transaction('oe.pl');
422 sub action_save_and_quotation {
425 $::auth->assert('sales_quotation_edit');
427 $::form->{type} = 'sales_quotation';
428 $self->_transaction('oe.pl');
434 my $db = $self->{cv}->db;
436 if( !$self->is_orphaned() ) {
437 $self->action_edit();
440 $db->with_transaction(sub {
441 $self->{cv}->delete(cascade => 1);
443 my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
444 SL::DB::History->new(
445 trans_id => $self->{cv}->id,
446 snumbers => $snumbers,
447 employee_id => SL::DB::Manager::Employee->current->id,
448 addition => 'DELETED',
450 }) || die($db->error);
452 my $msg = $self->is_vendor() ? $::locale->text('Vendor deleted!') : $::locale->text('Customer deleted!');
453 $::form->redirect($msg);
459 sub action_delete_contact {
462 my $db = $self->{contact}->db;
464 if ( !$self->{contact}->cp_id ) {
465 SL::Helper::Flash::flash('error', $::locale->text('No contact selected to delete'));
468 $db->with_transaction(sub {
469 if ( $self->{contact}->used ) {
470 $self->{contact}->detach();
471 $self->{contact}->save();
472 SL::Helper::Flash::flash('info', $::locale->text('Contact is in use and was flagged invalid.'));
474 $self->{contact}->delete(cascade => 1);
475 SL::Helper::Flash::flash('info', $::locale->text('Contact deleted.'));
479 }) || die($db->error);
481 $self->{contact} = $self->_new_contact_object;
484 $self->action_edit();
487 sub action_delete_shipto {
490 my $db = $self->{shipto}->db;
492 if ( !$self->{shipto}->shipto_id ) {
493 SL::Helper::Flash::flash('error', $::locale->text('No shipto selected to delete'));
496 $db->with_transaction(sub {
497 if ( $self->{shipto}->used ) {
498 $self->{shipto}->detach();
499 $self->{shipto}->save(cascade => 1);
500 SL::Helper::Flash::flash('info', $::locale->text('Shipto is in use and was flagged invalid.'));
502 $self->{shipto}->delete(cascade => 1);
503 SL::Helper::Flash::flash('info', $::locale->text('Shipto deleted.'));
507 }) || die($db->error);
509 $self->{shipto} = SL::DB::Shipto->new();
512 $self->action_edit();
520 controller => 'ct.pl',
522 db => $self->is_vendor() ? 'vendor' : 'customer',
525 if ( $::form->{callback} ) {
526 push(@url_params, callback => $::form->{callback});
529 $self->redirect_to(@url_params);
533 sub action_search_contact {
536 my $url = 'ct.pl?action=search_contact&db=customer';
538 if ( $::form->{callback} ) {
539 $url .= '&callback='. $::form->escape($::form->{callback});
542 print $::form->redirect_header($url);
545 sub action_get_delivery {
548 $::auth->assert('sales_all_edit') if $self->is_customer();
549 $::auth->assert('purchase_all_edit') if $self->is_vendor();
551 my $dbh = $::form->get_standard_dbh();
553 my ($arap, $db, $qty_sign);
554 if ( $self->is_vendor() ) {
557 $qty_sign = ' * -1 AS qty';
564 my $where = ' WHERE 1=1';
567 if ( !$self->is_vendor() && $::form->{shipto_id} && $::form->{shipto_id} ne 'all' ) {
568 $where .= " AND ${arap}.shipto_id = ?";
569 push(@values, $::form->{shipto_id});
571 $where .= " AND ${arap}.${db}_id = ?";
572 push(@values, $::form->{id});
575 if ( $::form->{delivery_from} ) {
576 $where .= " AND ${arap}.transdate >= ?";
577 push(@values, conv_date($::form->{delivery_from}));
580 if ( $::form->{delivery_to} ) {
581 $where .= " AND ${arap}.transdate <= ?";
582 push(@values, conv_date($::form->{delivery_to}));
601 ON ". ($arap eq 'ar' ? '(ar.shipto_id = s.shipto_id) ' : '(ap.id = s.trans_id) ') ."
604 ON ${arap}.id = i.trans_id
610 ON (oe.ordnumber = ${arap}.ordnumber AND NOT ${arap}.ordnumber = ''
611 AND ". ($arap eq 'ar' ? 'oe.customer_id IS NOT NULL' : 'oe.vendor_id IS NOT NULL') ." )
614 ORDER BY ${arap}.transdate DESC LIMIT 15";
616 $self->{delivery} = selectall_hashref_query($::form, $dbh, $query, @values);
618 $self->render('customer_vendor/get_delivery', { layout => 0 });
621 sub action_ajaj_get_shipto {
628 my $name = 'shipto'. $_;
629 $name => $self->{shipto}->$name;
631 qw(_id name department_1 department_2 street zipcode city gln country contact phone fax email)
635 $data->{shipto_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{shipto}->cvars_by_config);
637 $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
640 sub action_ajaj_get_contact {
648 my $name = 'cp_'. $_;
650 if ( $_ eq 'birthday' && $self->{contact}->$name ) {
651 $name => $self->{contact}->$name->to_lxoffice;
653 $name => $self->{contact}->$name;
657 id gender abteilung title position givenname name email phone1 phone2 fax mobile1 mobile2
658 satphone satfax project street zipcode city privatphone privatemail birthday main
663 $data->{contact_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{contact}->cvars_by_config);
665 # avoid two or more main_cp
666 my $has_main_cp = grep { $_->cp_main == 1 } @{ $self->{cv}->contacts };
667 $data->{contact}->{disable_cp_main} = 1 if ($has_main_cp && !$data->{contact}->{cp_main});
669 $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
672 sub action_ajaj_autocomplete {
673 my ($self, %params) = @_;
675 my ($model, $manager, $number, $matches);
677 # first see if this is customer or vendor picking
678 if ($::form->{type} eq 'customer') {
679 $model = $self->customer_models;
680 $manager = 'SL::DB::Manager::Customer';
681 $number = 'customernumber';
682 } elsif ($::form->{type} eq 'vendor') {
683 $model = $self->vendor_models;
684 $manager = 'SL::DB::Manager::Vendor';
685 $number = 'vendornumber';
687 die "unknown type $::form->{type}";
690 # if someone types something, and hits enter, assume he entered the full name.
691 # if something matches, treat that as the sole match
692 # unfortunately get_models can't do more than one per package atm, so we do it
693 # the oldfashioned way.
694 if ($::form->{prefer_exact}) {
696 if (1 == scalar @{ $exact_matches = $manager->get_all(
700 name => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
701 $number => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
706 $matches = $exact_matches;
710 $matches //= $model->get;
714 value => $_->displayable_name,
715 label => $_->displayable_name,
717 $number => $_->$number,
719 type => $::form->{type},
720 cvars => { map { ($_->config->name => { value => $_->value_as_text, is_valid => $_->is_valid }) } @{ $_->cvars_by_config } },
724 $self->render(\ SL::JSON::to_json(\@hashes), { layout => 0, type => 'json', process => 0 });
727 sub action_test_page {
728 $_[0]->render('customer_vendor/test_page');
731 sub action_ajax_list_prices {
732 my ($self, %params) = @_;
734 my $report = SL::ReportGenerator->new(\%::myconfig, $::form);
735 my @columns = qw(partnumber description price);
736 my @visible = qw(partnumber description price);
737 my @sortable = qw(partnumber description price);
740 partnumber => { text => $::locale->text('Part Number'), sub => sub { $_[0]->parts->partnumber } },
741 description => { text => $::locale->text('Part Description'), sub => sub { $_[0]->parts->description } },
742 price => { text => $::locale->text('Price'), sub => sub { $::form->format_amount(\%::myconfig, $_[0]->price, 2) }, align => 'right' },
745 $::form->{sort_by} ||= 'partnumber';
746 $::form->{sort_dir} //= 1;
748 for my $col (@sortable) {
749 $column_defs{$col}{link} = $self->url_for(
750 action => 'ajax_list_prices',
751 callback => $::form->{callback},
753 id => $self->{cv}->id,
755 sort_dir => ($::form->{sort_by} eq $col ? 1 - $::form->{sort_dir} : $::form->{sort_dir})
759 map { $column_defs{$_}{visible} = 1 } @visible;
762 $pricegroup = $self->{cv}->pricegroup->pricegroup if $self->{cv}->pricegroup;
764 $report->set_columns(%column_defs);
765 $report->set_column_order(@columns);
766 $report->set_options(allow_pdf_export => 0, allow_csv_export => 0);
767 $report->set_sort_indicator($::form->{sort_by}, $::form->{sort_dir});
768 $report->set_export_options(@{ $params{report_generator_export_options} || [] });
769 $report->set_options(
770 %{ $params{report_generator_options} || {} },
771 output_format => 'HTML',
772 top_info_text => $::locale->text('Pricegroup') . ': ' . $pricegroup,
773 title => $::locale->text('Price List'),
776 my $sort_param = $::form->{sort_by} eq 'price' ? 'price' :
777 $::form->{sort_by} eq 'description' ? 'parts.description' :
779 $sort_param .= ' ' . ($::form->{sort_dir} ? 'ASC' : 'DESC');
780 my $prices = SL::DB::Manager::Price->get_all(where => [ pricegroup_id => $self->{cv}->pricegroup_id ],
781 sort_by => $sort_param,
782 with_objects => 'parts');
784 $self->report_generator_list_objects(report => $report, objects => $prices, layout => 0, header => 0);
788 return $::form->{db} eq 'vendor';
792 return $::form->{db} eq 'customer';
798 if ( defined($self->{_is_orphaned}) ) {
799 return $self->{_is_orphaned};
802 my $arap = $self->is_vendor ? 'ap' : 'ar';
805 my $cv = $self->is_vendor ? 'vendor' : 'customer';
809 FROM '. $arap .' AS a
810 JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
817 JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
823 FROM delivery_orders a
824 JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
828 if ( $self->is_vendor ) {
831 SELECT 1 FROM makemodel mm WHERE mm.make = ?';
835 my ($dummy) = selectrow_query($::form, $::form->get_standard_dbh(), $query, (conv_i($self->{cv}->id)) x $num_args);
837 return $self->{_is_orphaned} = !$dummy;
840 sub _copy_form_to_cvars {
841 my ($self, %params) = @_;
843 foreach my $cvar (@{ $params{target}->cvars_by_config }) {
844 my $value = $params{source}->{$cvar->config->name};
845 $value = $::form->parse_amount(\%::myconfig, $value) if $cvar->config->type eq 'number';
847 $cvar->value($value);
851 sub _instantiate_args {
854 my $curr_employee = SL::DB::Manager::Employee->current;
856 if ( $::form->{cv}->{id} ) {
857 if ( $self->is_vendor() ) {
858 $self->{cv} = SL::DB::Vendor->new(id => $::form->{cv}->{id})->load();
860 $self->{cv} = SL::DB::Customer->new(id => $::form->{cv}->{id})->load();
863 $self->{cv} = $self->_new_customer_vendor_object;
865 $self->{cv}->assign_attributes(%{$::form->{cv}});
867 if ( $self->is_customer() && $::form->{cv}->{taxincluded_checked} eq '' ) {
868 $self->{cv}->taxincluded_checked(undef);
871 $self->{cv}->hourly_rate($::instance_conf->get_customer_hourly_rate) if $self->is_customer && !$self->{cv}->hourly_rate;
873 if ( $::form->{note}->{id} ) {
874 $self->{note} = SL::DB::Note->new(id => $::form->{note}->{id})->load();
875 $self->{note_followup} = $self->{note}->follow_up;
876 $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
878 $self->{note} = SL::DB::Note->new();
879 $self->{note_followup} = SL::DB::FollowUp->new();
880 $self->{note_followup_link} = SL::DB::FollowUpLink->new();
883 $self->{note}->assign_attributes(%{$::form->{note}});
884 $self->{note}->created_by($curr_employee->id);
885 $self->{note}->trans_module('ct');
887 $self->{note_followup}->assign_attributes(%{$::form->{note_followup}});
888 $self->{note_followup}->note($self->{note});
889 $self->{note_followup}->created_by($curr_employee->id);
891 $self->{note_followup_link}->trans_type($self->is_vendor() ? 'vendor' : 'customer');
892 $self->{note_followup_link}->trans_info($self->{cv}->name);
894 if ( $::form->{shipto}->{shipto_id} ) {
895 $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto}->{shipto_id})->load();
897 $self->{shipto} = SL::DB::Shipto->new();
899 $self->{shipto}->assign_attributes(%{$::form->{shipto}});
900 $self->{shipto}->module('CT');
902 if ( $::form->{contact}->{cp_id} ) {
903 $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact}->{cp_id})->load();
905 $self->{contact} = $self->_new_contact_object;
907 $self->{contact}->assign_attributes(%{$::form->{contact}});
909 $self->_copy_form_to_cvars(target => $self->{cv}, source => $::form->{cv_cvars});
910 $self->_copy_form_to_cvars(target => $self->{contact}, source => $::form->{contact_cvars});
911 $self->_copy_form_to_cvars(target => $self->{shipto}, source => $::form->{shipto_cvars});
914 sub _load_customer_vendor {
917 if ( $self->is_vendor() ) {
918 $self->{cv} = SL::DB::Vendor->new(id => $::form->{id})->load();
920 $self->{cv} = SL::DB::Customer->new(id => $::form->{id})->load();
923 if ( $::form->{note_id} ) {
924 $self->{note} = SL::DB::Note->new(id => $::form->{note_id})->load();
925 $self->{note_followup} = $self->{note}->follow_up;
926 $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
928 $self->{note} = SL::DB::Note->new();
929 $self->{note_followup} = SL::DB::FollowUp->new();
930 $self->{note_followup_link} = SL::DB::FollowUpLink->new();
933 if ( $::form->{shipto_id} ) {
934 $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto_id})->load();
936 if ( $self->{shipto}->trans_id != $self->{cv}->id ) {
937 die($::locale->text('Error'));
940 $self->{shipto} = SL::DB::Shipto->new();
943 if ( $::form->{contact_id} ) {
944 $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact_id})->load();
946 if ( $self->{contact}->cp_cv_id != $self->{cv}->id ) {
947 die($::locale->text('Error'));
950 $self->{contact} = $self->_new_contact_object;
954 sub _may_access_action {
955 my ($self, $action) = @_;
957 my $is_new = !$self->{cv} || !$self->{cv}->id;
958 my $is_own_customer = !$is_new
959 && $self->{cv}->is_customer
960 && (SL::DB::Manager::Employee->current->id == $self->{cv}->salesman_id);
961 my $has_edit_rights = $::auth->assert('customer_vendor_all_edit', 1);
962 $has_edit_rights ||= $::auth->assert('customer_vendor_edit', 1) && ($is_new || $is_own_customer);
963 my $needs_edit_rights = $action =~ m{^(?:add|save|delete|update)};
965 $self->user_has_edit_rights($has_edit_rights);
967 return 1 if $has_edit_rights;
968 return 0 if $needs_edit_rights;
973 my ($self, $action) = @_;
975 if (!$self->_may_access_action($action)) {
976 $::auth->deny_access;
980 sub _create_customer_vendor {
983 $self->{cv} = $self->_new_customer_vendor_object;
984 $self->{cv}->currency_id($::instance_conf->get_currency_id());
986 $self->{note} = SL::DB::Note->new();
988 $self->{note_followup} = SL::DB::FollowUp->new();
990 $self->{shipto} = SL::DB::Shipto->new();
992 $self->{contact} = $self->_new_contact_object;
998 my $dbh = $::form->get_standard_dbh();
1002 $self->{all_business} = SL::DB::Manager::Business->get_all();
1004 $self->{all_employees} = SL::DB::Manager::Employee->get_all(query => [ deleted => 0 ]);
1006 $self->{all_greetings} = SL::DB::Manager::Greeting->get_all_sorted();
1007 if ($self->{cv}->id && $self->{cv}->greeting && !grep {$self->{cv}->greeting eq $_->description} @{$self->{all_greetings}}) {
1008 unshift @{$self->{all_greetings}}, (SL::DB::Greeting->new(description => $self->{cv}->greeting));
1011 $self->{all_contact_titles} = SL::DB::Manager::ContactTitle->get_all_sorted();
1012 foreach my $contact (@{ $self->{cv}->contacts }) {
1013 if ($contact->cp_title && !grep {$contact->cp_title eq $_->description} @{$self->{all_contact_titles}}) {
1014 unshift @{$self->{all_contact_titles}}, (SL::DB::ContactTitle->new(description => $contact->cp_title));
1018 $self->{all_contact_departments} = SL::DB::Manager::ContactDepartment->get_all_sorted();
1019 foreach my $contact (@{ $self->{cv}->contacts }) {
1020 if ($contact->cp_abteilung && !grep {$contact->cp_abteilung eq $_->description} @{$self->{all_contact_departments}}) {
1021 unshift @{$self->{all_contact_departments}}, (SL::DB::ContactDepartment->new(description => $contact->cp_abteilung));
1025 $self->{all_currencies} = SL::DB::Manager::Currency->get_all();
1027 $self->{all_languages} = SL::DB::Manager::Language->get_all();
1029 $self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all_sorted();
1031 if ( $::instance_conf->get_vertreter() ) {
1036 my $business_ids = [
1039 selectall_hashref_query($::form, $dbh, $query)
1043 if ( $business_ids->[0] ) {
1044 $self->{all_salesman_customers} = SL::DB::Manager::Customer->get_all(query => [business_id => $business_ids]);
1046 $self->{all_salesman_customers} = [];
1049 $self->{all_salesmen} = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $self->{cv}->salesman_id, deleted => 0 ] ]);
1052 $self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id => $self->{cv}->payment_id,
1055 $self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_all();
1057 if ($self->{cv}->is_customer) {
1058 $self->{all_pricegroups} = SL::DB::Manager::Pricegroup->get_all_sorted(query => [ or => [ id => $self->{cv}->pricegroup_id, obsolete => 0 ] ]);
1061 $self->{contacts} = $self->{cv}->contacts;
1062 $self->{contacts} ||= [];
1064 $self->{shiptos} = $self->{cv}->shipto;
1065 $self->{shiptos} ||= [];
1067 $self->{notes} = SL::DB::Manager::Note->get_all(
1069 trans_id => $self->{cv}->id,
1070 trans_module => 'ct',
1072 with_objects => ['follow_up'],
1075 if ( $self->is_vendor()) {
1076 $self->{open_items} = SL::DB::Manager::PurchaseInvoice->get_all_count(
1078 vendor_id => $self->{cv}->id,
1079 paid => {lt_sql => 'amount'},
1083 $self->{open_items} = SL::DB::Manager::Invoice->get_all_count(
1085 customer_id => $self->{cv}->id,
1086 paid => {lt_sql => 'amount'},
1091 if ( $self->is_vendor() ) {
1092 $self->{open_orders} = SL::DB::Manager::Order->get_all_count(
1094 vendor_id => $self->{cv}->id,
1099 $self->{open_orders} = SL::DB::Manager::Order->get_all_count(
1101 customer_id => $self->{cv}->id,
1107 if ($self->{cv}->number && $::instance_conf->get_webdav) {
1108 my $webdav = SL::Webdav->new(
1109 type => $self->is_customer ? 'customer'
1110 : $self->is_vendor ? 'vendor'
1112 number => $self->{cv}->number,
1114 my @all_objects = $webdav->get_all_objects;
1115 @{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
1117 link => File::Spec->catfile($_->full_filedescriptor),
1121 $self->{template_args} ||= {};
1123 $::request->{layout}->add_javascripts('kivi.CustomerVendor.js');
1124 $::request->{layout}->add_javascripts('kivi.File.js');
1125 $::request->{layout}->add_javascripts('kivi.CustomerVendorTurnover.js');
1127 $self->_setup_form_action_bar;
1130 sub _setup_form_action_bar {
1133 my $no_rights = $self->user_has_edit_rights ? undef
1134 : $self->{cv}->is_customer ? t8("You don't have the rights to edit this customer.")
1135 : t8("You don't have the rights to edit this vendor.");
1137 for my $bar ($::request->layout->get('actionbar')) {
1142 submit => [ '#form', { action => "CustomerVendor/save" } ],
1143 checks => [ 'check_taxzone_and_ustid' ],
1144 accesskey => 'enter',
1145 disabled => $no_rights,
1148 t8('Save and Close'),
1149 submit => [ '#form', { action => "CustomerVendor/save_and_close" } ],
1150 checks => [ 'check_taxzone_and_ustid' ],
1151 disabled => $no_rights,
1153 ], # end of combobox "Save"
1156 action => [ t8('Workflow') ],
1158 t8('Save and AP Transaction'),
1159 submit => [ '#form', { action => "CustomerVendor/save_and_ap_transaction" } ],
1160 checks => [ 'check_taxzone_and_ustid' ],
1161 disabled => $no_rights,
1162 ]) x !!$self->is_vendor,
1164 t8('Save and AR Transaction'),
1165 submit => [ '#form', { action => "CustomerVendor/save_and_ar_transaction" } ],
1166 checks => [ 'check_taxzone_and_ustid' ],
1167 disabled => $no_rights,
1168 ]) x !$self->is_vendor,
1170 t8('Save and Invoice'),
1171 submit => [ '#form', { action => "CustomerVendor/save_and_invoice" } ],
1172 checks => [ 'check_taxzone_and_ustid' ],
1173 disabled => $no_rights,
1176 t8('Save and Order'),
1177 submit => [ '#form', { action => "CustomerVendor/save_and_order" } ],
1178 checks => [ 'check_taxzone_and_ustid' ],
1179 disabled => $no_rights,
1183 submit => [ '#form', { action => "CustomerVendor/save_and_rfq" } ],
1184 checks => [ 'check_taxzone_and_ustid' ],
1185 disabled => $no_rights,
1186 ]) x !!$self->is_vendor,
1188 t8('Save and Quotation'),
1189 submit => [ '#form', { action => "CustomerVendor/save_and_quotation" } ],
1190 checks => [ 'check_taxzone_and_ustid' ],
1191 disabled => $no_rights,
1192 ]) x !$self->is_vendor,
1193 ], # end of combobox "Workflow"
1197 submit => [ '#form', { action => "CustomerVendor/delete" } ],
1198 confirm => t8('Do you really want to delete this object?'),
1199 disabled => !$self->{cv}->id ? t8('This object has not been saved yet.')
1200 : !$self->is_orphaned ? t8('This object has already been used.')
1208 call => [ 'kivi.CustomerVendor.showHistoryWindow', $self->{cv}->id ],
1209 disabled => !$self->{cv}->id ? t8('This object has not been saved yet.') : undef,
1215 sub _prepare_cvar_configs_for_ajaj {
1216 my ($self, $cvars) = @_;
1221 my $result = { type => $cvar->config->type };
1223 if ($cvar->config->type eq 'number') {
1224 $result->{value} = $::form->format_amount(\%::myconfig, $cvar->value, -2);
1226 } elsif ($result->{type} eq 'date') {
1227 $result->{value} = $cvar->value ? $cvar->value->to_kivitendo : undef;
1229 } elsif ($result->{type} =~ m{customer|vendor|part}) {
1230 my $object = $cvar->value;
1231 my $method = $result->{type} eq 'part' ? 'description' : 'name';
1233 $result->{id} = int($cvar->number_value) || undef;
1234 $result->{value} = $object ? $object->$method // '' : '';
1237 $result->{value} = $cvar->value;
1240 ( $cvar->config->name => $result )
1242 } grep { $_->is_valid } @{ $cvars }
1246 sub normalize_name {
1249 # check if feature is enabled (select normalize_vc_names from defaults)
1250 return unless ($::instance_conf->get_normalize_vc_names);
1252 return unless $self->{cv};
1253 my $name = $self->{cv}->name;
1257 $self->{cv}->name($name);
1260 sub home_address_for_google_maps {
1263 my $address = $::instance_conf->get_address // '';
1264 $address =~ s{^\s+|\s+$|\r+}{}g;
1265 $address =~ s{\n+}{,}g;
1266 $address =~ s{\s+}{ }g;
1271 sub init_customer_models {
1274 SL::Controller::Helper::GetModels->new(
1275 controller => $self,
1276 model => 'Customer',
1279 by => 'customernumber',
1282 customernumber => t8('Customer Number'),
1287 sub init_vendor_models {
1290 SL::Controller::Helper::GetModels->new(
1291 controller => $self,
1295 by => 'vendornumber',
1298 vendornumber => t8('Vendor Number'),
1303 sub init_zugferd_settings {
1305 [ -1, t8('Use settings from client configuration') ],
1306 @SL::ZUGFeRD::customer_settings,
1310 sub _new_customer_vendor_object {
1313 my $class = 'SL::DB::' . ($self->is_vendor ? 'Vendor' : 'Customer');
1317 custom_variables => [],
1321 sub _new_contact_object {
1324 return SL::DB::Contact->new(custom_variables => []);