1 package FS::ClientAPI::MyAccount;
3 use 5.008; #require 5.8+ for Time::Local 1.05+
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard 0.35;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
21 use FS::UI::bytecount qw( display_bytecount );
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types money_pretty);
27 use FS::Misc::DateTime qw(parse_datetime);
29 use FS::ClientAPI_SessionCache;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
46 use FS::acct_rt_transaction;
50 use FS::cust_location;
53 # for code organization
54 use FS::ClientAPI::MyAccount::contact;
55 use FS::ClientAPI::MyAccount::quotation;
58 $me = '[FS::ClientAPI::MyAccount]';
60 use vars qw( @cust_main_editable_fields @location_editable_fields );
61 @cust_main_editable_fields = qw(
62 first last company daytime night fax mobile
64 ss stateid stateid_state
66 @location_editable_fields = qw(
67 address1 address2 city county state zip country
71 BEGIN { #preload to reduce time customer_info takes
72 if ( $FS::TicketSystem::system ) {
73 warn "$me: initializing ticket system\n" if $DEBUG;
74 FS::TicketSystem->init();
79 $cache ||= new FS::ClientAPI_SessionCache( {
80 'namespace' => 'FS::ClientAPI::MyAccount',
87 my($context, $session, $custnum) = _custoragent_session_custnum($p);
88 #return { 'error' => $session } if $context eq 'error';
91 if ( $context eq 'customer' && $custnum ) {
93 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
96 $sth->execute($custnum) or die $sth->errstr;
98 $agentnum = $sth->fetchrow_arrayref->[0]
99 or die "no agentnum for custnum $custnum";
101 #} elsif ( $context eq 'agent' ) {
102 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
105 $p->{'agentnum'} = $agentnum;
107 my $conf = new FS::Conf;
109 #false laziness w/Signup.pm
111 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
113 if ( $skin_info_cache_agent ) {
115 warn "$me loading cached skin info for agentnum $agentnum\n"
120 warn "$me populating skin info cache for agentnum $agentnum\n"
123 $skin_info_cache_agent = {
124 'agentnum' => $agentnum,
125 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
126 qw( company_name date_format ) ),
127 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
128 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
129 text_color link_color vlink_color hlink_color alink_color
130 font title_color title_align title_size menu_bgcolor menu_fontsize
133 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
134 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
135 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
137 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
138 qw( title_left_image title_right_image
139 menu_top_image menu_body_image menu_bottom_image
142 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
143 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
144 qw( head body_header body_footer company_address ) ),
145 'money_char' => $conf->config("money_char") || '$',
146 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
149 services.php Services
150 services.php My Services
151 services_new.php Order a new service
154 personal.php Personal Information
155 password.php Change Password
158 payment_cc.php Credit Card Payment
159 payment_ach.php Electronic Check Payment
160 payment_paypal.php PayPal Payment
161 payment_webpay.php Webpay Payments
164 usage_data.php Data usage
165 usage_cdr.php Call usage
167 tickets.php Help Desk
168 tickets.php Open Tickets
169 tickets_resolved.php Resolved Tickets
170 ticket_create.php Create a new ticket
178 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
182 #{ %$skin_info_cache_agent };
183 $skin_info_cache_agent;
190 my $conf = new FS::Conf;
194 'phone_login' => $conf->exists('selfservice_server-phone_login'),
195 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
196 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
197 'banner_image_md5' =>
198 md5_hex($conf->config_binary('selfservice-login_banner_image')),
205 sub login_banner_image {
207 my $conf = new FS::Conf;
208 my $image = $conf->config_binary('selfservice-login_banner_image');
210 'md5' => md5_hex($image),
215 #false laziness w/FS::ClientAPI::passwd::passwd
219 my $conf = new FS::Conf;
223 if ( $p->{'domain'} eq 'svc_phone'
224 && $conf->exists('selfservice_server-phone_login') ) {
226 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
227 return { error => 'Number not found.' } unless $svc_phone;
230 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
231 #return { error => 'Only primary user may log in.' }
232 # if $conf->exists('selfservice_server-primary_only')
233 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
235 return { error => 'Incorrect PIN.' }
236 unless $svc_phone->check_pin($p->{'password'});
240 } elsif ( $p->{email}
241 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
244 return { error => 'Incorrect contact password.' }
245 unless $contact->authenticate_password($p->{'password'});
247 $session->{'contactnum'} = $contact->contactnum;
249 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
250 if ( scalar(@cust_contact) == 1 ) {
251 $session->{'custnum'} = $cust_contact[0]->custnum;
252 } elsif ( scalar(@cust_contact) ) {
253 $session->{'customers'} = { map { $_->custnum => $_->cust_main->name }
257 return { error => 'No customer self-service access for contact' }; #??
262 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
264 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
265 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
267 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
268 'domsvc' => $svc_domain->svcnum, }
271 if ( $conf->exists('selfservice_server-login_svcpart') ) {
272 my @svcpart = $conf->config('selfservice_server-login_svcpart');
273 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
274 scalar( grep( $_ eq $svcpart, @svcpart ) );
279 if ( $conf->exists('selfservice_server-primary_only') ) {
282 my $cust_svc = $_->cust_svc;
283 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
284 == $cust_svc->svcpart
289 return { error => 'User not found.' } unless @svc_acct;
291 return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
293 my $svc_acct = $svc_acct[0];
295 if ( $conf->exists('selfservice_server-login_svcpart') ) {
296 my @svcpart = $conf->config('selfservice_server-login_svcpart');
297 my $svcpart = $svc_acct->cust_svc->svcpart;
298 return { error => 'Invalid user.' }
299 unless grep($_ eq $svcpart, @svcpart);
302 return { error => 'Incorrect password.' }
303 unless $svc_acct->check_password($p->{'password'});
311 $session->{'svcnum'} = $svc_x->svcnum;
313 my $cust_svc = $svc_x->cust_svc;
314 my $cust_pkg = $cust_svc->cust_pkg;
316 my $cust_main = $cust_pkg->cust_main;
317 $session->{'custnum'} = $cust_main->custnum;
318 if ( $conf->exists('pkg-balances') ) {
319 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
320 $cust_main->ncancelled_pkgs;
321 $session->{'pkgnum'} = $cust_pkg->pkgnum
322 if scalar(@cust_pkg) > 1;
326 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
327 #return { error => 'Only primary user may log in.' }
328 # if $conf->exists('selfservice_server-primary_only')
329 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
330 my $part_pkg = $cust_pkg->part_pkg;
331 return { error => 'Only primary user may log in.' }
332 if $conf->exists('selfservice_server-primary_only')
333 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
339 $session_id = sha512_hex(time(). {}. rand(). $$)
340 } until ( ! defined _cache->get($session_id) ); #just in case
342 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
343 _cache->set( $session_id, $session, $timeout );
345 return { 'error' => '',
346 'session_id' => $session_id,
353 my $skin_info = skin_info($p);
354 if ( $p->{'session_id'} ) {
355 _cache->remove($p->{'session_id'});
356 return { %$skin_info, 'error' => '' };
358 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
365 my($context, $session, $custnum) = _custoragent_session_custnum($p);
366 return { 'error' => $session } if $context eq 'error';
368 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
369 or return { 'error' => "Service not found" };
371 $session->{'svcnum'} = $svc_acct->svcnum;
373 my $conf = new FS::Conf;
374 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
375 _cache->set( $p->{'session_id'}, $session, $timeout );
377 return { 'error' => '' };
383 my($context, $session, $custnum) = _custoragent_session_custnum($p);
384 return { 'error' => $session } if $context eq 'error';
386 $session->{'custnum'} = $p->{'custnum'}
387 if exists $session->{'customers'}{ $p->{'custnum'} };
389 my $conf = new FS::Conf;
390 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
391 _cache->set( $p->{'session_id'}, $session, $timeout );
393 return { 'error' => '',
394 %{ customer_info( { session_id=>$p->{'session_id'} } ) },
398 sub payment_gateway {
400 # takes a cust_main and a cust_payby entry, returns the payment_gateway
401 my $conf = new FS::Conf;
402 my $cust_main = shift;
403 my $cust_payby = shift;
404 my $gatewaynum = $conf->config('selfservice-payment_gateway');
406 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
407 die "configured gatewaynum $gatewaynum not found!" if !$pg;
411 return '' if ! FS::payby->realtime($cust_payby);
412 my $pg = $cust_main->agent->payment_gateway(
413 'method' => FS::payby->payby2bop($cust_payby),
423 my $conf = new FS::Conf;
425 my $info = skin_info($p);
427 use vars qw( $cust_paybys ); #cache for performance
428 unless ( $cust_paybys ) {
430 my %cust_paybys = map { $_ => 1 }
431 map { FS::payby->payby2payment($_) }
432 $conf->config('signup_server-payby');
434 $cust_paybys = [ keys %cust_paybys ];
437 $info->{'cust_paybys'} = $cust_paybys;
439 my($context, $session, $custnum) = _custoragent_session_custnum($p);
440 return { 'error' => $session } if $context eq 'error';
442 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } );
444 $info->{'hide_payment_fields'} = [
446 my $pg = $cust_main && payment_gateway($cust_main, $_);
447 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
448 } @{ $info->{cust_paybys} }
451 $info->{'self_suspend_reason'} =
452 $conf->config('selfservice-self_suspend_reason',
453 $cust_main ? $cust_main->agentnum : ''
456 $info->{'edit_ticket_subject'} =
457 $conf->exists('ticket_system-selfservice_edit_subject') &&
458 $cust_main && $cust_main->edit_subject;
460 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
462 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
465 'custnum' => $custnum,
466 'access_pkgnum' => $session->{'pkgnum'},
467 'access_svcnum' => $session->{'svcnum'},
474 my($context, $session, $custnum) = _custoragent_session_custnum($p);
475 return { 'error' => $session } if $context eq 'error';
479 my $conf = new FS::Conf;
480 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
482 # if ( $FS::TicketSystem::system ) {
483 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
484 # FS::TicketSystem->init();
487 if ( $custnum ) { #customer record
489 %return = ( %return, %{ customer_info_short($p) } );
491 #redundant with customer_info_short, but we need it for several things below
492 my $search = { 'custnum' => $custnum };
493 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
494 my $cust_main = qsearchs('cust_main', $search )
495 or return { 'error' => "customer_info: unknown custnum $custnum" };
497 my $list_tickets = list_tickets($p);
498 $return{'tickets'} = $list_tickets->{'tickets'};
500 if ( $session->{'pkgnum'} ) {
501 #XXX open invoices in the pkg-balances case
503 $return{'money_char'} = $conf->config("money_char") || '$';
506 invnum => $_->invnum,
507 date => time2str("%b %o, %Y", $_->_date),
509 charged => $_->charged,
511 } $cust_main->open_cust_bill;
512 $return{open_invoices} = \@open;
514 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
515 my $sth = dbh->prepare($sql) or die dbh->errstr;
516 $sth->execute($custnum) or die $sth->errstr;
517 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
518 $return{'last_invoice_date_pretty'} =
519 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
522 #customer_info_short always has nobalance on..
523 $return{small_custview} =
524 small_custview( $cust_main,
525 $return{countrydefault},
526 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
529 $return{has_ship_address} = $cust_main->has_ship_address;
530 $return{status} = $cust_main->status_label; #$cust_main->status; #better to break anyone obscurely testing for strings in self-service than to have to upgrade every front-end to get the new status to display
531 $return{statuscolor} = $cust_main->statuscolor;
532 $return{status_label} = $cust_main->status_label;
534 # compatibility: some places in selfservice use this to determine
535 # if there's a ship address
536 if ( $return{has_ship_address} ) {
537 $return{ship_last} = $cust_main->last;
538 $return{ship_first} = $cust_main->first;
541 if (scalar($conf->config('support_packages'))) {
542 my @support_services = ();
543 foreach ($cust_main->support_services) {
544 my $seconds = $_->svc_x->seconds || 0;
545 my $time_remaining = (($seconds < 0) ? '-' : '' ).
546 int(abs($seconds)/3600)."h".
547 sprintf("%02d",(abs($seconds)%3600)/60)."m";
548 my $cust_pkg = $_->cust_pkg;
551 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
552 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
553 push @support_services, { svcnum => $_->svcnum,
554 time => $time_remaining,
559 $return{support_services} = \@support_services;
562 if ( $conf->config('prepayment_discounts-credit_type') ) {
564 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
567 } elsif ( $session->{'svcnum'} ) { #no customer record
569 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
570 or die "unknown svcnum";
571 $return{name} = $svc_acct->email;
575 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
579 return { 'error' => '',
580 'custnum' => $custnum,
586 sub customer_info_short {
589 my($context, $session, $custnum) = _custoragent_session_custnum($p);
590 return { 'error' => $session } if $context eq 'error';
594 my $conf = new FS::Conf;
596 if ( $custnum ) { #customer record
598 my $search = { 'custnum' => $custnum };
599 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
600 my $cust_main = qsearchs('cust_main', $search )
601 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
603 $return{display_custnum} = $cust_main->display_custnum;
605 if ( $session->{'pkgnum'} ) {
606 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
607 #next_bill_date from cust_pkg?
609 $return{balance} = $cust_main->balance;
610 $return{next_bill_date} = $cust_main->next_bill_date;
611 $return{next_bill_date_pretty} =
612 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
615 $return{balance_pretty} = money_pretty($return{balance});
617 $return{countrydefault} = scalar($conf->config('countrydefault'));
619 $return{small_custview} =
620 small_custview( $cust_main,
621 $return{countrydefault},
625 $return{first} = $cust_main->first;
626 $return{'last'} = $cust_main->get('last');
627 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
629 #none of these are terribly expensive if we want 'em...
630 for (@cust_main_editable_fields) {
631 $return{$_} = $cust_main->get($_);
633 #maybe a little more expensive, but it should be cached by now
634 for (@location_editable_fields) {
635 $return{$_} = $cust_main->bill_location->get($_)
636 if $cust_main->bill_locationnum;
637 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
638 if $cust_main->ship_locationnum;
641 my @invoicing_list = $cust_main->invoicing_list;
642 $return{'invoicing_list'} =
643 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
644 $return{'postal_invoicing'} =
645 0 < ( grep { $_ eq 'POST' } @invoicing_list );
647 if ( $session->{'svcnum'} ) {
648 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
649 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
650 $return{'svcnum'} = $session->{'svcnum'};
653 } elsif ( $session->{'svcnum'} ) { #no customer record
655 #uuh, not supproted yet... die?
656 return { 'error' => 'customer_info_short not yet supported as agent' };
660 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
664 # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
665 # it is not customer-specific, though it is only shown to authenticated customers
666 # it is not currently agent-specific, though at some point it might be
667 $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
669 return { 'error' => '',
670 'custnum' => $custnum,
675 sub customer_recurring {
678 my($context, $session, $custnum) = _custoragent_session_custnum($p);
679 return { 'error' => $session } if $context eq 'error';
683 my $conf = new FS::Conf;
685 my $search = { 'custnum' => $custnum };
686 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
687 my $cust_main = qsearchs('cust_main', $search )
688 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
690 $return{'display_recurring'} = [ $cust_main->display_recurring ];
692 return { 'error' => '',
693 'custnum' => $custnum,
698 sub billing_history {
701 my($context, $session, $custnum) = _custoragent_session_custnum($p);
702 return { 'error' => $session } if $context eq 'error';
704 return { 'error' => 'No customer' } unless $custnum;
706 my $search = { 'custnum' => $custnum };
707 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
708 my $cust_main = qsearchs('cust_main', $search )
709 or return { 'error' => "unknown custnum $custnum" };
713 if ( $session->{'pkgnum'} ) {
714 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
715 #next_bill_date from cust_pkg?
716 return { 'error' => 'No history for package' };
719 $return{balance} = $cust_main->balance;
720 $return{balance_pretty} = money_pretty($return{balance});
721 $return{next_bill_date} = $cust_main->next_bill_date;
722 $return{next_bill_date_pretty} =
723 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
726 my $conf = new FS::Conf;
728 $return{'history'} = [
729 $cust_main->payment_history(
730 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
735 $return{'money_char'} = $conf->config("money_char") || '$',
743 my $session = _cache->get($p->{'session_id'})
744 or return { 'error' => "Can't resume session" }; #better error message
746 my $custnum = $session->{'custnum'}
747 or return { 'error' => "no customer record" };
749 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
750 or return { 'error' => "unknown custnum $custnum" };
752 my $new = new FS::cust_main { $cust_main->hash };
754 $new->set( $_ => $p->{$_} )
755 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
757 if ( exists($p->{address1}) ) {
758 my $bill_location = FS::cust_location->new({
759 map { $_ => $p->{$_} } @location_editable_fields
761 # if this is unchanged from before, cust_main::replace will ignore it
762 $new->set('bill_location' => $bill_location);
765 if ( exists($p->{ship_address1}) ) {
766 my $ship_location = FS::cust_location->new({
767 map { $_ => $p->{"ship_$_"} } @location_editable_fields
769 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
770 # Selfservice unfortunately tries to indicate "same as billing
771 # address" by sending all fields empty. Did this ever work?
772 $ship_location = $cust_main->bill_location;
774 $new->set('ship_location' => $ship_location);
776 # but if it hasn't been passed in at all, leave ship_location alone--
777 # DON'T change it to match bill_location.
779 my $conf = new FS::Conf;
782 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
783 #false laziness with httemplate/edit/process/cust_main.cgi
784 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
785 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
787 @invoicing_list = $cust_main->invoicing_list;
790 my $error = $new->replace($cust_main, \@invoicing_list);
791 return { 'error' => $error } if $error;
794 return { 'error' => '' };
799 my $session = _cache->get($p->{'session_id'})
800 or return { 'error' => "Can't resume session" }; #better error message
806 my $conf = new FS::Conf;
807 use vars qw($payment_info); #cache for performance
808 unless ( $payment_info ) {
810 my %states = map { $_->state => 1 }
811 qsearch('cust_main_county', {
812 'country' => $conf->config('countrydefault') || 'US'
815 my %cust_paybys = map { $_ => 1 }
816 map { FS::payby->payby2payment($_) }
817 $conf->config('signup_server-payby');
819 my @cust_paybys = keys %cust_paybys;
823 #list all counties/states/countries
824 'cust_main_county' =>
825 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
827 #shortcut for one-country folks
829 [ sort { $a cmp $b } keys %states ],
831 'card_types' => card_types(),
833 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
834 'require_cvv' => $conf->exists('selfservice-require_cvv'),
835 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
837 'paytypes' => [ FS::cust_payby::paytypes ],
839 'paybys' => [ $conf->config('signup_server-payby') ],
840 'cust_paybys' => \@cust_paybys,
842 'stateid_label' => FS::Msgcat::_gettext('stateid'),
843 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
845 'show_ss' => $conf->exists('show_ss'),
846 'show_stateid' => $conf->exists('show_stateid'),
847 'show_paystate' => $conf->exists('show_bankstate'),
849 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
851 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
860 my %return = %$payment_info;
862 my $custnum = $session->{'custnum'};
864 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
865 or return { 'error' => "unknown custnum $custnum" };
867 $return{'hide_payment_fields'} = [
869 my $pg = payment_gateway($cust_main, $_);
870 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
871 } @{ $return{cust_paybys} }
874 $return{balance} = $cust_main->balance; #XXX pkg-balances?
876 $return{$_} = $cust_main->bill_location->get($_)
877 for qw(address1 address2 city state zip);
879 # look for stored cust_payby info
880 # only if we've been given a clear payment_payby (to avoid payname conflicts)
881 if ($p->{'payment_payby'} =~ /^(CARD|CHEK)$/) {
882 my @search_payby = ($p->{'payment_payby'} eq 'CARD') ? ('CARD','DCRD') : ('CHEK','DCHK');
883 my ($cust_payby) = $cust_main->cust_payby(@search_payby);
885 $return{payname} = $cust_payby->payname
886 || ( $cust_main->first. ' '. $cust_main->get('last') );
888 if ( $cust_payby->payby =~ /^(CARD|DCRD)$/ ) {
889 $return{card_type} = cardtype($cust_payby->payinfo);
890 $return{payinfo} = $cust_payby->paymask;
892 @return{'month', 'year'} = $cust_payby->paydate_monthyear;
896 if ( $cust_payby->payby =~ /^(CHEK|DCHK)$/ ) {
897 my ($payinfo1, $payinfo2) = split '@', $cust_payby->paymask;
898 $return{payinfo1} = $payinfo1;
899 $return{payinfo2} = $payinfo2;
900 $return{paytype} = $cust_payby->paytype;
901 $return{paystate} = $cust_payby->paystate;
902 $return{payname} = $cust_payby->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
907 if ( $conf->config('prepayment_discounts-credit_type') ) {
909 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
912 #doubleclick protection
914 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
915 $return{paybatch} = $return{payunique}; #back compat
917 return { 'error' => '',
923 #some false laziness with httemplate/process/payment.cgi - look there for
924 #ACH and CVV support stuff
926 sub validate_payment {
929 my $session = _cache->get($p->{'session_id'})
930 or return { 'error' => "Can't resume session" }; #better error message
932 my $custnum = $session->{'custnum'};
934 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
935 or return { 'error' => "unknown custnum $custnum" };
937 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
938 or return { 'error' => gettext('illegal_amount') };
940 return { error => 'Amount must be greater than 0' } unless $amount > 0;
942 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
943 #changing the hidden form values
944 my $conf = new FS::Conf;
945 my $fee_display = $conf->config('selfservice_process-display') || 'add';
946 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
947 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
948 if ( $fee_display eq 'add'
950 and ! $fee_skip_first || scalar($cust_main->cust_pay)
953 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
954 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
957 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
958 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
959 my $discount_term = $1;
961 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
962 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
965 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
966 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
969 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
970 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
973 $payunique = $paybatch if ! length($payunique) && length($paybatch);
975 $p->{'payby'} ||= 'CARD';
976 $p->{'payby'} =~ /^([A-Z]{4})$/
977 or return { 'error' => "illegal_payby " . $p->{'payby'} };
980 #false laziness w/process/payment.cgi
983 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
985 $p->{'payinfo1'} =~ /^([\dx]+)$/
986 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
988 $p->{'payinfo2'} =~ /^([\dx]+)$/
989 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
991 $payinfo = $payinfo1. '@'. $payinfo2;
993 foreach my $cust_payby ($cust_main->cust_payby('CHEK','DCHK')) {
994 if ( $cust_payby->paymask eq $payinfo ) {
995 $payinfo = $cust_payby->payinfo;
1000 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1002 $payinfo = $p->{'payinfo'};
1006 #more intelligent matching will be needed here if you change
1007 #card_masking_method and don't remove existing paymasks
1008 foreach my $cust_payby ($cust_main->cust_payby('CARD','DCRD')) {
1009 if ( $cust_payby->paymask eq $payinfo ) {
1010 $payinfo = $cust_payby->payinfo;
1016 $payinfo =~ s/\D//g;
1017 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1018 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1022 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1023 return { 'error' => gettext('unknown_card_type') }
1024 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1026 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1027 if ( cardtype($payinfo) eq 'American Express card' ) {
1028 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1029 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1032 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1033 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1036 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1037 return { 'error' => 'CVV2 is required' };
1038 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1039 return { 'error' => 'CVV2 is required' };
1043 die "unknown payby $payby";
1046 my %payby2fields = (
1047 'CARD' => [ qw( paystart_month paystart_year payissue payip
1048 address1 address2 city state zip country ) ],
1049 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1053 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1056 'cust_main' => $cust_main, #XXX or just custnum??
1057 'amount' => sprintf('%.2f', $amount),
1059 'payinfo' => $payinfo,
1060 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1061 'card_type' => $card_type,
1062 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1063 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1064 'month' => $p->{'month'},
1065 'year' => $p->{'year'},
1066 'payname' => $payname,
1067 'payunique' => $payunique,
1068 'paybatch' => $paybatch,
1069 'paycvv' => $paycvv,
1070 'payname' => $payname,
1071 'discount_term' => $discount_term,
1072 'pkgnum' => $session->{'pkgnum'},
1073 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1083 my $validate = validate_payment($p);
1084 return $validate if $validate->{'error'};
1086 my $conf = new FS::Conf;
1087 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1088 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1090 +{ map { $_=>$validate->{$_} }
1091 qw( card_type paymask payname paydate_pretty month year amount
1092 address1 address2 city state zip country
1098 sub process_stored_payment {
1101 my $session_id = $p->{'session_id'};
1103 my $payment_info = _cache->get( "payment_$session_id" )
1104 or return { 'error' => "Can't resume session" }; #better error message
1106 do_process_payment($payment_info);
1110 sub process_payment {
1113 my $payment_info = validate_payment($p);
1114 return $payment_info if $payment_info->{'error'};
1116 do_process_payment($payment_info);
1120 sub do_process_payment {
1121 my $validate = shift;
1123 my $cust_main = $validate->{'cust_main'};
1125 my $amount = delete $validate->{'amount'};
1128 my $payby = delete $validate->{'payby'};
1130 if ( $validate->{'save'} ) {
1133 foreach my $field ( qw( auto payinfo paymask payname payip ) ) {
1134 $saveopt{$field} = $validate->{$field};
1137 if ( $payby eq 'CARD' ) {
1138 my $bill_location = FS::cust_location->new({
1139 map { $_ => $validate->{$_} }
1140 qw(address1 address2 city state country zip)
1142 $saveopt{'bill_location'} = $bill_location;
1143 foreach my $field ( qw( paydate paystart_month paystart_year payissue ) ) {
1144 $saveopt{$field} = $validate->{$field};
1147 # stateid/stateid_state won't be saved, might be broken as of 4.x
1148 foreach my $field ( qw( paytype paystate ) ) {
1149 $saveopt{$field} = $validate->{$field};
1153 my $error = $cust_main->save_cust_payby(
1154 'payment_payby' => $payby,
1159 #no, this causes customers to process their payments again
1160 #return { 'error' => $error };
1161 #XXX just warn verosely for now so i can figure out how these happen in
1162 # the first place, eventually should redirect them to the "change
1163 #address" page but indicate if the payment processed?
1164 delete($validate->{'payinfo'}); #don't want to log this!
1165 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1167 "SAVEOPT: ".Dumper(\%saveopt)."\n".
1168 "CUST_MAIN: ". Dumper($cust_main)."\n".
1169 "PACKET: ". Dumper($validate)."\n";
1173 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1177 'paynum_ref' => \$paynum,
1180 return { 'error' => $error } if $error;
1182 #no error, so order the fee package if applicable...
1183 my $conf = new FS::Conf;
1184 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1185 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1187 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1189 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1191 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1192 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1195 #and generate an invoice for it now too
1196 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1197 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1202 $cust_main->apply_payments;
1205 my $receipt_html = '';
1207 # currently supported for realtime CC only; send receipt data to SS
1208 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1211 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1214 <TD ALIGN="right">Payment#</TD>
1215 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1219 <TD ALIGN="right">Date</TD>
1221 <TD BGCOLOR="#FFFFFF"><B>! .
1222 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1228 <TD ALIGN="right">Amount</TD>
1229 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1234 <TD ALIGN="right">Payment method</TD>
1235 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1248 'amount' => sprintf('%.2f', $cust_pay->paid),
1249 'date' => $cust_pay->_date,
1250 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1251 'time_pretty' => time2str('%T', $cust_pay->_date),
1252 'auth_num' => $cust_pay->auth,
1253 'order_num' => $cust_pay->order_number,
1254 'receipt_html' => $receipt_html,
1261 'receipt_html' => '',
1268 sub realtime_collect {
1271 my $session = _cache->get($p->{'session_id'})
1272 or return { 'error' => "Can't resume session" }; #better error message
1274 my $custnum = $session->{'custnum'};
1276 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1277 or return { 'error' => "unknown custnum $custnum" };
1280 if ( $p->{'amount'} ) {
1281 $amount = $p->{'amount'};
1283 elsif ( $session->{'pkgnum'} ) {
1284 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1287 $amount = $cust_main->balance;
1290 my $error = $cust_main->realtime_collect(
1291 'method' => $p->{'method'},
1292 'amount' => $amount,
1293 'pkgnum' => $session->{'pkgnum'},
1294 'session_id' => $p->{'session_id'},
1298 return { 'error' => $error } unless ref( $error );
1300 return { 'error' => '', amount => $amount, %$error };
1303 sub start_thirdparty {
1305 my $session = _cache->get($p->{'session_id'})
1306 or return { 'error' => "Can't resume session" }; #better error message
1307 my $custnum = $session->{'custnum'};
1308 my $cust_main = FS::cust_main->by_key($custnum);
1310 my $amount = $p->{'amount'}
1311 or return { error => 'no amount' };
1313 my $result = $cust_main->create_payment(
1314 'method' => $p->{'method'},
1315 'amount' => $p->{'amount'},
1316 'pkgnum' => $session->{'pkgnum'},
1317 'session_id' => $p->{'session_id'},
1320 if ( ref($result) ) { # hashref or error
1323 return { error => $result };
1327 sub finish_thirdparty {
1329 my $session_id = delete $p->{'session_id'};
1330 my $session = _cache->get($session_id)
1331 or return { 'error' => "Can't resume session" };
1332 my $custnum = $session->{'custnum'};
1333 my $cust_main = FS::cust_main->by_key($custnum);
1335 if ( $p->{_cancel} ) {
1336 # customer backed out of making a payment
1337 return $cust_main->cancel_payment( $session_id );
1339 my $result = $cust_main->execute_payment( $session_id, %$p );
1340 if ( ref($result) ) {
1343 return { error => $result };
1347 sub process_payment_order_pkg {
1350 my $hr = process_payment($p);
1351 return $hr if $hr->{'error'};
1356 sub process_payment_order_renew {
1359 my $hr = process_payment($p);
1360 return $hr if $hr->{'error'};
1365 sub process_prepay {
1369 my $session = _cache->get($p->{'session_id'})
1370 or return { 'error' => "Can't resume session" }; #better error message
1374 my $custnum = $session->{'custnum'};
1376 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1377 or return { 'error' => "unknown custnum $custnum" };
1379 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1380 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1388 return { 'error' => $error } if $error;
1390 return { 'error' => '',
1391 'amount' => $amount,
1392 'seconds' => $seconds,
1393 'duration' => duration_exact($seconds),
1394 'upbytes' => $upbytes,
1395 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1396 'downbytes' => $downbytes,
1397 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1398 'totalbytes'=> $totalbytes,
1399 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1406 my $session = _cache->get($p->{'session_id'})
1407 or return { 'error' => "Can't resume session" }; #better error message
1409 my $custnum = $session->{'custnum'};
1411 my $invnum = $p->{'invnum'};
1413 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1414 'custnum' => $custnum } )
1415 or return { 'error' => "Can't find invnum" };
1419 return { 'error' => '',
1420 'invnum' => $invnum,
1421 'invoice_text' => join('', $cust_bill->print_text ),
1422 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1429 my $session = _cache->get($p->{'session_id'})
1430 or return { 'error' => "Can't resume session" }; #better error message
1432 my $custnum = $session->{'custnum'};
1434 my $invnum = $p->{'invnum'};
1436 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1437 'custnum' => $custnum } )
1438 or return { 'error' => "Can't find invnum" };
1442 return { 'error' => '',
1443 'invnum' => $invnum,
1444 'invoice_pdf' => $cust_bill->print_pdf({
1445 'unsquelch_cdr' => 1,
1446 'locale' => $p->{'locale'},
1452 sub legacy_invoice {
1454 my $session = _cache->get($p->{'session_id'})
1455 or return { 'error' => "Can't resume session" }; #better error message
1457 my $custnum = $session->{'custnum'};
1459 my $legacyinvnum = $p->{'legacyinvnum'};
1462 'legacyinvnum' => $legacyinvnum,
1463 'custnum' => $custnum,
1466 my $legacy_cust_bill =
1467 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1468 || qsearchs('legacy_cust_bill', \%hash )
1469 or return { 'error' => "Can't find legacyinvnum" };
1473 return { 'error' => '',
1474 'legacyinvnum' => $legacyinvnum,
1475 'legacyid' => $legacy_cust_bill->legacyid,
1476 'invoice_html' => $legacy_cust_bill->content_html,
1481 sub legacy_invoice_pdf {
1483 my $session = _cache->get($p->{'session_id'})
1484 or return { 'error' => "Can't resume session" }; #better error message
1486 my $custnum = $session->{'custnum'};
1488 my $legacyinvnum = $p->{'legacyinvnum'};
1490 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1491 'legacyinvnum' => $legacyinvnum,
1492 'custnum' => $custnum,
1493 }) or return { 'error' => "Can't find legacyinvnum" };
1497 return { 'error' => '',
1498 'legacyinvnum' => $legacyinvnum,
1499 'legacyid' => $legacy_cust_bill->legacyid,
1500 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1508 #sessioning for this? how do we get the session id to the backend invoice
1509 # template so it can add it to the link, blah
1512 if ( $p->{'invnum'} ) {
1513 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1514 or return { 'error' => 'unknown invnum' };
1515 $agentnum = $cust_bill->cust_main->agentnum;
1518 my $templatename = $p->{'template'} || $p->{'templatename'};
1520 #false laziness-ish w/view/cust_bill-logo.cgi
1522 my $conf = new FS::Conf;
1523 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1524 $templatename = "_$1";
1529 my $filename = "logo$templatename.png";
1531 return { 'error' => '',
1532 'logo' => $conf->config_binary($filename, $agentnum),
1533 'content_type' => 'image/png', #should allow gif, jpg too
1539 my $session = _cache->get($p->{'session_id'})
1540 or return { 'error' => "Can't resume session" }; #better error message
1542 my $custnum = $session->{'custnum'};
1544 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1545 or return { 'error' => "unknown custnum $custnum" };
1547 my $conf = new FS::Conf;
1549 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1551 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1556 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1557 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1558 my $owed = $_->owed;
1560 +{ 'invnum' => $_->invnum,
1561 '_date' => $_->_date,
1562 'date' => time2str("%b %o, %Y", $_->_date),
1563 'date_short' => time2str("%m-%d-%Y", $_->_date),
1564 'previous' => sprintf('%.2f', ($_->previous)[0]),
1565 'charged' => sprintf('%.2f', $_->charged),
1566 'owed' => sprintf('%.2f', $owed),
1567 'balance' => sprintf('%.2f', $balance),
1568 'lastpay' => @payments_and_credits
1569 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1575 return { 'error' => '',
1576 'balance' => $cust_main->balance,
1577 'money_char' => $conf->config("money_char") || '$',
1578 'invoices' => $invoices,
1579 'legacy_invoices' => [
1581 +{ 'legacyinvnum' => $_->legacyinvnum,
1582 'legacyid' => $_->legacyid,
1583 '_date' => $_->_date,
1584 'date' => time2str("%b %o, %Y", $_->_date),
1585 'date_short' => time2str("%m-%d-%Y", $_->_date),
1586 'charged' => sprintf('%.2f', $_->charged),
1587 'has_content' => ( length($_->content_pdf)
1588 || length($_->content_html) ),
1599 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1600 return { 'error' => $session } if $context eq 'error';
1602 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1603 or return { 'error' => "unknown custnum $custnum" };
1607 my $cust_payby = $_;
1609 map { $_ => $cust_payby->$_ }
1610 qw( custpaybynum weight payby paymask paydate
1611 payname paystate paytype
1615 $cust_main->cust_payby
1623 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1624 return { 'error' => $session } if $context eq 'error';
1626 #XXX payinfo1 + payinfo2 for CHEK?
1627 #or take the opportunity to use separate, more well- named fields?
1629 # $p->{'payinfo1'} =~ /^([\dx]+)$/
1630 # or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1631 # my $payinfo1 = $1;
1632 # $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1633 # or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1634 # my $payinfo2 = $1;
1635 # $payinfo = $payinfo1. '@'. $payinfo2;
1637 my $cust_payby = new FS::cust_payby {
1638 'custnum' => $custnum,
1639 map { $_ => $p->{$_} } qw( weight payby payinfo paycvv paydate payname
1640 paystate paytype payip
1644 my $error = $cust_payby->insert;
1646 return { 'error' => $error };
1648 return { 'custpaybynum' => $cust_payby->custpaybynum };
1656 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1657 return { 'error' => $session } if $context eq 'error';
1659 my $cust_payby = qsearchs('cust_payby', {
1660 'custnum' => $custnum,
1661 'custpaybynum' => $p->{'custpaybynum'},
1663 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1666 qw( weight payby payinfo paycvv paydate payname paystate paytype payip )
1668 next unless exists($p->{$field});
1669 $cust_payby->set($field,$p->{$field});
1672 my $error = $cust_payby->replace;
1674 return { 'error' => $error };
1676 return { 'custpaybynum' => $cust_payby->custpaybynum };
1684 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1685 return { 'error' => $session } if $context eq 'error';
1687 my $cust_payby = qsearchs('cust_payby', {
1688 'custnum' => $custnum,
1689 'custpaybynum' => $p->{'custpaybynum'},
1691 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1693 return { 'error' => $cust_payby->verify };
1700 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1701 return { 'error' => $session } if $context eq 'error';
1703 my $cust_payby = qsearchs('cust_payby', {
1704 'custnum' => $custnum,
1705 'custpaybynum' => $p->{'custpaybynum'},
1707 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1709 return { 'error' => $cust_payby->delete };
1715 my $session = _cache->get($p->{'session_id'})
1716 or return { 'error' => "Can't resume session" }; #better error message
1718 my $custnum = $session->{'custnum'};
1720 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1721 or return { 'error' => "unknown custnum $custnum" };
1723 my @errors = $cust_main->cancel( 'quiet'=>1 );
1725 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1727 return { 'error' => $error };
1734 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1735 return { 'error' => $session } if $context eq 'error';
1737 my $search = { 'custnum' => $custnum };
1738 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1739 my $cust_main = qsearchs('cust_main', $search )
1740 or return { 'error' => "unknown custnum $custnum" };
1742 my $conf = new FS::Conf;
1743 my $immutable = $conf->exists('selfservice_immutable-package');
1745 # the duplication below is necessary:
1746 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1747 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1748 # non-backwards-compatible change breaking the software of anyone using the API
1749 # instead of the stock selfservice
1750 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1751 if( $conf->exists('selfservice_server-view-wholesale') ) {
1752 return { 'svcnum' => $session->{'svcnum'},
1753 'custnum' => $custnum,
1754 'cust_pkg' => [ map {
1756 immutable => $immutable,
1757 part_pkg => [ map $_->hashref, $_->part_pkg ],
1759 [ map $_->hashref, $_->available_part_svc ],
1761 [ map { my $ref = { $_->hash,
1762 label => [ $_->label ],
1764 $ref->{_password} = $_->svc_x->_password
1765 if $context eq 'agent'
1766 && $conf->exists('agent-showpasswords')
1767 && $_->part_svc->svcdb eq 'svc_acct';
1772 } $cust_main->cust_pkg
1775 small_custview( $cust_main, $conf->config('countrydefault') ),
1776 'wholesale_view' => 1,
1777 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1778 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1779 'lnp' => $conf->exists('svc_phone-lnp'),
1783 { 'svcnum' => $session->{'svcnum'},
1784 'custnum' => $custnum,
1785 'cust_pkg' => [ map {
1786 my $primary_cust_svc = $_->primary_cust_svc;
1789 immutable => $immutable,
1790 pkg_label => $_->pkg_locale,
1791 status => $_->status,
1792 statuscolor => $_->statuscolor,
1794 [ map { $_->hashref }
1795 grep { $_->selfservice_access ne 'hidden' }
1796 $_->available_part_svc
1799 [ map { my $ref = { $_->hash,
1800 label => [ $_->label ],
1802 $ref->{_password} = $_->svc_x->_password
1803 if $context eq 'agent'
1804 && $conf->exists('agent-showpasswords')
1805 && $_->part_svc->svcdb eq 'svc_acct';
1806 $ref->{svchash} = { $_->svc_x->hash } if
1807 $_->part_svc->svcdb eq 'svc_phone';
1808 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1809 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1812 grep { $_->part_svc->selfservice_access ne 'hidden' }
1817 ? { $primary_cust_svc->hash,
1818 label => [ $primary_cust_svc->label ],
1819 finger => $primary_cust_svc->svc_x->finger, #uuh
1820 $primary_cust_svc->part_svc->hash,
1824 } $cust_main->ncancelled_pkgs
1827 small_custview( $cust_main, $conf->config('countrydefault') ),
1828 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1836 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1837 return { 'error' => $session } if $context eq 'error';
1839 my $conf = new FS::Conf;
1841 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1842 my $search = { 'custnum' => $custnum };
1843 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1844 my $cust_main = qsearchs('cust_main', $search )
1845 or return { 'error' => "unknown custnum $custnum" };
1847 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1848 if ( ! $pkgnum && $p->{'svcnum'} ) {
1849 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1850 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1854 my @cust_pkg_usage = ();
1855 foreach my $cust_pkg ( $p->{'ncancelled'}
1856 ? $cust_main->ncancelled_pkgs
1857 : $cust_main->unsuspended_pkgs ) {
1858 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1859 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1860 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1863 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1866 foreach (@cust_pkg_usage) {
1867 my $part = $_->part_pkg_usage;
1868 my $tag = $part->description . ($part->shared ? 1 : 0);
1869 my $row = $usage_pools{$tag}
1870 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1871 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1872 $row->[2] += $part->minutes; # minutes total
1874 } # otherwise just leave them empty
1876 if ( $p->{'svcdb'} ) {
1877 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1879 : ref($p->{'svcdb'}) eq 'ARRAY'
1880 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1881 : { $p->{'svcdb'} => 1 };
1882 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1885 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1888 my @svcs; # stuff to return to the client
1889 my %bytes_used_total; # for _used columns only
1890 foreach my $cust_svc (@cust_svc) {
1891 my $svc_x = $cust_svc->svc_x;
1892 my($label, $value) = $cust_svc->label;
1893 my $part_svc = $cust_svc->part_svc;
1894 my $svcdb = $part_svc->svcdb;
1895 my $cust_pkg = $cust_svc->cust_pkg;
1896 my $part_pkg = $cust_pkg->part_pkg;
1899 'svcnum' => $cust_svc->svcnum,
1900 'display_svcnum' => $cust_svc->display_svcnum,
1904 'pkg_label' => $cust_pkg->pkg_locale,
1905 'pkg_status' => $cust_pkg->status,
1906 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1909 # would it make sense to put this in a svc_* method?
1911 if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
1912 my $last_bill = $cust_pkg->last_bill || 0;
1914 my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
1915 my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
1918 'seconds_used' => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
1919 'upbytes_used' => display_bytecount($up_used),
1920 'downbytes_used' => display_bytecount($down_used),
1921 'totalbytes_used' => display_bytecount($up_used + $down_used)
1923 $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
1924 $bytes_used_total{'upbytes_used'} += $up_used;
1925 $bytes_used_total{'downbytes_used'} += $down_used;
1926 $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
1929 if ( $svcdb eq 'svc_acct' ) {
1930 foreach (qw(username email finger seconds)) {
1931 $hash{$_} = $svc_x->$_;
1937 'upbytes' => display_bytecount($svc_x->upbytes),
1938 'downbytes' => display_bytecount($svc_x->downbytes),
1939 'totalbytes' => display_bytecount($svc_x->totalbytes),
1941 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1942 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1943 'recharge_upbytes' =>
1944 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1945 'recharge_downbytes' =>
1946 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1947 'recharge_totalbytes' =>
1948 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1953 } elsif ( $svcdb eq 'svc_dsl' ) {
1955 $hash{'phonenum'} = $svc_x->phonenum;
1956 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1957 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1958 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1961 $hash{'name'} = $cust_main->name;
1963 # no usage to hide here
1965 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1967 # could potentially show lots of things...
1968 $hash{'outbound'} = 1;
1969 $hash{'inbound'} = 0;
1970 if ( $svcdb eq 'svc_phone' ) {
1971 if ( $part_pkg->plan eq 'voip_inbound' ) {
1972 $hash{'outbound'} = 0;
1973 $hash{'inbound'} = 1;
1974 } elsif ( $part_pkg->option('selfservice_inbound_format')
1975 or $conf->config('selfservice-default_inbound_cdr_format')
1977 $hash{'inbound'} = 1;
1980 foreach (qw(inbound outbound)) {
1981 # hmm...we can't filter by status here, because there might
1982 # not be cdr_terminations at all. have to go by date.
1983 # find all since the last bill date.
1984 # XXX cdr types? we are going to need them.
1986 my $sum_cdr = $svc_x->sum_cdrs(
1987 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1988 'begin' => ($cust_pkg->last_bill || 0),
1990 'disable_charged_party' => 1,
1992 $hash{$_} = $sum_cdr->hashref;
1995 } # not hiding usage
1999 } # foreach $cust_svc
2001 foreach my $field (keys %bytes_used_total) {
2002 if ($field =~ /bytes/) {
2003 $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
2008 'svcnum' => $session->{'svcnum'},
2009 'custnum' => $custnum,
2010 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2011 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
2013 'bytes_used_total' => \%bytes_used_total,
2015 map { $usage_pools{$_} }
2019 'hide_usage' => $hide_usage,
2024 sub _customer_svc_x {
2025 my($custnum, $svcnum, $table) = (shift, shift, shift);
2026 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
2028 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2029 my $search = " AND custnum = $1";
2030 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2033 'table' => ($table || 'svc_acct'),
2034 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2035 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
2036 #'LEFT JOIN cust_main USING ( custnum ) ',
2037 'hashref' => $hashref,
2038 'extra_sql' => $search, #important
2043 sub svc_status_html {
2046 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2047 return { 'error' => $session } if $context eq 'error';
2049 #XXX only svc_dsl for now
2050 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2051 or return { 'error' => "Service not found" };
2053 my $html = $svc_x->getstatus_html;
2055 return { 'html' => $html };
2059 sub svc_status_hash {
2062 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2063 return { 'error' => $session } if $context eq 'error';
2065 #XXX only svc_acct for now
2066 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2067 or return { 'error' => "Service not found" };
2069 my ( $html, $hashref ) = $svc_x->export_getstatus;
2074 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
2075 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2076 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2077 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2078 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2081 my( $p, $method ) = @_;
2083 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2084 return { 'error' => $session } if $context eq 'error';
2086 #XXX only svc_acct for now
2087 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2088 or return { 'error' => "Service not found" };
2090 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2092 my $error = $svc_x->$method($p); #$p? returns error?
2093 return { 'error' => $error } if $error;
2095 return {}; #? { 'error' => '' }
2099 sub acct_forward_info {
2102 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2103 return { 'error' => $session } if $context eq 'error';
2105 my $svc_forward = _customer_svc_x( $custnum,
2106 { 'srcsvc' => $p->{'svcnum'} },
2109 or return { 'error' => '',
2113 return { 'error' => '',
2114 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2119 sub process_acct_forward {
2121 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2122 return { 'error' => $session } if $context eq 'error';
2124 my $old = _customer_svc_x( $custnum,
2125 { 'srcsvc' => $p->{'svcnum'} },
2129 if ( $p->{'dst'} eq '' ) {
2131 my $error = $old->delete;
2132 return { 'error' => $error };
2134 return { 'error' => '' };
2137 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2138 'dst' => $p->{'dst'},
2143 $new->svcnum($old->svcnum);
2144 my $cust_svc = $old->cust_svc;
2145 $new->svcpart($old->svcpart);
2146 $new->pkgnuym($old->pkgnum);
2147 $error = $new->replace($old);
2149 my $conf = new FS::Conf;
2150 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2152 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2153 or return { 'error' => 'No service' }; #how would we even get here?
2155 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2157 $error = $new->insert;
2160 return { 'error' => $error };
2164 sub list_dsl_devices {
2167 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2168 return { 'error' => $session } if $context eq 'error';
2170 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2171 or return { 'error' => "Service not found" };
2174 'devices' => [ map {
2175 +{ 'mac_addr' => $_->mac_addr };
2176 } $svc_dsl->dsl_device
2182 sub add_dsl_device {
2185 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2186 return { 'error' => $session } if $context eq 'error';
2188 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2189 or return { 'error' => "Service not found" };
2191 return { 'error' => 'No MAC address supplied' }
2192 unless length($p->{'mac_addr'});
2194 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2195 'mac_addr' => scalar($p->{'mac_addr'}),
2197 my $error = $dsl_device->insert;
2198 return { 'error' => $error };
2202 sub delete_dsl_device {
2205 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2206 return { 'error' => $session } if $context eq 'error';
2208 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2209 or return { 'error' => "Service not found" };
2211 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2212 'mac_addr' => scalar($p->{'mac_addr'}),
2215 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2217 my $error = $dsl_device->delete;
2218 return { 'error' => $error };
2224 _usage_details( \&_port_graph, $p,
2225 'svcdb' => 'svc_port',
2230 my($svc_port, $begin, $end) = @_;
2232 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2233 push @usage, { 'png' => $pngOrError };
2237 sub _list_svc_usage {
2238 my($svc_acct, $begin, $end) = @_;
2240 foreach my $part_export (
2241 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2242 qw( sqlradius sqlradius_withdomain )
2244 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2249 sub list_svc_usage {
2250 _usage_details(\&_list_svc_usage, @_);
2253 sub _list_support_usage {
2254 my($svc_acct, $begin, $end) = @_;
2256 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2257 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2259 push @usage, { 'seconds' => $_->seconds,
2260 'support' => $_->support,
2261 '_date' => $_->_date,
2262 'id' => $_->transaction_id,
2263 'creator' => $_->creator,
2264 'subject' => $_->subject,
2265 'status' => $_->status,
2266 'ticketid' => $_->ticketid,
2272 sub list_support_usage {
2273 _usage_details(\&_list_support_usage, @_);
2276 sub _list_cdr_usage {
2277 # XXX CDR type support...
2278 # XXX any way to do a paged search on this?
2279 # we have to return the results all at once...
2280 my($svc_x, $begin, $end, %opt) = @_;
2281 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2285 'disable_charged_party' => 1,
2290 sub list_cdr_usage {
2292 _usage_details( \&_list_cdr_usage, $p );
2295 sub _usage_details {
2296 my($callback, $p, %opt) = @_;
2297 my $conf = FS::Conf->new;
2299 if ( $conf->exists('selfservice_hide-usage') ) {
2300 return { 'error' => 'Viewing usage is not allowed.' };
2303 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2304 return { 'error' => $session } if $context eq 'error';
2306 my $search = { 'svcnum' => $p->{'svcnum'} };
2307 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2309 my $cust_svc = qsearchs( 'cust_svc', $search );
2310 return { 'error' => 'No service selected in list_svc_usage' }
2313 my $svc_x = $cust_svc->svc_x;
2314 my $svcdb = $svc_x->table;
2315 my $cust_pkg = $cust_svc->cust_pkg;
2316 my $freq = $cust_pkg->part_pkg->freq;
2319 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2321 if ( $p->{inbound} ) {
2322 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2323 || $conf->config('selfservice-default_inbound_cdr_format')
2324 || 'source_default';
2325 $callback_opt{inbound} = 1;
2327 $format = $cust_pkg->part_pkg->option('selfservice_format')
2328 || $conf->config('selfservice-default_cdr_format')
2332 $callback_opt{format} = $format;
2333 $callback_opt{use_clid} = 1;
2334 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2337 my $start = $cust_pkg->setup;
2338 #my $end = $cust_pkg->bill; # or time?
2341 unless ( $p->{beginning} ) {
2342 $p->{beginning} = $cust_pkg->last_bill;
2343 $p->{ending} = $end;
2346 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2347 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2349 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2353 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2354 # ugly kludge, I know
2355 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2356 if (defined $delete_col) {
2357 delete($_->[$delete_col]) foreach ($header, @usage);
2361 #kinda false laziness with FS::cust_main::bill, but perhaps
2362 #we should really change this bit to DateTime and DateTime::Duration
2364 #change this bit to use Date::Manip? CAREFUL with timezones (see
2365 # mailing list archive)
2366 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2367 (localtime($p->{ending}) )[0,1,2,3,4,5];
2368 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2369 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2371 if ( $freq =~ /^\d+$/ ) {
2373 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2375 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2376 } elsif ( $freq =~ /^(\d+)w$/ ) {
2378 $nmday += $weeks * 7;
2379 $pmday -= $weeks * 7;
2380 } elsif ( $freq =~ /^(\d+)d$/ ) {
2384 } elsif ( $freq =~ /^(\d+)h$/ ) {
2389 return { 'error' => "unparsable frequency: ". $freq };
2392 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2393 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2397 'svcnum' => $p->{svcnum},
2398 'beginning' => $p->{beginning},
2399 'ending' => $p->{ending},
2400 'inbound' => $p->{inbound},
2401 'previous' => ($previous > $start) ? $previous : $start,
2402 'next' => ($next < $end) ? $next : $end,
2403 'header' => $header,
2411 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2412 return { 'error' => $session } if $context eq 'error';
2414 my $search = { 'custnum' => $custnum };
2415 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2416 my $cust_main = qsearchs('cust_main', $search )
2417 or return { 'error' => "unknown custnum $custnum" };
2419 my $status = $cust_main->status;
2421 my %order_pkg_options = ();
2422 if ( $p->{locationnum} > 0 ) {
2423 $order_pkg_options{locationnum} = delete($p->{locationnum});
2424 } elsif ( $p->{address1} ) {
2425 $order_pkg_options{'cust_location'} = new FS::cust_location {
2426 map { $_ => $p->{$_} }
2427 qw( address1 address2 city county state zip country )
2431 #false laziness w/ClientAPI/Signup.pm
2433 my $cust_pkg = new FS::cust_pkg ( {
2434 'custnum' => $custnum,
2435 'pkgpart' => $p->{'pkgpart'},
2436 'quantity' => $p->{'quantity'} || 1,
2438 my $error = $cust_pkg->check;
2439 return { 'error' => $error } if $error;
2442 unless ( $p->{'svcpart'} eq 'none' ) {
2446 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2448 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2449 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2450 $svcdb = $part_svc->svcdb;
2452 $svcdb = 'svc_acct';
2454 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2457 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2458 'svc_domain' => [ qw( domain ) ],
2459 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2460 'svc_external' => [ qw( id title ) ],
2461 'svc_pbx' => [ qw( id title ) ],
2464 my $svc_x = "FS::$svcdb"->new( {
2465 'svcpart' => $svcpart,
2466 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2469 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2472 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2473 my $acct_snarf = new FS::acct_snarf ( {
2474 'machine' => $p->{"snarf_machine$snarfnum"},
2475 'protocol' => $p->{"snarf_protocol$snarfnum"},
2476 'username' => $p->{"snarf_username$snarfnum"},
2477 '_password' => $p->{"snarf_password$snarfnum"},
2480 push @acct_snarf, $acct_snarf;
2482 $svc_x->child_objects( \@acct_snarf );
2485 my $y = $svc_x->setdefault; # arguably should be in new method
2486 return { 'error' => $y } if $y && !ref($y);
2488 $error = $svc_x->check;
2489 return { 'error' => $error } if $error;
2495 $error = $cust_main->order_pkg(
2496 'cust_pkg' => $cust_pkg,
2501 return { 'error' => $error } if $error;
2503 my $conf = new FS::Conf;
2504 if ( $conf->exists('signup_server-realtime') ) {
2506 my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2509 $cust_pkg->cancel('quiet'=>1);
2512 $cust_pkg->reexport;
2516 $cust_pkg->reexport;
2519 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2521 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2528 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2529 return { 'error' => $session } if $context eq 'error';
2531 my $conf = new FS::Conf;
2532 my $immutable = $conf->exists('selfservice_immutable-package');
2533 return { 'error' => "Package modification disabled" } if $immutable;
2535 my $search = { 'custnum' => $custnum };
2536 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2537 my $cust_main = qsearchs('cust_main', $search )
2538 or return { 'error' => "unknown custnum $custnum" };
2540 my $status = $cust_main->status;
2541 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2542 or return { 'error' => "unknown package $p->{pkgnum}" };
2544 #if someone does need self-service package change of suspended packages,
2545 # figure out how to be more discriminating
2546 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2547 if $cust_pkg->status eq 'suspended';
2549 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2550 'quantity' => $p->{'quantity'} || 1,
2553 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2554 unless ref($err_or_cust_pkg);
2556 if ( $conf->exists('signup_server-realtime') ) {
2558 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2561 $err_or_cust_pkg->suspend;
2564 $err_or_cust_pkg->reexport;
2568 $err_or_cust_pkg->reexport;
2571 return { error => '', pkgnum => $cust_pkg->pkgnum };
2575 sub order_recharge {
2578 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2579 return { 'error' => $session } if $context eq 'error';
2581 my $search = { 'custnum' => $custnum };
2582 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2583 my $cust_main = qsearchs('cust_main', $search )
2584 or return { 'error' => "unknown custnum $custnum" };
2586 my $status = $cust_main->status;
2587 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2588 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2590 my $svc_x = $cust_svc->svc_x;
2591 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2594 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2595 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2596 recharge_totalbytes );
2597 my $amount = $part_pkg->option('recharge_amount', 1);
2599 my ($l, $v, $d) = $cust_svc->label; # blah
2600 my $pkg = "Recharge $v";
2602 my $bill_error = $cust_main->charge($amount, $pkg,
2603 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2604 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2605 $part_pkg->taxclass); #meh
2607 my $conf = new FS::Conf;
2608 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2610 $bill_error = _do_bop_realtime( $cust_main, $status );
2615 my $error = $svc_x->recharge (\%vhash);
2616 return { 'error' => $error } if $error;
2620 my $error = $bill_error;
2621 $error ||= $svc_x->recharge (\%vhash);
2622 return { 'error' => $error } if $error;
2625 return { error => '', svc => $cust_svc->part_svc->svc };
2629 sub _do_bop_realtime {
2630 my ($cust_main, $status, %opt) = @_;
2632 my $old_balance = $cust_main->balance;
2635 my $bill_error = $cust_main->bill(
2636 'return_bill' => \@cust_bill,
2639 $bill_error ||= $cust_main->apply_payments_and_credits;
2641 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1);
2643 if ( $cust_main->balance > $old_balance
2644 && $cust_main->balance > 0
2645 && ( $cust_main->has_cust_payby_auto || $status eq 'suspended' )
2648 unless ( $opt{'no_invoice_void'} ) {
2650 #this used to apply a credit, but now we can void invoices...
2651 foreach my $cust_bill (@cust_bill) {
2652 my $voiderror = $cust_bill->void('automatic payment failed');
2653 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2658 return { 'error' => '_decline', 'bill_error' => $bill_error };
2661 if ( $opt{'collect'} ) {
2662 my $collect_error = $cust_main->collect();
2663 return { 'error' => '_decline', 'bill_error' => $collect_error }
2664 if $collect_error; #?
2673 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2674 return { 'error' => $session } if $context eq 'error';
2676 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2677 or return { 'error' => "unknown custnum $custnum" };
2679 my @cust_pkg = sort { $a->bill <=> $b->bill }
2680 grep { $_->part_pkg->freq ne '0' }
2681 $cust_main->ncancelled_pkgs;
2683 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2685 my $total = $cust_main->balance;
2688 my $bill = $_->bill;
2689 $total += $_->part_pkg->base_recur($_, \$bill);
2690 my $renew_date = $_->part_pkg->add_freq($_->bill);
2692 'pkgnum' => $_->pkgnum,
2693 'amount' => sprintf('%.2f', $total),
2694 'bill_date' => $_->bill,
2695 'bill_date_pretty' => time2str('%x', $_->bill),
2696 'renew_date' => $renew_date,
2697 'renew_date_pretty' => time2str('%x', $renew_date),
2698 'expire_date' => $_->expire,
2699 'expire_date_pretty' => time2str('%x', $_->expire),
2704 return { 'dates' => \@array };
2708 sub payment_info_renew_info {
2710 my $renew_info = renew_info($p);
2711 my $payment_info = payment_info($p);
2712 return { %$renew_info,
2720 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2721 return { 'error' => $session } if $context eq 'error';
2723 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2724 or return { 'error' => "unknown custnum $custnum" };
2726 my $date = $p->{'date'};
2730 #freeside-daily -n -d $date fs_daily $custnum
2731 $cust_main->bill_and_collect( 'time' => $date,
2732 'invoice_time' => $now,
2733 'actual_time' => $now,
2734 'check_freq' => '1d',
2737 return { 'error' => '' };
2743 my $session = _cache->get($p->{'session_id'})
2744 or return { 'error' => "Can't resume session" }; #better error message
2746 my $custnum = $session->{'custnum'};
2748 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2749 or return { 'error' => "unknown custnum $custnum" };
2751 my $conf = new FS::Conf;
2753 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2754 or return { 'error' => 'Permission denied' };
2756 my $pkgnum = $p->{'pkgnum'};
2758 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2759 'pkgnum' => $pkgnum, } )
2760 or return { 'error' => "unknown pkgnum $pkgnum" };
2762 my $error = $cust_pkg->suspend(reason => $reasonnum);
2763 return { 'error' => $error };
2769 my $session = _cache->get($p->{'session_id'})
2770 or return { 'error' => "Can't resume session" }; #better error message
2772 my $custnum = $session->{'custnum'};
2773 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2774 or return { 'error' => "unknown custnum $custnum" };
2776 my $pkgnum = $p->{'pkgnum'};
2777 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2778 'pkgnum' => $pkgnum, } )
2779 or return { 'error' => "unknown pkgnum $pkgnum" };
2781 my $error = $cust_pkg->cancel( 'quiet' => 1,
2782 'date' => $p->{'date'},
2784 return { 'error' => $error };
2787 sub provision_phone {
2790 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2792 #editing an existing phone number
2793 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2794 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2795 return { 'error' => $session } if $context eq 'error';
2797 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2798 return { 'error' => 'service not found' } unless $svc_phone;
2799 return { 'error' => 'invalid svcnum' }
2800 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2802 $svc_phone->email($p->{'email'})
2803 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2804 $svc_phone->forwarddst($p->{'forwarddst'})
2805 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2806 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2807 return { 'error' => $svc_phone->replace };
2811 unless ( $p->{'lnp'} ) {
2812 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2813 $p->{'lnp_status'} = "portingin";
2814 return _provision( 'FS::svc_phone',
2815 [qw(lnp_desired_due_date lnp_other_provider
2816 lnp_other_provider_account phonenum countrycode lnp_status)],
2817 [qw(phonenum countrycode)],
2823 # single DID order (the usual case)
2824 unless (scalar(@bulkdid)) {
2825 return _provision( 'FS::svc_phone',
2826 [qw(phonenum countrycode)],
2827 [qw(phonenum countrycode)],
2833 # bulk DID order case
2835 foreach my $did ( @bulkdid ) {
2836 $did =~ s/[^0-9]//g;
2837 $error = _provision( 'FS::svc_phone',
2838 [qw(phonenum countrycode)],
2839 [qw(phonenum countrycode)],
2841 'pkgnum' => $p->{'pkgnum'},
2842 'svcpart' => $p->{'svcpart'},
2844 'countrycode' => $p->{'countrycode'},
2845 'session_id' => $p->{'session_id'},
2848 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2850 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2855 warn "provision_pbx called\n"
2858 warn "provision_pbx calling _provision\n"
2860 _provision( 'FS::svc_pbx',
2861 [qw(id title max_extensions max_simultaneous ip_addr)],
2862 [qw(id title max_extensions max_simultaneous ip_addr)],
2868 sub provision_acct {
2870 warn "provision_acct called\n"
2873 return { 'error' => gettext('passwords_dont_match') }
2874 if $p->{'_password'} ne $p->{'_password2'};
2875 return { 'error' => gettext('empty_password') }
2876 unless length($p->{'_password'});
2878 if ($p->{'domsvc'}) {
2879 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2880 qw ( svcpart pkgnum ) );
2881 return { 'error' => gettext('invalid_domain') }
2882 unless ($domains{$p->{'domsvc'}});
2885 warn "provision_acct calling _provision\n"
2887 _provision( 'FS::svc_acct',
2888 [qw(username _password domsvc)],
2889 [qw(username _password domsvc)],
2895 sub provision_external {
2897 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2898 _provision( 'FS::svc_external',
2906 sub provision_forward {
2908 _provision( 'FS::svc_forward',
2909 ['srcsvc','src','dstsvc','dst'],
2916 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2917 warn "_provision called for $class\n"
2920 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2921 return { 'error' => $session } if $context eq 'error';
2923 my $search = { 'custnum' => $custnum };
2924 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2925 my $cust_main = qsearchs('cust_main', $search )
2926 or return { 'error' => "unknown custnum $custnum" };
2928 my $pkgnum = $p->{'pkgnum'};
2930 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2932 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2933 'pkgnum' => $pkgnum,
2935 or return { 'error' => "unknown pkgnum $pkgnum" };
2937 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2939 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2940 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2942 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2943 if $class ne 'FS::'. $part_svc->svcdb;
2945 warn "creating $class record\n"
2947 my $svc_x = $class->new( {
2948 'pkgnum' => $p->{'pkgnum'},
2949 'svcpart' => $p->{'svcpart'},
2950 map { $_ => $p->{$_} } @$fields
2953 my %insert_args = ();
2954 #i shouldn't be a special case here (pass an option or something)
2955 if ( $class eq 'FS::svc_phone'
2956 && grep length($p->{$_}), @location_editable_fields
2959 $insert_args{'cust_location'} = new FS::cust_location {
2960 map { $_ => $p->{$_} } @location_editable_fields
2964 warn "inserting $class record\n"
2966 my $error = $svc_x->insert(%insert_args);
2969 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2971 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2974 my $return = { 'svc' => $part_svc->svc,
2976 map { $_ => $svc_x->get($_) } @$return_fields
2978 warn "_provision returning ". Dumper($return). "\n"
2987 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2988 return { 'error' => $session } if $context eq 'error';
2990 my $search = { 'custnum' => $custnum };
2991 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2992 my $cust_main = qsearchs('cust_main', $search )
2993 or return { 'error' => "unknown custnum $custnum" };
2995 my $pkgnum = $p->{'pkgnum'};
2997 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2998 'pkgnum' => $pkgnum,
3000 or return { 'error' => "unknown pkgnum $pkgnum" };
3002 my $svcpart = $p->{'svcpart'};
3004 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
3005 'svcpart' => $svcpart, } )
3006 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
3007 my $part_svc = $pkg_svc->part_svc;
3009 my $conf = new FS::Conf;
3012 'svc' => $part_svc->svc,
3013 'svcdb' => $part_svc->svcdb,
3014 'pkgnum' => $pkgnum,
3015 'svcpart' => $svcpart,
3016 'custnum' => $custnum,
3018 'security_phrase' => 0, #XXX !
3019 'svc_acct_pop' => [], #XXX !
3021 'init_popstate' => '',
3026 small_custview( $cust_main, $conf->config('countrydefault') ),
3030 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
3031 && $ret->{'svcdb'} eq 'svc_phone') {
3032 $ret->{'svcnum'} = $p->{'svcnum'};
3033 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3034 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3035 $ret->{'email'} = $svc_phone->email;
3036 $ret->{'forwarddst'} = $svc_phone->forwarddst;
3040 if ($ret->{'svcdb'} eq 'svc_forward') {
3041 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3047 sub unprovision_svc {
3050 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3051 return { 'error' => $session } if $context eq 'error';
3053 my $search = { 'custnum' => $custnum };
3054 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3055 my $cust_main = qsearchs('cust_main', $search )
3056 or return { 'error' => "unknown custnum $custnum" };
3058 my $svcnum = $p->{'svcnum'};
3060 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
3061 or return { 'error' => "unknown svcnum $svcnum" };
3063 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3064 unless $cust_svc->cust_pkg->custnum == $custnum;
3066 my $conf = new FS::Conf;
3068 return { 'svc' => $cust_svc->part_svc->svc,
3069 'error' => $cust_svc->cancel,
3071 small_custview( $cust_main, $conf->config('countrydefault') ),
3076 sub myaccount_passwd {
3078 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3079 return { 'error' => $session } if $context eq 'error';
3081 return { 'error' => "New passwords don't match." }
3082 if $p->{'new_password'} ne $p->{'new_password2'};
3084 return { 'error' => 'Enter new password' }
3085 unless length($p->{'new_password'});
3087 #my $search = { 'custnum' => $custnum };
3088 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3089 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3090 my $search = " AND custnum = $1";
3091 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3093 my $svc_acct = qsearchs( {
3094 'table' => 'svc_acct',
3095 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3096 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3097 'LEFT JOIN cust_main USING ( custnum ) ',
3098 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3099 'extra_sql' => $search, #important
3101 or return { 'error' => "Service not found" };
3105 my $conf = new FS::Conf;
3107 return { 'error' => 'Incorrect current password.' }
3108 if ( exists($p->{'old_password'})
3109 || $conf->exists('selfservice-password_change_oldpass')
3111 && ! $svc_acct->check_password($p->{'old_password'});
3113 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3114 || $svc_acct->set_password($p->{'new_password'})
3115 || $svc_acct->replace();
3117 #regular pw change in self-service should change contact pw too, otherwise its
3118 #way too confusing. hell its confusing they're separate at all, but alas.
3119 #need to support the "ISP provides email that's used as a contact email" case
3121 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3122 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3123 custnum => $custnum,
3124 selfservice_access => 'Y',
3128 #svc_acct was successful but this one returns an error? "shouldn't happen"
3129 #don't recheck is_password_allowed here; if the svc_acct password was
3130 #legal, that's good enough
3131 $error ||= $contact->change_password($p->{'new_password'});
3134 my($label, $value) = $svc_acct->cust_svc->label;
3136 return { 'error' => $error,
3146 my $info = skin_info($p);
3148 my $conf = new FS::Conf;
3149 my $verification = $conf->config('selfservice-password_reset_verification')
3150 or return { %$info, 'error' => 'Password resets disabled' };
3155 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3157 $contact = FS::contact->by_selfservice_email($p->{'email'});
3160 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3161 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3164 #also look for an svc_acct, otherwise it would be super confusing
3166 my($username, $domain) = split('@', $p->{'email'});
3167 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3168 if ( $svc_domain ) {
3169 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3170 'domsvc' => $svc_domain->svcnum }
3173 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3174 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3176 #precaution: don't change svc_acct password not part of the same
3177 # customer as contact
3178 $svc_acct = '' if ! $cust_pkg
3179 || $cust_pkg->custnum != $cust_main->custnum;
3184 return { %$info, 'error' => 'Email address not found' }
3185 unless $contact || $svc_acct;
3187 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3189 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3190 or return { %$info, 'error' => 'Account not found' };
3192 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3193 'domsvc' => $svc_domain->svcnum }
3195 or return { %$info, 'error' => 'Account not found' };
3197 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3198 or return { %$info, 'error' => 'Account not found' };
3200 $cust_main = $cust_pkg->cust_main;
3204 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3205 if ! $cust_main && $verification ne 'email';
3208 'email' => sub { 1; },
3210 my( $p, $cust_main ) = @_;
3211 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3212 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3215 my( $p, $cust_main ) = @_;
3216 my $cust_pay = qsearchs({
3217 'table' => 'cust_pay',
3218 'hashref' => { 'custnum' => $cust_main->custnum },
3219 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3223 $p->{'amount'} == $cust_pay->paid;
3226 my( $p, $cust_main ) = @_;
3227 $p->{'zip'} eq $cust_main->zip
3228 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3232 foreach my $verify ( split(',', $verification) ) {
3234 &{ $verify{$verify} }( $p, $cust_main )
3235 or return { %$info, 'error' => 'Account not found' };
3239 #okay, we're verified
3243 my $error = $contact->send_reset_email(
3244 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3248 return { %$info, 'error' => $error }; #????
3251 } elsif ( $svc_acct ) {
3253 #create a unique session
3255 my $reset_session = {
3256 'svcnum' => $svc_acct->svcnum,
3257 'agentnum' => $svc_acct->cust_main->agentnum,
3260 my $timeout = '1 hour'; #?
3262 my $reset_session_id;
3264 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3265 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3268 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3272 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3273 $cust_main->agentnum);
3274 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3275 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3277 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3278 my $error = $msg_template->send( 'cust_main' => $cust_main,
3279 'object' => $svc_acct,
3280 'substitutions' => {
3281 'session_id' => $reset_session_id,
3285 return { %$info, 'error' => $error }; #????
3290 return { %$info, 'error' => '' };
3293 sub check_reset_passwd {
3296 my $conf = new FS::Conf;
3297 my $verification = $conf->config('selfservice-password_reset_verification')
3298 or return { 'error' => 'Password resets disabled' };
3300 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3301 or return { 'error' => "Can't resume session" }; #better error message
3303 if ( $reset_session->{'svcnum'} ) {
3305 my $svcnum = $reset_session->{'svcnum'};
3307 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3308 or return { 'error' => "Service not found" };
3310 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3311 my $info = skin_info($p);
3315 'session_id' => $p->{'session_id'},
3316 'username' => $svc_acct->username,
3319 } elsif ( $reset_session->{'contactnum'} ) {
3321 my $contactnum = $reset_session->{'contactnum'};
3323 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3324 or return { 'error' => "Contact not found" };
3326 my @contact_email = $contact->contact_email;
3327 return { 'error' => 'No contact email' } unless @contact_email;
3329 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3330 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3331 if scalar(@cust_contact) == 1;
3332 my $info = skin_info($p);
3336 'session_id' => $p->{'session_id'},
3337 'email' => $contact_email[0]->email, #the first?
3342 return { 'error' => 'No svcnum or contactnum in session' }; #??
3348 sub process_reset_passwd {
3351 my $conf = new FS::Conf;
3352 my $verification = $conf->config('selfservice-password_reset_verification')
3353 or return { 'error' => 'Password resets disabled' };
3355 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3356 or return { 'error' => "Can't resume session" }; #better error message
3361 if ( $reset_session->{'svcnum'} ) {
3363 my $svcnum = $reset_session->{'svcnum'};
3365 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3366 or return { 'error' => "Service not found" };
3368 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3369 $info ||= skin_info($p);
3374 if ( $reset_session->{'contactnum'} ) {
3376 my $contactnum = $reset_session->{'contactnum'};
3378 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3379 or return { 'error' => "Contact not found" };
3381 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3382 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3383 if scalar(@cust_contact) == 1;
3384 $info ||= skin_info($p);
3388 return { %$info, 'error' => "New passwords don't match." }
3389 if $p->{'new_password'} ne $p->{'new_password2'};
3391 return { %$info, 'error' => 'Enter new password' }
3392 unless length($p->{'new_password'});
3396 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3397 || $svc_acct->set_password($p->{'new_password'})
3398 || $svc_acct->replace();
3400 return { %$info, 'error' => $error } if $error;
3402 #my($label, $value) = $svc_acct->cust_svc->label;
3403 #return { 'error' => $error,
3404 # #'label' => $label,
3405 # #'value' => $value,
3412 my $error = $contact->is_password_allowed($p->{'new_password'})
3413 || $contact->change_password($p->{'new_password'});
3415 return { %$info, 'error' => $error }; # if $error;
3419 #password changed ,so remove session, don't want it reused
3420 _cache->remove($p->{'session_id'});
3422 return { %$info, 'error' => '' };
3426 sub validate_passwd {
3430 %result = ( 'fieldid' => $p->{'fieldid'} )
3431 if $p->{'fieldid'} =~ /^\w+$/;
3433 return { %result, 'password_invalid' => 'Enter new password' }
3434 unless length($p->{'check_password'});
3437 if ($p->{'svcnum'}) {
3438 # false laziness with myaccount_passwd
3439 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3440 return { %result, 'error' => $session } if $context eq 'error';
3442 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3443 my $search = " AND custnum = $1";
3444 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3446 $svc_acct = qsearchs( {
3447 'table' => 'svc_acct',
3448 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3449 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3450 'LEFT JOIN cust_main USING ( custnum ) ',
3451 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3452 'extra_sql' => $search, #important
3454 or return { %result, 'error' => "Service not found" };
3455 # end false laziness
3458 $svc_acct ||= new FS::svc_acct {};
3460 my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3461 return { %result, 'password_invalid' => $error } if $error;
3462 return { %result, 'password_valid' => 1 };
3467 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3468 return { 'error' => $session } if $context eq 'error';
3471 if ( $session->{'pkgnum'} ) {
3473 #tickets for specific service with pkg-balances on
3474 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3475 'pkgnum' => $session->{'pkgnum'} })
3476 or return { 'error' => 'unknown package' };
3477 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3478 push @tickets, $cust_svc->tickets( $p->{status} );
3483 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3484 or return { 'error' => "unknown custnum $custnum" };
3486 @tickets = $cust_main->tickets( $p->{status} );
3489 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3490 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3491 my $conf = new FS::Conf;
3492 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3496 ($a->{'_selfservice_priority'} eq '') <=>
3497 ($b->{'_selfservice_priority'} eq '')
3500 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3506 +{ tickets => \@tickets };
3513 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3514 return { 'error' => $session } if $context eq 'error';
3516 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3517 FS::TicketSystem->init();
3519 my $conf = new FS::Conf;
3520 my $queue = $p->{'queue'}
3521 || $conf->config('ticket_system-selfservice_queueid')
3522 || $conf->config('ticket_system-default_queueid');
3524 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3525 my $err_or_ticket = FS::TicketSystem->create_ticket(
3526 '', #create RT session based on FS CurrentUser (fs_selfservice)
3528 'custnum' => $custnum,
3529 'svcnum' => $session->{'svcnum'},
3530 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3533 if ( ref($err_or_ticket) ) {
3534 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3536 return { 'error' => '',
3537 'ticket_id' => $err_or_ticket->id,
3540 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3542 return { 'error' => $err_or_ticket };
3550 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3551 return { 'error' => $session } if $context eq 'error';
3553 return { error => 'requested format not implemented' }
3554 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3556 my $conf = new FS::Conf;
3557 my $age_threshold = 0;
3558 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3559 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3561 my $search = { 'custnum' => $custnum };
3562 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3563 my $cust_main = qsearchs('cust_main', $search )
3564 or return { 'error' => "unknown custnum $custnum" };
3566 # does it make more sense to just run one sql query for this instead of all the
3567 # insanity below? would increase performance greately for large data sets?
3569 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3570 my @part_svc = $cust_pkg->part_svc;
3571 foreach my $part_svc ( @part_svc ) {
3572 if($part_svc->svcdb eq 'svc_phone'){
3573 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3574 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3575 push @svc_phone, $cust_pkg_svc->svc_x
3576 if $cust_pkg_svc->date_inserted >= $age_threshold;
3584 my($xls_r,$xls_c) = (0,0);
3587 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3588 if($p->{'format'} eq 'csv') {
3589 $csv = new Text::CSV_XS { 'always_quote' => 1,
3592 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3593 $content .= $csv->string;
3595 elsif($p->{'format'} eq 'xls') {
3596 my $XLS1 = new IO::Scalar \$content;
3597 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3598 or return { 'error' => "Error opening .xls file: $!" };
3599 $xls = $xls_workbook->add_worksheet('DIDs');
3600 foreach ( @fields ) {
3601 $xls->write(0,$xls_c++,$_);
3606 foreach my $svc_phone ( @svc_phone ) {
3607 my @cols = map { $svc_phone->$_ } @fields;
3608 if($p->{'format'} eq 'csv') {
3609 return { 'error' => 'Unable to create CSV' }
3610 unless $csv->combine(@cols);
3611 $content .= $csv->string;
3613 elsif($p->{'format'} eq 'xls') {
3616 $xls->write($xls_r,$xls_c++,$_);
3622 $xls_workbook->close() if $p->{'format'} eq 'xls';
3624 { content => $content, format => $p->{'format'}, };
3629 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3630 return { 'error' => $session } if $context eq 'error';
3632 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3633 # FS::TicketSystem->init();
3634 # return { 'error' => 'get_ticket configuration error' }
3635 # if $FS::TicketSystem::system ne 'RT_Internal';
3637 # check existence and ownership as part of this
3638 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3639 my $rt_session = FS::TicketSystem->session('');
3640 my $Ticket = FS::TicketSystem->get_ticket_object(
3642 ticket_id => $p->{'ticket_id'},
3645 return { 'error' => 'ticket not found' } if !$Ticket;
3647 if ( length( $p->{'subject'} || '' ) ) {
3649 if ( $p->{'subject'} ne $Ticket->Subject ) {
3650 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3651 return { 'error' => "unable to set subject: $msg" } if !$val;
3655 if(length($p->{'reply'})) {
3656 my @err_or_res = FS::TicketSystem->correspond_ticket(
3658 'ticket_id' => $p->{'ticket_id'},
3659 'content' => $p->{'reply'},
3662 return { 'error' => 'unable to reply to ticket' }
3663 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3666 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3667 my $err_or_ticket = FS::TicketSystem->get_ticket(
3669 'ticket_id' => $p->{'ticket_id'},
3672 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3673 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3675 return { 'error' => $err_or_ticket };
3678 my @custs = @{$err_or_ticket->{'custs'}};
3679 my @txns = @{$err_or_ticket->{'txns'}};
3682 # superseded by check in get_ticket_object
3683 #return { 'error' => 'invalid ticket requested' }
3684 #unless grep($_ eq $custnum, @custs);
3686 foreach my $txn ( @txns ) {
3687 push @filtered_txns, $txn
3688 if ($txn->{'type'} eq 'EmailRecord'
3689 || $txn->{'type'} eq 'Correspond'
3690 || $txn->{'type'} eq 'Create');
3693 warn "$me get_ticket: successful: \n"
3695 return { 'error' => '',
3696 'transactions' => \@filtered_txns,
3697 'ticket_fields' => $err_or_ticket->{'fields'},
3698 'ticket_id' => $p->{'ticket_id'},
3702 sub adjust_ticket_priority {
3704 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3705 return { 'error' => $session } if $context eq 'error';
3707 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3708 # FS::TicketSystem->init;
3709 my $ss_priority = FS::TicketSystem->selfservice_priority;
3711 return { 'error' => 'adjust_ticket_priority configuration error' }
3712 if $FS::TicketSystem::system ne 'RT_Internal'
3715 my $values = $p->{'values'}; #hashref, id => priority value
3718 foreach my $id (keys %$values) {
3719 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3720 my $Ticket = FS::TicketSystem->get_ticket_object('',
3722 'custnum' => $custnum,
3725 $ticket_error{$id} = 'ticket not found';
3729 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3730 # We're not going to implement it for RT_External.
3731 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3732 my $new_value = $values->{$id};
3733 next if $old_value eq $new_value;
3735 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3737 # AddCustomFieldValue works fine (replacing any existing value) if it's
3738 # a single-valued custom field, which it should be. If it's not, you're
3739 # doing something wrong.
3741 if ( length($new_value) ) {
3742 ($val, $msg) = $Ticket->AddCustomFieldValue(
3743 Field => $ss_priority,
3744 Value => $new_value,
3748 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3749 Field => $ss_priority,
3750 Value => $old_value,
3754 $ticket_error{$id} = $msg if !$val;
3755 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3757 return { 'error' => '',
3758 'ticket_error' => \%ticket_error,
3759 %{ customer_info($p) } # send updated customer info back
3765 sub _custoragent_session_custnum {
3768 my($context, $session, $custnum);
3769 if ( $p->{'session_id'} ) {
3771 $context = 'customer';
3772 $session = _cache->get($p->{'session_id'})
3773 or return ( 'error' => "Can't resume session" ); #better error message
3774 $custnum = $session->{'custnum'};
3776 } elsif ( $p->{'agent_session_id'} ) {
3779 my $agent_cache = new FS::ClientAPI_SessionCache( {
3780 'namespace' => 'FS::ClientAPI::Agent',
3782 $session = $agent_cache->get($p->{'agent_session_id'})
3783 or return ( 'error' => "Can't resume session" ); #better error message
3784 $custnum = $p->{'custnum'};
3788 return ( 'error' => "Can't resume session" ); #better error message
3791 ($context, $session, $custnum);