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);
12 use Time::Local qw(timelocal_nocheck);
13 use Business::CreditCard;
16 use Spreadsheet::WriteExcel;
17 use FS::UI::Web::small_custview qw(small_custview); #less doh
19 use FS::UI::bytecount qw( display_bytecount );
22 use FS::Record qw(qsearch qsearchs dbh);
23 use FS::Msgcat qw(gettext);
24 use FS::Misc qw(card_types);
25 use FS::Misc::DateTime qw(parse_datetime);
27 use FS::ClientAPI_SessionCache;
39 use FS::legacy_cust_bill;
40 use FS::cust_main_county;
43 use FS::acct_rt_transaction;
47 $me = '[FS::ClientAPI::MyAccount]';
49 use vars qw( @cust_main_editable_fields );
50 @cust_main_editable_fields = qw(
51 first last company address1 address2 city
52 county state zip country
53 daytime night fax mobile
54 ship_first ship_last ship_company ship_address1 ship_address2 ship_city
55 ship_state ship_zip ship_country
56 ship_daytime ship_night ship_fax ship_mobile
58 payby payinfo payname paystart_month paystart_year payissue payip
59 ss paytype paystate stateid stateid_state
62 BEGIN { #preload to reduce time customer_info takes
63 if ( $FS::TicketSystem::system ) {
64 warn "$me: initializing ticket system\n" if $DEBUG;
65 FS::TicketSystem->init();
70 $cache ||= new FS::ClientAPI_SessionCache( {
71 'namespace' => 'FS::ClientAPI::MyAccount',
78 my($context, $session, $custnum) = _custoragent_session_custnum($p);
79 #return { 'error' => $session } if $context eq 'error';
82 if ( $context eq 'customer' ) {
84 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
87 $sth->execute($custnum) or die $sth->errstr;
89 $agentnum = $sth->fetchrow_arrayref->[0]
90 or die "no agentnum for custnum $custnum";
92 #} elsif ( $context eq 'agent' ) {
93 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
97 my $conf = new FS::Conf;
99 #false laziness w/Signup.pm
101 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
103 if ( $skin_info_cache_agent ) {
105 warn "$me loading cached skin info for agentnum $agentnum\n"
110 warn "$me populating skin info cache for agentnum $agentnum\n"
113 $skin_info_cache_agent = {
114 'agentnum' => $agentnum,
115 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
116 qw( company_name date_format ) ),
117 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
118 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
119 text_color link_color vlink_color hlink_color alink_color
120 font title_color title_align title_size menu_bgcolor menu_fontsize
123 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
124 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
126 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
127 qw( title_left_image title_right_image
128 menu_top_image menu_body_image menu_bottom_image
131 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
132 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
133 qw( head body_header body_footer company_address ) ),
136 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
140 #{ %$skin_info_cache_agent };
141 $skin_info_cache_agent;
148 my $conf = new FS::Conf;
152 'phone_login' => $conf->exists('selfservice_server-phone_login'),
153 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
154 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
155 'banner_image_md5' =>
156 md5_hex($conf->config_binary('selfservice-login_banner_image')),
163 sub login_banner_image {
165 my $conf = new FS::Conf;
166 my $image = $conf->config_binary('selfservice-login_banner_image');
168 'md5' => md5_hex($image),
173 #false laziness w/FS::ClientAPI::passwd::passwd
177 my $conf = new FS::Conf;
180 if ( $p->{'domain'} eq 'svc_phone'
181 && $conf->exists('selfservice_server-phone_login') ) {
183 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
184 return { error => 'Number not found.' } unless $svc_phone;
187 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
188 #return { error => 'Only primary user may log in.' }
189 # if $conf->exists('selfservice_server-primary_only')
190 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
192 return { error => 'Incorrect PIN.' }
193 unless $svc_phone->check_pin($p->{'password'});
201 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
202 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
204 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
205 'domsvc' => $svc_domain->svcnum, }
207 return { error => 'User not found.' } unless $svc_acct;
209 if($conf->exists('selfservice_server-login_svcpart')) {
210 my @svcpart = $conf->config('selfservice_server-login_svcpart');
211 my $svcpart = $svc_acct->cust_svc->svcpart;
212 return { error => 'Invalid user.' }
213 unless grep($_ eq $svcpart, @svcpart);
216 return { error => 'Incorrect password.' }
217 unless $svc_acct->check_password($p->{'password'});
224 'svcnum' => $svc_x->svcnum,
227 my $cust_svc = $svc_x->cust_svc;
228 my $cust_pkg = $cust_svc->cust_pkg;
230 my $cust_main = $cust_pkg->cust_main;
231 $session->{'custnum'} = $cust_main->custnum;
232 if ( $conf->exists('pkg-balances') ) {
233 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
234 $cust_main->ncancelled_pkgs;
235 $session->{'pkgnum'} = $cust_pkg->pkgnum
236 if scalar(@cust_pkg) > 1;
240 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
241 #return { error => 'Only primary user may log in.' }
242 # if $conf->exists('selfservice_server-primary_only')
243 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
244 my $part_pkg = $cust_pkg->part_pkg;
245 return { error => 'Only primary user may log in.' }
246 if $conf->exists('selfservice_server-primary_only')
247 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
251 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
252 } until ( ! defined _cache->get($session_id) ); #just in case
254 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
255 _cache->set( $session_id, $session, $timeout );
257 return { 'error' => '',
258 'session_id' => $session_id,
264 if ( $p->{'session_id'} ) {
265 _cache->remove($p->{'session_id'});
266 return { %{ skin_info($p) }, 'error' => '' };
268 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
275 my($context, $session, $custnum) = _custoragent_session_custnum($p);
276 return { 'error' => $session } if $context eq 'error';
278 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
279 or return { 'error' => "Service not found" };
281 $session->{'svcnum'} = $svc_acct->svcnum;
283 my $conf = new FS::Conf;
284 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
285 _cache->set( $p->{'session_id'}, $session, $timeout );
287 return { 'error' => '' };
291 sub payment_gateway {
293 # takes a cust_main and a cust_payby entry, returns the payment_gateway
294 my $conf = new FS::Conf;
295 my $cust_main = shift;
296 my $cust_payby = shift;
297 my $gatewaynum = $conf->config('selfservice-payment_gateway');
299 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
300 die "configured gatewaynum $gatewaynum not found!" if !$pg;
304 return '' if ! FS::payby->realtime($cust_payby);
305 my $pg = $cust_main->agent->payment_gateway(
306 'method' => FS::payby->payby2bop($cust_payby),
316 my $conf = new FS::Conf;
318 my $info = skin_info($p);
320 use vars qw( $cust_paybys ); #cache for performance
321 unless ( $cust_paybys ) {
323 my %cust_paybys = map { $_ => 1 }
324 map { FS::payby->payby2payment($_) }
325 $conf->config('signup_server-payby');
327 $cust_paybys = [ keys %cust_paybys ];
330 $info->{'cust_paybys'} = $cust_paybys;
332 my($context, $session, $custnum) = _custoragent_session_custnum($p);
333 return { 'error' => $session } if $context eq 'error';
335 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
336 or return { 'error' => "unknown custnum $custnum" };
338 $info->{'hide_payment_fields'} = [
340 my $pg = payment_gateway($cust_main, $_);
341 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
342 } @{ $info->{cust_paybys} }
345 $info->{'self_suspend_reason'} =
346 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
348 $info->{'edit_ticket_subject'} =
349 $conf->exists('ticket_system-selfservice_edit_subject') &&
350 $cust_main->edit_subject;
353 'custnum' => $custnum,
354 'access_pkgnum' => $session->{'pkgnum'},
355 'access_svcnum' => $session->{'svcnum'},
362 my($context, $session, $custnum) = _custoragent_session_custnum($p);
363 return { 'error' => $session } if $context eq 'error';
367 my $conf = new FS::Conf;
368 if ($conf->exists('cust_main-require_address2')) {
369 $return{'require_address2'} = '1';
371 $return{'require_address2'} = '';
374 if ( $FS::TicketSystem::system ) {
375 warn "$me customer_info: initializing ticket system\n" if $DEBUG;
376 FS::TicketSystem->init();
379 if ( $custnum ) { #customer record
381 my $search = { 'custnum' => $custnum };
382 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
383 my $cust_main = qsearchs('cust_main', $search )
384 or return { 'error' => "unknown custnum $custnum" };
386 if ( $session->{'pkgnum'} ) {
387 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
388 #next_bill_date from cust_pkg?
390 $return{balance} = $cust_main->balance;
391 $return{next_bill_date} = $cust_main->next_bill_date;
392 $return{next_bill_date_pretty} =
393 time2str('%m/%d/%Y', $return{next_bill_date} );
396 my @tickets = $cust_main->tickets;
397 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
398 if ( FS::TicketSystem->selfservice_priority ) {
399 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
403 ($a->{'_selfservice_priority'} eq '') <=>
404 ($b->{'_selfservice_priority'} eq '')
407 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
413 $return{tickets} = \@tickets;
416 unless ( $session->{'pkgnum'} ) {
419 invnum => $_->invnum,
420 date => time2str("%b %o, %Y", $_->_date),
423 } $cust_main->open_cust_bill;
424 $return{open_invoices} = \@open;
427 $return{countrydefault} = scalar($conf->config('countrydefault'));
429 $return{small_custview} =
430 small_custview( $cust_main,
431 $return{countrydefault},
432 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
435 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
436 $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
438 $return{has_ship_address} = $cust_main->has_ship_address;
439 $return{status} = $cust_main->status;
440 $return{statuscolor} = $cust_main->statuscolor;
442 for (@cust_main_editable_fields) {
443 $return{$_} = $cust_main->get($_);
446 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
447 $return{payinfo} = $cust_main->paymask;
448 @return{'month', 'year'} = $cust_main->paydate_monthyear;
451 $return{'invoicing_list'} =
452 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
453 $return{'postal_invoicing'} =
454 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
456 if (scalar($conf->config('support_packages'))) {
457 my @support_services = ();
458 foreach ($cust_main->support_services) {
459 my $seconds = $_->svc_x->seconds;
460 my $time_remaining = (($seconds < 0) ? '-' : '' ).
461 int(abs($seconds)/3600)."h".
462 sprintf("%02d",(abs($seconds)%3600)/60)."m";
463 my $cust_pkg = $_->cust_pkg;
466 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
467 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
468 push @support_services, { svcnum => $_->svcnum,
469 time => $time_remaining,
474 $return{support_services} = \@support_services;
477 if ( $conf->config('prepayment_discounts-credit_type') ) {
479 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
482 if ( $session->{'svcnum'} ) {
483 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
484 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
485 $return{'svcnum'} = $session->{'svcnum'};
488 } elsif ( $session->{'svcnum'} ) { #no customer record
490 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
491 or die "unknown svcnum";
492 $return{name} = $svc_acct->email;
496 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
500 return { 'error' => '',
501 'custnum' => $custnum,
507 sub customer_info_short {
510 my($context, $session, $custnum) = _custoragent_session_custnum($p);
511 return { 'error' => $session } if $context eq 'error';
515 my $conf = new FS::Conf;
517 if ( $custnum ) { #customer record
519 my $search = { 'custnum' => $custnum };
520 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
521 my $cust_main = qsearchs('cust_main', $search )
522 or return { 'error' => "unknown custnum $custnum" };
524 $return{countrydefault} = scalar($conf->config('countrydefault'));
526 $return{small_custview} =
527 small_custview( $cust_main,
528 $return{countrydefault},
532 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
533 $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
535 $return{payby} = $cust_main->payby;
537 #none of these are terribly expensive if we want 'em...
538 for (@cust_main_editable_fields) {
539 $return{$_} = $cust_main->get($_);
542 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
543 $return{payinfo} = $cust_main->paymask;
544 @return{'month', 'year'} = $cust_main->paydate_monthyear;
547 $return{'invoicing_list'} =
548 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
549 #$return{'postal_invoicing'} =
550 # 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
552 if ( $session->{'svcnum'} ) {
553 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
554 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
555 $return{'svcnum'} = $session->{'svcnum'};
558 } elsif ( $session->{'svcnum'} ) { #no customer record
560 #uuh, not supproted yet... die?
561 return { 'error' => 'customer_info_short not yet supported as agent' };
565 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
569 return { 'error' => '',
570 'custnum' => $custnum,
575 sub billing_history {
578 my($context, $session, $custnum) = _custoragent_session_custnum($p);
579 return { 'error' => $session } if $context eq 'error';
581 return { 'error' => 'No customer' } unless $custnum;
583 my $search = { 'custnum' => $custnum };
584 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
585 my $cust_main = qsearchs('cust_main', $search )
586 or return { 'error' => "unknown custnum $custnum" };
590 if ( $session->{'pkgnum'} ) {
591 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
592 #next_bill_date from cust_pkg?
593 return { 'error' => 'No history for package' };
596 $return{balance} = $cust_main->balance;
597 $return{next_bill_date} = $cust_main->next_bill_date;
598 $return{next_bill_date_pretty} =
599 time2str('%m/%d/%Y', $return{next_bill_date} );
603 my $conf = new FS::Conf;
605 if ( $conf->exists('selfservice-billing_history-line_items') ) {
607 foreach my $cust_bill ( $cust_main->cust_bill ) {
610 'type' => 'Line item',
611 'description' => $_->desc. ( $_->sdate && $_->edate
612 ? ' '. time2str('%d-%b-%Y', $_->sdate).
613 ' To '. time2str('%d-%b-%Y', $_->edate)
616 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
617 'date' => $cust_bill->_date,
618 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
620 foreach $cust_bill->cust_bill_pkg;
628 'description' => 'Invoice #'. $_->display_invnum,
629 'amount' => sprintf('%.2f', $_->charged ),
631 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
633 foreach $cust_main->cust_bill;
639 'description' => 'Payment', #XXX type
640 'amount' => sprintf('%.2f', 0 - $_->paid ),
642 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
644 foreach $cust_main->cust_pay;
648 'description' => 'Credit', #more info?
649 'amount' => sprintf('%.2f', 0 -$_->amount ),
651 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
653 foreach $cust_main->cust_credit;
657 'description' => 'Refund', #more info? type, like payment?
658 'amount' => $_->refund,
660 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
662 foreach $cust_main->cust_refund;
664 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
666 $return{'history'} = \@history;
674 my $session = _cache->get($p->{'session_id'})
675 or return { 'error' => "Can't resume session" }; #better error message
677 my $custnum = $session->{'custnum'}
678 or return { 'error' => "no customer record" };
680 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
681 or return { 'error' => "unknown custnum $custnum" };
683 my $new = new FS::cust_main { $cust_main->hash };
684 # Avoid accidentally changing the service address.
685 if ( !$new->has_ship_address ) {
686 $new->set( $_ => $new->get($_) )
687 foreach $new->addr_fields;
690 $new->set( $_ => $p->{$_} )
691 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
694 if (exists($p->{'payby'})) {
695 $p->{'payby'} =~ /^([A-Z]{4})$/
696 or return { 'error' => "illegal_payby " . $p->{'payby'} };
700 if ( $payby =~ /^(CARD|DCRD)$/ ) {
702 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
704 if ( $new->payinfo eq $cust_main->paymask ) {
705 $new->payinfo($cust_main->payinfo);
707 $new->payinfo($p->{'payinfo'});
710 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
712 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
715 $p->{'payinfo1'} =~ /^([\dx]+)$/
716 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
718 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
719 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
721 $payinfo = $payinfo1. '@'. $payinfo2;
723 $new->payinfo( ($payinfo eq $cust_main->paymask)
724 ? $cust_main->payinfo
728 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
730 } elsif ( $payby =~ /^(BILL)$/ ) {
732 } elsif ( $payby ) { #notyet ready
733 return { 'error' => "unknown payby $payby" };
737 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
738 #false laziness with httemplate/edit/process/cust_main.cgi
739 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
740 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
742 @invoicing_list = $cust_main->invoicing_list;
745 my $error = $new->replace($cust_main, \@invoicing_list);
746 return { 'error' => $error } if $error;
749 return { 'error' => '' };
754 my $session = _cache->get($p->{'session_id'})
755 or return { 'error' => "Can't resume session" }; #better error message
761 my $conf = new FS::Conf;
762 use vars qw($payment_info); #cache for performance
763 unless ( $payment_info ) {
765 my %states = map { $_->state => 1 }
766 qsearch('cust_main_county', {
767 'country' => $conf->config('countrydefault') || 'US'
770 my %cust_paybys = map { $_ => 1 }
771 map { FS::payby->payby2payment($_) }
772 $conf->config('signup_server-payby');
774 my @cust_paybys = keys %cust_paybys;
778 #list all counties/states/countries
779 'cust_main_county' =>
780 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
782 #shortcut for one-country folks
784 [ sort { $a cmp $b } keys %states ],
786 'card_types' => card_types(),
788 'paytypes' => [ @FS::cust_main::paytypes ],
790 'paybys' => [ $conf->config('signup_server-payby') ],
791 'cust_paybys' => \@cust_paybys,
793 'stateid_label' => FS::Msgcat::_gettext('stateid'),
794 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
796 'show_ss' => $conf->exists('show_ss'),
797 'show_stateid' => $conf->exists('show_stateid'),
798 'show_paystate' => $conf->exists('show_bankstate'),
800 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
802 'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
811 my %return = %$payment_info;
813 my $custnum = $session->{'custnum'};
815 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
816 or return { 'error' => "unknown custnum $custnum" };
818 $return{'hide_payment_fields'} = [
820 my $pg = payment_gateway($cust_main, $_);
821 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
822 } @{ $return{cust_paybys} }
825 $return{balance} = $cust_main->balance; #XXX pkg-balances?
827 $return{payname} = $cust_main->payname
828 || ( $cust_main->first. ' '. $cust_main->get('last') );
830 $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
832 $return{payby} = $cust_main->payby;
833 $return{stateid_state} = $cust_main->stateid_state;
835 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
836 $return{card_type} = cardtype($cust_main->payinfo);
837 $return{payinfo} = $cust_main->paymask;
839 @return{'month', 'year'} = $cust_main->paydate_monthyear;
843 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
844 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
845 $return{payinfo1} = $payinfo1;
846 $return{payinfo2} = $payinfo2;
847 $return{paytype} = $cust_main->paytype;
848 $return{paystate} = $cust_main->paystate;
849 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
852 if ( $conf->config('prepayment_discounts-credit_type') ) {
854 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
857 #doubleclick protection
859 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
861 return { 'error' => '',
867 #some false laziness with httemplate/process/payment.cgi - look there for
868 #ACH and CVV support stuff
870 sub validate_payment {
873 my $session = _cache->get($p->{'session_id'})
874 or return { 'error' => "Can't resume session" }; #better error message
876 my $custnum = $session->{'custnum'};
878 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
879 or return { 'error' => "unknown custnum $custnum" };
881 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
882 or return { 'error' => gettext('illegal_amount') };
884 return { error => 'Amount must be greater than 0' } unless $amount > 0;
886 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
887 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
888 my $discount_term = $1;
890 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
891 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
894 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
895 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
898 $p->{'payby'} ||= 'CARD';
899 $p->{'payby'} =~ /^([A-Z]{4})$/
900 or return { 'error' => "illegal_payby " . $p->{'payby'} };
903 #false laziness w/process/payment.cgi
906 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
908 $p->{'payinfo1'} =~ /^([\dx]+)$/
909 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
911 $p->{'payinfo2'} =~ /^([\dx]+)$/
912 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
914 $payinfo = $payinfo1. '@'. $payinfo2;
916 $payinfo = $cust_main->payinfo
917 if $cust_main->paymask eq $payinfo;
919 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
921 $payinfo = $p->{'payinfo'};
923 #more intelligent matching will be needed here if you change
924 #card_masking_method and don't remove existing paymasks
925 $payinfo = $cust_main->payinfo
926 if $cust_main->paymask eq $payinfo;
929 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
930 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
934 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
935 return { 'error' => gettext('unknown_card_type') }
936 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
938 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
939 if ( cardtype($payinfo) eq 'American Express card' ) {
940 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
941 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
944 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
945 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
951 die "unknown payby $payby";
955 'CARD' => [ qw( paystart_month paystart_year payissue payip
956 address1 address2 city state zip country ) ],
957 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
961 $card_type = cardtype($payinfo) if $payby eq 'CARD';
964 'cust_main' => $cust_main, #XXX or just custnum??
967 'payinfo' => $payinfo,
968 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
969 'card_type' => $card_type,
970 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
971 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
972 'payname' => $payname,
973 'paybatch' => $paybatch, #this doesn't actually do anything
975 'payname' => $payname,
976 'discount_term' => $discount_term,
977 'pkgnum' => $session->{'pkgnum'},
978 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
988 my $validate = validate_payment($p);
989 return $validate if $validate->{'error'};
991 my $conf = new FS::Conf;
992 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
993 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
995 +{ map { $_=>$validate->{$_} }
996 qw( card_type paymask payname paydate_pretty amount )
1001 sub process_stored_payment {
1004 my $session_id = $p->{'session_id'};
1006 my $payment_info = _cache->get( "payment_$session_id" )
1007 or return { 'error' => "Can't resume session" }; #better error message
1009 do_process_payment($payment_info);
1013 sub process_payment {
1016 my $payment_info = validate_payment($p);
1017 return $payment_info if $payment_info->{'error'};
1019 do_process_payment($payment_info);
1023 sub do_process_payment {
1024 my $validate = shift;
1026 my $cust_main = $validate->{'cust_main'};
1028 my $amount = delete $validate->{'amount'};
1031 my $payby = delete $validate->{'payby'};
1033 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1036 'paynum_ref' => \$paynum,
1039 return { 'error' => $error } if $error;
1041 $cust_main->apply_payments;
1043 if ( $validate->{'save'} ) {
1044 my $new = new FS::cust_main { $cust_main->hash };
1045 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1046 $new->set( $_ => $validate->{$_} )
1047 foreach qw( payname paystart_month paystart_year payissue payip );
1048 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1050 # Avoid accidentally changing the service address.
1051 if ( !$new->has_ship_address ) {
1052 $new->set( "ship_$_" => $new->get($_) )
1053 foreach $new->addr_fields;
1055 $new->set( $_ => $validate->{$_} )
1056 foreach qw(address1 address2 city state country zip);
1058 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1059 $new->set( $_ => $validate->{$_} )
1060 foreach qw( payname payip paytype paystate
1061 stateid stateid_state );
1062 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1064 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1065 $new->set( 'paydate' => $validate->{'paydate'} );
1066 my $error = $new->replace($cust_main);
1068 #no, this causes customers to process their payments again
1069 #return { 'error' => $error };
1070 #XXX just warn verosely for now so i can figure out how these happen in
1071 # the first place, eventually should redirect them to the "change
1072 #address" page but indicate the payment did process??
1073 delete($validate->{'payinfo'}); #don't want to log this!
1074 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1075 "NEW: ". Dumper($new)."\n".
1076 "OLD: ". Dumper($cust_main)."\n".
1077 "PACKET: ". Dumper($validate)."\n";
1085 my $receipt_html = '';
1087 # currently supported for realtime CC only; send receipt data to SS
1088 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1091 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1094 <TD ALIGN="right">Payment#</TD>
1095 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1099 <TD ALIGN="right">Date</TD>
1101 <TD BGCOLOR="#FFFFFF"><B>! .
1102 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1108 <TD ALIGN="right">Amount</TD>
1109 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1114 <TD ALIGN="right">Payment method</TD>
1115 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1126 my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
1130 'amount' => sprintf('%.2f', $cust_pay->paid),
1131 'date' => $cust_pay->_date,
1132 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1133 'time_pretty' => time2str('%T', $cust_pay->_date),
1134 'auth_num' => $auth,
1135 'order_num' => $order,
1136 'receipt_html' => $receipt_html,
1143 'receipt_html' => '',
1150 sub realtime_collect {
1153 my $session = _cache->get($p->{'session_id'})
1154 or return { 'error' => "Can't resume session" }; #better error message
1156 my $custnum = $session->{'custnum'};
1158 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1159 or return { 'error' => "unknown custnum $custnum" };
1162 if ( $p->{'amount'} ) {
1163 $amount = $p->{'amount'};
1165 elsif ( $session->{'pkgnum'} ) {
1166 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1169 $amount = $cust_main->balance;
1172 my $error = $cust_main->realtime_collect(
1173 'method' => $p->{'method'},
1174 'amount' => $amount,
1175 'pkgnum' => $session->{'pkgnum'},
1176 'session_id' => $p->{'session_id'},
1180 return { 'error' => $error } unless ref( $error );
1182 return { 'error' => '', amount => $amount, %$error };
1185 sub process_payment_order_pkg {
1188 my $hr = process_payment($p);
1189 return $hr if $hr->{'error'};
1194 sub process_payment_order_renew {
1197 my $hr = process_payment($p);
1198 return $hr if $hr->{'error'};
1203 sub process_prepay {
1207 my $session = _cache->get($p->{'session_id'})
1208 or return { 'error' => "Can't resume session" }; #better error message
1212 my $custnum = $session->{'custnum'};
1214 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1215 or return { 'error' => "unknown custnum $custnum" };
1217 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1218 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1226 return { 'error' => $error } if $error;
1228 return { 'error' => '',
1229 'amount' => $amount,
1230 'seconds' => $seconds,
1231 'duration' => duration_exact($seconds),
1232 'upbytes' => $upbytes,
1233 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1234 'downbytes' => $downbytes,
1235 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1236 'totalbytes'=> $totalbytes,
1237 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1244 my $session = _cache->get($p->{'session_id'})
1245 or return { 'error' => "Can't resume session" }; #better error message
1247 my $custnum = $session->{'custnum'};
1249 my $invnum = $p->{'invnum'};
1251 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1252 'custnum' => $custnum } )
1253 or return { 'error' => "Can't find invnum" };
1257 return { 'error' => '',
1258 'invnum' => $invnum,
1259 'invoice_text' => join('', $cust_bill->print_text ),
1260 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1267 my $session = _cache->get($p->{'session_id'})
1268 or return { 'error' => "Can't resume session" }; #better error message
1270 my $custnum = $session->{'custnum'};
1272 my $invnum = $p->{'invnum'};
1274 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1275 'custnum' => $custnum } )
1276 or return { 'error' => "Can't find invnum" };
1280 return { 'error' => '',
1281 'invnum' => $invnum,
1282 'invoice_pdf' => $cust_bill->print_pdf({
1283 'unsquelch_cdr' => 1,
1284 'locale' => $p->{'locale'},
1290 sub legacy_invoice {
1292 my $session = _cache->get($p->{'session_id'})
1293 or return { 'error' => "Can't resume session" }; #better error message
1295 my $custnum = $session->{'custnum'};
1297 my $legacyinvnum = $p->{'legacyinvnum'};
1300 'legacyinvnum' => $legacyinvnum,
1301 'custnum' => $custnum,
1304 my $legacy_cust_bill =
1305 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1306 || qsearchs('legacy_cust_bill', \%hash )
1307 or return { 'error' => "Can't find legacyinvnum" };
1311 return { 'error' => '',
1312 'legacyinvnum' => $legacyinvnum,
1313 'legacyid' => $legacy_cust_bill->legacyid,
1314 'invoice_html' => $legacy_cust_bill->content_html,
1319 sub legacy_invoice_pdf {
1321 my $session = _cache->get($p->{'session_id'})
1322 or return { 'error' => "Can't resume session" }; #better error message
1324 my $custnum = $session->{'custnum'};
1326 my $legacyinvnum = $p->{'legacyinvnum'};
1328 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1329 'legacyinvnum' => $legacyinvnum,
1330 'custnum' => $custnum,
1331 }) or return { 'error' => "Can't find legacyinvnum" };
1335 return { 'error' => '',
1336 'legacyinvnum' => $legacyinvnum,
1337 'legacyid' => $legacy_cust_bill->legacyid,
1338 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1346 #sessioning for this? how do we get the session id to the backend invoice
1347 # template so it can add it to the link, blah
1350 if ( $p->{'invnum'} ) {
1351 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1352 or return { 'error' => 'unknown invnum' };
1353 $agentnum = $cust_bill->cust_main->agentnum;
1356 my $templatename = $p->{'template'} || $p->{'templatename'};
1358 #false laziness-ish w/view/cust_bill-logo.cgi
1360 my $conf = new FS::Conf;
1361 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1362 $templatename = "_$1";
1367 my $filename = "logo$templatename.png";
1369 return { 'error' => '',
1370 'logo' => $conf->config_binary($filename, $agentnum),
1371 'content_type' => 'image/png', #should allow gif, jpg too
1378 my $session = _cache->get($p->{'session_id'})
1379 or return { 'error' => "Can't resume session" }; #better error message
1381 my $custnum = $session->{'custnum'};
1383 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1384 or return { 'error' => "unknown custnum $custnum" };
1386 my $conf = new FS::Conf;
1388 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1390 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1394 return { 'error' => '',
1395 'balance' => $cust_main->balance,
1398 my $owed = $_->owed;
1400 +{ 'invnum' => $_->invnum,
1401 '_date' => $_->_date,
1402 'date' => time2str("%b %o, %Y", $_->_date),
1403 'date_short' => time2str("%m-%d-%Y", $_->_date),
1404 'previous' => sprintf('%.2f', ($_->previous)[0]),
1405 'charged' => sprintf('%.2f', $_->charged),
1406 'owed' => sprintf('%.2f', $owed),
1407 'balance' => sprintf('%.2f', $balance),
1412 'legacy_invoices' => [
1414 +{ 'legacyinvnum' => $_->legacyinvnum,
1415 'legacyid' => $_->legacyid,
1416 '_date' => $_->_date,
1417 'date' => time2str("%b %o, %Y", $_->_date),
1418 'date_short' => time2str("%m-%d-%Y", $_->_date),
1419 'charged' => sprintf('%.2f', $_->charged),
1420 'has_content' => ( length($_->content_pdf)
1421 || length($_->content_html) ),
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 $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1437 or return { 'error' => "unknown custnum $custnum" };
1439 my @errors = $cust_main->cancel( 'quiet'=>1 );
1441 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1443 return { 'error' => $error };
1450 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1451 return { 'error' => $session } if $context eq 'error';
1453 my $search = { 'custnum' => $custnum };
1454 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1455 my $cust_main = qsearchs('cust_main', $search )
1456 or return { 'error' => "unknown custnum $custnum" };
1458 my $conf = new FS::Conf;
1460 # the duplication below is necessary:
1461 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1462 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1463 # non-backwards-compatible change breaking the software of anyone using the API
1464 # instead of the stock selfservice
1465 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1466 if( $conf->exists('selfservice_server-view-wholesale') ) {
1467 return { 'svcnum' => $session->{'svcnum'},
1468 'custnum' => $custnum,
1469 'cust_pkg' => [ map {
1471 part_pkg => [ map $_->hashref, $_->part_pkg ],
1473 [ map $_->hashref, $_->available_part_svc ],
1475 [ map { my $ref = { $_->hash,
1476 label => [ $_->label ],
1478 $ref->{_password} = $_->svc_x->_password
1479 if $context eq 'agent'
1480 && $conf->exists('agent-showpasswords')
1481 && $_->part_svc->svcdb eq 'svc_acct';
1486 } $cust_main->cust_pkg
1489 small_custview( $cust_main, $conf->config('countrydefault') ),
1490 'wholesale_view' => 1,
1491 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1492 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1493 'lnp' => $conf->exists('svc_phone-lnp'),
1497 { 'svcnum' => $session->{'svcnum'},
1498 'custnum' => $custnum,
1499 'cust_pkg' => [ map {
1500 my $primary_cust_svc = $_->primary_cust_svc;
1503 status => $_->status,
1505 [ map $_->hashref, $_->available_part_svc ],
1507 [ map { my $ref = { $_->hash,
1508 label => [ $_->label ],
1510 $ref->{_password} = $_->svc_x->_password
1511 if $context eq 'agent'
1512 && $conf->exists('agent-showpasswords')
1513 && $_->part_svc->svcdb eq 'svc_acct';
1514 $ref->{svchash} = { $_->svc_x->hash } if
1515 $_->part_svc->svcdb eq 'svc_phone';
1516 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1517 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1523 ? { $primary_cust_svc->hash,
1524 label => [ $primary_cust_svc->label ],
1525 finger => $primary_cust_svc->svc_x->finger, #uuh
1526 $primary_cust_svc->part_svc->hash,
1530 } $cust_main->ncancelled_pkgs
1533 small_custview( $cust_main, $conf->config('countrydefault') ),
1541 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1542 return { 'error' => $session } if $context eq 'error';
1544 my $search = { 'custnum' => $custnum };
1545 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1546 my $cust_main = qsearchs('cust_main', $search )
1547 or return { 'error' => "unknown custnum $custnum" };
1549 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1550 if ( ! $pkgnum && $p->{'svcnum'} ) {
1551 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1552 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1556 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1557 foreach my $cust_pkg ( $p->{'ncancelled'}
1558 ? $cust_main->ncancelled_pkgs
1559 : $cust_main->unsuspended_pkgs ) {
1560 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1561 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1564 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1566 if ( $p->{'svcdb'} ) {
1567 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1569 : ref($p->{'svcdb'}) eq 'ARRAY'
1570 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1571 : { $p->{'svcdb'} => 1 };
1572 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1575 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1578 my $conf = new FS::Conf;
1581 'svcnum' => $session->{'svcnum'},
1582 'custnum' => $custnum,
1583 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1584 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1587 my $svc_x = $_->svc_x;
1588 my($label, $value) = $_->label;
1589 my $part_svc = $_->part_svc;
1590 my $svcdb = $part_svc->svcdb;
1591 my $cust_pkg = $_->cust_pkg;
1592 my $part_pkg = $cust_pkg->part_pkg;
1595 'svcnum' => $_->svcnum,
1599 'pkg_status' => $cust_pkg->status,
1600 'readonly' => ( $part_svc->selfservice_access eq 'readonly' ),
1603 if ( $svcdb eq 'svc_acct' ) {
1606 'username' => $svc_x->username,
1607 'email' => $svc_x->email,
1608 'finger' => $svc_x->finger,
1609 'seconds' => $svc_x->seconds,
1610 'upbytes' => display_bytecount($svc_x->upbytes),
1611 'downbytes' => display_bytecount($svc_x->downbytes),
1612 'totalbytes' => display_bytecount($svc_x->totalbytes),
1614 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1615 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1616 'recharge_upbytes' =>
1617 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1618 'recharge_downbytes' =>
1619 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1620 'recharge_totalbytes' =>
1621 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1625 } elsif ( $svcdb eq 'svc_dsl' ) {
1626 $hash{'phonenum'} = $svc_x->phonenum;
1627 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1628 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1629 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1632 $hash{'name'} = $cust_main->name;
1635 # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1649 sub _customer_svc_x {
1650 my($custnum, $svcnum, $table) = (shift, shift, shift);
1651 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1653 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1654 my $search = " AND custnum = $1";
1655 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1658 'table' => ($table || 'svc_acct'),
1659 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1660 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1661 #'LEFT JOIN cust_main USING ( custnum ) ',
1662 'hashref' => $hashref,
1663 'extra_sql' => $search, #important
1668 sub svc_status_html {
1671 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1672 return { 'error' => $session } if $context eq 'error';
1674 #XXX only svc_dsl for now
1675 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1676 or return { 'error' => "Service not found" };
1678 my $html = $svc_x->getstatus_html;
1680 return { 'html' => $html };
1684 sub svc_status_hash {
1687 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1688 return { 'error' => $session } if $context eq 'error';
1690 #XXX only svc_acct for now
1691 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1692 or return { 'error' => "Service not found" };
1694 my ( $html, $hashref ) = $svc_x->export_getstatus;
1699 sub set_svc_status_hash {
1702 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1703 return { 'error' => $session } if $context eq 'error';
1705 #XXX only svc_acct for now
1706 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1707 or return { 'error' => "Service not found" };
1709 warn "set_svc_status_hash ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1711 my $error = $svc_x->export_setstatus($p); #$p? returns error?
1712 return { 'error' => $error } if $error;
1714 return {}; #? { 'error' => '' }
1719 sub acct_forward_info {
1722 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1723 return { 'error' => $session } if $context eq 'error';
1725 my $svc_forward = _customer_svc_x( $custnum,
1726 { 'srcsvc' => $p->{'svcnum'} },
1729 or return { 'error' => '',
1733 return { 'error' => '',
1734 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1739 sub process_acct_forward {
1741 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1742 return { 'error' => $session } if $context eq 'error';
1744 my $old = _customer_svc_x( $custnum,
1745 { 'srcsvc' => $p->{'svcnum'} },
1749 if ( $p->{'dst'} eq '' ) {
1751 my $error = $old->delete;
1752 return { 'error' => $error };
1754 return { 'error' => '' };
1757 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1758 'dst' => $p->{'dst'},
1763 $new->svcnum($old->svcnum);
1764 my $cust_svc = $old->cust_svc;
1765 $new->svcpart($old->svcpart);
1766 $new->pkgnuym($old->pkgnum);
1767 $error = $new->replace($old);
1769 my $conf = new FS::Conf;
1770 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1772 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1773 or return { 'error' => 'No service' }; #how would we even get here?
1775 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
1777 $error = $new->insert;
1780 return { 'error' => $error };
1784 sub list_dsl_devices {
1787 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1788 return { 'error' => $session } if $context eq 'error';
1790 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1791 or return { 'error' => "Service not found" };
1794 'devices' => [ map {
1795 +{ 'mac_addr' => $_->mac_addr };
1796 } $svc_dsl->dsl_device
1802 sub add_dsl_device {
1805 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1806 return { 'error' => $session } if $context eq 'error';
1808 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1809 or return { 'error' => "Service not found" };
1811 return { 'error' => 'No MAC address supplied' }
1812 unless length($p->{'mac_addr'});
1814 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
1815 'mac_addr' => scalar($p->{'mac_addr'}),
1817 my $error = $dsl_device->insert;
1818 return { 'error' => $error };
1822 sub delete_dsl_device {
1825 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1826 return { 'error' => $session } if $context eq 'error';
1828 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1829 or return { 'error' => "Service not found" };
1831 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
1832 'mac_addr' => scalar($p->{'mac_addr'}),
1835 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
1837 my $error = $dsl_device->delete;
1838 return { 'error' => $error };
1844 _usage_details( \&_port_graph, $p,
1845 'svcdb' => 'svc_port',
1850 my($svc_port, $begin, $end) = @_;
1852 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1853 push @usage, { 'png' => $pngOrError };
1857 sub _list_svc_usage {
1858 my($svc_acct, $begin, $end) = @_;
1860 foreach my $part_export (
1861 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1862 qw( sqlradius sqlradius_withdomain )
1864 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1869 sub list_svc_usage {
1870 _usage_details(\&_list_svc_usage, @_);
1873 sub _list_support_usage {
1874 my($svc_acct, $begin, $end) = @_;
1876 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1877 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1879 push @usage, { 'seconds' => $_->seconds,
1880 'support' => $_->support,
1881 '_date' => $_->_date,
1882 'id' => $_->transaction_id,
1883 'creator' => $_->creator,
1884 'subject' => $_->subject,
1885 'status' => $_->status,
1886 'ticketid' => $_->ticketid,
1892 sub list_support_usage {
1893 _usage_details(\&_list_support_usage, @_);
1896 sub _list_cdr_usage {
1897 # XXX CDR type support...
1898 my($svc_phone, $begin, $end, %opt) = @_;
1899 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
1900 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1903 sub list_cdr_usage {
1905 _usage_details( \&_list_cdr_usage, $p,
1906 'svcdb' => 'svc_phone',
1910 sub _usage_details {
1911 my($callback, $p, %opt) = @_;
1913 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1914 return { 'error' => $session } if $context eq 'error';
1916 my $search = { 'svcnum' => $p->{'svcnum'} };
1917 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1919 my $svcdb = $opt{'svcdb'} || 'svc_acct';
1921 my $svc_x = qsearchs( $svcdb, $search );
1922 return { 'error' => 'No service selected in list_svc_usage' }
1925 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1926 my $freq = $cust_pkg->part_pkg->freq;
1929 if ( $svcdb eq 'svc_phone' ) {
1930 my $format = $cust_pkg->part_pkg->option('output_format') || '';
1931 $format = '' if $format =~ /^sum_/;
1932 # sensible default if there is no format or it's a summary format
1933 if ( $cust_pkg->part_pkg->plan eq 'voip_inbound' ) {
1934 $format ||= 'source_default';
1935 $callback_opt{inbound} = 1;
1938 $format ||= 'default';
1941 $callback_opt{format} = $format;
1942 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
1945 my $start = $cust_pkg->setup;
1946 #my $end = $cust_pkg->bill; # or time?
1949 unless ( $p->{beginning} ) {
1950 $p->{beginning} = $cust_pkg->last_bill;
1951 $p->{ending} = $end;
1954 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
1958 #kinda false laziness with FS::cust_main::bill, but perhaps
1959 #we should really change this bit to DateTime and DateTime::Duration
1961 #change this bit to use Date::Manip? CAREFUL with timezones (see
1962 # mailing list archive)
1963 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1964 (localtime($p->{ending}) )[0,1,2,3,4,5];
1965 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1966 (localtime($p->{beginning}) )[0,1,2,3,4,5];
1968 if ( $freq =~ /^\d+$/ ) {
1970 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1972 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1973 } elsif ( $freq =~ /^(\d+)w$/ ) {
1975 $nmday += $weeks * 7;
1976 $pmday -= $weeks * 7;
1977 } elsif ( $freq =~ /^(\d+)d$/ ) {
1981 } elsif ( $freq =~ /^(\d+)h$/ ) {
1986 return { 'error' => "unparsable frequency: ". $freq };
1989 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1990 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1994 'svcnum' => $p->{svcnum},
1995 'beginning' => $p->{beginning},
1996 'ending' => $p->{ending},
1997 'previous' => ($previous > $start) ? $previous : $start,
1998 'next' => ($next < $end) ? $next : $end,
1999 'header' => $header,
2007 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2008 return { 'error' => $session } if $context eq 'error';
2010 my $search = { 'custnum' => $custnum };
2011 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2012 my $cust_main = qsearchs('cust_main', $search )
2013 or return { 'error' => "unknown custnum $custnum" };
2015 my $status = $cust_main->status;
2016 #false laziness w/ClientAPI/Signup.pm
2018 my $cust_pkg = new FS::cust_pkg ( {
2019 'custnum' => $custnum,
2020 'pkgpart' => $p->{'pkgpart'},
2022 my $error = $cust_pkg->check;
2023 return { 'error' => $error } if $error;
2026 unless ( $p->{'svcpart'} eq 'none' ) {
2030 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2032 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2033 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2034 $svcdb = $part_svc->svcdb;
2036 $svcdb = 'svc_acct';
2038 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2041 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2042 'svc_domain' => [ qw( domain ) ],
2043 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2044 'svc_external' => [ qw( id title ) ],
2045 'svc_pbx' => [ qw( id title ) ],
2048 my $svc_x = "FS::$svcdb"->new( {
2049 'svcpart' => $svcpart,
2050 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2053 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2056 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2057 my $acct_snarf = new FS::acct_snarf ( {
2058 'machine' => $p->{"snarf_machine$snarfnum"},
2059 'protocol' => $p->{"snarf_protocol$snarfnum"},
2060 'username' => $p->{"snarf_username$snarfnum"},
2061 '_password' => $p->{"snarf_password$snarfnum"},
2064 push @acct_snarf, $acct_snarf;
2066 $svc_x->child_objects( \@acct_snarf );
2069 my $y = $svc_x->setdefault; # arguably should be in new method
2070 return { 'error' => $y } if $y && !ref($y);
2072 $error = $svc_x->check;
2073 return { 'error' => $error } if $error;
2080 tie my %hash, 'Tie::RefHash';
2081 %hash = ( $cust_pkg => \@svc );
2083 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2084 return { 'error' => $error } if $error;
2086 my $conf = new FS::Conf;
2087 if ( $conf->exists('signup_server-realtime') ) {
2089 my $bill_error = _do_bop_realtime( $cust_main, $status );
2092 $cust_pkg->cancel('quiet'=>1);
2095 $cust_pkg->reexport;
2099 $cust_pkg->reexport;
2102 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2104 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2111 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2112 return { 'error' => $session } if $context eq 'error';
2114 my $search = { 'custnum' => $custnum };
2115 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2116 my $cust_main = qsearchs('cust_main', $search )
2117 or return { 'error' => "unknown custnum $custnum" };
2119 my $status = $cust_main->status;
2120 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2121 or return { 'error' => "unknown package $p->{pkgnum}" };
2124 my $error = FS::cust_pkg::order( $custnum,
2130 my $conf = new FS::Conf;
2131 if ( $conf->exists('signup_server-realtime') ) {
2133 my $bill_error = _do_bop_realtime( $cust_main, $status );
2136 $newpkg[0]->suspend;
2139 $newpkg[0]->reexport;
2143 $newpkg[0]->reexport;
2146 return { error => '', pkgnum => $cust_pkg->pkgnum };
2150 sub order_recharge {
2153 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2154 return { 'error' => $session } if $context eq 'error';
2156 my $search = { 'custnum' => $custnum };
2157 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2158 my $cust_main = qsearchs('cust_main', $search )
2159 or return { 'error' => "unknown custnum $custnum" };
2161 my $status = $cust_main->status;
2162 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2163 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2165 my $svc_x = $cust_svc->svc_x;
2166 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2169 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2170 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2171 recharge_totalbytes );
2172 my $amount = $part_pkg->option('recharge_amount', 1);
2174 my ($l, $v, $d) = $cust_svc->label; # blah
2175 my $pkg = "Recharge $v";
2177 my $bill_error = $cust_main->charge($amount, $pkg,
2178 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2179 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2180 $part_pkg->taxclass); #meh
2182 my $conf = new FS::Conf;
2183 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2185 $bill_error = _do_bop_realtime( $cust_main, $status );
2190 my $error = $svc_x->recharge (\%vhash);
2191 return { 'error' => $error } if $error;
2195 my $error = $bill_error;
2196 $error ||= $svc_x->recharge (\%vhash);
2197 return { 'error' => $error } if $error;
2200 return { error => '', svc => $cust_svc->part_svc->svc };
2204 sub _do_bop_realtime {
2205 my ($cust_main, $status) = (shift, shift);
2207 my $old_balance = $cust_main->balance;
2209 my $bill_error = $cust_main->bill
2210 || $cust_main->apply_payments_and_credits
2211 || $cust_main->realtime_collect('selfservice' => 1);
2213 if ( $cust_main->balance > $old_balance
2214 && $cust_main->balance > 0
2215 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
2216 1 : $status eq 'suspended' ) ) {
2217 #this makes sense. credit is "un-doing" the invoice
2218 my $conf = new FS::Conf;
2219 $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
2220 'self-service decline',
2221 'reason_type' => $conf->config('signup_credit_type'),
2223 $cust_main->apply_credits( 'order' => 'newest' );
2225 return { 'error' => '_decline', 'bill_error' => $bill_error };
2234 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2235 return { 'error' => $session } if $context eq 'error';
2237 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2238 or return { 'error' => "unknown custnum $custnum" };
2240 my @cust_pkg = sort { $a->bill <=> $b->bill }
2241 grep { $_->part_pkg->freq ne '0' }
2242 $cust_main->ncancelled_pkgs;
2244 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2246 my $total = $cust_main->balance;
2249 my $bill = $_->bill;
2250 $total += $_->part_pkg->base_recur($_, \$bill);
2251 my $renew_date = $_->part_pkg->add_freq($_->bill);
2253 'pkgnum' => $_->pkgnum,
2254 'amount' => sprintf('%.2f', $total),
2255 'bill_date' => $_->bill,
2256 'bill_date_pretty' => time2str('%x', $_->bill),
2257 'renew_date' => $renew_date,
2258 'renew_date_pretty' => time2str('%x', $renew_date),
2259 'expire_date' => $_->expire,
2260 'expire_date_pretty' => time2str('%x', $_->expire),
2265 return { 'dates' => \@array };
2269 sub payment_info_renew_info {
2271 my $renew_info = renew_info($p);
2272 my $payment_info = payment_info($p);
2273 return { %$renew_info,
2281 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2282 return { 'error' => $session } if $context eq 'error';
2284 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2285 or return { 'error' => "unknown custnum $custnum" };
2287 my $date = $p->{'date'};
2291 #freeside-daily -n -d $date fs_daily $custnum
2292 $cust_main->bill_and_collect( 'time' => $date,
2293 'invoice_time' => $now,
2294 'actual_time' => $now,
2295 'check_freq' => '1d',
2298 return { 'error' => '' };
2304 my $session = _cache->get($p->{'session_id'})
2305 or return { 'error' => "Can't resume session" }; #better error message
2307 my $custnum = $session->{'custnum'};
2309 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2310 or return { 'error' => "unknown custnum $custnum" };
2312 my $conf = new FS::Conf;
2314 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2315 or return { 'error' => 'Permission denied' };
2317 my $pkgnum = $p->{'pkgnum'};
2319 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2320 'pkgnum' => $pkgnum, } )
2321 or return { 'error' => "unknown pkgnum $pkgnum" };
2323 my $error = $cust_pkg->suspend(reason => $reasonnum);
2324 return { 'error' => $error };
2330 my $session = _cache->get($p->{'session_id'})
2331 or return { 'error' => "Can't resume session" }; #better error message
2333 my $custnum = $session->{'custnum'};
2335 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2336 or return { 'error' => "unknown custnum $custnum" };
2338 my $pkgnum = $p->{'pkgnum'};
2340 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2341 'pkgnum' => $pkgnum, } )
2342 or return { 'error' => "unknown pkgnum $pkgnum" };
2344 my $error = $cust_pkg->cancel('quiet' => 1);
2345 return { 'error' => $error };
2349 sub provision_phone {
2352 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2354 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2355 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2356 return { 'error' => $session } if $context eq 'error';
2358 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2359 return { 'error' => 'service not found' } unless $svc_phone;
2360 return { 'error' => 'invalid svcnum' }
2361 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2363 $svc_phone->email($p->{'email'})
2364 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2365 $svc_phone->forwarddst($p->{'forwarddst'})
2366 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2367 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2368 return { 'error' => $svc_phone->replace };
2372 unless($p->{'lnp'}) {
2373 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2374 $p->{'lnp_status'} = "portingin";
2375 return _provision( 'FS::svc_phone',
2376 [qw(lnp_desired_due_date lnp_other_provider
2377 lnp_other_provider_account phonenum countrycode lnp_status)],
2378 [qw(phonenum countrycode)],
2385 unless (scalar(@bulkdid)) {
2386 return _provision( 'FS::svc_phone',
2387 [qw(phonenum countrycode)],
2388 [qw(phonenum countrycode)],
2394 # bulk DID order case
2396 foreach my $did ( @bulkdid ) {
2397 $did =~ s/[^0-9]//g;
2398 $error = _provision( 'FS::svc_phone',
2399 [qw(phonenum countrycode)],
2400 [qw(phonenum countrycode)],
2402 'pkgnum' => $p->{'pkgnum'},
2403 'svcpart' => $p->{'svcpart'},
2405 'countrycode' => $p->{'countrycode'},
2406 'session_id' => $p->{'session_id'},
2409 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2411 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2414 sub provision_acct {
2416 warn "provision_acct called\n"
2419 return { 'error' => gettext('passwords_dont_match') }
2420 if $p->{'_password'} ne $p->{'_password2'};
2421 return { 'error' => gettext('empty_password') }
2422 unless length($p->{'_password'});
2424 if ($p->{'domsvc'}) {
2425 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2426 qw ( svcpart pkgnum ) );
2427 return { 'error' => gettext('invalid_domain') }
2428 unless ($domains{$p->{'domsvc'}});
2431 warn "provision_acct calling _provision\n"
2433 _provision( 'FS::svc_acct',
2434 [qw(username _password domsvc)],
2435 [qw(username _password domsvc)],
2441 sub provision_external {
2443 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2444 _provision( 'FS::svc_external',
2453 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2454 warn "_provision called for $class\n"
2457 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2458 return { 'error' => $session } if $context eq 'error';
2460 my $search = { 'custnum' => $custnum };
2461 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2462 my $cust_main = qsearchs('cust_main', $search )
2463 or return { 'error' => "unknown custnum $custnum" };
2465 my $pkgnum = $p->{'pkgnum'};
2467 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2469 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2470 'pkgnum' => $pkgnum,
2472 or return { 'error' => "unknown pkgnum $pkgnum" };
2474 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2476 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2477 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2479 warn "creating $class record\n"
2481 my $svc_x = $class->new( {
2482 'pkgnum' => $p->{'pkgnum'},
2483 'svcpart' => $p->{'svcpart'},
2484 map { $_ => $p->{$_} } @$fields
2486 warn "inserting $class record\n"
2488 my $error = $svc_x->insert;
2491 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2493 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2496 my $return = { 'svc' => $part_svc->svc,
2498 map { $_ => $svc_x->get($_) } @$return_fields
2500 warn "_provision returning ". Dumper($return). "\n"
2509 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2510 return { 'error' => $session } if $context eq 'error';
2512 my $search = { 'custnum' => $custnum };
2513 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2514 my $cust_main = qsearchs('cust_main', $search )
2515 or return { 'error' => "unknown custnum $custnum" };
2517 my $pkgnum = $p->{'pkgnum'};
2519 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2520 'pkgnum' => $pkgnum,
2522 or return { 'error' => "unknown pkgnum $pkgnum" };
2524 my $svcpart = $p->{'svcpart'};
2526 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2527 'svcpart' => $svcpart, } )
2528 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2529 my $part_svc = $pkg_svc->part_svc;
2531 my $conf = new FS::Conf;
2534 'svc' => $part_svc->svc,
2535 'svcdb' => $part_svc->svcdb,
2536 'pkgnum' => $pkgnum,
2537 'svcpart' => $svcpart,
2538 'custnum' => $custnum,
2540 'security_phrase' => 0, #XXX !
2541 'svc_acct_pop' => [], #XXX !
2543 'init_popstate' => '',
2548 small_custview( $cust_main, $conf->config('countrydefault') ),
2552 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2553 && $ret->{'svcdb'} eq 'svc_phone') {
2554 $ret->{'svcnum'} = $p->{'svcnum'};
2555 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2556 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2557 $ret->{'email'} = $svc_phone->email;
2558 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2565 sub unprovision_svc {
2568 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2569 return { 'error' => $session } if $context eq 'error';
2571 my $search = { 'custnum' => $custnum };
2572 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2573 my $cust_main = qsearchs('cust_main', $search )
2574 or return { 'error' => "unknown custnum $custnum" };
2576 my $svcnum = $p->{'svcnum'};
2578 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2579 or return { 'error' => "unknown svcnum $svcnum" };
2581 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2582 unless $cust_svc->cust_pkg->custnum == $custnum;
2584 my $conf = new FS::Conf;
2586 return { 'svc' => $cust_svc->part_svc->svc,
2587 'error' => $cust_svc->cancel,
2589 small_custview( $cust_main, $conf->config('countrydefault') ),
2594 sub myaccount_passwd {
2596 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2597 return { 'error' => $session } if $context eq 'error';
2599 return { 'error' => "New passwords don't match." }
2600 if $p->{'new_password'} ne $p->{'new_password2'};
2602 return { 'error' => 'Enter new password' }
2603 unless length($p->{'new_password'});
2605 #my $search = { 'custnum' => $custnum };
2606 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2607 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2608 my $search = " AND custnum = $1";
2609 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2611 my $svc_acct = qsearchs( {
2612 'table' => 'svc_acct',
2613 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2614 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2615 'LEFT JOIN cust_main USING ( custnum ) ',
2616 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2617 'extra_sql' => $search, #important
2619 or return { 'error' => "Service not found" };
2621 if ( exists($p->{'old_password'}) ) {
2622 return { 'error' => "Incorrect password." }
2623 unless $svc_acct->check_password($p->{'old_password'});
2626 $svc_acct->set_password($p->{'new_password'});
2627 my $error = $svc_acct->replace();
2629 my($label, $value) = $svc_acct->cust_svc->label;
2631 return { 'error' => $error,
2641 my $conf = new FS::Conf;
2642 my $verification = $conf->config('selfservice-password_reset_verification')
2643 or return { 'error' => 'Password resets disabled' };
2645 my $username = $p->{'username'};
2647 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2648 or return { 'error' => 'Account not found' };
2650 my $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2651 'domsvc' => $svc_domain->svcnum }
2653 or return { 'error' => 'Account not found' };
2655 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2656 or return { 'error' => 'Account not found' };
2658 my $cust_main = $cust_pkg->cust_main;
2662 my( $p, $cust_main ) = @_;
2663 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2664 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2667 my( $p, $cust_main ) = @_;
2668 my $cust_pay = qsearchs({
2669 'table' => 'cust_pay',
2670 'hashref' => { 'custnum' => $cust_main->custnum },
2671 'order_by' => 'ORDER BY _date DESC LIMIT 1',
2675 $p->{'amount'} == $cust_pay->paid;
2678 my( $p, $cust_main ) = @_;
2679 $p->{'zip'} eq $cust_main->zip
2680 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2684 foreach my $verify ( split(',', $verification) ) {
2686 &{ $verify{$verify} }( $p, $cust_main )
2687 or return { 'error' => 'Account not found' };
2691 #okay, we're verified, now create a unique session
2693 my $reset_session = {
2694 'svcnum' => $svc_acct->svcnum,
2697 my $timeout = '1 hour'; #?
2699 my $reset_session_id;
2701 $reset_session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
2702 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") ); #just in case
2704 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
2708 my $msgnum = $conf->config('selfservice-password_reset_msgnum', $cust_main->agentnum);
2709 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
2710 return { 'error' => "selfservice-password_reset_msgnum unset" } unless $msgnum;
2711 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
2712 my $error = $msg_template->send( 'cust_main' => $cust_main,
2713 'object' => $svc_acct,
2714 'substitutions' => {
2715 'session_id' => $reset_session_id,
2719 return { 'error' => $error }; #????
2722 return { 'error' => '' };
2725 sub check_reset_passwd {
2728 my $conf = new FS::Conf;
2729 my $verification = $conf->config('selfservice-password_reset_verification')
2730 or return { 'error' => 'Password resets disabled' };
2732 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2733 or return { 'error' => "Can't resume session" }; #better error message
2735 my $svcnum = $reset_session->{'svcnum'};
2737 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2738 or return { 'error' => "Service not found" };
2740 return { 'error' => '',
2741 'username' => $svc_acct->username,
2746 sub process_reset_passwd {
2749 my $conf = new FS::Conf;
2750 my $verification = $conf->config('selfservice-password_reset_verification')
2751 or return { 'error' => 'Password resets disabled' };
2753 return { 'error' => "New passwords don't match." }
2754 if $p->{'new_password'} ne $p->{'new_password2'};
2756 return { 'error' => 'Enter new password' }
2757 unless length($p->{'new_password'});
2759 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2760 or return { 'error' => "Can't resume session" }; #better error message
2762 my $svcnum = $reset_session->{'svcnum'};
2764 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2765 or return { 'error' => "Service not found" };
2767 $svc_acct->set_password($p->{'new_password'});
2768 my $error = $svc_acct->replace();
2770 my($label, $value) = $svc_acct->cust_svc->label;
2772 return { 'error' => $error,
2781 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2782 return { 'error' => $session } if $context eq 'error';
2784 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2785 FS::TicketSystem->init();
2787 my $conf = new FS::Conf;
2788 my $queue = $p->{'queue'}
2789 || $conf->config('ticket_system-selfservice_queueid')
2790 || $conf->config('ticket_system-default_queueid');
2792 warn "$me create_ticket: creating ticket\n" if $DEBUG;
2793 my $err_or_ticket = FS::TicketSystem->create_ticket(
2794 '', #create RT session based on FS CurrentUser (fs_selfservice)
2796 'custnum' => $custnum,
2797 'svcnum' => $session->{'svcnum'},
2798 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2801 if ( ref($err_or_ticket) ) {
2802 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2804 return { 'error' => '',
2805 'ticket_id' => $err_or_ticket->id,
2808 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2810 return { 'error' => $err_or_ticket };
2818 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2819 return { 'error' => $session } if $context eq 'error';
2821 return { error => 'requested format not implemented' }
2822 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2824 my $conf = new FS::Conf;
2825 my $age_threshold = 0;
2826 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2827 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2829 my $search = { 'custnum' => $custnum };
2830 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2831 my $cust_main = qsearchs('cust_main', $search )
2832 or return { 'error' => "unknown custnum $custnum" };
2834 # does it make more sense to just run one sql query for this instead of all the
2835 # insanity below? would increase performance greately for large data sets?
2837 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2838 my @part_svc = $cust_pkg->part_svc;
2839 foreach my $part_svc ( @part_svc ) {
2840 if($part_svc->svcdb eq 'svc_phone'){
2841 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2842 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2843 push @svc_phone, $cust_pkg_svc->svc_x
2844 if $cust_pkg_svc->date_inserted >= $age_threshold;
2852 my($xls_r,$xls_c) = (0,0);
2855 my @fields = qw( countrycode phonenum pin sip_password phone_name );
2856 if($p->{'format'} eq 'csv') {
2857 $csv = new Text::CSV_XS { 'always_quote' => 1,
2860 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2861 $content .= $csv->string;
2863 elsif($p->{'format'} eq 'xls') {
2864 my $XLS1 = new IO::Scalar \$content;
2865 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
2866 or return { 'error' => "Error opening .xls file: $!" };
2867 $xls = $xls_workbook->add_worksheet('DIDs');
2868 foreach ( @fields ) {
2869 $xls->write(0,$xls_c++,$_);
2874 foreach my $svc_phone ( @svc_phone ) {
2875 my @cols = map { $svc_phone->$_ } @fields;
2876 if($p->{'format'} eq 'csv') {
2877 return { 'error' => 'Unable to create CSV' }
2878 unless $csv->combine(@cols);
2879 $content .= $csv->string;
2881 elsif($p->{'format'} eq 'xls') {
2884 $xls->write($xls_r,$xls_c++,$_);
2890 $xls_workbook->close() if $p->{'format'} eq 'xls';
2892 { content => $content, format => $p->{'format'}, };
2897 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2898 return { 'error' => $session } if $context eq 'error';
2900 warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2901 FS::TicketSystem->init();
2902 return { 'error' => 'get_ticket configuration error' }
2903 if $FS::TicketSystem::system ne 'RT_Internal';
2905 # check existence and ownership as part of this
2906 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2907 my $rt_session = FS::TicketSystem->session('');
2908 my $Ticket = FS::TicketSystem->get_ticket_object(
2910 ticket_id => $p->{'ticket_id'},
2913 return { 'error' => 'ticket not found' } if !$Ticket;
2915 if ( length( $p->{'subject'} || '' ) ) {
2917 if ( $p->{'subject'} ne $Ticket->Subject ) {
2918 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2919 return { 'error' => "unable to set subject: $msg" } if !$val;
2923 if(length($p->{'reply'})) {
2924 my @err_or_res = FS::TicketSystem->correspond_ticket(
2926 'ticket_id' => $p->{'ticket_id'},
2927 'content' => $p->{'reply'},
2930 return { 'error' => 'unable to reply to ticket' }
2931 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2934 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2935 my $err_or_ticket = FS::TicketSystem->get_ticket(
2937 'ticket_id' => $p->{'ticket_id'},
2940 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2941 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2943 return { 'error' => $err_or_ticket };
2946 my @custs = @{$err_or_ticket->{'custs'}};
2947 my @txns = @{$err_or_ticket->{'txns'}};
2950 # superseded by check in get_ticket_object
2951 #return { 'error' => 'invalid ticket requested' }
2952 #unless grep($_ eq $custnum, @custs);
2954 foreach my $txn ( @txns ) {
2955 push @filtered_txns, $txn
2956 if ($txn->{'type'} eq 'EmailRecord'
2957 || $txn->{'type'} eq 'Correspond'
2958 || $txn->{'type'} eq 'Create');
2961 warn "$me get_ticket: successful: \n"
2963 return { 'error' => '',
2964 'transactions' => \@filtered_txns,
2965 'ticket_fields' => $err_or_ticket->{'fields'},
2966 'ticket_id' => $p->{'ticket_id'},
2970 sub adjust_ticket_priority {
2972 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2973 return { 'error' => $session } if $context eq 'error';
2975 warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2976 FS::TicketSystem->init;
2977 my $ss_priority = FS::TicketSystem->selfservice_priority;
2979 return { 'error' => 'adjust_ticket_priority configuration error' }
2980 if $FS::TicketSystem::system ne 'RT_Internal'
2983 my $values = $p->{'values'}; #hashref, id => priority value
2986 foreach my $id (keys %$values) {
2987 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
2988 my $Ticket = FS::TicketSystem->get_ticket_object('',
2990 'custnum' => $custnum,
2993 $ticket_error{$id} = 'ticket not found';
2997 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
2998 # We're not going to implement it for RT_External.
2999 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3000 my $new_value = $values->{$id};
3001 next if $old_value eq $new_value;
3003 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3005 # AddCustomFieldValue works fine (replacing any existing value) if it's
3006 # a single-valued custom field, which it should be. If it's not, you're
3007 # doing something wrong.
3009 if ( length($new_value) ) {
3010 ($val, $msg) = $Ticket->AddCustomFieldValue(
3011 Field => $ss_priority,
3012 Value => $new_value,
3016 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3017 Field => $ss_priority,
3018 Value => $old_value,
3022 $ticket_error{$id} = $msg if !$val;
3023 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3025 return { 'error' => '',
3026 'ticket_error' => \%ticket_error,
3027 %{ customer_info($p) } # send updated customer info back
3033 sub _custoragent_session_custnum {
3036 my($context, $session, $custnum);
3037 if ( $p->{'session_id'} ) {
3039 $context = 'customer';
3040 $session = _cache->get($p->{'session_id'})
3041 or return ( 'error' => "Can't resume session" ); #better error message
3042 $custnum = $session->{'custnum'};
3044 } elsif ( $p->{'agent_session_id'} ) {
3047 my $agent_cache = new FS::ClientAPI_SessionCache( {
3048 'namespace' => 'FS::ClientAPI::Agent',
3050 $session = $agent_cache->get($p->{'agent_session_id'})
3051 or return ( 'error' => "Can't resume session" ); #better error message
3052 $custnum = $p->{'custnum'};
3056 return ( 'error' => "Can't resume session" ); #better error message
3059 ($context, $session, $custnum);