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'),
859 my %return = %$payment_info;
861 my $custnum = $session->{'custnum'};
863 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
864 or return { 'error' => "unknown custnum $custnum" };
866 $return{'hide_payment_fields'} = [
868 my $pg = payment_gateway($cust_main, $_);
869 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
870 } @{ $return{cust_paybys} }
873 $return{balance} = $cust_main->balance; #XXX pkg-balances?
875 $return{$_} = $cust_main->bill_location->get($_)
876 for qw(address1 address2 city state zip);
878 # look for stored cust_payby info
879 # only if we've been given a clear payment_payby (to avoid payname conflicts)
880 if ($p->{'payment_payby'} =~ /^(CARD|CHEK)$/) {
881 my @search_payby = ($p->{'payment_payby'} eq 'CARD') ? ('CARD','DCRD') : ('CHEK','DCHK');
882 my ($cust_payby) = $cust_main->cust_payby(@search_payby);
884 $return{payname} = $cust_payby->payname
885 || ( $cust_main->first. ' '. $cust_main->get('last') );
887 if ( $cust_payby->payby =~ /^(CARD|DCRD)$/ ) {
888 $return{card_type} = cardtype($cust_payby->payinfo);
889 $return{payinfo} = $cust_payby->paymask;
891 @return{'month', 'year'} = $cust_payby->paydate_monthyear;
895 if ( $cust_payby->payby =~ /^(CHEK|DCHK)$/ ) {
896 my ($payinfo1, $payinfo2) = split '@', $cust_payby->paymask;
897 $return{payinfo1} = $payinfo1;
898 $return{payinfo2} = $payinfo2;
899 $return{paytype} = $cust_payby->paytype;
900 $return{paystate} = $cust_payby->paystate;
901 $return{payname} = $cust_payby->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
906 if ( $conf->config('prepayment_discounts-credit_type') ) {
908 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
911 #doubleclick protection
913 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
914 $return{paybatch} = $return{payunique}; #back compat
916 $return{credit_card_surcharge_percentage} = $conf->config('credit-card-surcharge-percentage', $cust_main->agentnum);
918 return { 'error' => '',
924 #some false laziness with httemplate/process/payment.cgi - look there for
925 #ACH and CVV support stuff
927 sub validate_payment {
930 my $session = _cache->get($p->{'session_id'})
931 or return { 'error' => "Can't resume session" }; #better error message
933 my $custnum = $session->{'custnum'};
935 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
936 or return { 'error' => "unknown custnum $custnum" };
938 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
939 or return { 'error' => gettext('illegal_amount') };
941 return { error => 'Amount must be greater than 0' } unless $amount > 0;
943 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
944 #changing the hidden form values
945 my $conf = new FS::Conf;
946 my $fee_display = $conf->config('selfservice_process-display') || 'add';
947 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
948 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
949 if ( $fee_display eq 'add'
951 and ! $fee_skip_first || scalar($cust_main->cust_pay)
954 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
955 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
958 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
959 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
960 my $discount_term = $1;
962 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
963 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
966 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
967 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
970 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
971 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
974 $payunique = $paybatch if ! length($payunique) && length($paybatch);
976 $p->{'payby'} ||= 'CARD';
977 $p->{'payby'} =~ /^([A-Z]{4})$/
978 or return { 'error' => "illegal_payby " . $p->{'payby'} };
981 #false laziness w/process/payment.cgi
984 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
986 $p->{'payinfo1'} =~ /^([\dx]+)$/
987 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
989 $p->{'payinfo2'} =~ /^([\dx]+)$/
990 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
992 $payinfo = $payinfo1. '@'. $payinfo2;
994 foreach my $cust_payby ($cust_main->cust_payby('CHEK','DCHK')) {
995 if ( $cust_payby->paymask eq $payinfo ) {
996 $payinfo = $cust_payby->payinfo;
1001 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1003 $payinfo = $p->{'payinfo'};
1007 #more intelligent matching will be needed here if you change
1008 #card_masking_method and don't remove existing paymasks
1009 foreach my $cust_payby ($cust_main->cust_payby('CARD','DCRD')) {
1010 if ( $cust_payby->paymask eq $payinfo ) {
1011 $payinfo = $cust_payby->payinfo;
1017 $payinfo =~ s/\D//g;
1018 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1019 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1023 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1024 return { 'error' => gettext('unknown_card_type') }
1025 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1027 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1028 if ( cardtype($payinfo) eq 'American Express card' ) {
1029 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1030 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1033 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1034 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1037 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1038 return { 'error' => 'CVV2 is required' };
1039 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1040 return { 'error' => 'CVV2 is required' };
1044 die "unknown payby $payby";
1047 my %payby2fields = (
1048 'CARD' => [ qw( paystart_month paystart_year payissue payip
1049 address1 address2 city state zip country ) ],
1050 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1054 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1057 'cust_main' => $cust_main, #XXX or just custnum??
1058 'amount' => sprintf('%.2f', $amount),
1060 'payinfo' => $payinfo,
1061 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1062 'card_type' => $card_type,
1063 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1064 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1065 'month' => $p->{'month'},
1066 'year' => $p->{'year'},
1067 'payname' => $payname,
1068 'payunique' => $payunique,
1069 'paybatch' => $paybatch,
1070 'paycvv' => $paycvv,
1071 'payname' => $payname,
1072 'discount_term' => $discount_term,
1073 'pkgnum' => $session->{'pkgnum'},
1074 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1084 my $validate = validate_payment($p);
1085 return $validate if $validate->{'error'};
1087 my $conf = new FS::Conf;
1088 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1089 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1091 +{ map { $_=>$validate->{$_} }
1092 qw( card_type paymask payname paydate_pretty month year amount
1093 address1 address2 city state zip country
1099 sub process_stored_payment {
1102 my $session_id = $p->{'session_id'};
1104 my $payment_info = _cache->get( "payment_$session_id" )
1105 or return { 'error' => "Can't resume session" }; #better error message
1107 do_process_payment($payment_info);
1111 sub process_payment {
1114 my $payment_info = validate_payment($p);
1115 return $payment_info if $payment_info->{'error'};
1117 do_process_payment($payment_info);
1121 sub do_process_payment {
1122 my $validate = shift;
1124 my $cust_main = $validate->{'cust_main'};
1126 my $amount = delete $validate->{'amount'};
1129 my $payby = delete $validate->{'payby'};
1131 if ( $validate->{'save'} ) {
1134 foreach my $field ( qw( auto payinfo paymask payname payip ) ) {
1135 $saveopt{$field} = $validate->{$field};
1138 if ( $payby eq 'CARD' ) {
1139 my $bill_location = FS::cust_location->new({
1140 map { $_ => $validate->{$_} }
1141 qw(address1 address2 city state country zip)
1143 $saveopt{'bill_location'} = $bill_location;
1144 foreach my $field ( qw( paydate paystart_month paystart_year payissue ) ) {
1145 $saveopt{$field} = $validate->{$field};
1148 # stateid/stateid_state won't be saved, might be broken as of 4.x
1149 foreach my $field ( qw( paytype paystate ) ) {
1150 $saveopt{$field} = $validate->{$field};
1154 my $error = $cust_main->save_cust_payby(
1155 'payment_payby' => $payby,
1160 #no, this causes customers to process their payments again
1161 #return { 'error' => $error };
1162 #XXX just warn verosely for now so i can figure out how these happen in
1163 # the first place, eventually should redirect them to the "change
1164 #address" page but indicate if the payment processed?
1165 delete($validate->{'payinfo'}); #don't want to log this!
1166 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1168 "SAVEOPT: ".Dumper(\%saveopt)."\n".
1169 "CUST_MAIN: ". Dumper($cust_main)."\n".
1170 "PACKET: ". Dumper($validate)."\n";
1174 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1178 'paynum_ref' => \$paynum,
1181 return { 'error' => $error } if $error;
1183 #no error, so order the fee package if applicable...
1184 my $conf = new FS::Conf;
1185 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1186 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1188 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1190 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1192 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1193 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1196 #and generate an invoice for it now too
1197 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1198 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1203 $cust_main->apply_payments;
1206 my $receipt_html = '';
1208 # currently supported for realtime CC only; send receipt data to SS
1209 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1212 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1215 <TD ALIGN="right">Payment#</TD>
1216 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1220 <TD ALIGN="right">Date</TD>
1222 <TD BGCOLOR="#FFFFFF"><B>! .
1223 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1229 <TD ALIGN="right">Amount</TD>
1230 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1235 <TD ALIGN="right">Payment method</TD>
1236 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1249 'amount' => sprintf('%.2f', $cust_pay->paid),
1250 'date' => $cust_pay->_date,
1251 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1252 'time_pretty' => time2str('%T', $cust_pay->_date),
1253 'auth_num' => $cust_pay->auth,
1254 'order_num' => $cust_pay->order_number,
1255 'receipt_html' => $receipt_html,
1262 'receipt_html' => '',
1269 sub realtime_collect {
1272 my $session = _cache->get($p->{'session_id'})
1273 or return { 'error' => "Can't resume session" }; #better error message
1275 my $custnum = $session->{'custnum'};
1277 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1278 or return { 'error' => "unknown custnum $custnum" };
1281 if ( $p->{'amount'} ) {
1282 $amount = $p->{'amount'};
1284 elsif ( $session->{'pkgnum'} ) {
1285 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1288 $amount = $cust_main->balance;
1291 my $error = $cust_main->realtime_collect(
1292 'method' => $p->{'method'},
1293 'amount' => $amount,
1294 'pkgnum' => $session->{'pkgnum'},
1295 'session_id' => $p->{'session_id'},
1299 return { 'error' => $error } unless ref( $error );
1301 return { 'error' => '', amount => $amount, %$error };
1304 sub start_thirdparty {
1306 my $session = _cache->get($p->{'session_id'})
1307 or return { 'error' => "Can't resume session" }; #better error message
1308 my $custnum = $session->{'custnum'};
1309 my $cust_main = FS::cust_main->by_key($custnum);
1311 my $amount = $p->{'amount'}
1312 or return { error => 'no amount' };
1314 my $result = $cust_main->create_payment(
1315 'method' => $p->{'method'},
1316 'amount' => $p->{'amount'},
1317 'pkgnum' => $session->{'pkgnum'},
1318 'session_id' => $p->{'session_id'},
1321 if ( ref($result) ) { # hashref or error
1324 return { error => $result };
1328 sub finish_thirdparty {
1330 my $session_id = delete $p->{'session_id'};
1331 my $session = _cache->get($session_id)
1332 or return { 'error' => "Can't resume session" };
1333 my $custnum = $session->{'custnum'};
1334 my $cust_main = FS::cust_main->by_key($custnum);
1336 if ( $p->{_cancel} ) {
1337 # customer backed out of making a payment
1338 return $cust_main->cancel_payment( $session_id );
1340 my $result = $cust_main->execute_payment( $session_id, %$p );
1341 if ( ref($result) ) {
1344 return { error => $result };
1348 sub process_payment_order_pkg {
1351 my $hr = process_payment($p);
1352 return $hr if $hr->{'error'};
1357 sub process_payment_order_renew {
1360 my $hr = process_payment($p);
1361 return $hr if $hr->{'error'};
1366 sub process_prepay {
1370 my $session = _cache->get($p->{'session_id'})
1371 or return { 'error' => "Can't resume session" }; #better error message
1375 my $custnum = $session->{'custnum'};
1377 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1378 or return { 'error' => "unknown custnum $custnum" };
1380 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1381 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1389 return { 'error' => $error } if $error;
1391 return { 'error' => '',
1392 'amount' => $amount,
1393 'seconds' => $seconds,
1394 'duration' => duration_exact($seconds),
1395 'upbytes' => $upbytes,
1396 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1397 'downbytes' => $downbytes,
1398 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1399 'totalbytes'=> $totalbytes,
1400 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1407 my $session = _cache->get($p->{'session_id'})
1408 or return { 'error' => "Can't resume session" }; #better error message
1410 my $custnum = $session->{'custnum'};
1412 my $invnum = $p->{'invnum'};
1414 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1415 'custnum' => $custnum } )
1416 or return { 'error' => "Can't find invnum" };
1420 return { 'error' => '',
1421 'invnum' => $invnum,
1422 'invoice_text' => join('', $cust_bill->print_text ),
1423 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1430 my $session = _cache->get($p->{'session_id'})
1431 or return { 'error' => "Can't resume session" }; #better error message
1433 my $custnum = $session->{'custnum'};
1435 my $invnum = $p->{'invnum'};
1437 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1438 'custnum' => $custnum } )
1439 or return { 'error' => "Can't find invnum" };
1443 return { 'error' => '',
1444 'invnum' => $invnum,
1445 'invoice_pdf' => $cust_bill->print_pdf({
1446 'unsquelch_cdr' => 1,
1447 'locale' => $p->{'locale'},
1453 sub legacy_invoice {
1455 my $session = _cache->get($p->{'session_id'})
1456 or return { 'error' => "Can't resume session" }; #better error message
1458 my $custnum = $session->{'custnum'};
1460 my $legacyinvnum = $p->{'legacyinvnum'};
1463 'legacyinvnum' => $legacyinvnum,
1464 'custnum' => $custnum,
1467 my $legacy_cust_bill =
1468 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1469 || qsearchs('legacy_cust_bill', \%hash )
1470 or return { 'error' => "Can't find legacyinvnum" };
1474 return { 'error' => '',
1475 'legacyinvnum' => $legacyinvnum,
1476 'legacyid' => $legacy_cust_bill->legacyid,
1477 'invoice_html' => $legacy_cust_bill->content_html,
1482 sub legacy_invoice_pdf {
1484 my $session = _cache->get($p->{'session_id'})
1485 or return { 'error' => "Can't resume session" }; #better error message
1487 my $custnum = $session->{'custnum'};
1489 my $legacyinvnum = $p->{'legacyinvnum'};
1491 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1492 'legacyinvnum' => $legacyinvnum,
1493 'custnum' => $custnum,
1494 }) or return { 'error' => "Can't find legacyinvnum" };
1498 return { 'error' => '',
1499 'legacyinvnum' => $legacyinvnum,
1500 'legacyid' => $legacy_cust_bill->legacyid,
1501 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1509 #sessioning for this? how do we get the session id to the backend invoice
1510 # template so it can add it to the link, blah
1513 if ( $p->{'invnum'} ) {
1514 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1515 or return { 'error' => 'unknown invnum' };
1516 $agentnum = $cust_bill->cust_main->agentnum;
1519 my $templatename = $p->{'template'} || $p->{'templatename'};
1521 #false laziness-ish w/view/cust_bill-logo.cgi
1523 my $conf = new FS::Conf;
1524 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1525 $templatename = "_$1";
1530 my $filename = "logo$templatename.png";
1532 return { 'error' => '',
1533 'logo' => $conf->config_binary($filename, $agentnum),
1534 'content_type' => 'image/png', #should allow gif, jpg too
1540 my $session = _cache->get($p->{'session_id'})
1541 or return { 'error' => "Can't resume session" }; #better error message
1543 my $custnum = $session->{'custnum'};
1545 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1546 or return { 'error' => "unknown custnum $custnum" };
1548 my $conf = new FS::Conf;
1550 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1552 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1557 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1558 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1559 my $owed = $_->owed;
1561 +{ 'invnum' => $_->invnum,
1562 '_date' => $_->_date,
1563 'date' => time2str("%b %o, %Y", $_->_date),
1564 'date_short' => time2str("%m-%d-%Y", $_->_date),
1565 'previous' => sprintf('%.2f', ($_->previous)[0]),
1566 'charged' => sprintf('%.2f', $_->charged),
1567 'owed' => sprintf('%.2f', $owed),
1568 'balance' => sprintf('%.2f', $balance),
1569 'lastpay' => @payments_and_credits
1570 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1576 return { 'error' => '',
1577 'balance' => $cust_main->balance,
1578 'money_char' => $conf->config("money_char") || '$',
1579 'invoices' => $invoices,
1580 'legacy_invoices' => [
1582 +{ 'legacyinvnum' => $_->legacyinvnum,
1583 'legacyid' => $_->legacyid,
1584 '_date' => $_->_date,
1585 'date' => time2str("%b %o, %Y", $_->_date),
1586 'date_short' => time2str("%m-%d-%Y", $_->_date),
1587 'charged' => sprintf('%.2f', $_->charged),
1588 'has_content' => ( length($_->content_pdf)
1589 || length($_->content_html) ),
1600 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1601 return { 'error' => $session } if $context eq 'error';
1603 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1604 or return { 'error' => "unknown custnum $custnum" };
1608 my $cust_payby = $_;
1610 map { $_ => $cust_payby->$_ }
1611 qw( custpaybynum weight payby paymask paydate
1612 payname paystate paytype
1616 $cust_main->cust_payby
1624 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1625 return { 'error' => $session } if $context eq 'error';
1627 #XXX payinfo1 + payinfo2 for CHEK?
1628 #or take the opportunity to use separate, more well- named fields?
1630 # $p->{'payinfo1'} =~ /^([\dx]+)$/
1631 # or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1632 # my $payinfo1 = $1;
1633 # $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1634 # or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1635 # my $payinfo2 = $1;
1636 # $payinfo = $payinfo1. '@'. $payinfo2;
1638 my $cust_payby = new FS::cust_payby {
1639 'custnum' => $custnum,
1640 map { $_ => $p->{$_} } qw( weight payby payinfo paycvv paydate payname
1641 paystate paytype payip
1645 my $error = $cust_payby->insert;
1647 return { 'error' => $error };
1649 return { 'custpaybynum' => $cust_payby->custpaybynum };
1657 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1658 return { 'error' => $session } if $context eq 'error';
1660 my $cust_payby = qsearchs('cust_payby', {
1661 'custnum' => $custnum,
1662 'custpaybynum' => $p->{'custpaybynum'},
1664 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1667 qw( weight payby payinfo paycvv paydate payname paystate paytype payip )
1669 next unless exists($p->{$field});
1670 $cust_payby->set($field,$p->{$field});
1673 my $error = $cust_payby->replace;
1675 return { 'error' => $error };
1677 return { 'custpaybynum' => $cust_payby->custpaybynum };
1685 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1686 return { 'error' => $session } if $context eq 'error';
1688 my $cust_payby = qsearchs('cust_payby', {
1689 'custnum' => $custnum,
1690 'custpaybynum' => $p->{'custpaybynum'},
1692 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1694 return { 'error' => $cust_payby->verify };
1701 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1702 return { 'error' => $session } if $context eq 'error';
1704 my $cust_payby = qsearchs('cust_payby', {
1705 'custnum' => $custnum,
1706 'custpaybynum' => $p->{'custpaybynum'},
1708 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1710 return { 'error' => $cust_payby->delete };
1716 my $session = _cache->get($p->{'session_id'})
1717 or return { 'error' => "Can't resume session" }; #better error message
1719 my $custnum = $session->{'custnum'};
1721 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1722 or return { 'error' => "unknown custnum $custnum" };
1724 my @errors = $cust_main->cancel( 'quiet'=>1 );
1726 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1728 return { 'error' => $error };
1735 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1736 return { 'error' => $session } if $context eq 'error';
1738 my $search = { 'custnum' => $custnum };
1739 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1740 my $cust_main = qsearchs('cust_main', $search )
1741 or return { 'error' => "unknown custnum $custnum" };
1743 my $conf = new FS::Conf;
1744 my $immutable = $conf->exists('selfservice_immutable-package');
1746 # the duplication below is necessary:
1747 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1748 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1749 # non-backwards-compatible change breaking the software of anyone using the API
1750 # instead of the stock selfservice
1751 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1752 if( $conf->exists('selfservice_server-view-wholesale') ) {
1753 return { 'svcnum' => $session->{'svcnum'},
1754 'custnum' => $custnum,
1755 'cust_pkg' => [ map {
1757 immutable => $immutable,
1758 part_pkg => [ map $_->hashref, $_->part_pkg ],
1760 [ map $_->hashref, $_->available_part_svc ],
1762 [ map { my $ref = { $_->hash,
1763 label => [ $_->label ],
1765 $ref->{_password} = $_->svc_x->_password
1766 if $context eq 'agent'
1767 && $conf->exists('agent-showpasswords')
1768 && $_->part_svc->svcdb eq 'svc_acct';
1773 } $cust_main->cust_pkg
1776 small_custview( $cust_main, $conf->config('countrydefault') ),
1777 'wholesale_view' => 1,
1778 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1779 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1780 'lnp' => $conf->exists('svc_phone-lnp'),
1784 { 'svcnum' => $session->{'svcnum'},
1785 'custnum' => $custnum,
1786 'cust_pkg' => [ map {
1787 my $primary_cust_svc = $_->primary_cust_svc;
1790 immutable => $immutable,
1791 pkg_label => $_->pkg_locale,
1792 status => $_->status,
1793 statuscolor => $_->statuscolor,
1795 [ map { $_->hashref }
1796 grep { $_->selfservice_access ne 'hidden' }
1797 $_->available_part_svc
1800 [ map { my $ref = { $_->hash,
1801 label => [ $_->label ],
1803 $ref->{_password} = $_->svc_x->_password
1804 if $context eq 'agent'
1805 && $conf->exists('agent-showpasswords')
1806 && $_->part_svc->svcdb eq 'svc_acct';
1807 $ref->{svchash} = { $_->svc_x->hash } if
1808 $_->part_svc->svcdb eq 'svc_phone';
1809 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1810 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1813 grep { $_->part_svc->selfservice_access ne 'hidden' }
1818 ? { $primary_cust_svc->hash,
1819 label => [ $primary_cust_svc->label ],
1820 finger => $primary_cust_svc->svc_x->finger, #uuh
1821 $primary_cust_svc->part_svc->hash,
1825 } $cust_main->ncancelled_pkgs
1828 small_custview( $cust_main, $conf->config('countrydefault') ),
1829 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1837 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1838 return { 'error' => $session } if $context eq 'error';
1840 my $conf = new FS::Conf;
1842 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1843 my $search = { 'custnum' => $custnum };
1844 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1845 my $cust_main = qsearchs('cust_main', $search )
1846 or return { 'error' => "unknown custnum $custnum" };
1848 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1849 if ( ! $pkgnum && $p->{'svcnum'} ) {
1850 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1851 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1855 my @cust_pkg_usage = ();
1856 foreach my $cust_pkg ( $p->{'ncancelled'}
1857 ? $cust_main->ncancelled_pkgs
1858 : $cust_main->unsuspended_pkgs ) {
1859 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1860 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1861 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1864 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1867 foreach (@cust_pkg_usage) {
1868 my $part = $_->part_pkg_usage;
1869 my $tag = $part->description . ($part->shared ? 1 : 0);
1870 my $row = $usage_pools{$tag}
1871 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1872 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1873 $row->[2] += $part->minutes; # minutes total
1875 } # otherwise just leave them empty
1877 if ( $p->{'svcdb'} ) {
1878 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1880 : ref($p->{'svcdb'}) eq 'ARRAY'
1881 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1882 : { $p->{'svcdb'} => 1 };
1883 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1886 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1889 my @svcs; # stuff to return to the client
1890 my %bytes_used_total; # for _used columns only
1891 foreach my $cust_svc (@cust_svc) {
1892 my $svc_x = $cust_svc->svc_x;
1893 my($label, $value) = $cust_svc->label;
1894 my $part_svc = $cust_svc->part_svc;
1895 my $svcdb = $part_svc->svcdb;
1896 my $cust_pkg = $cust_svc->cust_pkg;
1897 my $part_pkg = $cust_pkg->part_pkg;
1900 'svcnum' => $cust_svc->svcnum,
1901 'display_svcnum' => $cust_svc->display_svcnum,
1905 'pkg_label' => $cust_pkg->pkg_locale,
1906 'pkg_status' => $cust_pkg->status,
1907 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1910 # would it make sense to put this in a svc_* method?
1912 if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
1913 my $last_bill = $cust_pkg->last_bill || 0;
1915 my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
1916 my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
1919 'seconds_used' => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
1920 'upbytes_used' => display_bytecount($up_used),
1921 'downbytes_used' => display_bytecount($down_used),
1922 'totalbytes_used' => display_bytecount($up_used + $down_used)
1924 $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
1925 $bytes_used_total{'upbytes_used'} += $up_used;
1926 $bytes_used_total{'downbytes_used'} += $down_used;
1927 $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
1930 if ( $svcdb eq 'svc_acct' ) {
1931 foreach (qw(username email finger seconds)) {
1932 $hash{$_} = $svc_x->$_;
1938 'upbytes' => display_bytecount($svc_x->upbytes),
1939 'downbytes' => display_bytecount($svc_x->downbytes),
1940 'totalbytes' => display_bytecount($svc_x->totalbytes),
1942 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1943 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1944 'recharge_upbytes' =>
1945 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1946 'recharge_downbytes' =>
1947 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1948 'recharge_totalbytes' =>
1949 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1954 } elsif ( $svcdb eq 'svc_dsl' ) {
1956 $hash{'phonenum'} = $svc_x->phonenum;
1957 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1958 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1959 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1962 $hash{'name'} = $cust_main->name;
1964 # no usage to hide here
1966 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1968 # could potentially show lots of things...
1969 $hash{'outbound'} = 1;
1970 $hash{'inbound'} = 0;
1971 if ( $svcdb eq 'svc_phone' ) {
1972 if ( $part_pkg->plan eq 'voip_inbound' ) {
1973 $hash{'outbound'} = 0;
1974 $hash{'inbound'} = 1;
1975 } elsif ( $part_pkg->option('selfservice_inbound_format')
1976 or $conf->config('selfservice-default_inbound_cdr_format')
1978 $hash{'inbound'} = 1;
1981 foreach (qw(inbound outbound)) {
1982 # hmm...we can't filter by status here, because there might
1983 # not be cdr_terminations at all. have to go by date.
1984 # find all since the last bill date.
1985 # XXX cdr types? we are going to need them.
1987 my $sum_cdr = $svc_x->sum_cdrs(
1988 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1989 'begin' => ($cust_pkg->last_bill || 0),
1991 'disable_charged_party' => 1,
1993 $hash{$_} = $sum_cdr->hashref;
1996 } # not hiding usage
2000 } # foreach $cust_svc
2002 foreach my $field (keys %bytes_used_total) {
2003 if ($field =~ /bytes/) {
2004 $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
2009 'svcnum' => $session->{'svcnum'},
2010 'custnum' => $custnum,
2011 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2012 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
2014 'bytes_used_total' => \%bytes_used_total,
2016 map { $usage_pools{$_} }
2020 'hide_usage' => $hide_usage,
2025 sub _customer_svc_x {
2026 my($custnum, $svcnum, $table) = (shift, shift, shift);
2027 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
2029 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2030 my $search = " AND custnum = $1";
2031 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2034 'table' => ($table || 'svc_acct'),
2035 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2036 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
2037 #'LEFT JOIN cust_main USING ( custnum ) ',
2038 'hashref' => $hashref,
2039 'extra_sql' => $search, #important
2044 sub svc_status_html {
2047 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2048 return { 'error' => $session } if $context eq 'error';
2050 #XXX only svc_dsl for now
2051 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2052 or return { 'error' => "Service not found" };
2054 my $html = $svc_x->getstatus_html;
2056 return { 'html' => $html };
2060 sub svc_status_hash {
2063 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2064 return { 'error' => $session } if $context eq 'error';
2066 #XXX only svc_acct for now
2067 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2068 or return { 'error' => "Service not found" };
2070 my ( $html, $hashref ) = $svc_x->export_getstatus;
2075 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
2076 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2077 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2078 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2079 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2082 my( $p, $method ) = @_;
2084 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2085 return { 'error' => $session } if $context eq 'error';
2087 #XXX only svc_acct for now
2088 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2089 or return { 'error' => "Service not found" };
2091 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2093 my $error = $svc_x->$method($p); #$p? returns error?
2094 return { 'error' => $error } if $error;
2096 return {}; #? { 'error' => '' }
2100 sub acct_forward_info {
2103 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2104 return { 'error' => $session } if $context eq 'error';
2106 my $svc_forward = _customer_svc_x( $custnum,
2107 { 'srcsvc' => $p->{'svcnum'} },
2110 or return { 'error' => '',
2114 return { 'error' => '',
2115 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2120 sub process_acct_forward {
2122 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2123 return { 'error' => $session } if $context eq 'error';
2125 my $old = _customer_svc_x( $custnum,
2126 { 'srcsvc' => $p->{'svcnum'} },
2130 if ( $p->{'dst'} eq '' ) {
2132 my $error = $old->delete;
2133 return { 'error' => $error };
2135 return { 'error' => '' };
2138 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2139 'dst' => $p->{'dst'},
2144 $new->svcnum($old->svcnum);
2145 my $cust_svc = $old->cust_svc;
2146 $new->svcpart($old->svcpart);
2147 $new->pkgnuym($old->pkgnum);
2148 $error = $new->replace($old);
2150 my $conf = new FS::Conf;
2151 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2153 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2154 or return { 'error' => 'No service' }; #how would we even get here?
2156 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2158 $error = $new->insert;
2161 return { 'error' => $error };
2165 sub list_dsl_devices {
2168 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2169 return { 'error' => $session } if $context eq 'error';
2171 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2172 or return { 'error' => "Service not found" };
2175 'devices' => [ map {
2176 +{ 'mac_addr' => $_->mac_addr };
2177 } $svc_dsl->dsl_device
2183 sub add_dsl_device {
2186 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2187 return { 'error' => $session } if $context eq 'error';
2189 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2190 or return { 'error' => "Service not found" };
2192 return { 'error' => 'No MAC address supplied' }
2193 unless length($p->{'mac_addr'});
2195 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2196 'mac_addr' => scalar($p->{'mac_addr'}),
2198 my $error = $dsl_device->insert;
2199 return { 'error' => $error };
2203 sub delete_dsl_device {
2206 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2207 return { 'error' => $session } if $context eq 'error';
2209 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2210 or return { 'error' => "Service not found" };
2212 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2213 'mac_addr' => scalar($p->{'mac_addr'}),
2216 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2218 my $error = $dsl_device->delete;
2219 return { 'error' => $error };
2225 _usage_details( \&_port_graph, $p,
2226 'svcdb' => 'svc_port',
2231 my($svc_port, $begin, $end) = @_;
2233 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2234 push @usage, { 'png' => $pngOrError };
2238 sub _list_svc_usage {
2239 my($svc_acct, $begin, $end) = @_;
2241 foreach my $part_export (
2242 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2243 qw( sqlradius sqlradius_withdomain )
2245 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2250 sub list_svc_usage {
2251 _usage_details(\&_list_svc_usage, @_);
2254 sub _list_support_usage {
2255 my($svc_acct, $begin, $end) = @_;
2257 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2258 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2260 push @usage, { 'seconds' => $_->seconds,
2261 'support' => $_->support,
2262 '_date' => $_->_date,
2263 'id' => $_->transaction_id,
2264 'creator' => $_->creator,
2265 'subject' => $_->subject,
2266 'status' => $_->status,
2267 'ticketid' => $_->ticketid,
2273 sub list_support_usage {
2274 _usage_details(\&_list_support_usage, @_);
2277 sub _list_cdr_usage {
2278 # XXX CDR type support...
2279 # XXX any way to do a paged search on this?
2280 # we have to return the results all at once...
2281 my($svc_x, $begin, $end, %opt) = @_;
2282 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2286 'disable_charged_party' => 1,
2291 sub list_cdr_usage {
2293 _usage_details( \&_list_cdr_usage, $p );
2296 sub _usage_details {
2297 my($callback, $p, %opt) = @_;
2298 my $conf = FS::Conf->new;
2300 if ( $conf->exists('selfservice_hide-usage') ) {
2301 return { 'error' => 'Viewing usage is not allowed.' };
2304 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2305 return { 'error' => $session } if $context eq 'error';
2307 my $search = { 'svcnum' => $p->{'svcnum'} };
2308 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2310 my $cust_svc = qsearchs( 'cust_svc', $search );
2311 return { 'error' => 'No service selected in list_svc_usage' }
2314 my $svc_x = $cust_svc->svc_x;
2315 my $svcdb = $svc_x->table;
2316 my $cust_pkg = $cust_svc->cust_pkg;
2317 my $freq = $cust_pkg->part_pkg->freq;
2320 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2322 if ( $p->{inbound} ) {
2323 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2324 || $conf->config('selfservice-default_inbound_cdr_format')
2325 || 'source_default';
2326 $callback_opt{inbound} = 1;
2328 $format = $cust_pkg->part_pkg->option('selfservice_format')
2329 || $conf->config('selfservice-default_cdr_format')
2333 $callback_opt{format} = $format;
2334 $callback_opt{use_clid} = 1;
2335 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2338 my $start = $cust_pkg->setup;
2339 #my $end = $cust_pkg->bill; # or time?
2342 unless ( $p->{beginning} ) {
2343 $p->{beginning} = $cust_pkg->last_bill;
2344 $p->{ending} = $end;
2347 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2348 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2350 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2354 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2355 # ugly kludge, I know
2356 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2357 if (defined $delete_col) {
2358 delete($_->[$delete_col]) foreach ($header, @usage);
2362 #kinda false laziness with FS::cust_main::bill, but perhaps
2363 #we should really change this bit to DateTime and DateTime::Duration
2365 #change this bit to use Date::Manip? CAREFUL with timezones (see
2366 # mailing list archive)
2367 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2368 (localtime($p->{ending}) )[0,1,2,3,4,5];
2369 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2370 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2372 if ( $freq =~ /^\d+$/ ) {
2374 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2376 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2377 } elsif ( $freq =~ /^(\d+)w$/ ) {
2379 $nmday += $weeks * 7;
2380 $pmday -= $weeks * 7;
2381 } elsif ( $freq =~ /^(\d+)d$/ ) {
2385 } elsif ( $freq =~ /^(\d+)h$/ ) {
2390 return { 'error' => "unparsable frequency: ". $freq };
2393 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2394 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2398 'svcnum' => $p->{svcnum},
2399 'beginning' => $p->{beginning},
2400 'ending' => $p->{ending},
2401 'inbound' => $p->{inbound},
2402 'previous' => ($previous > $start) ? $previous : $start,
2403 'next' => ($next < $end) ? $next : $end,
2404 'header' => $header,
2412 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2413 return { 'error' => $session } if $context eq 'error';
2415 my $search = { 'custnum' => $custnum };
2416 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2417 my $cust_main = qsearchs('cust_main', $search )
2418 or return { 'error' => "unknown custnum $custnum" };
2420 my $status = $cust_main->status;
2422 my %order_pkg_options = ();
2423 if ( $p->{locationnum} > 0 ) {
2424 $order_pkg_options{locationnum} = delete($p->{locationnum});
2425 } elsif ( $p->{address1} ) {
2426 $order_pkg_options{'cust_location'} = new FS::cust_location {
2427 map { $_ => $p->{$_} }
2428 qw( address1 address2 city county state zip country )
2432 #false laziness w/ClientAPI/Signup.pm
2434 my $cust_pkg = new FS::cust_pkg ( {
2435 'custnum' => $custnum,
2436 'pkgpart' => $p->{'pkgpart'},
2437 'quantity' => $p->{'quantity'} || 1,
2439 my $error = $cust_pkg->check;
2440 return { 'error' => $error } if $error;
2443 unless ( $p->{'svcpart'} eq 'none' ) {
2447 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2449 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2450 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2451 $svcdb = $part_svc->svcdb;
2453 $svcdb = 'svc_acct';
2455 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2458 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2459 'svc_domain' => [ qw( domain ) ],
2460 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2461 'svc_external' => [ qw( id title ) ],
2462 'svc_pbx' => [ qw( id title ) ],
2465 my $svc_x = "FS::$svcdb"->new( {
2466 'svcpart' => $svcpart,
2467 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2470 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2473 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2474 my $acct_snarf = new FS::acct_snarf ( {
2475 'machine' => $p->{"snarf_machine$snarfnum"},
2476 'protocol' => $p->{"snarf_protocol$snarfnum"},
2477 'username' => $p->{"snarf_username$snarfnum"},
2478 '_password' => $p->{"snarf_password$snarfnum"},
2481 push @acct_snarf, $acct_snarf;
2483 $svc_x->child_objects( \@acct_snarf );
2486 my $y = $svc_x->setdefault; # arguably should be in new method
2487 return { 'error' => $y } if $y && !ref($y);
2489 $error = $svc_x->check;
2490 return { 'error' => $error } if $error;
2496 $error = $cust_main->order_pkg(
2497 'cust_pkg' => $cust_pkg,
2502 return { 'error' => $error } if $error;
2504 my $conf = new FS::Conf;
2505 if ( $conf->exists('signup_server-realtime') ) {
2507 my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2510 $cust_pkg->cancel('quiet'=>1);
2513 $cust_pkg->reexport;
2517 $cust_pkg->reexport;
2520 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2522 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2529 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2530 return { 'error' => $session } if $context eq 'error';
2532 my $conf = new FS::Conf;
2533 my $immutable = $conf->exists('selfservice_immutable-package');
2534 return { 'error' => "Package modification disabled" } if $immutable;
2536 my $search = { 'custnum' => $custnum };
2537 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2538 my $cust_main = qsearchs('cust_main', $search )
2539 or return { 'error' => "unknown custnum $custnum" };
2541 my $status = $cust_main->status;
2542 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2543 or return { 'error' => "unknown package $p->{pkgnum}" };
2545 #if someone does need self-service package change of suspended packages,
2546 # figure out how to be more discriminating
2547 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2548 if $cust_pkg->status eq 'suspended';
2550 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2551 'quantity' => $p->{'quantity'} || 1,
2554 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2555 unless ref($err_or_cust_pkg);
2557 if ( $conf->exists('signup_server-realtime') ) {
2559 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2562 $err_or_cust_pkg->suspend;
2565 $err_or_cust_pkg->reexport;
2569 $err_or_cust_pkg->reexport;
2572 return { error => '', pkgnum => $cust_pkg->pkgnum };
2576 sub order_recharge {
2579 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2580 return { 'error' => $session } if $context eq 'error';
2582 my $search = { 'custnum' => $custnum };
2583 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2584 my $cust_main = qsearchs('cust_main', $search )
2585 or return { 'error' => "unknown custnum $custnum" };
2587 my $status = $cust_main->status;
2588 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2589 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2591 my $svc_x = $cust_svc->svc_x;
2592 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2595 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2596 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2597 recharge_totalbytes );
2598 my $amount = $part_pkg->option('recharge_amount', 1);
2600 my ($l, $v, $d) = $cust_svc->label; # blah
2601 my $pkg = "Recharge $v";
2603 my $bill_error = $cust_main->charge($amount, $pkg,
2604 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2605 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2606 $part_pkg->taxclass); #meh
2608 my $conf = new FS::Conf;
2609 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2611 $bill_error = _do_bop_realtime( $cust_main, $status );
2616 my $error = $svc_x->recharge (\%vhash);
2617 return { 'error' => $error } if $error;
2621 my $error = $bill_error;
2622 $error ||= $svc_x->recharge (\%vhash);
2623 return { 'error' => $error } if $error;
2626 return { error => '', svc => $cust_svc->part_svc->svc };
2630 sub _do_bop_realtime {
2631 my ($cust_main, $status, %opt) = @_;
2633 my $old_balance = $cust_main->balance;
2636 my $bill_error = $cust_main->bill(
2637 'return_bill' => \@cust_bill,
2640 $bill_error ||= $cust_main->apply_payments_and_credits;
2642 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1);
2644 if ( $cust_main->balance > $old_balance
2645 && $cust_main->balance > 0
2646 && ( $cust_main->has_cust_payby_auto || $status eq 'suspended' )
2649 unless ( $opt{'no_invoice_void'} ) {
2651 #this used to apply a credit, but now we can void invoices...
2652 foreach my $cust_bill (@cust_bill) {
2653 my $voiderror = $cust_bill->void('automatic payment failed');
2654 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2659 return { 'error' => '_decline', 'bill_error' => $bill_error };
2662 if ( $opt{'collect'} ) {
2663 my $collect_error = $cust_main->collect();
2664 return { 'error' => '_decline', 'bill_error' => $collect_error }
2665 if $collect_error; #?
2674 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2675 return { 'error' => $session } if $context eq 'error';
2677 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2678 or return { 'error' => "unknown custnum $custnum" };
2680 my @cust_pkg = sort { $a->bill <=> $b->bill }
2681 grep { $_->part_pkg->freq ne '0' }
2682 $cust_main->ncancelled_pkgs;
2684 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2686 my $total = $cust_main->balance;
2689 my $bill = $_->bill;
2690 $total += $_->part_pkg->base_recur($_, \$bill);
2691 my $renew_date = $_->part_pkg->add_freq($_->bill);
2693 'pkgnum' => $_->pkgnum,
2694 'amount' => sprintf('%.2f', $total),
2695 'bill_date' => $_->bill,
2696 'bill_date_pretty' => time2str('%x', $_->bill),
2697 'renew_date' => $renew_date,
2698 'renew_date_pretty' => time2str('%x', $renew_date),
2699 'expire_date' => $_->expire,
2700 'expire_date_pretty' => time2str('%x', $_->expire),
2705 return { 'dates' => \@array };
2709 sub payment_info_renew_info {
2711 my $renew_info = renew_info($p);
2712 my $payment_info = payment_info($p);
2713 return { %$renew_info,
2721 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2722 return { 'error' => $session } if $context eq 'error';
2724 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2725 or return { 'error' => "unknown custnum $custnum" };
2727 my $date = $p->{'date'};
2731 #freeside-daily -n -d $date fs_daily $custnum
2732 $cust_main->bill_and_collect( 'time' => $date,
2733 'invoice_time' => $now,
2734 'actual_time' => $now,
2735 'check_freq' => '1d',
2738 return { 'error' => '' };
2744 my $session = _cache->get($p->{'session_id'})
2745 or return { 'error' => "Can't resume session" }; #better error message
2747 my $custnum = $session->{'custnum'};
2749 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2750 or return { 'error' => "unknown custnum $custnum" };
2752 my $conf = new FS::Conf;
2754 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2755 or return { 'error' => 'Permission denied' };
2757 my $pkgnum = $p->{'pkgnum'};
2759 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2760 'pkgnum' => $pkgnum, } )
2761 or return { 'error' => "unknown pkgnum $pkgnum" };
2763 my $error = $cust_pkg->suspend(reason => $reasonnum);
2764 return { 'error' => $error };
2770 my $session = _cache->get($p->{'session_id'})
2771 or return { 'error' => "Can't resume session" }; #better error message
2773 my $custnum = $session->{'custnum'};
2774 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2775 or return { 'error' => "unknown custnum $custnum" };
2777 my $pkgnum = $p->{'pkgnum'};
2778 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2779 'pkgnum' => $pkgnum, } )
2780 or return { 'error' => "unknown pkgnum $pkgnum" };
2782 my $error = $cust_pkg->cancel( 'quiet' => 1,
2783 'date' => $p->{'date'},
2785 return { 'error' => $error };
2788 sub provision_phone {
2791 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2793 #editing an existing phone number
2794 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2795 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2796 return { 'error' => $session } if $context eq 'error';
2798 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2799 return { 'error' => 'service not found' } unless $svc_phone;
2800 return { 'error' => 'invalid svcnum' }
2801 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2803 $svc_phone->email($p->{'email'})
2804 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2805 $svc_phone->forwarddst($p->{'forwarddst'})
2806 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2807 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2808 return { 'error' => $svc_phone->replace };
2812 unless ( $p->{'lnp'} ) {
2813 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2814 $p->{'lnp_status'} = "portingin";
2815 return _provision( 'FS::svc_phone',
2816 [qw(lnp_desired_due_date lnp_other_provider
2817 lnp_other_provider_account phonenum countrycode lnp_status)],
2818 [qw(phonenum countrycode)],
2824 # single DID order (the usual case)
2825 unless (scalar(@bulkdid)) {
2826 return _provision( 'FS::svc_phone',
2827 [qw(phonenum countrycode)],
2828 [qw(phonenum countrycode)],
2834 # bulk DID order case
2836 foreach my $did ( @bulkdid ) {
2837 $did =~ s/[^0-9]//g;
2838 $error = _provision( 'FS::svc_phone',
2839 [qw(phonenum countrycode)],
2840 [qw(phonenum countrycode)],
2842 'pkgnum' => $p->{'pkgnum'},
2843 'svcpart' => $p->{'svcpart'},
2845 'countrycode' => $p->{'countrycode'},
2846 'session_id' => $p->{'session_id'},
2849 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2851 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2856 warn "provision_pbx called\n"
2859 warn "provision_pbx calling _provision\n"
2861 _provision( 'FS::svc_pbx',
2862 [qw(id title max_extensions max_simultaneous ip_addr)],
2863 [qw(id title max_extensions max_simultaneous ip_addr)],
2869 sub provision_acct {
2871 warn "provision_acct called\n"
2874 return { 'error' => gettext('passwords_dont_match') }
2875 if $p->{'_password'} ne $p->{'_password2'};
2876 return { 'error' => gettext('empty_password') }
2877 unless length($p->{'_password'});
2879 if ($p->{'domsvc'}) {
2880 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2881 qw ( svcpart pkgnum ) );
2882 return { 'error' => gettext('invalid_domain') }
2883 unless ($domains{$p->{'domsvc'}});
2886 warn "provision_acct calling _provision\n"
2888 _provision( 'FS::svc_acct',
2889 [qw(username _password domsvc)],
2890 [qw(username _password domsvc)],
2896 sub provision_external {
2898 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2899 _provision( 'FS::svc_external',
2907 sub provision_forward {
2909 _provision( 'FS::svc_forward',
2910 ['srcsvc','src','dstsvc','dst'],
2917 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2918 warn "_provision called for $class\n"
2921 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2922 return { 'error' => $session } if $context eq 'error';
2924 my $search = { 'custnum' => $custnum };
2925 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2926 my $cust_main = qsearchs('cust_main', $search )
2927 or return { 'error' => "unknown custnum $custnum" };
2929 my $pkgnum = $p->{'pkgnum'};
2931 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2933 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2934 'pkgnum' => $pkgnum,
2936 or return { 'error' => "unknown pkgnum $pkgnum" };
2938 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2940 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2941 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2943 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2944 if $class ne 'FS::'. $part_svc->svcdb;
2946 warn "creating $class record\n"
2948 my $svc_x = $class->new( {
2949 'pkgnum' => $p->{'pkgnum'},
2950 'svcpart' => $p->{'svcpart'},
2951 map { $_ => $p->{$_} } @$fields
2954 my %insert_args = ();
2955 #i shouldn't be a special case here (pass an option or something)
2956 if ( $class eq 'FS::svc_phone'
2957 && grep length($p->{$_}), @location_editable_fields
2960 $insert_args{'cust_location'} = new FS::cust_location {
2961 map { $_ => $p->{$_} } @location_editable_fields
2965 warn "inserting $class record\n"
2967 my $error = $svc_x->insert(%insert_args);
2970 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2972 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2975 my $return = { 'svc' => $part_svc->svc,
2977 map { $_ => $svc_x->get($_) } @$return_fields
2979 warn "_provision returning ". Dumper($return). "\n"
2988 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2989 return { 'error' => $session } if $context eq 'error';
2991 my $search = { 'custnum' => $custnum };
2992 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2993 my $cust_main = qsearchs('cust_main', $search )
2994 or return { 'error' => "unknown custnum $custnum" };
2996 my $pkgnum = $p->{'pkgnum'};
2998 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2999 'pkgnum' => $pkgnum,
3001 or return { 'error' => "unknown pkgnum $pkgnum" };
3003 my $svcpart = $p->{'svcpart'};
3005 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
3006 'svcpart' => $svcpart, } )
3007 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
3008 my $part_svc = $pkg_svc->part_svc;
3010 my $conf = new FS::Conf;
3013 'svc' => $part_svc->svc,
3014 'svcdb' => $part_svc->svcdb,
3015 'pkgnum' => $pkgnum,
3016 'svcpart' => $svcpart,
3017 'custnum' => $custnum,
3019 'security_phrase' => 0, #XXX !
3020 'svc_acct_pop' => [], #XXX !
3022 'init_popstate' => '',
3027 small_custview( $cust_main, $conf->config('countrydefault') ),
3031 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
3032 && $ret->{'svcdb'} eq 'svc_phone') {
3033 $ret->{'svcnum'} = $p->{'svcnum'};
3034 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3035 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3036 $ret->{'email'} = $svc_phone->email;
3037 $ret->{'forwarddst'} = $svc_phone->forwarddst;
3041 if ($ret->{'svcdb'} eq 'svc_forward') {
3042 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3048 sub unprovision_svc {
3051 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3052 return { 'error' => $session } if $context eq 'error';
3054 my $search = { 'custnum' => $custnum };
3055 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3056 my $cust_main = qsearchs('cust_main', $search )
3057 or return { 'error' => "unknown custnum $custnum" };
3059 my $svcnum = $p->{'svcnum'};
3061 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
3062 or return { 'error' => "unknown svcnum $svcnum" };
3064 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3065 unless $cust_svc->cust_pkg->custnum == $custnum;
3067 my $conf = new FS::Conf;
3069 return { 'svc' => $cust_svc->part_svc->svc,
3070 'error' => $cust_svc->cancel,
3072 small_custview( $cust_main, $conf->config('countrydefault') ),
3077 sub myaccount_passwd {
3079 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3080 return { 'error' => $session } if $context eq 'error';
3082 return { 'error' => "New passwords don't match." }
3083 if $p->{'new_password'} ne $p->{'new_password2'};
3085 return { 'error' => 'Enter new password' }
3086 unless length($p->{'new_password'});
3088 #my $search = { 'custnum' => $custnum };
3089 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3090 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3091 my $search = " AND custnum = $1";
3092 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3094 my $svc_acct = qsearchs( {
3095 'table' => 'svc_acct',
3096 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3097 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3098 'LEFT JOIN cust_main USING ( custnum ) ',
3099 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3100 'extra_sql' => $search, #important
3102 or return { 'error' => "Service not found" };
3106 my $conf = new FS::Conf;
3108 return { 'error' => 'Incorrect current password.' }
3109 if ( exists($p->{'old_password'})
3110 || $conf->exists('selfservice-password_change_oldpass')
3112 && ! $svc_acct->check_password($p->{'old_password'});
3114 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3115 || $svc_acct->set_password($p->{'new_password'})
3116 || $svc_acct->replace();
3118 #regular pw change in self-service should change contact pw too, otherwise its
3119 #way too confusing. hell its confusing they're separate at all, but alas.
3120 #need to support the "ISP provides email that's used as a contact email" case
3122 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3123 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3124 custnum => $custnum,
3125 selfservice_access => 'Y',
3129 #svc_acct was successful but this one returns an error? "shouldn't happen"
3130 #don't recheck is_password_allowed here; if the svc_acct password was
3131 #legal, that's good enough
3132 $error ||= $contact->change_password($p->{'new_password'});
3135 my($label, $value) = $svc_acct->cust_svc->label;
3137 return { 'error' => $error,
3147 my $info = skin_info($p);
3149 my $conf = new FS::Conf;
3150 my $verification = $conf->config('selfservice-password_reset_verification')
3151 or return { %$info, 'error' => 'Password resets disabled' };
3156 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3158 $contact = FS::contact->by_selfservice_email($p->{'email'});
3161 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3162 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3165 #also look for an svc_acct, otherwise it would be super confusing
3167 my($username, $domain) = split('@', $p->{'email'});
3168 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3169 if ( $svc_domain ) {
3170 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3171 'domsvc' => $svc_domain->svcnum }
3174 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3175 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3177 #precaution: don't change svc_acct password not part of the same
3178 # customer as contact
3179 $svc_acct = '' if ! $cust_pkg
3180 || $cust_pkg->custnum != $cust_main->custnum;
3185 return { %$info, 'error' => 'Email address not found' }
3186 unless $contact || $svc_acct;
3188 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3190 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3191 or return { %$info, 'error' => 'Account not found' };
3193 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3194 'domsvc' => $svc_domain->svcnum }
3196 or return { %$info, 'error' => 'Account not found' };
3198 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3199 or return { %$info, 'error' => 'Account not found' };
3201 $cust_main = $cust_pkg->cust_main;
3205 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3206 if ! $cust_main && $verification ne 'email';
3209 'email' => sub { 1; },
3211 my( $p, $cust_main ) = @_;
3212 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3213 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3216 my( $p, $cust_main ) = @_;
3217 my $cust_pay = qsearchs({
3218 'table' => 'cust_pay',
3219 'hashref' => { 'custnum' => $cust_main->custnum },
3220 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3224 $p->{'amount'} == $cust_pay->paid;
3227 my( $p, $cust_main ) = @_;
3228 $p->{'zip'} eq $cust_main->zip
3229 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3233 foreach my $verify ( split(',', $verification) ) {
3235 &{ $verify{$verify} }( $p, $cust_main )
3236 or return { %$info, 'error' => 'Account not found' };
3240 #okay, we're verified
3244 my $error = $contact->send_reset_email(
3245 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3249 return { %$info, 'error' => $error }; #????
3252 } elsif ( $svc_acct ) {
3254 #create a unique session
3256 my $reset_session = {
3257 'svcnum' => $svc_acct->svcnum,
3258 'agentnum' => $svc_acct->cust_main->agentnum,
3261 my $timeout = '1 hour'; #?
3263 my $reset_session_id;
3265 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3266 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3269 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3273 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3274 $cust_main->agentnum);
3275 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3276 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3278 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3279 my $error = $msg_template->send( 'cust_main' => $cust_main,
3280 'object' => $svc_acct,
3281 'substitutions' => {
3282 'session_id' => $reset_session_id,
3286 return { %$info, 'error' => $error }; #????
3291 return { %$info, 'error' => '' };
3294 sub check_reset_passwd {
3297 my $conf = new FS::Conf;
3298 my $verification = $conf->config('selfservice-password_reset_verification')
3299 or return { 'error' => 'Password resets disabled' };
3301 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3302 or return { 'error' => "Can't resume session" }; #better error message
3304 if ( $reset_session->{'svcnum'} ) {
3306 my $svcnum = $reset_session->{'svcnum'};
3308 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3309 or return { 'error' => "Service not found" };
3311 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3312 my $info = skin_info($p);
3316 'session_id' => $p->{'session_id'},
3317 'username' => $svc_acct->username,
3320 } elsif ( $reset_session->{'contactnum'} ) {
3322 my $contactnum = $reset_session->{'contactnum'};
3324 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3325 or return { 'error' => "Contact not found" };
3327 my @contact_email = $contact->contact_email;
3328 return { 'error' => 'No contact email' } unless @contact_email;
3330 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3331 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3332 if scalar(@cust_contact) == 1;
3333 my $info = skin_info($p);
3337 'session_id' => $p->{'session_id'},
3338 'email' => $contact_email[0]->email, #the first?
3343 return { 'error' => 'No svcnum or contactnum in session' }; #??
3349 sub process_reset_passwd {
3352 my $conf = new FS::Conf;
3353 my $verification = $conf->config('selfservice-password_reset_verification')
3354 or return { 'error' => 'Password resets disabled' };
3356 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3357 or return { 'error' => "Can't resume session" }; #better error message
3362 if ( $reset_session->{'svcnum'} ) {
3364 my $svcnum = $reset_session->{'svcnum'};
3366 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3367 or return { 'error' => "Service not found" };
3369 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3370 $info ||= skin_info($p);
3375 if ( $reset_session->{'contactnum'} ) {
3377 my $contactnum = $reset_session->{'contactnum'};
3379 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3380 or return { 'error' => "Contact not found" };
3382 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3383 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3384 if scalar(@cust_contact) == 1;
3385 $info ||= skin_info($p);
3389 return { %$info, 'error' => "New passwords don't match." }
3390 if $p->{'new_password'} ne $p->{'new_password2'};
3392 return { %$info, 'error' => 'Enter new password' }
3393 unless length($p->{'new_password'});
3397 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3398 || $svc_acct->set_password($p->{'new_password'})
3399 || $svc_acct->replace();
3401 return { %$info, 'error' => $error } if $error;
3403 #my($label, $value) = $svc_acct->cust_svc->label;
3404 #return { 'error' => $error,
3405 # #'label' => $label,
3406 # #'value' => $value,
3413 my $error = $contact->is_password_allowed($p->{'new_password'})
3414 || $contact->change_password($p->{'new_password'});
3416 return { %$info, 'error' => $error }; # if $error;
3420 #password changed ,so remove session, don't want it reused
3421 _cache->remove($p->{'session_id'});
3423 return { %$info, 'error' => '' };
3427 sub validate_passwd {
3431 %result = ( 'fieldid' => $p->{'fieldid'} )
3432 if $p->{'fieldid'} =~ /^\w+$/;
3434 return { %result, 'password_invalid' => 'Enter new password' }
3435 unless length($p->{'check_password'});
3438 if ($p->{'svcnum'}) {
3439 # false laziness with myaccount_passwd
3440 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3441 return { %result, 'error' => $session } if $context eq 'error';
3443 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3444 my $search = " AND custnum = $1";
3445 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3447 $svc_acct = qsearchs( {
3448 'table' => 'svc_acct',
3449 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3450 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3451 'LEFT JOIN cust_main USING ( custnum ) ',
3452 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3453 'extra_sql' => $search, #important
3455 or return { %result, 'error' => "Service not found" };
3456 # end false laziness
3459 $svc_acct ||= new FS::svc_acct {};
3461 my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3462 return { %result, 'password_invalid' => $error } if $error;
3463 return { %result, 'password_valid' => 1 };
3468 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3469 return { 'error' => $session } if $context eq 'error';
3472 if ( $session->{'pkgnum'} ) {
3474 #tickets for specific service with pkg-balances on
3475 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3476 'pkgnum' => $session->{'pkgnum'} })
3477 or return { 'error' => 'unknown package' };
3478 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3479 push @tickets, $cust_svc->tickets( $p->{status} );
3484 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3485 or return { 'error' => "unknown custnum $custnum" };
3487 @tickets = $cust_main->tickets( $p->{status} );
3490 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3491 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3492 my $conf = new FS::Conf;
3493 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3497 ($a->{'_selfservice_priority'} eq '') <=>
3498 ($b->{'_selfservice_priority'} eq '')
3501 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3507 +{ tickets => \@tickets };
3514 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3515 return { 'error' => $session } if $context eq 'error';
3517 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3518 FS::TicketSystem->init();
3520 my $conf = new FS::Conf;
3521 my $queue = $p->{'queue'}
3522 || $conf->config('ticket_system-selfservice_queueid')
3523 || $conf->config('ticket_system-default_queueid');
3525 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3526 my $err_or_ticket = FS::TicketSystem->create_ticket(
3527 '', #create RT session based on FS CurrentUser (fs_selfservice)
3529 'custnum' => $custnum,
3530 'svcnum' => $session->{'svcnum'},
3531 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3534 if ( ref($err_or_ticket) ) {
3535 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3537 return { 'error' => '',
3538 'ticket_id' => $err_or_ticket->id,
3541 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3543 return { 'error' => $err_or_ticket };
3551 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3552 return { 'error' => $session } if $context eq 'error';
3554 return { error => 'requested format not implemented' }
3555 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3557 my $conf = new FS::Conf;
3558 my $age_threshold = 0;
3559 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3560 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3562 my $search = { 'custnum' => $custnum };
3563 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3564 my $cust_main = qsearchs('cust_main', $search )
3565 or return { 'error' => "unknown custnum $custnum" };
3567 # does it make more sense to just run one sql query for this instead of all the
3568 # insanity below? would increase performance greately for large data sets?
3570 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3571 my @part_svc = $cust_pkg->part_svc;
3572 foreach my $part_svc ( @part_svc ) {
3573 if($part_svc->svcdb eq 'svc_phone'){
3574 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3575 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3576 push @svc_phone, $cust_pkg_svc->svc_x
3577 if $cust_pkg_svc->date_inserted >= $age_threshold;
3585 my($xls_r,$xls_c) = (0,0);
3588 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3589 if($p->{'format'} eq 'csv') {
3590 $csv = new Text::CSV_XS { 'always_quote' => 1,
3593 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3594 $content .= $csv->string;
3596 elsif($p->{'format'} eq 'xls') {
3597 my $XLS1 = new IO::Scalar \$content;
3598 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3599 or return { 'error' => "Error opening .xls file: $!" };
3600 $xls = $xls_workbook->add_worksheet('DIDs');
3601 foreach ( @fields ) {
3602 $xls->write(0,$xls_c++,$_);
3607 foreach my $svc_phone ( @svc_phone ) {
3608 my @cols = map { $svc_phone->$_ } @fields;
3609 if($p->{'format'} eq 'csv') {
3610 return { 'error' => 'Unable to create CSV' }
3611 unless $csv->combine(@cols);
3612 $content .= $csv->string;
3614 elsif($p->{'format'} eq 'xls') {
3617 $xls->write($xls_r,$xls_c++,$_);
3623 $xls_workbook->close() if $p->{'format'} eq 'xls';
3625 { content => $content, format => $p->{'format'}, };
3630 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3631 return { 'error' => $session } if $context eq 'error';
3633 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3634 # FS::TicketSystem->init();
3635 # return { 'error' => 'get_ticket configuration error' }
3636 # if $FS::TicketSystem::system ne 'RT_Internal';
3638 # check existence and ownership as part of this
3639 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3640 my $rt_session = FS::TicketSystem->session('');
3641 my $Ticket = FS::TicketSystem->get_ticket_object(
3643 ticket_id => $p->{'ticket_id'},
3646 return { 'error' => 'ticket not found' } if !$Ticket;
3648 if ( length( $p->{'subject'} || '' ) ) {
3650 if ( $p->{'subject'} ne $Ticket->Subject ) {
3651 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3652 return { 'error' => "unable to set subject: $msg" } if !$val;
3656 if(length($p->{'reply'})) {
3657 my @err_or_res = FS::TicketSystem->correspond_ticket(
3659 'ticket_id' => $p->{'ticket_id'},
3660 'content' => $p->{'reply'},
3663 return { 'error' => 'unable to reply to ticket' }
3664 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3667 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3668 my $err_or_ticket = FS::TicketSystem->get_ticket(
3670 'ticket_id' => $p->{'ticket_id'},
3673 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3674 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3676 return { 'error' => $err_or_ticket };
3679 my @custs = @{$err_or_ticket->{'custs'}};
3680 my @txns = @{$err_or_ticket->{'txns'}};
3683 # superseded by check in get_ticket_object
3684 #return { 'error' => 'invalid ticket requested' }
3685 #unless grep($_ eq $custnum, @custs);
3687 foreach my $txn ( @txns ) {
3688 push @filtered_txns, $txn
3689 if ($txn->{'type'} eq 'EmailRecord'
3690 || $txn->{'type'} eq 'Correspond'
3691 || $txn->{'type'} eq 'Create');
3694 warn "$me get_ticket: successful: \n"
3696 return { 'error' => '',
3697 'transactions' => \@filtered_txns,
3698 'ticket_fields' => $err_or_ticket->{'fields'},
3699 'ticket_id' => $p->{'ticket_id'},
3703 sub adjust_ticket_priority {
3705 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3706 return { 'error' => $session } if $context eq 'error';
3708 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3709 # FS::TicketSystem->init;
3710 my $ss_priority = FS::TicketSystem->selfservice_priority;
3712 return { 'error' => 'adjust_ticket_priority configuration error' }
3713 if $FS::TicketSystem::system ne 'RT_Internal'
3716 my $values = $p->{'values'}; #hashref, id => priority value
3719 foreach my $id (keys %$values) {
3720 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3721 my $Ticket = FS::TicketSystem->get_ticket_object('',
3723 'custnum' => $custnum,
3726 $ticket_error{$id} = 'ticket not found';
3730 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3731 # We're not going to implement it for RT_External.
3732 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3733 my $new_value = $values->{$id};
3734 next if $old_value eq $new_value;
3736 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3738 # AddCustomFieldValue works fine (replacing any existing value) if it's
3739 # a single-valued custom field, which it should be. If it's not, you're
3740 # doing something wrong.
3742 if ( length($new_value) ) {
3743 ($val, $msg) = $Ticket->AddCustomFieldValue(
3744 Field => $ss_priority,
3745 Value => $new_value,
3749 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3750 Field => $ss_priority,
3751 Value => $old_value,
3755 $ticket_error{$id} = $msg if !$val;
3756 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3758 return { 'error' => '',
3759 'ticket_error' => \%ticket_error,
3760 %{ customer_info($p) } # send updated customer info back
3766 sub _custoragent_session_custnum {
3769 my($context, $session, $custnum);
3770 if ( $p->{'session_id'} ) {
3772 $context = 'customer';
3773 $session = _cache->get($p->{'session_id'})
3774 or return ( 'error' => "Can't resume session" ); #better error message
3775 $custnum = $session->{'custnum'};
3777 } elsif ( $p->{'agent_session_id'} ) {
3780 my $agent_cache = new FS::ClientAPI_SessionCache( {
3781 'namespace' => 'FS::ClientAPI::Agent',
3783 $session = $agent_cache->get($p->{'agent_session_id'})
3784 or return ( 'error' => "Can't resume session" ); #better error message
3785 $custnum = $p->{'custnum'};
3789 return ( 'error' => "Can't resume session" ); #better error message
3792 ($context, $session, $custnum);