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;
49 use FS::cust_location;
51 # for code organization
52 use FS::ClientAPI::MyAccount::contact;
53 use FS::ClientAPI::MyAccount::quotation;
56 $me = '[FS::ClientAPI::MyAccount]';
58 use vars qw( @cust_main_editable_fields @location_editable_fields );
59 @cust_main_editable_fields = qw(
60 first last company daytime night fax mobile
62 payby payinfo payname paystart_month paystart_year payissue payip
63 ss paytype paystate stateid stateid_state
65 @location_editable_fields = qw(
66 address1 address2 city county state zip country
70 BEGIN { #preload to reduce time customer_info takes
71 if ( $FS::TicketSystem::system ) {
72 warn "$me: initializing ticket system\n" if $DEBUG;
73 FS::TicketSystem->init();
78 $cache ||= new FS::ClientAPI_SessionCache( {
79 'namespace' => 'FS::ClientAPI::MyAccount',
86 my($context, $session, $custnum) = _custoragent_session_custnum($p);
87 #return { 'error' => $session } if $context eq 'error';
90 if ( $context eq 'customer' ) {
92 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
95 $sth->execute($custnum) or die $sth->errstr;
97 $agentnum = $sth->fetchrow_arrayref->[0]
98 or die "no agentnum for custnum $custnum";
100 #} elsif ( $context eq 'agent' ) {
101 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
104 $p->{'agentnum'} = $agentnum;
106 my $conf = new FS::Conf;
108 #false laziness w/Signup.pm
110 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
112 if ( $skin_info_cache_agent ) {
114 warn "$me loading cached skin info for agentnum $agentnum\n"
119 warn "$me populating skin info cache for agentnum $agentnum\n"
122 $skin_info_cache_agent = {
123 'agentnum' => $agentnum,
124 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
125 qw( company_name date_format ) ),
126 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
127 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
128 text_color link_color vlink_color hlink_color alink_color
129 font title_color title_align title_size menu_bgcolor menu_fontsize
132 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
133 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
134 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
136 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
137 qw( title_left_image title_right_image
138 menu_top_image menu_body_image menu_bottom_image
141 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
142 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
143 qw( head body_header body_footer company_address ) ),
144 'money_char' => $conf->config("money_char") || '$',
145 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
148 services.php Services
149 services.php My Services
150 services_new.php Order a new service
153 personal.php Personal Information
154 payment_accounts.php Payment Accounts
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 $session->{'custnum'} = $contact->custnum;
253 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
255 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
256 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
258 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
259 'domsvc' => $svc_domain->svcnum, }
262 if ( $conf->exists('selfservice_server-login_svcpart') ) {
263 my @svcpart = $conf->config('selfservice_server-login_svcpart');
264 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
265 scalar( grep( $_ eq $svcpart, @svcpart ) );
270 if ( $conf->exists('selfservice_server-primary_only') ) {
273 my $cust_svc = $_->cust_svc;
274 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
275 == $cust_svc->svcpart
280 return { error => 'User not found.' } unless @svc_acct;
282 #return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
284 my $svc_acct = $svc_acct[0];
286 if ( $conf->exists('selfservice_server-login_svcpart') ) {
287 my @svcpart = $conf->config('selfservice_server-login_svcpart');
288 my $svcpart = $svc_acct->cust_svc->svcpart;
289 return { error => 'Invalid user.' }
290 unless grep($_ eq $svcpart, @svcpart);
293 return { error => 'Incorrect password.' }
294 unless $svc_acct->check_password($p->{'password'});
302 $session->{'svcnum'} = $svc_x->svcnum;
304 my $cust_svc = $svc_x->cust_svc;
305 my $cust_pkg = $cust_svc->cust_pkg;
307 my $cust_main = $cust_pkg->cust_main;
308 $session->{'custnum'} = $cust_main->custnum;
309 if ( $conf->exists('pkg-balances') ) {
310 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
311 $cust_main->ncancelled_pkgs;
312 $session->{'pkgnum'} = $cust_pkg->pkgnum
313 if scalar(@cust_pkg) > 1;
317 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
318 #return { error => 'Only primary user may log in.' }
319 # if $conf->exists('selfservice_server-primary_only')
320 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
321 my $part_pkg = $cust_pkg->part_pkg;
322 return { error => 'Only primary user may log in.' }
323 if $conf->exists('selfservice_server-primary_only')
324 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
330 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
331 } until ( ! defined _cache->get($session_id) ); #just in case
333 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
334 _cache->set( $session_id, $session, $timeout );
336 return { 'error' => '',
337 'session_id' => $session_id,
343 my $skin_info = skin_info($p);
344 if ( $p->{'session_id'} ) {
345 _cache->remove($p->{'session_id'});
346 return { %$skin_info, 'error' => '' };
348 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
355 my($context, $session, $custnum) = _custoragent_session_custnum($p);
356 return { 'error' => $session } if $context eq 'error';
358 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
359 or return { 'error' => "Service not found" };
361 $session->{'svcnum'} = $svc_acct->svcnum;
363 my $conf = new FS::Conf;
364 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
365 _cache->set( $p->{'session_id'}, $session, $timeout );
367 return { 'error' => '' };
371 sub payment_gateway {
373 # takes a cust_main and a cust_payby entry, returns the payment_gateway
374 my $conf = new FS::Conf;
375 my $cust_main = shift;
376 my $cust_payby = shift;
377 my $gatewaynum = $conf->config('selfservice-payment_gateway');
379 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
380 die "configured gatewaynum $gatewaynum not found!" if !$pg;
384 return '' if ! FS::payby->realtime($cust_payby);
385 my $pg = $cust_main->agent->payment_gateway(
386 'method' => FS::payby->payby2bop($cust_payby),
396 my $conf = new FS::Conf;
398 my $info = skin_info($p);
400 use vars qw( $cust_paybys ); #cache for performance
401 unless ( $cust_paybys ) {
403 my %cust_paybys = map { $_ => 1 }
404 map { FS::payby->payby2payment($_) }
405 $conf->config('signup_server-payby');
407 $cust_paybys = [ keys %cust_paybys ];
410 $info->{'cust_paybys'} = $cust_paybys;
412 my($context, $session, $custnum) = _custoragent_session_custnum($p);
413 return { 'error' => $session } if $context eq 'error';
415 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
416 or return { 'error' => "unknown custnum $custnum" };
418 $info->{'hide_payment_fields'} = [
420 my $pg = payment_gateway($cust_main, $_);
421 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
422 } @{ $info->{cust_paybys} }
425 $info->{'self_suspend_reason'} =
426 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
428 $info->{'edit_ticket_subject'} =
429 $conf->exists('ticket_system-selfservice_edit_subject') &&
430 $cust_main->edit_subject;
432 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
434 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
437 'custnum' => $custnum,
438 'access_pkgnum' => $session->{'pkgnum'},
439 'access_svcnum' => $session->{'svcnum'},
446 my($context, $session, $custnum) = _custoragent_session_custnum($p);
447 return { 'error' => $session } if $context eq 'error';
451 my $conf = new FS::Conf;
452 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
454 # if ( $FS::TicketSystem::system ) {
455 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
456 # FS::TicketSystem->init();
459 if ( $custnum ) { #customer record
461 %return = ( %return, %{ customer_info_short($p) } );
463 #redundant with customer_info_short, but we need it for several things below
464 my $search = { 'custnum' => $custnum };
465 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
466 my $cust_main = qsearchs('cust_main', $search )
467 or return { 'error' => "unknown custnum $custnum" };
469 my $list_tickets = list_tickets($p);
470 $return{'tickets'} = $list_tickets->{'tickets'};
472 if ( $session->{'pkgnum'} ) {
473 #XXX open invoices in the pkg-balances case
475 $return{'money_char'} = $conf->config("money_char") || '$';
478 invnum => $_->invnum,
479 date => time2str("%b %o, %Y", $_->_date),
481 charged => $_->charged,
483 } $cust_main->open_cust_bill;
484 $return{open_invoices} = \@open;
486 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
487 my $sth = dbh->prepare($sql) or die dbh->errstr;
488 $sth->execute($custnum) or die $sth->errstr;
489 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
490 $return{'last_invoice_date_pretty'} =
491 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
494 #customer_info_short always has nobalance on..
495 $return{small_custview} =
496 small_custview( $cust_main,
497 $return{countrydefault},
498 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
501 $return{has_ship_address} = $cust_main->has_ship_address;
502 $return{status} = $cust_main->status;
503 $return{statuscolor} = $cust_main->statuscolor;
505 # compatibility: some places in selfservice use this to determine
506 # if there's a ship address
507 if ( $return{has_ship_address} ) {
508 $return{ship_last} = $cust_main->last;
509 $return{ship_first} = $cust_main->first;
512 if (scalar($conf->config('support_packages'))) {
513 my @support_services = ();
514 foreach ($cust_main->support_services) {
515 my $seconds = $_->svc_x->seconds || 0;
516 my $time_remaining = (($seconds < 0) ? '-' : '' ).
517 int(abs($seconds)/3600)."h".
518 sprintf("%02d",(abs($seconds)%3600)/60)."m";
519 my $cust_pkg = $_->cust_pkg;
522 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
523 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
524 push @support_services, { svcnum => $_->svcnum,
525 time => $time_remaining,
530 $return{support_services} = \@support_services;
533 if ( $conf->config('prepayment_discounts-credit_type') ) {
535 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
538 } elsif ( $session->{'svcnum'} ) { #no customer record
540 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
541 or die "unknown svcnum";
542 $return{name} = $svc_acct->email;
546 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
550 return { 'error' => '',
551 'custnum' => $custnum,
557 sub customer_info_short {
560 my($context, $session, $custnum) = _custoragent_session_custnum($p);
561 return { 'error' => $session } if $context eq 'error';
565 my $conf = new FS::Conf;
567 if ( $custnum ) { #customer record
569 my $search = { 'custnum' => $custnum };
570 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
571 my $cust_main = qsearchs('cust_main', $search )
572 or return { 'error' => "unknown custnum $custnum" };
574 $return{display_custnum} = $cust_main->display_custnum;
576 if ( $session->{'pkgnum'} ) {
577 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
578 #next_bill_date from cust_pkg?
580 $return{balance} = $cust_main->balance;
581 $return{next_bill_date} = $cust_main->next_bill_date;
582 $return{next_bill_date_pretty} =
583 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
586 $return{balance_pretty} = money_pretty($return{balance});
588 $return{countrydefault} = scalar($conf->config('countrydefault'));
590 $return{small_custview} =
591 small_custview( $cust_main,
592 $return{countrydefault},
596 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
598 $return{payby} = $cust_main->payby;
600 #none of these are terribly expensive if we want 'em...
601 for (@cust_main_editable_fields) {
602 $return{$_} = $cust_main->get($_);
604 #maybe a little more expensive, but it should be cached by now
605 for (@location_editable_fields) {
606 $return{$_} = $cust_main->bill_location->get($_);
607 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
610 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
611 $return{payinfo} = $cust_main->paymask;
612 @return{'month', 'year'} = $cust_main->paydate_monthyear;
615 my @invoicing_list = $cust_main->invoicing_list;
616 $return{'invoicing_list'} =
617 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
618 $return{'postal_invoicing'} =
619 0 < ( grep { $_ eq 'POST' } @invoicing_list );
621 if ( $session->{'svcnum'} ) {
622 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
623 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
624 $return{'svcnum'} = $session->{'svcnum'};
627 } elsif ( $session->{'svcnum'} ) { #no customer record
629 #uuh, not supproted yet... die?
630 return { 'error' => 'customer_info_short not yet supported as agent' };
634 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
638 # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
639 # it is not customer-specific, though it is only shown to authenticated customers
640 # it is not currently agent-specific, though at some point it might be
641 $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
643 return { 'error' => '',
644 'custnum' => $custnum,
649 sub customer_recurring {
652 my($context, $session, $custnum) = _custoragent_session_custnum($p);
653 return { 'error' => $session } if $context eq 'error';
657 my $conf = new FS::Conf;
659 my $search = { 'custnum' => $custnum };
660 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
661 my $cust_main = qsearchs('cust_main', $search )
662 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
664 $return{'display_recurring'} = [ $cust_main->display_recurring ];
666 return { 'error' => '',
667 'custnum' => $custnum,
672 sub billing_history {
675 my($context, $session, $custnum) = _custoragent_session_custnum($p);
676 return { 'error' => $session } if $context eq 'error';
678 return { 'error' => 'No customer' } unless $custnum;
680 my $search = { 'custnum' => $custnum };
681 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
682 my $cust_main = qsearchs('cust_main', $search )
683 or return { 'error' => "unknown custnum $custnum" };
687 if ( $session->{'pkgnum'} ) {
688 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
689 #next_bill_date from cust_pkg?
690 return { 'error' => 'No history for package' };
693 $return{balance} = $cust_main->balance;
694 $return{balance_pretty} = money_pretty($return{balance});
695 $return{next_bill_date} = $cust_main->next_bill_date;
696 $return{next_bill_date_pretty} =
697 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
700 my $conf = new FS::Conf;
702 $return{'history'} = [
703 $cust_main->payment_history(
704 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
709 $return{'money_char'} = $conf->config("money_char") || '$',
717 my $session = _cache->get($p->{'session_id'})
718 or return { 'error' => "Can't resume session" }; #better error message
720 my $custnum = $session->{'custnum'}
721 or return { 'error' => "no customer record" };
723 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
724 or return { 'error' => "unknown custnum $custnum" };
726 my $conf = new FS::Conf;
727 if (($p->{payby} eq "CHEK" || $p->{payby} eq "DCHEK") && $conf->exists('selfservice-ACH_info_readonly')) {
728 return { 'error' => "You do not have authority to add a bank account" };
731 my $new = new FS::cust_main { $cust_main->hash };
733 $new->set( $_ => $p->{$_} )
734 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
736 if ( exists($p->{address1}) ) {
737 my $bill_location = FS::cust_location->new({
738 map { $_ => $p->{$_} } @location_editable_fields
740 # if this is unchanged from before, cust_main::replace will ignore it
741 $new->set('bill_location' => $bill_location);
744 if ( exists($p->{ship_address1}) ) {
745 my $ship_location = FS::cust_location->new({
746 map { $_ => $p->{"ship_$_"} } @location_editable_fields
748 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
749 # Selfservice unfortunately tries to indicate "same as billing
750 # address" by sending all fields empty. Did this ever work?
751 $ship_location = $cust_main->bill_location;
753 $new->set('ship_location' => $ship_location);
755 # but if it hasn't been passed in at all, leave ship_location alone--
756 # DON'T change it to match bill_location.
759 if (exists($p->{'payby'})) {
760 $p->{'payby'} =~ /^([A-Z]{4})$/
761 or return { 'error' => "illegal_payby " . $p->{'payby'} };
765 if ( $payby =~ /^(CARD|DCRD)$/ ) {
767 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
769 if ( $new->payinfo eq $cust_main->paymask ) {
770 $new->payinfo($cust_main->payinfo);
771 $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
773 $new->payinfo($p->{'payinfo'});
774 return { 'error' => 'CVV2 is required' }
775 if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
776 $new->paycvv( $p->{'paycvv'} )
779 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
781 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
784 $p->{'payinfo1'} =~ /^([\dx]+)$/
785 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
787 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
788 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
790 $payinfo = $payinfo1. '@'. $payinfo2;
792 $new->payinfo( ($payinfo eq $cust_main->paymask)
793 ? $cust_main->payinfo
797 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
799 } elsif ( $payby =~ /^(BILL)$/ ) {
801 } elsif ( $payby ) { #notyet ready
802 return { 'error' => "unknown payby $payby" };
806 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
807 #false laziness with httemplate/edit/process/cust_main.cgi
808 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
809 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
811 @invoicing_list = $cust_main->invoicing_list;
814 my $error = $new->replace($cust_main, \@invoicing_list);
815 return { 'error' => $error } if $error;
818 return { 'error' => '' };
823 my $session = _cache->get($p->{'session_id'})
824 or return { 'error' => "Can't resume session" }; #better error message
830 my $conf = new FS::Conf;
831 use vars qw($payment_info); #cache for performance
832 unless ( $payment_info ) {
834 my %states = map { $_->state => 1 }
835 qsearch('cust_main_county', {
836 'country' => $conf->config('countrydefault') || 'US'
839 my %cust_paybys = map { $_ => 1 }
840 map { FS::payby->payby2payment($_) }
841 $conf->config('signup_server-payby');
843 my @cust_paybys = keys %cust_paybys;
847 #list all counties/states/countries
848 'cust_main_county' =>
849 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
851 #shortcut for one-country folks
853 [ sort { $a cmp $b } keys %states ],
855 'card_types' => card_types(),
857 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
858 'require_cvv' => $conf->exists('selfservice-require_cvv'),
859 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
861 'paytypes' => [ @FS::cust_main::paytypes ],
863 'paybys' => [ $conf->config('signup_server-payby') ],
864 'cust_paybys' => \@cust_paybys,
866 'stateid_label' => FS::Msgcat::_gettext('stateid'),
867 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
869 'show_ss' => $conf->exists('show_ss'),
870 'show_stateid' => $conf->exists('show_stateid'),
871 'show_paystate' => $conf->exists('show_bankstate'),
873 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
874 'ach_read_only' => $conf->exists('selfservice-ACH_info_readonly'),
884 my %return = %$payment_info;
886 delete $return{'cust_main_county'} if $p->{'omit_cust_main_county'};
888 my $custnum = $session->{'custnum'};
890 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
891 or return { 'error' => "unknown custnum $custnum" };
893 $return{'hide_payment_fields'} = [
895 my $pg = payment_gateway($cust_main, $_);
896 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
897 } @{ $return{cust_paybys} }
900 $return{balance} = $cust_main->balance; #XXX pkg-balances?
902 $return{payname} = $cust_main->payname
903 || ( $cust_main->first. ' '. $cust_main->get('last') );
905 $return{$_} = $cust_main->bill_location->get($_)
906 for qw(address1 address2 city state zip);
908 $return{payby} = $cust_main->payby;
909 $return{stateid_state} = $cust_main->stateid_state;
911 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
912 $return{card_type} = cardtype($cust_main->payinfo);
913 $return{payinfo} = $cust_main->paymask;
915 @return{'month', 'year'} = $cust_main->paydate_monthyear;
919 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
920 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
921 $return{payinfo1} = $payinfo1;
922 $return{payinfo2} = $payinfo2;
923 $return{paytype} = $cust_main->paytype;
924 $return{paystate} = $cust_main->paystate;
925 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
928 if ( $conf->config('prepayment_discounts-credit_type') ) {
930 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
933 #doubleclick protection
935 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
936 $return{paybatch} = $return{payunique}; #back compat
938 $return{credit_card_surcharge_percentage} = $conf->config('credit-card-surcharge-percentage', $cust_main->agentnum);
940 return { 'error' => '',
946 #some false laziness with httemplate/process/payment.cgi - look there for
947 #ACH and CVV support stuff
949 sub validate_payment {
952 my $session = _cache->get($p->{'session_id'})
953 or return { 'error' => "Can't resume session" }; #better error message
955 my $custnum = $session->{'custnum'};
957 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
958 or return { 'error' => "unknown custnum $custnum" };
960 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
961 or return { 'error' => gettext('illegal_amount') };
963 return { error => 'Amount must be greater than 0' } unless $amount > 0;
965 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
966 #changing the hidden form values
967 my $conf = new FS::Conf;
968 my $fee_display = $conf->config('selfservice_process-display') || 'add';
969 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
970 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
971 if ( $fee_display eq 'add'
973 and ! $fee_skip_first || scalar($cust_main->cust_pay)
976 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
977 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
980 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
981 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
982 my $discount_term = $1;
984 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
985 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
988 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
989 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
992 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
993 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
996 $payunique = $paybatch if ! length($payunique) && length($paybatch);
998 $p->{'payby'} ||= 'CARD';
999 $p->{'payby'} =~ /^([A-Z]{4})$/
1000 or return { 'error' => "illegal_payby " . $p->{'payby'} };
1003 #false laziness w/process/payment.cgi
1006 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1008 $p->{'payinfo1'} =~ /^([\dx]+)$/
1009 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1011 $p->{'payinfo2'} =~ /^([\dx]+)$/
1012 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1014 $payinfo = $payinfo1. '@'. $payinfo2;
1016 $payinfo = $cust_main->payinfo
1017 if $cust_main->paymask eq $payinfo;
1020 foreach my $cust_payby ($cust_main->cust_payby('CHEK','DCHK')) {
1021 if ( $cust_payby->paymask eq $payinfo ) {
1022 $payinfo = $cust_payby->payinfo;
1028 if ($conf->exists('selfservice-ACH_info_readonly') && !$achonfile) {
1029 return { 'error' => "You are not allowed to change your payment information." };
1032 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1034 $payinfo = $p->{'payinfo'};
1038 #more intelligent matching will be needed here if you change
1039 #card_masking_method and don't remove existing paymasks
1040 if ( $cust_main->paymask eq $payinfo ) {
1041 $payinfo = $cust_main->payinfo;
1045 $payinfo =~ s/\D//g;
1046 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1047 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1051 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1052 return { 'error' => gettext('unknown_card_type') }
1053 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1055 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1056 if ( cardtype($payinfo) eq 'American Express card' ) {
1057 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1058 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1061 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1062 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1065 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1066 return { 'error' => 'CVV2 is required' };
1067 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1068 return { 'error' => 'CVV2 is required' };
1072 die "unknown payby $payby";
1075 my %payby2fields = (
1076 'CARD' => [ qw( paystart_month paystart_year payissue payip
1077 address1 address2 city state zip country ) ],
1078 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1082 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1085 'cust_main' => $cust_main, #XXX or just custnum??
1086 'amount' => sprintf('%.2f', $amount),
1088 'payinfo' => $payinfo,
1089 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1090 'card_type' => $card_type,
1091 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1092 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1093 'month' => $p->{'month'},
1094 'year' => $p->{'year'},
1095 'payname' => $payname,
1096 'payunique' => $payunique,
1097 'paybatch' => $paybatch,
1098 'paycvv' => $paycvv,
1099 'payname' => $payname,
1100 'discount_term' => $discount_term,
1101 'pkgnum' => $session->{'pkgnum'},
1102 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1112 my $validate = validate_payment($p);
1113 return $validate if $validate->{'error'};
1115 my $conf = new FS::Conf;
1116 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1117 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1119 +{ map { $_=>$validate->{$_} }
1120 qw( card_type paymask payname paydate_pretty month year amount
1121 address1 address2 city state zip country
1127 sub process_stored_payment {
1130 my $session_id = $p->{'session_id'};
1132 my $payment_info = _cache->get( "payment_$session_id" )
1133 or return { 'error' => "Can't resume session" }; #better error message
1135 do_process_payment($payment_info);
1139 sub process_payment {
1142 my $payment_info = validate_payment($p);
1143 return $payment_info if $payment_info->{'error'};
1145 do_process_payment($payment_info);
1149 sub do_process_payment {
1150 my $validate = shift;
1152 my $cust_main = $validate->{'cust_main'};
1154 my $amount = delete $validate->{'amount'};
1157 my $payby = delete $validate->{'payby'};
1159 if ( $validate->{'save'} ) {
1160 my $new = new FS::cust_main { $cust_main->hash };
1161 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1162 $new->set( $_ => $validate->{$_} )
1163 foreach qw( payname paystart_month paystart_year payissue payip );
1164 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1166 my $bill_location = FS::cust_location->new({
1167 map { $_ => $validate->{$_} }
1168 qw(address1 address2 city state country zip)
1170 $new->set('bill_location' => $bill_location);
1171 # but don't allow the service address to change this way.
1173 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1174 $new->set( $_ => $validate->{$_} )
1175 foreach qw( payname payip paytype paystate
1176 stateid stateid_state );
1177 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1179 $new->payinfo( $validate->{'payinfo'} ); #to properly set paymask
1180 $new->set( 'paydate' => $validate->{'paydate'} );
1181 my $error = $new->replace($cust_main);
1183 #no, this causes customers to process their payments again
1184 #return { 'error' => $error };
1185 #XXX just warn verosely for now so i can figure out how these happen in
1186 # the first place, eventually should redirect them to the "change
1187 #address" page but indicate if the payment processed?
1188 delete($validate->{'payinfo'}); #don't want to log this!
1189 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1190 "NEW: ". Dumper($new)."\n".
1191 "OLD: ". Dumper($cust_main)."\n".
1192 "PACKET: ". Dumper($validate)."\n";
1198 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1202 'paynum_ref' => \$paynum,
1205 return { 'error' => $error } if $error;
1207 #no error, so order the fee package if applicable...
1208 my $conf = new FS::Conf;
1209 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1210 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1212 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1214 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1216 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1217 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1220 #and generate an invoice for it now too
1221 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1222 return { 'error' => "payment processed and fee ordered successfully, but error billing fee: $error" }
1227 $cust_main->apply_payments;
1230 my $receipt_html = '';
1232 # currently supported for realtime CC only; send receipt data to SS
1233 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1236 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1239 <TD ALIGN="right">Payment#</TD>
1240 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1244 <TD ALIGN="right">Date</TD>
1246 <TD BGCOLOR="#FFFFFF"><B>! .
1247 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1253 <TD ALIGN="right">Amount</TD>
1254 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1259 <TD ALIGN="right">Payment method</TD>
1260 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1273 'amount' => sprintf('%.2f', $cust_pay->paid),
1274 'date' => $cust_pay->_date,
1275 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1276 'time_pretty' => time2str('%T', $cust_pay->_date),
1277 'auth_num' => $cust_pay->auth,
1278 'order_num' => $cust_pay->order_number,
1279 'receipt_html' => $receipt_html,
1286 'receipt_html' => '',
1293 sub realtime_collect {
1296 my $session = _cache->get($p->{'session_id'})
1297 or return { 'error' => "Can't resume session" }; #better error message
1299 my $custnum = $session->{'custnum'};
1301 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1302 or return { 'error' => "unknown custnum $custnum" };
1305 if ( $p->{'amount'} ) {
1306 $amount = $p->{'amount'};
1308 elsif ( $session->{'pkgnum'} ) {
1309 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1312 $amount = $cust_main->balance;
1315 my $error = $cust_main->realtime_collect(
1316 'method' => $p->{'method'},
1317 'amount' => $amount,
1318 'pkgnum' => $session->{'pkgnum'},
1319 'session_id' => $p->{'session_id'},
1323 return { 'error' => $error } unless ref( $error );
1325 return { 'error' => '', amount => $amount, %$error };
1328 sub start_thirdparty {
1330 my $session = _cache->get($p->{'session_id'})
1331 or return { 'error' => "Can't resume session" }; #better error message
1332 my $custnum = $session->{'custnum'};
1333 my $cust_main = FS::cust_main->by_key($custnum);
1335 my $amount = $p->{'amount'}
1336 or return { error => 'no amount' };
1338 my $result = $cust_main->create_payment(
1339 'method' => $p->{'method'},
1340 'amount' => $p->{'amount'},
1341 'pkgnum' => $session->{'pkgnum'},
1342 'session_id' => $p->{'session_id'},
1345 if ( ref($result) ) { # hashref or error
1348 return { error => $result };
1352 sub finish_thirdparty {
1354 my $session_id = delete $p->{'session_id'};
1355 my $session = _cache->get($session_id)
1356 or return { 'error' => "Can't resume session" };
1357 my $custnum = $session->{'custnum'};
1358 my $cust_main = FS::cust_main->by_key($custnum);
1360 if ( $p->{_cancel} ) {
1361 # customer backed out of making a payment
1362 return $cust_main->cancel_payment( $session_id );
1364 my $result = $cust_main->execute_payment( $session_id, %$p );
1365 if ( ref($result) ) {
1368 return { error => $result };
1372 sub process_payment_order_pkg {
1375 my $hr = process_payment($p);
1376 return $hr if $hr->{'error'};
1381 sub process_payment_order_renew {
1384 my $hr = process_payment($p);
1385 return $hr if $hr->{'error'};
1390 sub process_prepay {
1394 my $session = _cache->get($p->{'session_id'})
1395 or return { 'error' => "Can't resume session" }; #better error message
1399 my $custnum = $session->{'custnum'};
1401 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1402 or return { 'error' => "unknown custnum $custnum" };
1404 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1405 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1413 return { 'error' => $error } if $error;
1415 return { 'error' => '',
1416 'amount' => $amount,
1417 'seconds' => $seconds,
1418 'duration' => duration_exact($seconds),
1419 'upbytes' => $upbytes,
1420 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1421 'downbytes' => $downbytes,
1422 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1423 'totalbytes'=> $totalbytes,
1424 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1431 my $session = _cache->get($p->{'session_id'})
1432 or return { 'error' => "Can't resume session" }; #better error message
1434 my $custnum = $session->{'custnum'};
1436 my $invnum = $p->{'invnum'};
1438 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1439 'custnum' => $custnum } )
1440 or return { 'error' => "Can't find invnum" };
1444 return { 'error' => '',
1445 'invnum' => $invnum,
1446 'invoice_text' => join('', $cust_bill->print_text ),
1447 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1454 my $session = _cache->get($p->{'session_id'})
1455 or return { 'error' => "Can't resume session" }; #better error message
1457 my $custnum = $session->{'custnum'};
1459 my $invnum = $p->{'invnum'};
1461 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1462 'custnum' => $custnum } )
1463 or return { 'error' => "Can't find invnum" };
1467 return { 'error' => '',
1468 'invnum' => $invnum,
1469 'invoice_pdf' => $cust_bill->print_pdf({
1470 'unsquelch_cdr' => 1,
1471 'locale' => $p->{'locale'},
1477 sub legacy_invoice {
1479 my $session = _cache->get($p->{'session_id'})
1480 or return { 'error' => "Can't resume session" }; #better error message
1482 my $custnum = $session->{'custnum'};
1484 my $legacyinvnum = $p->{'legacyinvnum'};
1487 'legacyinvnum' => $legacyinvnum,
1488 'custnum' => $custnum,
1491 my $legacy_cust_bill =
1492 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1493 || qsearchs('legacy_cust_bill', \%hash )
1494 or return { 'error' => "Can't find legacyinvnum" };
1498 return { 'error' => '',
1499 'legacyinvnum' => $legacyinvnum,
1500 'legacyid' => $legacy_cust_bill->legacyid,
1501 'invoice_html' => $legacy_cust_bill->content_html,
1506 sub legacy_invoice_pdf {
1508 my $session = _cache->get($p->{'session_id'})
1509 or return { 'error' => "Can't resume session" }; #better error message
1511 my $custnum = $session->{'custnum'};
1513 my $legacyinvnum = $p->{'legacyinvnum'};
1515 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1516 'legacyinvnum' => $legacyinvnum,
1517 'custnum' => $custnum,
1518 }) or return { 'error' => "Can't find legacyinvnum" };
1522 return { 'error' => '',
1523 'legacyinvnum' => $legacyinvnum,
1524 'legacyid' => $legacy_cust_bill->legacyid,
1525 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1533 #sessioning for this? how do we get the session id to the backend invoice
1534 # template so it can add it to the link, blah
1537 if ( $p->{'invnum'} ) {
1538 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1539 or return { 'error' => 'unknown invnum' };
1540 $agentnum = $cust_bill->cust_main->agentnum;
1543 my $templatename = $p->{'template'} || $p->{'templatename'};
1545 #false laziness-ish w/view/cust_bill-logo.cgi
1547 my $conf = new FS::Conf;
1548 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1549 $templatename = "_$1";
1554 my $filename = "logo$templatename.png";
1556 return { 'error' => '',
1557 'logo' => $conf->config_binary($filename, $agentnum),
1558 'content_type' => 'image/png', #should allow gif, jpg too
1565 my $session = _cache->get($p->{'session_id'})
1566 or return { 'error' => "Can't resume session" }; #better error message
1568 my $custnum = $session->{'custnum'};
1570 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1571 or return { 'error' => "unknown custnum $custnum" };
1573 my $conf = new FS::Conf;
1575 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1577 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1582 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1583 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1584 my $owed = $_->owed;
1586 +{ 'invnum' => $_->invnum,
1587 '_date' => $_->_date,
1588 'date' => time2str("%b %o, %Y", $_->_date),
1589 'date_short' => time2str("%m-%d-%Y", $_->_date),
1590 'previous' => sprintf('%.2f', ($_->previous)[0]),
1591 'charged' => sprintf('%.2f', $_->charged),
1592 'owed' => sprintf('%.2f', $owed),
1593 'balance' => sprintf('%.2f', $balance),
1594 'lastpay' => @payments_and_credits
1595 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1601 return { 'error' => '',
1602 'balance' => $cust_main->balance,
1603 'money_char' => $conf->config("money_char") || '$',
1604 'invoices' => $invoices,
1605 'legacy_invoices' => [
1607 +{ 'legacyinvnum' => $_->legacyinvnum,
1608 'legacyid' => $_->legacyid,
1609 '_date' => $_->_date,
1610 'date' => time2str("%b %o, %Y", $_->_date),
1611 'date_short' => time2str("%m-%d-%Y", $_->_date),
1612 'charged' => sprintf('%.2f', $_->charged),
1613 'has_content' => ( length($_->content_pdf)
1614 || length($_->content_html) ),
1624 my $session = _cache->get($p->{'session_id'})
1625 or return { 'error' => "Can't resume session" }; #better error message
1627 my $custnum = $session->{'custnum'};
1629 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1630 or return { 'error' => "unknown custnum $custnum" };
1632 return { 'error' => '',
1633 'balance' => $cust_main->balance,
1634 'money_char' => FS::Conf->new->config("money_char") || '$',
1635 'payments' => [ map $_->SSAPI_getinfo, $cust_main->cust_pay ],
1639 sub payment_receipt {
1641 my $session = _cache->get($p->{'session_id'})
1642 or return { 'error' => "Can't resume session" }; #better error message
1644 my $custnum = $session->{'custnum'};
1646 my $cust_pay = qsearchs('cust_pay', { 'custnum' => $custnum,
1647 'paynum' => $p->{'paynum'},
1650 or return { 'error' => "unknown payment ". $p->{'paynum'} };
1654 %{ $cust_pay->SSAPI_getinfo },
1661 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1662 return { 'error' => $session } if $context eq 'error';
1664 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1665 or return { 'error' => "unknown custnum $custnum" };
1669 my $cust_payby = $_;
1671 map { $_ => $cust_payby->$_ }
1672 qw( custpaybynum weight payby paymask paydate
1673 payname paystate paytype
1677 $cust_main->cust_payby
1685 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1686 return { 'error' => $session } if $context eq 'error';
1688 #XXX payinfo1 + payinfo2 for CHEK?
1689 #or take the opportunity to use separate, more well- named fields?
1691 # $p->{'payinfo1'} =~ /^([\dx]+)$/
1692 # or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1693 # my $payinfo1 = $1;
1694 # $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1695 # or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1696 # my $payinfo2 = $1;
1697 # $payinfo = $payinfo1. '@'. $payinfo2;
1699 my $cust_payby = new FS::cust_payby {
1700 'custnum' => $custnum,
1701 map { $_ => $p->{$_} } qw( weight payby payinfo paycvv paydate payname
1702 paystate paytype payip
1706 my $error = $cust_payby->insert;
1708 return { 'error' => $error };
1710 return { 'custpaybynum' => $cust_payby->custpaybynum };
1718 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1719 return { 'error' => $session } if $context eq 'error';
1721 my $cust_payby = qsearchs('cust_payby', {
1722 'custnum' => $custnum,
1723 'custpaybynum' => $p->{'custpaybynum'},
1725 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1728 qw( weight payby payinfo paycvv paydate payname paystate paytype payip )
1730 next unless exists($p->{$field});
1731 $cust_payby->set($field,$p->{$field});
1734 my $error = $cust_payby->replace;
1736 return { 'error' => $error };
1738 return { 'custpaybynum' => $cust_payby->custpaybynum };
1746 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1747 return { 'error' => $session } if $context eq 'error';
1749 my $cust_payby = qsearchs('cust_payby', {
1750 'custnum' => $custnum,
1751 'custpaybynum' => $p->{'custpaybynum'},
1753 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1755 return { 'error' => $cust_payby->verify };
1762 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1763 return { 'error' => $session } if $context eq 'error';
1765 my $cust_payby = qsearchs('cust_payby', {
1766 'custnum' => $custnum,
1767 'custpaybynum' => $p->{'custpaybynum'},
1769 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1771 my $conf = new FS::Conf;
1772 if (($cust_payby->payby eq "DCHK" || $cust_payby->payby eq "CHEK") && $conf->exists('selfservice-ACH_info_readonly')) {
1773 return { 'error' => "Sorry you do not have permission to delete bank information." };
1776 return { 'error' => $cust_payby->delete };
1782 my $session = _cache->get($p->{'session_id'})
1783 or return { 'error' => "Can't resume session" }; #better error message
1785 my $custnum = $session->{'custnum'};
1787 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1788 or return { 'error' => "unknown custnum $custnum" };
1790 my @errors = $cust_main->cancel( 'quiet'=>1 );
1792 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1794 return { 'error' => $error };
1801 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1802 return { 'error' => $session } if $context eq 'error';
1804 my $pkg = qsearchs({
1805 'table' => 'cust_pkg',
1806 'addl_from' => 'LEFT JOIN part_pkg USING ( pkgpart )',
1808 'custnum' => $custnum,
1809 'pkgnum' => $p->{'pkgnum'},
1812 or return {'error' => 'unknown pkg num $pkgnum'};
1815 pkg_label => $pkg->pkg,
1816 pkgpart => $pkg->pkgpart,
1817 classnum => $pkg->classnum,
1825 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1826 return { 'error' => $session } if $context eq 'error';
1828 my $search = { 'custnum' => $custnum };
1829 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1830 my $cust_main = qsearchs('cust_main', $search )
1831 or return { 'error' => "unknown custnum $custnum" };
1833 my $conf = new FS::Conf;
1834 my $immutable = $conf->exists('selfservice_immutable-package');
1836 # the duplication below is necessary:
1837 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1838 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1839 # non-backwards-compatible change breaking the software of anyone using the API
1840 # instead of the stock selfservice
1841 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1842 if( $conf->exists('selfservice_server-view-wholesale') ) {
1843 return { 'svcnum' => $session->{'svcnum'},
1844 'custnum' => $custnum,
1845 'cust_pkg' => [ map {
1847 immutable => $immutable,
1848 part_pkg => [ map $_->hashref, $_->part_pkg ],
1850 [ map $_->hashref, $_->available_part_svc ],
1852 [ map { my $ref = { $_->hash,
1853 label => [ $_->label ],
1855 $ref->{_password} = $_->svc_x->_password
1856 if $context eq 'agent'
1857 && $conf->exists('agent-showpasswords')
1858 && $_->part_svc->svcdb eq 'svc_acct';
1863 } $cust_main->cust_pkg
1866 small_custview( $cust_main, $conf->config('countrydefault') ),
1867 'wholesale_view' => 1,
1868 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1869 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1870 'lnp' => $conf->exists('svc_phone-lnp'),
1874 { 'svcnum' => $session->{'svcnum'},
1875 'custnum' => $custnum,
1876 'cust_pkg' => [ map {
1877 my $primary_cust_svc = $_->primary_cust_svc;
1880 immutable => $immutable,
1881 pkg_label => $_->pkg_locale,
1882 status => $_->status,
1883 statuscolor => $_->statuscolor,
1885 [ map { $_->hashref }
1886 grep { $_->selfservice_access ne 'hidden' }
1887 $_->available_part_svc
1890 [ map { my $ref = { $_->hash,
1891 label => [ $_->label ],
1893 $ref->{_password} = $_->svc_x->_password
1894 if $context eq 'agent'
1895 && $conf->exists('agent-showpasswords')
1896 && $_->part_svc->svcdb eq 'svc_acct';
1897 $ref->{svchash} = { $_->svc_x->hash } if
1898 $_->part_svc->svcdb eq 'svc_phone';
1899 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1900 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1903 grep { $_->part_svc->selfservice_access ne 'hidden' }
1908 ? { $primary_cust_svc->hash,
1909 label => [ $primary_cust_svc->label ],
1910 finger => $primary_cust_svc->svc_x->finger, #uuh
1911 $primary_cust_svc->part_svc->hash,
1915 } $cust_main->ncancelled_pkgs
1918 small_custview( $cust_main, $conf->config('countrydefault') ),
1919 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1927 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1928 return { 'error' => $session } if $context eq 'error';
1930 my $conf = new FS::Conf;
1932 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1933 my $search = { 'custnum' => $custnum };
1934 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1935 my $cust_main = qsearchs('cust_main', $search )
1936 or return { 'error' => "unknown custnum $custnum" };
1938 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1939 if ( ! $pkgnum && $p->{'svcnum'} ) {
1940 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1941 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1945 my @cust_pkg_usage = ();
1946 foreach my $cust_pkg ( $p->{'ncancelled'}
1947 ? $cust_main->ncancelled_pkgs
1948 : $cust_main->unsuspended_pkgs ) {
1949 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1950 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1951 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1954 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1957 foreach (@cust_pkg_usage) {
1958 my $part = $_->part_pkg_usage;
1959 my $tag = $part->description . ($part->shared ? 1 : 0);
1960 my $row = $usage_pools{$tag}
1961 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1962 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1963 $row->[2] += $part->minutes; # minutes total
1965 } # otherwise just leave them empty
1967 if ( $p->{'svcdb'} ) {
1968 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1970 : ref($p->{'svcdb'}) eq 'ARRAY'
1971 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1972 : { $p->{'svcdb'} => 1 };
1973 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1976 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1979 my @svcs; # stuff to return to the client
1980 my %bytes_used_total; # for _used columns only
1981 foreach my $cust_svc (@cust_svc) {
1982 my $svc_x = $cust_svc->svc_x;
1983 my($label, $value) = $cust_svc->label;
1984 my $part_svc = $cust_svc->part_svc;
1985 my $svcdb = $part_svc->svcdb;
1986 my $cust_pkg = $cust_svc->cust_pkg;
1987 my $part_pkg = $cust_pkg->part_pkg;
1990 'svcnum' => $cust_svc->svcnum,
1991 'display_svcnum' => $cust_svc->display_svcnum,
1995 'pkg_label' => $cust_pkg->pkg_locale,
1996 'pkg_status' => $cust_pkg->status,
1997 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
2000 # would it make sense to put this in a svc_* method?
2002 if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
2003 my $last_bill = $cust_pkg->last_bill || 0;
2005 my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
2006 my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
2009 'seconds_used' => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
2010 'upbytes_used' => display_bytecount($up_used),
2011 'downbytes_used' => display_bytecount($down_used),
2012 'totalbytes_used' => display_bytecount($up_used + $down_used)
2014 $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
2015 $bytes_used_total{'upbytes_used'} += $up_used;
2016 $bytes_used_total{'downbytes_used'} += $down_used;
2017 $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
2020 if ( $svcdb eq 'svc_acct' ) {
2021 foreach (qw(username email finger seconds)) {
2022 $hash{$_} = $svc_x->$_;
2028 'upbytes' => display_bytecount($svc_x->upbytes),
2029 'downbytes' => display_bytecount($svc_x->downbytes),
2030 'totalbytes' => display_bytecount($svc_x->totalbytes),
2032 'recharge_amount' => $part_pkg->option('recharge_amount',1),
2033 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
2034 'recharge_upbytes' =>
2035 display_bytecount($part_pkg->option('recharge_upbytes',1)),
2036 'recharge_downbytes' =>
2037 display_bytecount($part_pkg->option('recharge_downbytes',1)),
2038 'recharge_totalbytes' =>
2039 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
2044 } elsif ( $svcdb eq 'svc_dsl' ) {
2046 $hash{'phonenum'} = $svc_x->phonenum;
2047 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
2048 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
2049 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
2052 $hash{'name'} = $cust_main->name;
2054 # no usage to hide here
2056 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2058 # could potentially show lots of things...
2059 $hash{'outbound'} = 1;
2060 $hash{'inbound'} = 0;
2061 if ( $svcdb eq 'svc_phone' ) {
2062 if ( $part_pkg->plan eq 'voip_inbound' ) {
2063 $hash{'outbound'} = 0;
2064 $hash{'inbound'} = 1;
2065 } elsif ( $part_pkg->option('selfservice_inbound_format')
2066 or $conf->config('selfservice-default_inbound_cdr_format')
2068 $hash{'inbound'} = 1;
2071 foreach (qw(inbound outbound)) {
2072 # hmm...we can't filter by status here, because there might
2073 # not be cdr_terminations at all. have to go by date.
2074 # find all since the last bill date.
2075 # XXX cdr types? we are going to need them.
2077 my $sum_cdr = $svc_x->sum_cdrs(
2078 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
2079 'begin' => ($cust_pkg->last_bill || 0),
2081 'disable_charged_party' => 1,
2083 $hash{$_} = $sum_cdr->hashref;
2086 } # not hiding usage
2090 } # foreach $cust_svc
2092 foreach my $field (keys %bytes_used_total) {
2093 if ($field =~ /bytes/) {
2094 $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
2099 'svcnum' => $session->{'svcnum'},
2100 'custnum' => $custnum,
2101 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2102 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
2104 'bytes_used_total' => \%bytes_used_total,
2106 map { $usage_pools{$_} }
2110 'hide_usage' => $hide_usage,
2115 sub _customer_svc_x {
2116 my($custnum, $svcnum, $table) = (shift, shift, shift);
2117 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
2119 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2120 my $search = " AND custnum = $1";
2121 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2124 'table' => ($table || 'svc_acct'),
2125 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2126 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
2127 #'LEFT JOIN cust_main USING ( custnum ) ',
2128 'hashref' => $hashref,
2129 'extra_sql' => $search, #important
2134 sub svc_status_html {
2137 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2138 return { 'error' => $session } if $context eq 'error';
2140 #XXX only svc_dsl for now
2141 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2142 or return { 'error' => "Service not found" };
2144 my $html = $svc_x->getstatus_html;
2146 return { 'html' => $html };
2150 sub svc_status_hash {
2153 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2154 return { 'error' => $session } if $context eq 'error';
2156 #XXX only svc_acct for now
2157 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2158 or return { 'error' => "Service not found" };
2160 my ( $html, $hashref ) = $svc_x->export_getstatus;
2165 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
2166 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2167 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2168 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2169 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2172 my( $p, $method ) = @_;
2174 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2175 return { 'error' => $session } if $context eq 'error';
2177 #XXX only svc_acct for now
2178 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2179 or return { 'error' => "Service not found" };
2181 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2183 my $error = $svc_x->$method($p); #$p? returns error?
2184 return { 'error' => $error } if $error;
2186 return {}; #? { 'error' => '' }
2190 sub acct_forward_info {
2193 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2194 return { 'error' => $session } if $context eq 'error';
2196 my $svc_forward = _customer_svc_x( $custnum,
2197 { 'srcsvc' => $p->{'svcnum'} },
2200 or return { 'error' => '',
2204 return { 'error' => '',
2205 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2210 sub process_acct_forward {
2212 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2213 return { 'error' => $session } if $context eq 'error';
2215 my $old = _customer_svc_x( $custnum,
2216 { 'srcsvc' => $p->{'svcnum'} },
2220 if ( $p->{'dst'} eq '' ) {
2222 my $error = $old->delete;
2223 return { 'error' => $error };
2225 return { 'error' => '' };
2228 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2229 'dst' => $p->{'dst'},
2234 $new->svcnum($old->svcnum);
2235 my $cust_svc = $old->cust_svc;
2236 $new->svcpart($old->svcpart);
2237 $new->pkgnuym($old->pkgnum);
2238 $error = $new->replace($old);
2240 my $conf = new FS::Conf;
2241 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2243 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2244 or return { 'error' => 'No service' }; #how would we even get here?
2246 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2248 $error = $new->insert;
2251 return { 'error' => $error };
2255 sub list_dsl_devices {
2258 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2259 return { 'error' => $session } if $context eq 'error';
2261 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2262 or return { 'error' => "Service not found" };
2265 'devices' => [ map {
2266 +{ 'mac_addr' => $_->mac_addr };
2267 } $svc_dsl->dsl_device
2273 sub add_dsl_device {
2276 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2277 return { 'error' => $session } if $context eq 'error';
2279 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2280 or return { 'error' => "Service not found" };
2282 return { 'error' => 'No MAC address supplied' }
2283 unless length($p->{'mac_addr'});
2285 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2286 'mac_addr' => scalar($p->{'mac_addr'}),
2288 my $error = $dsl_device->insert;
2289 return { 'error' => $error };
2293 sub delete_dsl_device {
2296 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2297 return { 'error' => $session } if $context eq 'error';
2299 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2300 or return { 'error' => "Service not found" };
2302 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2303 'mac_addr' => scalar($p->{'mac_addr'}),
2306 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2308 my $error = $dsl_device->delete;
2309 return { 'error' => $error };
2315 _usage_details( \&_port_graph, $p,
2316 'svcdb' => 'svc_port',
2321 my($svc_port, $begin, $end) = @_;
2323 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2324 push @usage, { 'png' => $pngOrError };
2328 sub _list_svc_usage {
2329 my($svc_acct, $begin, $end) = @_;
2331 foreach my $part_export (
2332 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2333 qw( sqlradius sqlradius_withdomain )
2335 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2340 sub list_svc_usage {
2341 _usage_details(\&_list_svc_usage, @_);
2344 sub _list_support_usage {
2345 my($svc_acct, $begin, $end) = @_;
2347 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2348 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2350 push @usage, { 'seconds' => $_->seconds,
2351 'support' => $_->support,
2352 '_date' => $_->_date,
2353 'id' => $_->transaction_id,
2354 'creator' => $_->creator,
2355 'subject' => $_->subject,
2356 'status' => $_->status,
2357 'ticketid' => $_->ticketid,
2363 sub list_support_usage {
2364 _usage_details(\&_list_support_usage, @_);
2367 sub _list_cdr_usage {
2368 # XXX CDR type support...
2369 # XXX any way to do a paged search on this?
2370 # we have to return the results all at once...
2371 my($svc_x, $begin, $end, %opt) = @_;
2372 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2376 'disable_charged_party' => 1,
2381 sub list_cdr_usage {
2383 _usage_details( \&_list_cdr_usage, $p );
2386 sub _usage_details {
2387 my($callback, $p, %opt) = @_;
2388 my $conf = FS::Conf->new;
2390 if ( $conf->exists('selfservice_hide-usage') ) {
2391 return { 'error' => 'Viewing usage is not allowed.' };
2394 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2395 return { 'error' => $session } if $context eq 'error';
2397 my $search = { 'svcnum' => $p->{'svcnum'} };
2398 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2400 my $cust_svc = qsearchs( 'cust_svc', $search );
2401 return { 'error' => 'No service selected in list_svc_usage' }
2404 my $svc_x = $cust_svc->svc_x;
2405 my $svcdb = $svc_x->table;
2406 my $cust_pkg = $cust_svc->cust_pkg;
2407 my $freq = $cust_pkg->part_pkg->freq;
2410 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2412 if ( $p->{inbound} ) {
2413 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2414 || $conf->config('selfservice-default_inbound_cdr_format')
2415 || 'source_default';
2416 $callback_opt{inbound} = 1;
2418 $format = $cust_pkg->part_pkg->option('selfservice_format')
2419 || $conf->config('selfservice-default_cdr_format')
2423 $callback_opt{format} = $format;
2424 $callback_opt{use_clid} = 1;
2425 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2428 my $start = $cust_pkg->setup;
2429 #my $end = $cust_pkg->bill; # or time?
2432 unless ( $p->{beginning} ) {
2433 $p->{beginning} = $cust_pkg->last_bill;
2434 $p->{ending} = $end;
2437 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2438 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2440 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2444 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2445 # ugly kludge, I know
2446 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2447 if (defined $delete_col) {
2448 delete($_->[$delete_col]) foreach ($header, @usage);
2452 #kinda false laziness with FS::cust_main::bill, but perhaps
2453 #we should really change this bit to DateTime and DateTime::Duration
2455 #change this bit to use Date::Manip? CAREFUL with timezones (see
2456 # mailing list archive)
2457 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2458 (localtime($p->{ending}) )[0,1,2,3,4,5];
2459 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2460 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2462 if ( $freq =~ /^\d+$/ ) {
2464 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2466 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2467 } elsif ( $freq =~ /^(\d+)w$/ ) {
2469 $nmday += $weeks * 7;
2470 $pmday -= $weeks * 7;
2471 } elsif ( $freq =~ /^(\d+)d$/ ) {
2475 } elsif ( $freq =~ /^(\d+)h$/ ) {
2480 return { 'error' => "unparsable frequency: ". $freq };
2483 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2484 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2488 'svcnum' => $p->{svcnum},
2489 'beginning' => $p->{beginning},
2490 'ending' => $p->{ending},
2491 'inbound' => $p->{inbound},
2492 'previous' => ($previous > $start) ? $previous : $start,
2493 'next' => ($next < $end) ? $next : $end,
2494 'header' => $header,
2502 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2503 return { 'error' => $session } if $context eq 'error';
2505 my $search = { 'custnum' => $custnum };
2506 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2507 my $cust_main = qsearchs('cust_main', $search )
2508 or return { 'error' => "unknown custnum $custnum" };
2510 my $status = $cust_main->status;
2512 my %order_pkg_options = ();
2513 if ( $p->{locationnum} > 0 ) {
2514 $order_pkg_options{locationnum} = delete($p->{locationnum});
2515 } elsif ( $p->{address1} ) {
2516 $order_pkg_options{'cust_location'} = new FS::cust_location {
2517 map { $_ => $p->{$_} }
2518 qw( address1 address2 city county state zip country )
2522 #false laziness w/ClientAPI/Signup.pm
2524 my $cust_pkg = new FS::cust_pkg ( {
2525 'custnum' => $custnum,
2526 'pkgpart' => $p->{'pkgpart'},
2527 'quantity' => $p->{'quantity'} || 1,
2529 my $error = $cust_pkg->check;
2530 return { 'error' => $error } if $error;
2533 unless ( $p->{'svcpart'} eq 'none' ) {
2537 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2539 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2540 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2541 $svcdb = $part_svc->svcdb;
2543 $svcdb = 'svc_acct';
2545 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2548 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2549 'svc_domain' => [ qw( domain ) ],
2550 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2551 'svc_external' => [ qw( id title ) ],
2552 'svc_pbx' => [ qw( id title ) ],
2555 my $svc_x = "FS::$svcdb"->new( {
2556 'svcpart' => $svcpart,
2557 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2560 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2563 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2564 my $acct_snarf = new FS::acct_snarf ( {
2565 'machine' => $p->{"snarf_machine$snarfnum"},
2566 'protocol' => $p->{"snarf_protocol$snarfnum"},
2567 'username' => $p->{"snarf_username$snarfnum"},
2568 '_password' => $p->{"snarf_password$snarfnum"},
2571 push @acct_snarf, $acct_snarf;
2573 $svc_x->child_objects( \@acct_snarf );
2576 my $y = $svc_x->setdefault; # arguably should be in new method
2577 return { 'error' => $y } if $y && !ref($y);
2579 $error = $svc_x->check;
2580 return { 'error' => $error } if $error;
2586 $error = $cust_main->order_pkg(
2587 'cust_pkg' => $cust_pkg,
2592 return { 'error' => $error } if $error;
2594 my $conf = new FS::Conf;
2595 if ( $conf->exists('signup_server-realtime') ) {
2597 my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2600 $cust_pkg->cancel('quiet'=>1);
2603 $cust_pkg->reexport;
2607 $cust_pkg->reexport;
2610 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2612 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2619 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2620 return { 'error' => $session } if $context eq 'error';
2622 my $conf = new FS::Conf;
2623 my $immutable = $conf->exists('selfservice_immutable-package');
2624 return { 'error' => "Package modification disabled" } if $immutable;
2626 my $search = { 'custnum' => $custnum };
2627 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2628 my $cust_main = qsearchs('cust_main', $search )
2629 or return { 'error' => "unknown custnum $custnum" };
2631 my $status = $cust_main->status;
2632 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2633 or return { 'error' => "unknown package $p->{pkgnum}" };
2635 #if someone does need self-service package change of suspended packages,
2636 # figure out how to be more discriminating
2637 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2638 if $cust_pkg->status eq 'suspended';
2640 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2641 'quantity' => $p->{'quantity'} || 1,
2644 my $new_pkg = qsearchs('part_pkg', { 'pkgpart' => $p->{pkgpart} } )
2645 or return { 'error' => "unknown package $p->{pkgpart}" };
2647 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2648 unless ref($err_or_cust_pkg);
2651 if ( $conf->exists('signup_server-realtime') ) {
2653 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2656 $err_or_cust_pkg->suspend;
2659 $err_or_cust_pkg->reexport;
2663 $err_or_cust_pkg->reexport;
2666 return { error => '', pkg => $new_pkg->pkg, pkgnum => $err_or_cust_pkg->pkgnum };
2670 sub order_recharge {
2673 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2674 return { 'error' => $session } if $context eq 'error';
2676 my $search = { 'custnum' => $custnum };
2677 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2678 my $cust_main = qsearchs('cust_main', $search )
2679 or return { 'error' => "unknown custnum $custnum" };
2681 my $status = $cust_main->status;
2682 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2683 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2685 my $svc_x = $cust_svc->svc_x;
2686 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2689 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2690 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2691 recharge_totalbytes );
2692 my $amount = $part_pkg->option('recharge_amount', 1);
2694 my ($l, $v, $d) = $cust_svc->label; # blah
2695 my $pkg = "Recharge $v";
2697 my $bill_error = $cust_main->charge($amount, $pkg,
2698 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2699 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2700 $part_pkg->taxclass); #meh
2702 my $conf = new FS::Conf;
2703 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2705 $bill_error = _do_bop_realtime( $cust_main, $status );
2710 my $error = $svc_x->recharge (\%vhash);
2711 return { 'error' => $error } if $error;
2715 my $error = $bill_error;
2716 $error ||= $svc_x->recharge (\%vhash);
2717 return { 'error' => $error } if $error;
2720 return { error => '', svc => $cust_svc->part_svc->svc };
2724 sub _do_bop_realtime {
2725 my ($cust_main, $status, %opt) = @_;
2727 my $old_balance = $cust_main->balance;
2730 my $bill_error = $cust_main->bill(
2731 'return_bill' => \@cust_bill,
2734 $bill_error ||= $cust_main->apply_payments_and_credits;
2736 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2737 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2739 if ( $cust_main->balance > $old_balance
2740 && $cust_main->balance > 0
2741 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2742 || $status eq 'suspended'
2746 unless ( $opt{'no_invoice_void'} ) {
2748 #this used to apply a credit, but now we can void invoices...
2749 foreach my $cust_bill (@cust_bill) {
2750 my $voiderror = $cust_bill->void('automatic payment failed');
2751 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2756 return { 'error' => '_decline', 'bill_error' => $bill_error };
2759 if ( $opt{'collect'} ) {
2760 my $collect_error = $cust_main->collect();
2761 return { 'error' => '_decline', 'bill_error' => $collect_error }
2762 if $collect_error; #?
2771 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2772 return { 'error' => $session } if $context eq 'error';
2774 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2775 or return { 'error' => "unknown custnum $custnum" };
2777 my @cust_pkg = sort { $a->bill <=> $b->bill }
2778 grep { $_->part_pkg->freq ne '0' }
2779 $cust_main->ncancelled_pkgs;
2781 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2783 my $total = $cust_main->balance;
2786 my $bill = $_->bill;
2787 $total += $_->part_pkg->base_recur($_, \$bill);
2788 my $renew_date = $_->part_pkg->add_freq($_->bill);
2790 'pkgnum' => $_->pkgnum,
2791 'amount' => sprintf('%.2f', $total),
2792 'bill_date' => $_->bill,
2793 'bill_date_pretty' => time2str('%x', $_->bill),
2794 'renew_date' => $renew_date,
2795 'renew_date_pretty' => time2str('%x', $renew_date),
2796 'expire_date' => $_->expire,
2797 'expire_date_pretty' => time2str('%x', $_->expire),
2802 return { 'dates' => \@array };
2806 sub payment_info_renew_info {
2808 my $renew_info = renew_info($p);
2809 my $payment_info = payment_info($p);
2810 return { %$renew_info,
2818 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2819 return { 'error' => $session } if $context eq 'error';
2821 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2822 or return { 'error' => "unknown custnum $custnum" };
2824 my $date = $p->{'date'};
2828 #freeside-daily -n -d $date fs_daily $custnum
2829 $cust_main->bill_and_collect( 'time' => $date,
2830 'invoice_time' => $now,
2831 'actual_time' => $now,
2832 'check_freq' => '1d',
2835 return { 'error' => '' };
2841 my $session = _cache->get($p->{'session_id'})
2842 or return { 'error' => "Can't resume session" }; #better error message
2844 my $custnum = $session->{'custnum'};
2846 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2847 or return { 'error' => "unknown custnum $custnum" };
2849 my $conf = new FS::Conf;
2851 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2852 or return { 'error' => 'Permission denied' };
2854 my $pkgnum = $p->{'pkgnum'};
2856 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2857 'pkgnum' => $pkgnum, } )
2858 or return { 'error' => "unknown pkgnum $pkgnum" };
2860 my $error = $cust_pkg->suspend(reason => $reasonnum);
2861 return { 'error' => $error };
2867 my $session = _cache->get($p->{'session_id'})
2868 or return { 'error' => "Can't resume session" }; #better error message
2870 my $custnum = $session->{'custnum'};
2871 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2872 or return { 'error' => "unknown custnum $custnum" };
2874 my $pkgnum = $p->{'pkgnum'};
2875 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2876 'pkgnum' => $pkgnum, } )
2877 or return { 'error' => "unknown pkgnum $pkgnum" };
2879 my $error = $cust_pkg->cancel( 'quiet' => 1,
2880 'date' => $p->{'date'},
2882 return { 'error' => $error };
2885 sub provision_phone {
2888 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2890 #editing an existing phone number
2891 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2892 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2893 return { 'error' => $session } if $context eq 'error';
2895 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2896 return { 'error' => 'service not found' } unless $svc_phone;
2897 return { 'error' => 'invalid svcnum' }
2898 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2900 $svc_phone->email($p->{'email'})
2901 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2902 $svc_phone->forwarddst($p->{'forwarddst'})
2903 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2904 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2905 return { 'error' => $svc_phone->replace };
2909 unless ( $p->{'lnp'} ) {
2910 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2911 $p->{'lnp_status'} = "portingin";
2912 return _provision( 'FS::svc_phone',
2913 [qw(lnp_desired_due_date lnp_other_provider
2914 lnp_other_provider_account phonenum countrycode lnp_status)],
2915 [qw(phonenum countrycode)],
2921 # single DID order (the usual case)
2922 unless (scalar(@bulkdid)) {
2923 return _provision( 'FS::svc_phone',
2924 [qw(phonenum countrycode)],
2925 [qw(phonenum countrycode)],
2931 # bulk DID order case
2933 foreach my $did ( @bulkdid ) {
2934 $did =~ s/[^0-9]//g;
2935 $error = _provision( 'FS::svc_phone',
2936 [qw(phonenum countrycode)],
2937 [qw(phonenum countrycode)],
2939 'pkgnum' => $p->{'pkgnum'},
2940 'svcpart' => $p->{'svcpart'},
2942 'countrycode' => $p->{'countrycode'},
2943 'session_id' => $p->{'session_id'},
2946 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2948 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2953 warn "provision_pbx called\n"
2956 warn "provision_pbx calling _provision\n"
2958 _provision( 'FS::svc_pbx',
2959 [qw(id title max_extensions max_simultaneous ip_addr)],
2960 [qw(id title max_extensions max_simultaneous ip_addr)],
2966 sub provision_acct {
2968 warn "provision_acct called\n"
2971 return { 'error' => gettext('passwords_dont_match') }
2972 if $p->{'_password'} ne $p->{'_password2'};
2973 return { 'error' => gettext('empty_password') }
2974 unless length($p->{'_password'});
2976 if ($p->{'domsvc'}) {
2977 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2978 qw ( svcpart pkgnum ) );
2979 return { 'error' => gettext('invalid_domain') }
2980 unless ($domains{$p->{'domsvc'}});
2983 warn "provision_acct calling _provision\n"
2985 _provision( 'FS::svc_acct',
2986 [qw(username _password domsvc)],
2987 [qw(username _password domsvc)],
2993 sub provision_external {
2995 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2996 _provision( 'FS::svc_external',
3004 sub provision_forward {
3006 _provision( 'FS::svc_forward',
3007 ['srcsvc','src','dstsvc','dst'],
3014 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
3015 warn "_provision called for $class\n"
3018 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3019 return { 'error' => $session } if $context eq 'error';
3021 my $search = { 'custnum' => $custnum };
3022 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3023 my $cust_main = qsearchs('cust_main', $search )
3024 or return { 'error' => "unknown custnum $custnum" };
3026 my $pkgnum = $p->{'pkgnum'};
3028 warn "searching for custnum $custnum pkgnum $pkgnum\n"
3030 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3031 'pkgnum' => $pkgnum,
3033 or return { 'error' => "unknown pkgnum $pkgnum" };
3035 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
3037 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
3038 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
3040 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
3041 if $class ne 'FS::'. $part_svc->svcdb;
3043 warn "creating $class record\n"
3045 my $svc_x = $class->new( {
3046 'pkgnum' => $p->{'pkgnum'},
3047 'svcpart' => $p->{'svcpart'},
3048 map { $_ => $p->{$_} } @$fields
3051 my %insert_args = ();
3052 #i shouldn't be a special case here (pass an option or something)
3053 if ( $class eq 'FS::svc_phone'
3054 && grep length($p->{$_}), @location_editable_fields
3057 $insert_args{'cust_location'} = new FS::cust_location {
3058 map { $_ => $p->{$_} } @location_editable_fields
3062 warn "inserting $class record\n"
3064 my $error = $svc_x->insert(%insert_args);
3067 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
3069 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
3072 my $return = { 'svc' => $part_svc->svc,
3074 map { $_ => $svc_x->get($_) } @$return_fields
3076 warn "_provision returning ". Dumper($return). "\n"
3085 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3086 return { 'error' => $session } if $context eq 'error';
3088 my $search = { 'custnum' => $custnum };
3089 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3090 my $cust_main = qsearchs('cust_main', $search )
3091 or return { 'error' => "unknown custnum $custnum" };
3093 my $pkgnum = $p->{'pkgnum'};
3095 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3096 'pkgnum' => $pkgnum,
3098 or return { 'error' => "unknown pkgnum $pkgnum" };
3100 my $svcpart = $p->{'svcpart'};
3102 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
3103 'svcpart' => $svcpart, } )
3104 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
3105 my $part_svc = $pkg_svc->part_svc;
3107 my $conf = new FS::Conf;
3110 'svc' => $part_svc->svc,
3111 'svcdb' => $part_svc->svcdb,
3112 'pkgnum' => $pkgnum,
3113 'svcpart' => $svcpart,
3114 'custnum' => $custnum,
3116 'security_phrase' => 0, #XXX !
3117 'svc_acct_pop' => [], #XXX !
3119 'init_popstate' => '',
3124 small_custview( $cust_main, $conf->config('countrydefault') ),
3128 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
3129 && $ret->{'svcdb'} eq 'svc_phone') {
3130 $ret->{'svcnum'} = $p->{'svcnum'};
3131 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3132 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3133 $ret->{'email'} = $svc_phone->email;
3134 $ret->{'forwarddst'} = $svc_phone->forwarddst;
3138 if ($ret->{'svcdb'} eq 'svc_forward') {
3139 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3145 sub unprovision_svc {
3148 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3149 return { 'error' => $session } if $context eq 'error';
3151 my $search = { 'custnum' => $custnum };
3152 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3153 my $cust_main = qsearchs('cust_main', $search )
3154 or return { 'error' => "unknown custnum $custnum" };
3156 my $svcnum = $p->{'svcnum'};
3158 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
3159 or return { 'error' => "unknown svcnum $svcnum" };
3161 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3162 unless $cust_svc->cust_pkg->custnum == $custnum;
3164 my $conf = new FS::Conf;
3166 return { 'svc' => $cust_svc->part_svc->svc,
3167 'error' => $cust_svc->cancel,
3169 small_custview( $cust_main, $conf->config('countrydefault') ),
3174 sub myaccount_passwd {
3176 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3177 return { 'error' => $session } if $context eq 'error';
3179 return { 'error' => "New passwords don't match." }
3180 if $p->{'new_password'} ne $p->{'new_password2'};
3182 return { 'error' => 'Enter new password' }
3183 unless length($p->{'new_password'});
3185 #my $search = { 'custnum' => $custnum };
3186 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3187 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3188 my $search = " AND custnum = $1";
3189 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3191 my $svc_acct = qsearchs( {
3192 'table' => 'svc_acct',
3193 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3194 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3195 'LEFT JOIN cust_main USING ( custnum ) ',
3196 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3197 'extra_sql' => $search, #important
3199 or return { 'error' => "Service not found" };
3203 my $conf = new FS::Conf;
3205 return { 'error' => 'Incorrect current password.' }
3206 if ( exists($p->{'old_password'})
3207 || $conf->exists('selfservice-password_change_oldpass')
3209 && ! $svc_acct->check_password($p->{'old_password'});
3211 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3212 || $svc_acct->set_password($p->{'new_password'})
3213 || $svc_acct->replace();
3215 #regular pw change in self-service should change contact pw too, otherwise its
3216 #way too confusing. hell its confusing they're separate at all, but alas.
3217 #need to support the "ISP provides email that's used as a contact email" case
3219 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3220 if ( $contact && $contact->custnum == $custnum ) {
3221 #svc_acct was successful but this one returns an error? "shouldn't happen"
3222 #don't recheck is_password_allowed here; if the svc_acct password was
3223 #legal, that's good enough
3224 $error ||= $contact->change_password($p->{'new_password'});
3227 my($label, $value) = $svc_acct->cust_svc->label;
3229 return { 'error' => $error,
3239 my $info = skin_info($p);
3241 my $conf = new FS::Conf;
3242 my $verification = $conf->config('selfservice-password_reset_verification')
3243 or return { %$info, 'error' => 'Password resets disabled' };
3248 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3250 $contact = FS::contact->by_selfservice_email($p->{'email'});
3252 $cust_main = $contact->cust_main if $contact;
3254 #also look for an svc_acct, otherwise it would be super confusing
3256 my($username, $domain) = split('@', $p->{'email'});
3257 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3258 if ( $svc_domain ) {
3259 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3260 'domsvc' => $svc_domain->svcnum }
3263 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3264 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3266 #precaution: don't change svc_acct password not part of the same
3267 # customer as contact
3268 $svc_acct = '' if ! $cust_pkg
3269 || $cust_pkg->custnum != $cust_main->custnum;
3274 return { %$info, 'error' => 'Email address not found' }
3275 unless $contact || $svc_acct;
3277 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3279 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3280 or return { %$info, 'error' => 'Account not found' };
3282 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3283 'domsvc' => $svc_domain->svcnum }
3285 or return { %$info, 'error' => 'Account not found' };
3287 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3288 or return { %$info, 'error' => 'Account not found' };
3290 $cust_main = $cust_pkg->cust_main;
3295 'email' => sub { 1; },
3297 my( $p, $cust_main ) = @_;
3298 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3299 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3302 my( $p, $cust_main ) = @_;
3303 my $cust_pay = qsearchs({
3304 'table' => 'cust_pay',
3305 'hashref' => { 'custnum' => $cust_main->custnum },
3306 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3310 $p->{'amount'} == $cust_pay->paid;
3313 my( $p, $cust_main ) = @_;
3314 $p->{'zip'} eq $cust_main->zip
3315 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3319 foreach my $verify ( split(',', $verification) ) {
3321 &{ $verify{$verify} }( $p, $cust_main )
3322 or return { %$info, 'error' => 'Account not found' };
3326 #okay, we're verified
3330 my $error = $contact->send_reset_email(
3331 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3335 return { %$info, 'error' => $error }; #????
3338 } elsif ( $svc_acct ) {
3340 #create a unique session
3342 my $reset_session = {
3343 'svcnum' => $svc_acct->svcnum,
3344 'agentnum' => $svc_acct->cust_main->agentnum,
3347 my $timeout = '1 hour'; #?
3349 my $reset_session_id;
3351 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3352 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3355 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3359 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3360 $cust_main->agentnum);
3361 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3362 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3364 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3365 my $error = $msg_template->send( 'cust_main' => $cust_main,
3366 'object' => $svc_acct,
3367 'substitutions' => {
3368 'session_id' => $reset_session_id,
3372 return { %$info, 'error' => $error }; #????
3377 return { %$info, 'error' => '' };
3380 sub check_reset_passwd {
3383 my $conf = new FS::Conf;
3384 my $verification = $conf->config('selfservice-password_reset_verification')
3385 or return { 'error' => 'Password resets disabled' };
3387 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3388 or return { 'error' => "Can't resume session" }; #better error message
3390 if ( $reset_session->{'svcnum'} ) {
3392 my $svcnum = $reset_session->{'svcnum'};
3394 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3395 or return { 'error' => "Service not found" };
3397 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3398 my $info = skin_info($p);
3402 'session_id' => $p->{'session_id'},
3403 'username' => $svc_acct->username,
3406 } elsif ( $reset_session->{'contactnum'} ) {
3408 my $contactnum = $reset_session->{'contactnum'};
3410 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3411 or return { 'error' => "Contact not found" };
3413 my @contact_email = $contact->contact_email;
3414 return { 'error' => 'No contact email' } unless @contact_email;
3416 $p->{'agentnum'} = $contact->cust_main->agentnum;
3417 my $info = skin_info($p);
3421 'session_id' => $p->{'session_id'},
3422 'email' => $contact_email[0]->email, #the first?
3427 return { 'error' => 'No svcnum or contactnum in session' }; #??
3433 sub process_reset_passwd {
3436 my $conf = new FS::Conf;
3437 my $verification = $conf->config('selfservice-password_reset_verification')
3438 or return { 'error' => 'Password resets disabled' };
3440 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3441 or return { 'error' => "Can't resume session" }; #better error message
3446 if ( $reset_session->{'svcnum'} ) {
3448 my $svcnum = $reset_session->{'svcnum'};
3450 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3451 or return { 'error' => "Service not found" };
3453 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3454 $info ||= skin_info($p);
3459 if ( $reset_session->{'contactnum'} ) {
3461 my $contactnum = $reset_session->{'contactnum'};
3463 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3464 or return { 'error' => "Contact not found" };
3466 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3467 $info ||= skin_info($p);
3471 return { %$info, 'error' => "New passwords don't match." }
3472 if $p->{'new_password'} ne $p->{'new_password2'};
3474 return { %$info, 'error' => 'Enter new password' }
3475 unless length($p->{'new_password'});
3479 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3480 || $svc_acct->set_password($p->{'new_password'})
3481 || $svc_acct->replace();
3483 return { %$info, 'error' => $error } if $error;
3485 #my($label, $value) = $svc_acct->cust_svc->label;
3486 #return { 'error' => $error,
3487 # #'label' => $label,
3488 # #'value' => $value,
3495 my $error = $contact->is_password_allowed($p->{'new_password'})
3496 || $contact->change_password($p->{'new_password'});
3498 return { %$info, 'error' => $error }; # if $error;
3502 #password changed ,so remove session, don't want it reused
3503 _cache->remove($p->{'session_id'});
3505 return { %$info, 'error' => '' };
3509 sub validate_passwd {
3513 %result = ( 'fieldid' => $p->{'fieldid'} )
3514 if $p->{'fieldid'} =~ /^\w+$/;
3516 return { %result, 'password_invalid' => 'Enter new password' }
3517 unless length($p->{'check_password'});
3520 if ($p->{'svcnum'}) {
3521 # false laziness with myaccount_passwd
3522 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3523 return { %result, 'error' => $session } if $context eq 'error';
3525 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3526 my $search = " AND custnum = $1";
3527 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3529 $svc_acct = qsearchs( {
3530 'table' => 'svc_acct',
3531 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3532 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3533 'LEFT JOIN cust_main USING ( custnum ) ',
3534 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3535 'extra_sql' => $search, #important
3537 or return { %result, 'error' => "Service not found" };
3538 # end false laziness
3541 unless ($svc_acct) {
3542 my $conf = new FS::Conf;
3543 my $agentnum = $p->{'agentnum'};
3544 return { %result, 'password_valid' => 1 }
3545 if $conf->config_bool('password-insecure', $p->{'agentnum'});
3548 $svc_acct ||= new FS::svc_acct {};
3550 my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3551 return { %result, 'password_invalid' => $error } if $error;
3552 return { %result, 'password_valid' => 1 };
3557 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3558 return { 'error' => $session } if $context eq 'error';
3561 if ( $session->{'pkgnum'} ) {
3563 #tickets for specific service with pkg-balances on
3564 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3565 'pkgnum' => $session->{'pkgnum'} })
3566 or return { 'error' => 'unknown package' };
3567 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3568 push @tickets, $cust_svc->tickets( $p->{status} );
3573 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3574 or return { 'error' => "unknown custnum $custnum" };
3576 @tickets = $cust_main->tickets( $p->{status} );
3579 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3580 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3581 my $conf = new FS::Conf;
3582 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3586 ($a->{'_selfservice_priority'} eq '') <=>
3587 ($b->{'_selfservice_priority'} eq '')
3590 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3596 +{ tickets => \@tickets };
3603 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3604 return { 'error' => $session } if $context eq 'error';
3606 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3607 FS::TicketSystem->init();
3609 my $conf = new FS::Conf;
3610 my $queue = $p->{'queue'}
3611 || $conf->config('ticket_system-selfservice_queueid')
3612 || $conf->config('ticket_system-default_queueid');
3614 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3615 my $err_or_ticket = FS::TicketSystem->create_ticket(
3616 '', #create RT session based on FS CurrentUser (fs_selfservice)
3618 'custnum' => $custnum,
3619 'svcnum' => $session->{'svcnum'},
3620 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3623 if ( ref($err_or_ticket) ) {
3624 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3626 return { 'error' => '',
3627 'ticket_id' => $err_or_ticket->id,
3630 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3632 return { 'error' => $err_or_ticket };
3640 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3641 return { 'error' => $session } if $context eq 'error';
3643 return { error => 'requested format not implemented' }
3644 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3646 my $conf = new FS::Conf;
3647 my $age_threshold = 0;
3648 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3649 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3651 my $search = { 'custnum' => $custnum };
3652 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3653 my $cust_main = qsearchs('cust_main', $search )
3654 or return { 'error' => "unknown custnum $custnum" };
3656 # does it make more sense to just run one sql query for this instead of all the
3657 # insanity below? would increase performance greately for large data sets?
3659 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3660 my @part_svc = $cust_pkg->part_svc;
3661 foreach my $part_svc ( @part_svc ) {
3662 if($part_svc->svcdb eq 'svc_phone'){
3663 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3664 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3665 push @svc_phone, $cust_pkg_svc->svc_x
3666 if $cust_pkg_svc->date_inserted >= $age_threshold;
3674 my($xls_r,$xls_c) = (0,0);
3677 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3678 if($p->{'format'} eq 'csv') {
3679 $csv = new Text::CSV_XS { 'always_quote' => 1,
3682 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3683 $content .= $csv->string;
3685 elsif($p->{'format'} eq 'xls') {
3686 my $XLS1 = new IO::Scalar \$content;
3687 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3688 or return { 'error' => "Error opening .xls file: $!" };
3689 $xls = $xls_workbook->add_worksheet('DIDs');
3690 foreach ( @fields ) {
3691 $xls->write(0,$xls_c++,$_);
3696 foreach my $svc_phone ( @svc_phone ) {
3697 my @cols = map { $svc_phone->$_ } @fields;
3698 if($p->{'format'} eq 'csv') {
3699 return { 'error' => 'Unable to create CSV' }
3700 unless $csv->combine(@cols);
3701 $content .= $csv->string;
3703 elsif($p->{'format'} eq 'xls') {
3706 $xls->write($xls_r,$xls_c++,$_);
3712 $xls_workbook->close() if $p->{'format'} eq 'xls';
3714 { content => $content, format => $p->{'format'}, };
3719 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3720 return { 'error' => $session } if $context eq 'error';
3722 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3723 # FS::TicketSystem->init();
3724 # return { 'error' => 'get_ticket configuration error' }
3725 # if $FS::TicketSystem::system ne 'RT_Internal';
3727 # check existence and ownership as part of this
3728 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3729 my $rt_session = FS::TicketSystem->session('');
3730 my $Ticket = FS::TicketSystem->get_ticket_object(
3732 ticket_id => $p->{'ticket_id'},
3735 return { 'error' => 'ticket not found' } if !$Ticket;
3737 if ( length( $p->{'subject'} || '' ) ) {
3739 if ( $p->{'subject'} ne $Ticket->Subject ) {
3740 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3741 return { 'error' => "unable to set subject: $msg" } if !$val;
3745 if(length($p->{'reply'})) {
3746 my @err_or_res = FS::TicketSystem->correspond_ticket(
3748 'ticket_id' => $p->{'ticket_id'},
3749 'content' => $p->{'reply'},
3752 return { 'error' => 'unable to reply to ticket' }
3753 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3756 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3757 my $err_or_ticket = FS::TicketSystem->get_ticket(
3759 'ticket_id' => $p->{'ticket_id'},
3762 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3763 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3765 return { 'error' => $err_or_ticket };
3768 my @custs = @{$err_or_ticket->{'custs'}};
3769 my @txns = @{$err_or_ticket->{'txns'}};
3772 # superseded by check in get_ticket_object
3773 #return { 'error' => 'invalid ticket requested' }
3774 #unless grep($_ eq $custnum, @custs);
3776 foreach my $txn ( @txns ) {
3777 push @filtered_txns, $txn
3778 if ($txn->{'type'} eq 'EmailRecord'
3779 || $txn->{'type'} eq 'Correspond'
3780 || $txn->{'type'} eq 'Create');
3783 warn "$me get_ticket: successful: \n"
3785 return { 'error' => '',
3786 'transactions' => \@filtered_txns,
3787 'ticket_fields' => $err_or_ticket->{'fields'},
3788 'ticket_id' => $p->{'ticket_id'},
3792 sub adjust_ticket_priority {
3794 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3795 return { 'error' => $session } if $context eq 'error';
3797 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3798 # FS::TicketSystem->init;
3799 my $ss_priority = FS::TicketSystem->selfservice_priority;
3801 return { 'error' => 'adjust_ticket_priority configuration error' }
3802 if $FS::TicketSystem::system ne 'RT_Internal'
3805 my $values = $p->{'values'}; #hashref, id => priority value
3808 foreach my $id (keys %$values) {
3809 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3810 my $Ticket = FS::TicketSystem->get_ticket_object('',
3812 'custnum' => $custnum,
3815 $ticket_error{$id} = 'ticket not found';
3819 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3820 # We're not going to implement it for RT_External.
3821 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3822 my $new_value = $values->{$id};
3823 next if $old_value eq $new_value;
3825 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3827 # AddCustomFieldValue works fine (replacing any existing value) if it's
3828 # a single-valued custom field, which it should be. If it's not, you're
3829 # doing something wrong.
3831 if ( length($new_value) ) {
3832 ($val, $msg) = $Ticket->AddCustomFieldValue(
3833 Field => $ss_priority,
3834 Value => $new_value,
3838 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3839 Field => $ss_priority,
3840 Value => $old_value,
3844 $ticket_error{$id} = $msg if !$val;
3845 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3847 return { 'error' => '',
3848 'ticket_error' => \%ticket_error,
3849 %{ customer_info($p) } # send updated customer info back
3855 sub _custoragent_session_custnum {
3858 my($context, $session, $custnum);
3859 if ( $p->{'session_id'} ) {
3861 $context = 'customer';
3862 $session = _cache->get($p->{'session_id'})
3863 or return ( 'error' => "Can't resume session" ); #better error message
3864 $custnum = $session->{'custnum'};
3866 } elsif ( $p->{'agent_session_id'} ) {
3869 my $agent_cache = new FS::ClientAPI_SessionCache( {
3870 'namespace' => 'FS::ClientAPI::Agent',
3872 $session = $agent_cache->get($p->{'agent_session_id'})
3873 or return ( 'error' => "Can't resume session" ); #better error message
3874 $custnum = $p->{'custnum'};
3878 return ( 'error' => "Can't resume session" ); #better error message
3881 ($context, $session, $custnum);