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;
44 use FS::acct_rt_transaction;
48 $me = '[FS::ClientAPI::MyAccount]';
50 use vars qw( @cust_main_editable_fields );
51 @cust_main_editable_fields = qw(
52 first last company address1 address2 city
53 county state zip country
54 daytime night fax mobile
55 ship_first ship_last ship_company ship_address1 ship_address2 ship_city
56 ship_state ship_zip ship_country
57 ship_daytime ship_night ship_fax ship_mobile
59 payby payinfo payname paystart_month paystart_year payissue payip
60 ss paytype paystate stateid stateid_state
63 BEGIN { #preload to reduce time customer_info takes
64 if ( $FS::TicketSystem::system ) {
65 warn "$me: initializing ticket system\n" if $DEBUG;
66 FS::TicketSystem->init();
71 $cache ||= new FS::ClientAPI_SessionCache( {
72 'namespace' => 'FS::ClientAPI::MyAccount',
79 my($context, $session, $custnum) = _custoragent_session_custnum($p);
80 #return { 'error' => $session } if $context eq 'error';
83 if ( $context eq 'customer' ) {
85 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
88 $sth->execute($custnum) or die $sth->errstr;
90 $agentnum = $sth->fetchrow_arrayref->[0]
91 or die "no agentnum for custnum $custnum";
93 #} elsif ( $context eq 'agent' ) {
94 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
98 my $conf = new FS::Conf;
100 #false laziness w/Signup.pm
102 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
104 if ( $skin_info_cache_agent ) {
106 warn "$me loading cached skin info for agentnum $agentnum\n"
111 warn "$me populating skin info cache for agentnum $agentnum\n"
114 $skin_info_cache_agent = {
115 'agentnum' => $agentnum,
116 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
117 qw( company_name date_format ) ),
118 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
119 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
120 text_color link_color vlink_color hlink_color alink_color
121 font title_color title_align title_size menu_bgcolor menu_fontsize
124 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
125 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
127 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
128 qw( title_left_image title_right_image
129 menu_top_image menu_body_image menu_bottom_image
132 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
133 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
134 qw( head body_header body_footer company_address ) ),
137 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
141 #{ %$skin_info_cache_agent };
142 $skin_info_cache_agent;
149 my $conf = new FS::Conf;
153 'phone_login' => $conf->exists('selfservice_server-phone_login'),
154 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
155 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
156 'banner_image_md5' =>
157 md5_hex($conf->config_binary('selfservice-login_banner_image')),
164 sub login_banner_image {
166 my $conf = new FS::Conf;
167 my $image = $conf->config_binary('selfservice-login_banner_image');
169 'md5' => md5_hex($image),
174 #false laziness w/FS::ClientAPI::passwd::passwd
178 my $conf = new FS::Conf;
181 if ( $p->{'domain'} eq 'svc_phone'
182 && $conf->exists('selfservice_server-phone_login') ) {
184 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
185 return { error => 'Number not found.' } unless $svc_phone;
188 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
189 #return { error => 'Only primary user may log in.' }
190 # if $conf->exists('selfservice_server-primary_only')
191 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
193 return { error => 'Incorrect PIN.' }
194 unless $svc_phone->check_pin($p->{'password'});
200 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
201 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
203 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
204 'domsvc' => $svc_domain->svcnum, }
206 return { error => 'User not found.' } unless $svc_acct;
208 if($conf->exists('selfservice_server-login_svcpart')) {
209 my @svcpart = $conf->config('selfservice_server-login_svcpart');
210 my $svcpart = $svc_acct->cust_svc->svcpart;
211 return { error => 'Invalid user.' }
212 unless grep($_ eq $svcpart, @svcpart);
215 return { error => 'Incorrect password.' }
216 unless $svc_acct->check_password($p->{'password'});
223 'svcnum' => $svc_x->svcnum,
226 my $cust_svc = $svc_x->cust_svc;
227 my $cust_pkg = $cust_svc->cust_pkg;
229 my $cust_main = $cust_pkg->cust_main;
230 $session->{'custnum'} = $cust_main->custnum;
231 if ( $conf->exists('pkg-balances') ) {
232 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
233 $cust_main->ncancelled_pkgs;
234 $session->{'pkgnum'} = $cust_pkg->pkgnum
235 if scalar(@cust_pkg) > 1;
239 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
240 #return { error => 'Only primary user may log in.' }
241 # if $conf->exists('selfservice_server-primary_only')
242 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
243 my $part_pkg = $cust_pkg->part_pkg;
244 return { error => 'Only primary user may log in.' }
245 if $conf->exists('selfservice_server-primary_only')
246 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
250 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
251 } until ( ! defined _cache->get($session_id) ); #just in case
253 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
254 _cache->set( $session_id, $session, $timeout );
256 return { 'error' => '',
257 'session_id' => $session_id,
263 if ( $p->{'session_id'} ) {
264 _cache->remove($p->{'session_id'});
265 return { %{ skin_info($p) }, 'error' => '' };
267 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
274 my($context, $session, $custnum) = _custoragent_session_custnum($p);
275 return { 'error' => $session } if $context eq 'error';
277 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
278 or return { 'error' => "Service not found" };
280 $session->{'svcnum'} = $svc_acct->svcnum;
282 my $conf = new FS::Conf;
283 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
284 _cache->set( $p->{'session_id'}, $session, $timeout );
286 return { 'error' => '' };
290 sub payment_gateway {
292 # takes a cust_main and a cust_payby entry, returns the payment_gateway
293 my $conf = new FS::Conf;
294 my $cust_main = shift;
295 my $cust_payby = shift;
296 my $gatewaynum = $conf->config('selfservice-payment_gateway');
298 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
299 die "configured gatewaynum $gatewaynum not found!" if !$pg;
303 return '' if ! FS::payby->realtime($cust_payby);
304 my $pg = $cust_main->agent->payment_gateway(
305 'method' => FS::payby->payby2bop($cust_payby),
315 my $conf = new FS::Conf;
317 my $info = skin_info($p);
319 use vars qw( $cust_paybys ); #cache for performance
320 unless ( $cust_paybys ) {
322 my %cust_paybys = map { $_ => 1 }
323 map { FS::payby->payby2payment($_) }
324 $conf->config('signup_server-payby');
326 $cust_paybys = [ keys %cust_paybys ];
329 $info->{'cust_paybys'} = $cust_paybys;
331 my($context, $session, $custnum) = _custoragent_session_custnum($p);
332 return { 'error' => $session } if $context eq 'error';
334 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
335 or return { 'error' => "unknown custnum $custnum" };
337 $info->{'hide_payment_fields'} = [
339 my $pg = payment_gateway($cust_main, $_);
340 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
341 } @{ $info->{cust_paybys} }
344 $info->{'self_suspend_reason'} =
345 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
347 $info->{'edit_ticket_subject'} =
348 $conf->exists('ticket_system-selfservice_edit_subject') &&
349 $cust_main->edit_subject;
352 'custnum' => $custnum,
353 'access_pkgnum' => $session->{'pkgnum'},
354 'access_svcnum' => $session->{'svcnum'},
361 my($context, $session, $custnum) = _custoragent_session_custnum($p);
362 return { 'error' => $session } if $context eq 'error';
366 my $conf = new FS::Conf;
367 if ($conf->exists('cust_main-require_address2')) {
368 $return{'require_address2'} = '1';
370 $return{'require_address2'} = '';
373 if ( $FS::TicketSystem::system ) {
374 warn "$me customer_info: initializing ticket system\n" if $DEBUG;
375 FS::TicketSystem->init();
378 if ( $custnum ) { #customer record
380 my $search = { 'custnum' => $custnum };
381 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
382 my $cust_main = qsearchs('cust_main', $search )
383 or return { 'error' => "unknown custnum $custnum" };
385 $return{display_custnum} = $cust_main->display_custnum;
387 if ( $session->{'pkgnum'} ) {
388 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
389 #next_bill_date from cust_pkg?
391 $return{balance} = $cust_main->balance;
392 $return{next_bill_date} = $cust_main->next_bill_date;
393 $return{next_bill_date_pretty} =
394 time2str('%m/%d/%Y', $return{next_bill_date} );
397 my @tickets = $cust_main->tickets;
398 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
399 if ( FS::TicketSystem->selfservice_priority ) {
400 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
404 ($a->{'_selfservice_priority'} eq '') <=>
405 ($b->{'_selfservice_priority'} eq '')
408 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
414 $return{tickets} = \@tickets;
417 unless ( $session->{'pkgnum'} ) {
420 invnum => $_->invnum,
421 date => time2str("%b %o, %Y", $_->_date),
424 } $cust_main->open_cust_bill;
425 $return{open_invoices} = \@open;
427 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
428 my $sth = dbh->prepare($sql) or die dbh->errstr;
429 $sth->execute($custnum) or die $sth->errstr;
430 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
431 $return{'last_invoice_date_pretty'} =
432 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
435 $return{countrydefault} = scalar($conf->config('countrydefault'));
437 $return{small_custview} =
438 small_custview( $cust_main,
439 $return{countrydefault},
440 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
443 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
444 $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
446 $return{has_ship_address} = $cust_main->has_ship_address;
447 $return{status} = $cust_main->status;
448 $return{statuscolor} = $cust_main->statuscolor;
450 for (@cust_main_editable_fields) {
451 $return{$_} = $cust_main->get($_);
454 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
455 $return{payinfo} = $cust_main->paymask;
456 @return{'month', 'year'} = $cust_main->paydate_monthyear;
459 $return{'invoicing_list'} =
460 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
461 $return{'postal_invoicing'} =
462 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
464 if (scalar($conf->config('support_packages'))) {
465 my @support_services = ();
466 foreach ($cust_main->support_services) {
467 my $seconds = $_->svc_x->seconds;
468 my $time_remaining = (($seconds < 0) ? '-' : '' ).
469 int(abs($seconds)/3600)."h".
470 sprintf("%02d",(abs($seconds)%3600)/60)."m";
471 my $cust_pkg = $_->cust_pkg;
474 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
475 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
476 push @support_services, { svcnum => $_->svcnum,
477 time => $time_remaining,
482 $return{support_services} = \@support_services;
485 if ( $conf->config('prepayment_discounts-credit_type') ) {
487 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
490 if ( $session->{'svcnum'} ) {
491 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
492 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
493 $return{'svcnum'} = $session->{'svcnum'};
496 } elsif ( $session->{'svcnum'} ) { #no customer record
498 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
499 or die "unknown svcnum";
500 $return{name} = $svc_acct->email;
504 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
508 return { 'error' => '',
509 'custnum' => $custnum,
515 sub customer_info_short {
518 my($context, $session, $custnum) = _custoragent_session_custnum($p);
519 return { 'error' => $session } if $context eq 'error';
523 my $conf = new FS::Conf;
525 if ( $custnum ) { #customer record
527 my $search = { 'custnum' => $custnum };
528 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
529 my $cust_main = qsearchs('cust_main', $search )
530 or return { 'error' => "unknown custnum $custnum" };
532 $return{display_custnum} = $cust_main->display_custnum;
534 $return{countrydefault} = scalar($conf->config('countrydefault'));
536 $return{small_custview} =
537 small_custview( $cust_main,
538 $return{countrydefault},
542 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
543 $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
545 $return{payby} = $cust_main->payby;
547 #none of these are terribly expensive if we want 'em...
548 for (@cust_main_editable_fields) {
549 $return{$_} = $cust_main->get($_);
552 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
553 $return{payinfo} = $cust_main->paymask;
554 @return{'month', 'year'} = $cust_main->paydate_monthyear;
557 $return{'invoicing_list'} =
558 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
559 #$return{'postal_invoicing'} =
560 # 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
562 if ( $session->{'svcnum'} ) {
563 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
564 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
565 $return{'svcnum'} = $session->{'svcnum'};
568 } elsif ( $session->{'svcnum'} ) { #no customer record
570 #uuh, not supproted yet... die?
571 return { 'error' => 'customer_info_short not yet supported as agent' };
575 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
579 return { 'error' => '',
580 'custnum' => $custnum,
585 sub billing_history {
588 my($context, $session, $custnum) = _custoragent_session_custnum($p);
589 return { 'error' => $session } if $context eq 'error';
591 return { 'error' => 'No customer' } unless $custnum;
593 my $search = { 'custnum' => $custnum };
594 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
595 my $cust_main = qsearchs('cust_main', $search )
596 or return { 'error' => "unknown custnum $custnum" };
600 if ( $session->{'pkgnum'} ) {
601 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
602 #next_bill_date from cust_pkg?
603 return { 'error' => 'No history for package' };
606 $return{balance} = $cust_main->balance;
607 $return{next_bill_date} = $cust_main->next_bill_date;
608 $return{next_bill_date_pretty} =
609 time2str('%m/%d/%Y', $return{next_bill_date} );
613 my $conf = new FS::Conf;
615 if ( $conf->exists('selfservice-billing_history-line_items') ) {
617 foreach my $cust_bill ( $cust_main->cust_bill ) {
620 'type' => 'Line item',
621 'description' => $_->desc. ( $_->sdate && $_->edate
622 ? ' '. time2str('%d-%b-%Y', $_->sdate).
623 ' To '. time2str('%d-%b-%Y', $_->edate)
626 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
627 'date' => $cust_bill->_date,
628 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
630 foreach $cust_bill->cust_bill_pkg;
638 'description' => 'Invoice #'. $_->display_invnum,
639 'amount' => sprintf('%.2f', $_->charged ),
641 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
643 foreach $cust_main->cust_bill;
649 'description' => 'Payment', #XXX type
650 'amount' => sprintf('%.2f', 0 - $_->paid ),
652 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
654 foreach $cust_main->cust_pay;
658 'description' => 'Credit', #more info?
659 'amount' => sprintf('%.2f', 0 -$_->amount ),
661 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
663 foreach $cust_main->cust_credit;
667 'description' => 'Refund', #more info? type, like payment?
668 'amount' => $_->refund,
670 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
672 foreach $cust_main->cust_refund;
674 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
676 $return{'history'} = \@history;
684 my $session = _cache->get($p->{'session_id'})
685 or return { 'error' => "Can't resume session" }; #better error message
687 my $custnum = $session->{'custnum'}
688 or return { 'error' => "no customer record" };
690 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
691 or return { 'error' => "unknown custnum $custnum" };
693 my $new = new FS::cust_main { $cust_main->hash };
694 # Avoid accidentally changing the service address.
695 if ( !$new->has_ship_address ) {
696 $new->set( $_ => $new->get($_) )
697 foreach $new->addr_fields;
700 $new->set( $_ => $p->{$_} )
701 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
704 if (exists($p->{'payby'})) {
705 $p->{'payby'} =~ /^([A-Z]{4})$/
706 or return { 'error' => "illegal_payby " . $p->{'payby'} };
710 if ( $payby =~ /^(CARD|DCRD)$/ ) {
712 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
714 if ( $new->payinfo eq $cust_main->paymask ) {
715 $new->payinfo($cust_main->payinfo);
717 $new->payinfo($p->{'payinfo'});
720 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
722 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
725 $p->{'payinfo1'} =~ /^([\dx]+)$/
726 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
728 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
729 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
731 $payinfo = $payinfo1. '@'. $payinfo2;
733 $new->payinfo( ($payinfo eq $cust_main->paymask)
734 ? $cust_main->payinfo
738 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
740 } elsif ( $payby =~ /^(BILL)$/ ) {
742 } elsif ( $payby ) { #notyet ready
743 return { 'error' => "unknown payby $payby" };
747 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
748 #false laziness with httemplate/edit/process/cust_main.cgi
749 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
750 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
752 @invoicing_list = $cust_main->invoicing_list;
755 my $error = $new->replace($cust_main, \@invoicing_list);
756 return { 'error' => $error } if $error;
759 return { 'error' => '' };
764 my $session = _cache->get($p->{'session_id'})
765 or return { 'error' => "Can't resume session" }; #better error message
771 my $conf = new FS::Conf;
772 use vars qw($payment_info); #cache for performance
773 unless ( $payment_info ) {
775 my %states = map { $_->state => 1 }
776 qsearch('cust_main_county', {
777 'country' => $conf->config('countrydefault') || 'US'
780 my %cust_paybys = map { $_ => 1 }
781 map { FS::payby->payby2payment($_) }
782 $conf->config('signup_server-payby');
784 my @cust_paybys = keys %cust_paybys;
788 #list all counties/states/countries
789 'cust_main_county' =>
790 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
792 #shortcut for one-country folks
794 [ sort { $a cmp $b } keys %states ],
796 'card_types' => card_types(),
798 'paytypes' => [ @FS::cust_main::paytypes ],
800 'paybys' => [ $conf->config('signup_server-payby') ],
801 'cust_paybys' => \@cust_paybys,
803 'stateid_label' => FS::Msgcat::_gettext('stateid'),
804 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
806 'show_ss' => $conf->exists('show_ss'),
807 'show_stateid' => $conf->exists('show_stateid'),
808 'show_paystate' => $conf->exists('show_bankstate'),
810 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
812 'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
821 my %return = %$payment_info;
823 my $custnum = $session->{'custnum'};
825 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
826 or return { 'error' => "unknown custnum $custnum" };
828 $return{'hide_payment_fields'} = [
830 my $pg = payment_gateway($cust_main, $_);
831 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
832 } @{ $return{cust_paybys} }
835 $return{balance} = $cust_main->balance; #XXX pkg-balances?
837 $return{payname} = $cust_main->payname
838 || ( $cust_main->first. ' '. $cust_main->get('last') );
840 $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
842 $return{payby} = $cust_main->payby;
843 $return{stateid_state} = $cust_main->stateid_state;
845 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
846 $return{card_type} = cardtype($cust_main->payinfo);
847 $return{payinfo} = $cust_main->paymask;
849 @return{'month', 'year'} = $cust_main->paydate_monthyear;
853 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
854 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
855 $return{payinfo1} = $payinfo1;
856 $return{payinfo2} = $payinfo2;
857 $return{paytype} = $cust_main->paytype;
858 $return{paystate} = $cust_main->paystate;
859 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
862 if ( $conf->config('prepayment_discounts-credit_type') ) {
864 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
867 #doubleclick protection
869 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
871 return { 'error' => '',
877 #some false laziness with httemplate/process/payment.cgi - look there for
878 #ACH and CVV support stuff
880 sub validate_payment {
883 my $session = _cache->get($p->{'session_id'})
884 or return { 'error' => "Can't resume session" }; #better error message
886 my $custnum = $session->{'custnum'};
888 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
889 or return { 'error' => "unknown custnum $custnum" };
891 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
892 or return { 'error' => gettext('illegal_amount') };
894 return { error => 'Amount must be greater than 0' } unless $amount > 0;
896 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
897 #changing the hidden form values
898 my $conf = new FS::Conf;
899 my $fee_display = $conf->config('selfservice_process-display') || 'add';
900 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart');
901 if ( $fee_display eq 'add' && $fee_pkgpart ) {
902 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
903 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
906 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
907 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
908 my $discount_term = $1;
910 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
911 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
914 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
915 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
918 $p->{'payby'} ||= 'CARD';
919 $p->{'payby'} =~ /^([A-Z]{4})$/
920 or return { 'error' => "illegal_payby " . $p->{'payby'} };
923 #false laziness w/process/payment.cgi
926 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
928 $p->{'payinfo1'} =~ /^([\dx]+)$/
929 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
931 $p->{'payinfo2'} =~ /^([\dx]+)$/
932 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
934 $payinfo = $payinfo1. '@'. $payinfo2;
936 $payinfo = $cust_main->payinfo
937 if $cust_main->paymask eq $payinfo;
939 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
941 $payinfo = $p->{'payinfo'};
943 #more intelligent matching will be needed here if you change
944 #card_masking_method and don't remove existing paymasks
945 $payinfo = $cust_main->payinfo
946 if $cust_main->paymask eq $payinfo;
949 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
950 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
954 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
955 return { 'error' => gettext('unknown_card_type') }
956 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
958 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
959 if ( cardtype($payinfo) eq 'American Express card' ) {
960 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
961 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
964 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
965 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
971 die "unknown payby $payby";
975 'CARD' => [ qw( paystart_month paystart_year payissue payip
976 address1 address2 city state zip country ) ],
977 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
981 $card_type = cardtype($payinfo) if $payby eq 'CARD';
984 'cust_main' => $cust_main, #XXX or just custnum??
987 'payinfo' => $payinfo,
988 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
989 'card_type' => $card_type,
990 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
991 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
992 'month' => $p->{'month'},
993 'year' => $p->{'year'},
994 'payname' => $payname,
995 'paybatch' => $paybatch, #this doesn't actually do anything
997 'payname' => $payname,
998 'discount_term' => $discount_term,
999 'pkgnum' => $session->{'pkgnum'},
1000 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1010 my $validate = validate_payment($p);
1011 return $validate if $validate->{'error'};
1013 my $conf = new FS::Conf;
1014 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1015 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1017 +{ map { $_=>$validate->{$_} }
1018 qw( card_type paymask payname paydate_pretty month year amount
1019 address1 address2 city state zip country
1025 sub process_stored_payment {
1028 my $session_id = $p->{'session_id'};
1030 my $payment_info = _cache->get( "payment_$session_id" )
1031 or return { 'error' => "Can't resume session" }; #better error message
1033 do_process_payment($payment_info);
1037 sub process_payment {
1040 my $payment_info = validate_payment($p);
1041 return $payment_info if $payment_info->{'error'};
1043 do_process_payment($payment_info);
1047 sub do_process_payment {
1048 my $validate = shift;
1050 my $cust_main = $validate->{'cust_main'};
1052 my $amount = delete $validate->{'amount'};
1055 my $payby = delete $validate->{'payby'};
1057 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1060 'paynum_ref' => \$paynum,
1063 return { 'error' => $error } if $error;
1065 #no error, so order the fee package if applicable...
1066 my $conf = new FS::Conf;
1067 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart');
1068 if ( $fee_pkgpart ) {
1070 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1072 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1073 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1076 #and generate an invoice for it now too
1077 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1078 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1083 $cust_main->apply_payments;
1085 if ( $validate->{'save'} ) {
1086 my $new = new FS::cust_main { $cust_main->hash };
1087 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1088 $new->set( $_ => $validate->{$_} )
1089 foreach qw( payname paystart_month paystart_year payissue payip );
1090 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1092 # Avoid accidentally changing the service address.
1093 if ( !$new->has_ship_address ) {
1094 $new->set( "ship_$_" => $new->get($_) )
1095 foreach $new->addr_fields;
1097 $new->set( $_ => $validate->{$_} )
1098 foreach qw(address1 address2 city state country zip);
1100 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1101 $new->set( $_ => $validate->{$_} )
1102 foreach qw( payname payip paytype paystate
1103 stateid stateid_state );
1104 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1106 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1107 $new->set( 'paydate' => $validate->{'paydate'} );
1108 my $error = $new->replace($cust_main);
1110 #no, this causes customers to process their payments again
1111 #return { 'error' => $error };
1112 #XXX just warn verosely for now so i can figure out how these happen in
1113 # the first place, eventually should redirect them to the "change
1114 #address" page but indicate the payment did process??
1115 delete($validate->{'payinfo'}); #don't want to log this!
1116 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1117 "NEW: ". Dumper($new)."\n".
1118 "OLD: ". Dumper($cust_main)."\n".
1119 "PACKET: ". Dumper($validate)."\n";
1127 my $receipt_html = '';
1129 # currently supported for realtime CC only; send receipt data to SS
1130 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1133 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1136 <TD ALIGN="right">Payment#</TD>
1137 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1141 <TD ALIGN="right">Date</TD>
1143 <TD BGCOLOR="#FFFFFF"><B>! .
1144 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1150 <TD ALIGN="right">Amount</TD>
1151 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1156 <TD ALIGN="right">Payment method</TD>
1157 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1168 my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
1172 'amount' => sprintf('%.2f', $cust_pay->paid),
1173 'date' => $cust_pay->_date,
1174 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1175 'time_pretty' => time2str('%T', $cust_pay->_date),
1176 'auth_num' => $auth,
1177 'order_num' => $order,
1178 'receipt_html' => $receipt_html,
1185 'receipt_html' => '',
1192 sub realtime_collect {
1195 my $session = _cache->get($p->{'session_id'})
1196 or return { 'error' => "Can't resume session" }; #better error message
1198 my $custnum = $session->{'custnum'};
1200 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1201 or return { 'error' => "unknown custnum $custnum" };
1204 if ( $p->{'amount'} ) {
1205 $amount = $p->{'amount'};
1207 elsif ( $session->{'pkgnum'} ) {
1208 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1211 $amount = $cust_main->balance;
1214 my $error = $cust_main->realtime_collect(
1215 'method' => $p->{'method'},
1216 'amount' => $amount,
1217 'pkgnum' => $session->{'pkgnum'},
1218 'session_id' => $p->{'session_id'},
1222 return { 'error' => $error } unless ref( $error );
1224 return { 'error' => '', amount => $amount, %$error };
1227 sub process_payment_order_pkg {
1230 my $hr = process_payment($p);
1231 return $hr if $hr->{'error'};
1236 sub process_payment_order_renew {
1239 my $hr = process_payment($p);
1240 return $hr if $hr->{'error'};
1245 sub process_prepay {
1249 my $session = _cache->get($p->{'session_id'})
1250 or return { 'error' => "Can't resume session" }; #better error message
1254 my $custnum = $session->{'custnum'};
1256 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1257 or return { 'error' => "unknown custnum $custnum" };
1259 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1260 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1268 return { 'error' => $error } if $error;
1270 return { 'error' => '',
1271 'amount' => $amount,
1272 'seconds' => $seconds,
1273 'duration' => duration_exact($seconds),
1274 'upbytes' => $upbytes,
1275 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1276 'downbytes' => $downbytes,
1277 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1278 'totalbytes'=> $totalbytes,
1279 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1286 my $session = _cache->get($p->{'session_id'})
1287 or return { 'error' => "Can't resume session" }; #better error message
1289 my $custnum = $session->{'custnum'};
1291 my $invnum = $p->{'invnum'};
1293 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1294 'custnum' => $custnum } )
1295 or return { 'error' => "Can't find invnum" };
1299 return { 'error' => '',
1300 'invnum' => $invnum,
1301 'invoice_text' => join('', $cust_bill->print_text ),
1302 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1309 my $session = _cache->get($p->{'session_id'})
1310 or return { 'error' => "Can't resume session" }; #better error message
1312 my $custnum = $session->{'custnum'};
1314 my $invnum = $p->{'invnum'};
1316 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1317 'custnum' => $custnum } )
1318 or return { 'error' => "Can't find invnum" };
1322 return { 'error' => '',
1323 'invnum' => $invnum,
1324 'invoice_pdf' => $cust_bill->print_pdf({
1325 'unsquelch_cdr' => 1,
1326 'locale' => $p->{'locale'},
1332 sub legacy_invoice {
1334 my $session = _cache->get($p->{'session_id'})
1335 or return { 'error' => "Can't resume session" }; #better error message
1337 my $custnum = $session->{'custnum'};
1339 my $legacyinvnum = $p->{'legacyinvnum'};
1342 'legacyinvnum' => $legacyinvnum,
1343 'custnum' => $custnum,
1346 my $legacy_cust_bill =
1347 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1348 || qsearchs('legacy_cust_bill', \%hash )
1349 or return { 'error' => "Can't find legacyinvnum" };
1353 return { 'error' => '',
1354 'legacyinvnum' => $legacyinvnum,
1355 'legacyid' => $legacy_cust_bill->legacyid,
1356 'invoice_html' => $legacy_cust_bill->content_html,
1361 sub legacy_invoice_pdf {
1363 my $session = _cache->get($p->{'session_id'})
1364 or return { 'error' => "Can't resume session" }; #better error message
1366 my $custnum = $session->{'custnum'};
1368 my $legacyinvnum = $p->{'legacyinvnum'};
1370 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1371 'legacyinvnum' => $legacyinvnum,
1372 'custnum' => $custnum,
1373 }) or return { 'error' => "Can't find legacyinvnum" };
1377 return { 'error' => '',
1378 'legacyinvnum' => $legacyinvnum,
1379 'legacyid' => $legacy_cust_bill->legacyid,
1380 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1388 #sessioning for this? how do we get the session id to the backend invoice
1389 # template so it can add it to the link, blah
1392 if ( $p->{'invnum'} ) {
1393 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1394 or return { 'error' => 'unknown invnum' };
1395 $agentnum = $cust_bill->cust_main->agentnum;
1398 my $templatename = $p->{'template'} || $p->{'templatename'};
1400 #false laziness-ish w/view/cust_bill-logo.cgi
1402 my $conf = new FS::Conf;
1403 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1404 $templatename = "_$1";
1409 my $filename = "logo$templatename.png";
1411 return { 'error' => '',
1412 'logo' => $conf->config_binary($filename, $agentnum),
1413 'content_type' => 'image/png', #should allow gif, jpg too
1420 my $session = _cache->get($p->{'session_id'})
1421 or return { 'error' => "Can't resume session" }; #better error message
1423 my $custnum = $session->{'custnum'};
1425 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1426 or return { 'error' => "unknown custnum $custnum" };
1428 my $conf = new FS::Conf;
1430 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1432 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1436 return { 'error' => '',
1437 'balance' => $cust_main->balance,
1440 my $owed = $_->owed;
1442 +{ 'invnum' => $_->invnum,
1443 '_date' => $_->_date,
1444 'date' => time2str("%b %o, %Y", $_->_date),
1445 'date_short' => time2str("%m-%d-%Y", $_->_date),
1446 'previous' => sprintf('%.2f', ($_->previous)[0]),
1447 'charged' => sprintf('%.2f', $_->charged),
1448 'owed' => sprintf('%.2f', $owed),
1449 'balance' => sprintf('%.2f', $balance),
1454 'legacy_invoices' => [
1456 +{ 'legacyinvnum' => $_->legacyinvnum,
1457 'legacyid' => $_->legacyid,
1458 '_date' => $_->_date,
1459 'date' => time2str("%b %o, %Y", $_->_date),
1460 'date_short' => time2str("%m-%d-%Y", $_->_date),
1461 'charged' => sprintf('%.2f', $_->charged),
1462 'has_content' => ( length($_->content_pdf)
1463 || length($_->content_html) ),
1473 my $session = _cache->get($p->{'session_id'})
1474 or return { 'error' => "Can't resume session" }; #better error message
1476 my $custnum = $session->{'custnum'};
1478 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1479 or return { 'error' => "unknown custnum $custnum" };
1481 my @errors = $cust_main->cancel( 'quiet'=>1 );
1483 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1485 return { 'error' => $error };
1492 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1493 return { 'error' => $session } if $context eq 'error';
1495 my $search = { 'custnum' => $custnum };
1496 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1497 my $cust_main = qsearchs('cust_main', $search )
1498 or return { 'error' => "unknown custnum $custnum" };
1500 my $conf = new FS::Conf;
1502 # the duplication below is necessary:
1503 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1504 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1505 # non-backwards-compatible change breaking the software of anyone using the API
1506 # instead of the stock selfservice
1507 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1508 if( $conf->exists('selfservice_server-view-wholesale') ) {
1509 return { 'svcnum' => $session->{'svcnum'},
1510 'custnum' => $custnum,
1511 'cust_pkg' => [ map {
1513 part_pkg => [ map $_->hashref, $_->part_pkg ],
1515 [ map $_->hashref, $_->available_part_svc ],
1517 [ map { my $ref = { $_->hash,
1518 label => [ $_->label ],
1520 $ref->{_password} = $_->svc_x->_password
1521 if $context eq 'agent'
1522 && $conf->exists('agent-showpasswords')
1523 && $_->part_svc->svcdb eq 'svc_acct';
1528 } $cust_main->cust_pkg
1531 small_custview( $cust_main, $conf->config('countrydefault') ),
1532 'wholesale_view' => 1,
1533 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1534 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1535 'lnp' => $conf->exists('svc_phone-lnp'),
1539 { 'svcnum' => $session->{'svcnum'},
1540 'custnum' => $custnum,
1541 'cust_pkg' => [ map {
1542 my $primary_cust_svc = $_->primary_cust_svc;
1545 pkg_label => $_->pkg_label,
1546 status => $_->status,
1548 [ map $_->hashref, $_->available_part_svc ],
1550 [ map { my $ref = { $_->hash,
1551 label => [ $_->label ],
1553 $ref->{_password} = $_->svc_x->_password
1554 if $context eq 'agent'
1555 && $conf->exists('agent-showpasswords')
1556 && $_->part_svc->svcdb eq 'svc_acct';
1557 $ref->{svchash} = { $_->svc_x->hash } if
1558 $_->part_svc->svcdb eq 'svc_phone';
1559 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1560 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1566 ? { $primary_cust_svc->hash,
1567 label => [ $primary_cust_svc->label ],
1568 finger => $primary_cust_svc->svc_x->finger, #uuh
1569 $primary_cust_svc->part_svc->hash,
1573 } $cust_main->ncancelled_pkgs
1576 small_custview( $cust_main, $conf->config('countrydefault') ),
1584 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1585 return { 'error' => $session } if $context eq 'error';
1587 my $search = { 'custnum' => $custnum };
1588 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1589 my $cust_main = qsearchs('cust_main', $search )
1590 or return { 'error' => "unknown custnum $custnum" };
1592 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1593 if ( ! $pkgnum && $p->{'svcnum'} ) {
1594 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1595 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1599 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1600 foreach my $cust_pkg ( $p->{'ncancelled'}
1601 ? $cust_main->ncancelled_pkgs
1602 : $cust_main->unsuspended_pkgs ) {
1603 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1604 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1607 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1609 if ( $p->{'svcdb'} ) {
1610 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1612 : ref($p->{'svcdb'}) eq 'ARRAY'
1613 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1614 : { $p->{'svcdb'} => 1 };
1615 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1618 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1621 my $conf = new FS::Conf;
1624 'svcnum' => $session->{'svcnum'},
1625 'custnum' => $custnum,
1626 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1627 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1630 my $svc_x = $_->svc_x;
1631 my($label, $value) = $_->label;
1632 my $part_svc = $_->part_svc;
1633 my $svcdb = $part_svc->svcdb;
1634 my $cust_pkg = $_->cust_pkg;
1635 my $part_pkg = $cust_pkg->part_pkg;
1638 'svcnum' => $_->svcnum,
1639 'display_svcnum' => $_->display_svcnum,
1643 'pkg_label' => $cust_pkg->pkg_label,
1644 'pkg_status' => $cust_pkg->status,
1645 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1648 if ( $svcdb eq 'svc_acct' ) {
1651 'username' => $svc_x->username,
1652 'email' => $svc_x->email,
1653 'finger' => $svc_x->finger,
1654 'seconds' => $svc_x->seconds,
1655 'upbytes' => display_bytecount($svc_x->upbytes),
1656 'downbytes' => display_bytecount($svc_x->downbytes),
1657 'totalbytes' => display_bytecount($svc_x->totalbytes),
1659 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1660 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1661 'recharge_upbytes' =>
1662 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1663 'recharge_downbytes' =>
1664 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1665 'recharge_totalbytes' =>
1666 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1670 } elsif ( $svcdb eq 'svc_dsl' ) {
1671 $hash{'phonenum'} = $svc_x->phonenum;
1672 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1673 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1674 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1677 $hash{'name'} = $cust_main->name;
1680 # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1694 sub _customer_svc_x {
1695 my($custnum, $svcnum, $table) = (shift, shift, shift);
1696 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1698 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1699 my $search = " AND custnum = $1";
1700 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1703 'table' => ($table || 'svc_acct'),
1704 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1705 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1706 #'LEFT JOIN cust_main USING ( custnum ) ',
1707 'hashref' => $hashref,
1708 'extra_sql' => $search, #important
1713 sub svc_status_html {
1716 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1717 return { 'error' => $session } if $context eq 'error';
1719 #XXX only svc_dsl for now
1720 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1721 or return { 'error' => "Service not found" };
1723 my $html = $svc_x->getstatus_html;
1725 return { 'html' => $html };
1729 sub svc_status_hash {
1732 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1733 return { 'error' => $session } if $context eq 'error';
1735 #XXX only svc_acct for now
1736 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1737 or return { 'error' => "Service not found" };
1739 my ( $html, $hashref ) = $svc_x->export_getstatus;
1744 sub set_svc_status_hash {
1747 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1748 return { 'error' => $session } if $context eq 'error';
1750 #XXX only svc_acct for now
1751 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1752 or return { 'error' => "Service not found" };
1754 warn "set_svc_status_hash ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1756 my $error = $svc_x->export_setstatus($p); #$p? returns error?
1757 return { 'error' => $error } if $error;
1759 return {}; #? { 'error' => '' }
1764 sub acct_forward_info {
1767 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1768 return { 'error' => $session } if $context eq 'error';
1770 my $svc_forward = _customer_svc_x( $custnum,
1771 { 'srcsvc' => $p->{'svcnum'} },
1774 or return { 'error' => '',
1778 return { 'error' => '',
1779 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1784 sub process_acct_forward {
1786 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1787 return { 'error' => $session } if $context eq 'error';
1789 my $old = _customer_svc_x( $custnum,
1790 { 'srcsvc' => $p->{'svcnum'} },
1794 if ( $p->{'dst'} eq '' ) {
1796 my $error = $old->delete;
1797 return { 'error' => $error };
1799 return { 'error' => '' };
1802 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1803 'dst' => $p->{'dst'},
1808 $new->svcnum($old->svcnum);
1809 my $cust_svc = $old->cust_svc;
1810 $new->svcpart($old->svcpart);
1811 $new->pkgnuym($old->pkgnum);
1812 $error = $new->replace($old);
1814 my $conf = new FS::Conf;
1815 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1817 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1818 or return { 'error' => 'No service' }; #how would we even get here?
1820 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
1822 $error = $new->insert;
1825 return { 'error' => $error };
1829 sub list_dsl_devices {
1832 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1833 return { 'error' => $session } if $context eq 'error';
1835 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1836 or return { 'error' => "Service not found" };
1839 'devices' => [ map {
1840 +{ 'mac_addr' => $_->mac_addr };
1841 } $svc_dsl->dsl_device
1847 sub add_dsl_device {
1850 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1851 return { 'error' => $session } if $context eq 'error';
1853 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1854 or return { 'error' => "Service not found" };
1856 return { 'error' => 'No MAC address supplied' }
1857 unless length($p->{'mac_addr'});
1859 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
1860 'mac_addr' => scalar($p->{'mac_addr'}),
1862 my $error = $dsl_device->insert;
1863 return { 'error' => $error };
1867 sub delete_dsl_device {
1870 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1871 return { 'error' => $session } if $context eq 'error';
1873 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1874 or return { 'error' => "Service not found" };
1876 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
1877 'mac_addr' => scalar($p->{'mac_addr'}),
1880 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
1882 my $error = $dsl_device->delete;
1883 return { 'error' => $error };
1889 _usage_details( \&_port_graph, $p,
1890 'svcdb' => 'svc_port',
1895 my($svc_port, $begin, $end) = @_;
1897 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1898 push @usage, { 'png' => $pngOrError };
1902 sub _list_svc_usage {
1903 my($svc_acct, $begin, $end) = @_;
1905 foreach my $part_export (
1906 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1907 qw( sqlradius sqlradius_withdomain )
1909 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1914 sub list_svc_usage {
1915 _usage_details(\&_list_svc_usage, @_);
1918 sub _list_support_usage {
1919 my($svc_acct, $begin, $end) = @_;
1921 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1922 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1924 push @usage, { 'seconds' => $_->seconds,
1925 'support' => $_->support,
1926 '_date' => $_->_date,
1927 'id' => $_->transaction_id,
1928 'creator' => $_->creator,
1929 'subject' => $_->subject,
1930 'status' => $_->status,
1931 'ticketid' => $_->ticketid,
1937 sub list_support_usage {
1938 _usage_details(\&_list_support_usage, @_);
1941 sub _list_cdr_usage {
1942 # XXX CDR type support...
1943 my($svc_phone, $begin, $end, %opt) = @_;
1944 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
1945 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1948 sub list_cdr_usage {
1950 _usage_details( \&_list_cdr_usage, $p,
1951 'svcdb' => 'svc_phone',
1955 sub _usage_details {
1956 my($callback, $p, %opt) = @_;
1958 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1959 return { 'error' => $session } if $context eq 'error';
1961 my $search = { 'svcnum' => $p->{'svcnum'} };
1962 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1964 my $svcdb = $opt{'svcdb'} || 'svc_acct';
1966 my $svc_x = qsearchs( $svcdb, $search );
1967 return { 'error' => 'No service selected in list_svc_usage' }
1970 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1971 my $freq = $cust_pkg->part_pkg->freq;
1974 if ( $svcdb eq 'svc_phone' ) {
1975 my $format = $cust_pkg->part_pkg->option('output_format') || '';
1976 $format = '' if $format =~ /^sum_/;
1977 # sensible default if there is no format or it's a summary format
1978 if ( $cust_pkg->part_pkg->plan eq 'voip_inbound' ) {
1979 $format ||= 'source_default';
1980 $callback_opt{inbound} = 1;
1983 $format ||= 'default';
1986 $callback_opt{format} = $format;
1987 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
1990 my $start = $cust_pkg->setup;
1991 #my $end = $cust_pkg->bill; # or time?
1994 unless ( $p->{beginning} ) {
1995 $p->{beginning} = $cust_pkg->last_bill;
1996 $p->{ending} = $end;
1999 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2003 #kinda false laziness with FS::cust_main::bill, but perhaps
2004 #we should really change this bit to DateTime and DateTime::Duration
2006 #change this bit to use Date::Manip? CAREFUL with timezones (see
2007 # mailing list archive)
2008 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2009 (localtime($p->{ending}) )[0,1,2,3,4,5];
2010 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2011 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2013 if ( $freq =~ /^\d+$/ ) {
2015 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2017 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2018 } elsif ( $freq =~ /^(\d+)w$/ ) {
2020 $nmday += $weeks * 7;
2021 $pmday -= $weeks * 7;
2022 } elsif ( $freq =~ /^(\d+)d$/ ) {
2026 } elsif ( $freq =~ /^(\d+)h$/ ) {
2031 return { 'error' => "unparsable frequency: ". $freq };
2034 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2035 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2039 'svcnum' => $p->{svcnum},
2040 'beginning' => $p->{beginning},
2041 'ending' => $p->{ending},
2042 'previous' => ($previous > $start) ? $previous : $start,
2043 'next' => ($next < $end) ? $next : $end,
2044 'header' => $header,
2052 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2053 return { 'error' => $session } if $context eq 'error';
2055 my $search = { 'custnum' => $custnum };
2056 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2057 my $cust_main = qsearchs('cust_main', $search )
2058 or return { 'error' => "unknown custnum $custnum" };
2060 my $status = $cust_main->status;
2061 #false laziness w/ClientAPI/Signup.pm
2063 my $cust_pkg = new FS::cust_pkg ( {
2064 'custnum' => $custnum,
2065 'pkgpart' => $p->{'pkgpart'},
2067 my $error = $cust_pkg->check;
2068 return { 'error' => $error } if $error;
2071 unless ( $p->{'svcpart'} eq 'none' ) {
2075 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2077 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2078 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2079 $svcdb = $part_svc->svcdb;
2081 $svcdb = 'svc_acct';
2083 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2086 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2087 'svc_domain' => [ qw( domain ) ],
2088 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2089 'svc_external' => [ qw( id title ) ],
2090 'svc_pbx' => [ qw( id title ) ],
2093 my $svc_x = "FS::$svcdb"->new( {
2094 'svcpart' => $svcpart,
2095 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2098 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2101 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2102 my $acct_snarf = new FS::acct_snarf ( {
2103 'machine' => $p->{"snarf_machine$snarfnum"},
2104 'protocol' => $p->{"snarf_protocol$snarfnum"},
2105 'username' => $p->{"snarf_username$snarfnum"},
2106 '_password' => $p->{"snarf_password$snarfnum"},
2109 push @acct_snarf, $acct_snarf;
2111 $svc_x->child_objects( \@acct_snarf );
2114 my $y = $svc_x->setdefault; # arguably should be in new method
2115 return { 'error' => $y } if $y && !ref($y);
2117 $error = $svc_x->check;
2118 return { 'error' => $error } if $error;
2125 tie my %hash, 'Tie::RefHash';
2126 %hash = ( $cust_pkg => \@svc );
2128 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2129 return { 'error' => $error } if $error;
2131 my $conf = new FS::Conf;
2132 if ( $conf->exists('signup_server-realtime') ) {
2134 my $bill_error = _do_bop_realtime( $cust_main, $status );
2137 $cust_pkg->cancel('quiet'=>1);
2140 $cust_pkg->reexport;
2144 $cust_pkg->reexport;
2147 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2149 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2156 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2157 return { 'error' => $session } if $context eq 'error';
2159 my $search = { 'custnum' => $custnum };
2160 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2161 my $cust_main = qsearchs('cust_main', $search )
2162 or return { 'error' => "unknown custnum $custnum" };
2164 my $status = $cust_main->status;
2165 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2166 or return { 'error' => "unknown package $p->{pkgnum}" };
2169 my $error = FS::cust_pkg::order( $custnum,
2175 my $conf = new FS::Conf;
2176 if ( $conf->exists('signup_server-realtime') ) {
2178 my $bill_error = _do_bop_realtime( $cust_main, $status );
2181 $newpkg[0]->suspend;
2184 $newpkg[0]->reexport;
2188 $newpkg[0]->reexport;
2191 return { error => '', pkgnum => $cust_pkg->pkgnum };
2195 sub order_recharge {
2198 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2199 return { 'error' => $session } if $context eq 'error';
2201 my $search = { 'custnum' => $custnum };
2202 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2203 my $cust_main = qsearchs('cust_main', $search )
2204 or return { 'error' => "unknown custnum $custnum" };
2206 my $status = $cust_main->status;
2207 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2208 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2210 my $svc_x = $cust_svc->svc_x;
2211 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2214 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2215 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2216 recharge_totalbytes );
2217 my $amount = $part_pkg->option('recharge_amount', 1);
2219 my ($l, $v, $d) = $cust_svc->label; # blah
2220 my $pkg = "Recharge $v";
2222 my $bill_error = $cust_main->charge($amount, $pkg,
2223 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2224 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2225 $part_pkg->taxclass); #meh
2227 my $conf = new FS::Conf;
2228 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2230 $bill_error = _do_bop_realtime( $cust_main, $status );
2235 my $error = $svc_x->recharge (\%vhash);
2236 return { 'error' => $error } if $error;
2240 my $error = $bill_error;
2241 $error ||= $svc_x->recharge (\%vhash);
2242 return { 'error' => $error } if $error;
2245 return { error => '', svc => $cust_svc->part_svc->svc };
2249 sub _do_bop_realtime {
2250 my ($cust_main, $status) = (shift, shift);
2252 my $old_balance = $cust_main->balance;
2254 my $bill_error = $cust_main->bill
2255 || $cust_main->apply_payments_and_credits
2256 || $cust_main->realtime_collect('selfservice' => 1);
2258 if ( $cust_main->balance > $old_balance
2259 && $cust_main->balance > 0
2260 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
2261 1 : $status eq 'suspended' ) ) {
2262 #this makes sense. credit is "un-doing" the invoice
2263 my $conf = new FS::Conf;
2264 $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
2265 'self-service decline',
2266 'reason_type' => $conf->config('signup_credit_type'),
2268 $cust_main->apply_credits( 'order' => 'newest' );
2270 return { 'error' => '_decline', 'bill_error' => $bill_error };
2279 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2280 return { 'error' => $session } if $context eq 'error';
2282 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2283 or return { 'error' => "unknown custnum $custnum" };
2285 my @cust_pkg = sort { $a->bill <=> $b->bill }
2286 grep { $_->part_pkg->freq ne '0' }
2287 $cust_main->ncancelled_pkgs;
2289 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2291 my $total = $cust_main->balance;
2294 my $bill = $_->bill;
2295 $total += $_->part_pkg->base_recur($_, \$bill);
2296 my $renew_date = $_->part_pkg->add_freq($_->bill);
2298 'pkgnum' => $_->pkgnum,
2299 'amount' => sprintf('%.2f', $total),
2300 'bill_date' => $_->bill,
2301 'bill_date_pretty' => time2str('%x', $_->bill),
2302 'renew_date' => $renew_date,
2303 'renew_date_pretty' => time2str('%x', $renew_date),
2304 'expire_date' => $_->expire,
2305 'expire_date_pretty' => time2str('%x', $_->expire),
2310 return { 'dates' => \@array };
2314 sub payment_info_renew_info {
2316 my $renew_info = renew_info($p);
2317 my $payment_info = payment_info($p);
2318 return { %$renew_info,
2326 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2327 return { 'error' => $session } if $context eq 'error';
2329 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2330 or return { 'error' => "unknown custnum $custnum" };
2332 my $date = $p->{'date'};
2336 #freeside-daily -n -d $date fs_daily $custnum
2337 $cust_main->bill_and_collect( 'time' => $date,
2338 'invoice_time' => $now,
2339 'actual_time' => $now,
2340 'check_freq' => '1d',
2343 return { 'error' => '' };
2349 my $session = _cache->get($p->{'session_id'})
2350 or return { 'error' => "Can't resume session" }; #better error message
2352 my $custnum = $session->{'custnum'};
2354 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2355 or return { 'error' => "unknown custnum $custnum" };
2357 my $conf = new FS::Conf;
2359 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2360 or return { 'error' => 'Permission denied' };
2362 my $pkgnum = $p->{'pkgnum'};
2364 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2365 'pkgnum' => $pkgnum, } )
2366 or return { 'error' => "unknown pkgnum $pkgnum" };
2368 my $error = $cust_pkg->suspend(reason => $reasonnum);
2369 return { 'error' => $error };
2375 my $session = _cache->get($p->{'session_id'})
2376 or return { 'error' => "Can't resume session" }; #better error message
2378 my $custnum = $session->{'custnum'};
2380 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2381 or return { 'error' => "unknown custnum $custnum" };
2383 my $pkgnum = $p->{'pkgnum'};
2385 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2386 'pkgnum' => $pkgnum, } )
2387 or return { 'error' => "unknown pkgnum $pkgnum" };
2389 my $error = $cust_pkg->cancel('quiet' => 1);
2390 return { 'error' => $error };
2394 sub provision_phone {
2397 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2399 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2400 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2401 return { 'error' => $session } if $context eq 'error';
2403 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2404 return { 'error' => 'service not found' } unless $svc_phone;
2405 return { 'error' => 'invalid svcnum' }
2406 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2408 $svc_phone->email($p->{'email'})
2409 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2410 $svc_phone->forwarddst($p->{'forwarddst'})
2411 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2412 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2413 return { 'error' => $svc_phone->replace };
2417 unless($p->{'lnp'}) {
2418 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2419 $p->{'lnp_status'} = "portingin";
2420 return _provision( 'FS::svc_phone',
2421 [qw(lnp_desired_due_date lnp_other_provider
2422 lnp_other_provider_account phonenum countrycode lnp_status)],
2423 [qw(phonenum countrycode)],
2430 unless (scalar(@bulkdid)) {
2431 return _provision( 'FS::svc_phone',
2432 [qw(phonenum countrycode)],
2433 [qw(phonenum countrycode)],
2439 # bulk DID order case
2441 foreach my $did ( @bulkdid ) {
2442 $did =~ s/[^0-9]//g;
2443 $error = _provision( 'FS::svc_phone',
2444 [qw(phonenum countrycode)],
2445 [qw(phonenum countrycode)],
2447 'pkgnum' => $p->{'pkgnum'},
2448 'svcpart' => $p->{'svcpart'},
2450 'countrycode' => $p->{'countrycode'},
2451 'session_id' => $p->{'session_id'},
2454 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2456 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2459 sub provision_acct {
2461 warn "provision_acct called\n"
2464 return { 'error' => gettext('passwords_dont_match') }
2465 if $p->{'_password'} ne $p->{'_password2'};
2466 return { 'error' => gettext('empty_password') }
2467 unless length($p->{'_password'});
2469 if ($p->{'domsvc'}) {
2470 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2471 qw ( svcpart pkgnum ) );
2472 return { 'error' => gettext('invalid_domain') }
2473 unless ($domains{$p->{'domsvc'}});
2476 warn "provision_acct calling _provision\n"
2478 _provision( 'FS::svc_acct',
2479 [qw(username _password domsvc)],
2480 [qw(username _password domsvc)],
2486 sub provision_external {
2488 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2489 _provision( 'FS::svc_external',
2498 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2499 warn "_provision called for $class\n"
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 $pkgnum = $p->{'pkgnum'};
2512 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2514 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2515 'pkgnum' => $pkgnum,
2517 or return { 'error' => "unknown pkgnum $pkgnum" };
2519 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2521 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2522 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2524 warn "creating $class record\n"
2526 my $svc_x = $class->new( {
2527 'pkgnum' => $p->{'pkgnum'},
2528 'svcpart' => $p->{'svcpart'},
2529 map { $_ => $p->{$_} } @$fields
2531 warn "inserting $class record\n"
2533 my $error = $svc_x->insert;
2536 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2538 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2541 my $return = { 'svc' => $part_svc->svc,
2543 map { $_ => $svc_x->get($_) } @$return_fields
2545 warn "_provision returning ". Dumper($return). "\n"
2554 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2555 return { 'error' => $session } if $context eq 'error';
2557 my $search = { 'custnum' => $custnum };
2558 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2559 my $cust_main = qsearchs('cust_main', $search )
2560 or return { 'error' => "unknown custnum $custnum" };
2562 my $pkgnum = $p->{'pkgnum'};
2564 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2565 'pkgnum' => $pkgnum,
2567 or return { 'error' => "unknown pkgnum $pkgnum" };
2569 my $svcpart = $p->{'svcpart'};
2571 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2572 'svcpart' => $svcpart, } )
2573 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2574 my $part_svc = $pkg_svc->part_svc;
2576 my $conf = new FS::Conf;
2579 'svc' => $part_svc->svc,
2580 'svcdb' => $part_svc->svcdb,
2581 'pkgnum' => $pkgnum,
2582 'svcpart' => $svcpart,
2583 'custnum' => $custnum,
2585 'security_phrase' => 0, #XXX !
2586 'svc_acct_pop' => [], #XXX !
2588 'init_popstate' => '',
2593 small_custview( $cust_main, $conf->config('countrydefault') ),
2597 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2598 && $ret->{'svcdb'} eq 'svc_phone') {
2599 $ret->{'svcnum'} = $p->{'svcnum'};
2600 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2601 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2602 $ret->{'email'} = $svc_phone->email;
2603 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2610 sub unprovision_svc {
2613 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2614 return { 'error' => $session } if $context eq 'error';
2616 my $search = { 'custnum' => $custnum };
2617 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2618 my $cust_main = qsearchs('cust_main', $search )
2619 or return { 'error' => "unknown custnum $custnum" };
2621 my $svcnum = $p->{'svcnum'};
2623 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2624 or return { 'error' => "unknown svcnum $svcnum" };
2626 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2627 unless $cust_svc->cust_pkg->custnum == $custnum;
2629 my $conf = new FS::Conf;
2631 return { 'svc' => $cust_svc->part_svc->svc,
2632 'error' => $cust_svc->cancel,
2634 small_custview( $cust_main, $conf->config('countrydefault') ),
2639 sub myaccount_passwd {
2641 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2642 return { 'error' => $session } if $context eq 'error';
2644 return { 'error' => "New passwords don't match." }
2645 if $p->{'new_password'} ne $p->{'new_password2'};
2647 return { 'error' => 'Enter new password' }
2648 unless length($p->{'new_password'});
2650 #my $search = { 'custnum' => $custnum };
2651 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2652 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2653 my $search = " AND custnum = $1";
2654 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2656 my $svc_acct = qsearchs( {
2657 'table' => 'svc_acct',
2658 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2659 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2660 'LEFT JOIN cust_main USING ( custnum ) ',
2661 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2662 'extra_sql' => $search, #important
2664 or return { 'error' => "Service not found" };
2666 if ( exists($p->{'old_password'}) ) {
2667 return { 'error' => "Incorrect password." }
2668 unless $svc_acct->check_password($p->{'old_password'});
2671 $svc_acct->set_password($p->{'new_password'});
2672 my $error = $svc_acct->replace();
2674 my($label, $value) = $svc_acct->cust_svc->label;
2676 return { 'error' => $error,
2686 my $conf = new FS::Conf;
2687 my $verification = $conf->config('selfservice-password_reset_verification')
2688 or return { 'error' => 'Password resets disabled' };
2690 my $username = $p->{'username'};
2692 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2693 or return { 'error' => 'Account not found' };
2695 my $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2696 'domsvc' => $svc_domain->svcnum }
2698 or return { 'error' => 'Account not found' };
2700 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2701 or return { 'error' => 'Account not found' };
2703 my $cust_main = $cust_pkg->cust_main;
2707 my( $p, $cust_main ) = @_;
2708 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2709 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2712 my( $p, $cust_main ) = @_;
2713 my $cust_pay = qsearchs({
2714 'table' => 'cust_pay',
2715 'hashref' => { 'custnum' => $cust_main->custnum },
2716 'order_by' => 'ORDER BY _date DESC LIMIT 1',
2720 $p->{'amount'} == $cust_pay->paid;
2723 my( $p, $cust_main ) = @_;
2724 $p->{'zip'} eq $cust_main->zip
2725 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2729 foreach my $verify ( split(',', $verification) ) {
2731 &{ $verify{$verify} }( $p, $cust_main )
2732 or return { 'error' => 'Account not found' };
2736 #okay, we're verified, now create a unique session
2738 my $reset_session = {
2739 'svcnum' => $svc_acct->svcnum,
2742 my $timeout = '1 hour'; #?
2744 my $reset_session_id;
2746 $reset_session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
2747 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") ); #just in case
2749 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
2753 my $msgnum = $conf->config('selfservice-password_reset_msgnum', $cust_main->agentnum);
2754 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
2755 return { 'error' => "selfservice-password_reset_msgnum unset" } unless $msgnum;
2756 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
2757 my $error = $msg_template->send( 'cust_main' => $cust_main,
2758 'object' => $svc_acct,
2759 'substitutions' => {
2760 'session_id' => $reset_session_id,
2764 return { 'error' => $error }; #????
2767 return { 'error' => '' };
2770 sub check_reset_passwd {
2773 my $conf = new FS::Conf;
2774 my $verification = $conf->config('selfservice-password_reset_verification')
2775 or return { 'error' => 'Password resets disabled' };
2777 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2778 or return { 'error' => "Can't resume session" }; #better error message
2780 my $svcnum = $reset_session->{'svcnum'};
2782 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2783 or return { 'error' => "Service not found" };
2785 return { 'error' => '',
2786 'username' => $svc_acct->username,
2791 sub process_reset_passwd {
2794 my $conf = new FS::Conf;
2795 my $verification = $conf->config('selfservice-password_reset_verification')
2796 or return { 'error' => 'Password resets disabled' };
2798 return { 'error' => "New passwords don't match." }
2799 if $p->{'new_password'} ne $p->{'new_password2'};
2801 return { 'error' => 'Enter new password' }
2802 unless length($p->{'new_password'});
2804 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2805 or return { 'error' => "Can't resume session" }; #better error message
2807 my $svcnum = $reset_session->{'svcnum'};
2809 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2810 or return { 'error' => "Service not found" };
2812 $svc_acct->set_password($p->{'new_password'});
2813 my $error = $svc_acct->replace();
2815 my($label, $value) = $svc_acct->cust_svc->label;
2817 return { 'error' => $error,
2826 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2827 return { 'error' => $session } if $context eq 'error';
2829 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2830 FS::TicketSystem->init();
2832 my $conf = new FS::Conf;
2833 my $queue = $p->{'queue'}
2834 || $conf->config('ticket_system-selfservice_queueid')
2835 || $conf->config('ticket_system-default_queueid');
2837 warn "$me create_ticket: creating ticket\n" if $DEBUG;
2838 my $err_or_ticket = FS::TicketSystem->create_ticket(
2839 '', #create RT session based on FS CurrentUser (fs_selfservice)
2841 'custnum' => $custnum,
2842 'svcnum' => $session->{'svcnum'},
2843 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2846 if ( ref($err_or_ticket) ) {
2847 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2849 return { 'error' => '',
2850 'ticket_id' => $err_or_ticket->id,
2853 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2855 return { 'error' => $err_or_ticket };
2863 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2864 return { 'error' => $session } if $context eq 'error';
2866 return { error => 'requested format not implemented' }
2867 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2869 my $conf = new FS::Conf;
2870 my $age_threshold = 0;
2871 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2872 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2874 my $search = { 'custnum' => $custnum };
2875 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2876 my $cust_main = qsearchs('cust_main', $search )
2877 or return { 'error' => "unknown custnum $custnum" };
2879 # does it make more sense to just run one sql query for this instead of all the
2880 # insanity below? would increase performance greately for large data sets?
2882 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2883 my @part_svc = $cust_pkg->part_svc;
2884 foreach my $part_svc ( @part_svc ) {
2885 if($part_svc->svcdb eq 'svc_phone'){
2886 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2887 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2888 push @svc_phone, $cust_pkg_svc->svc_x
2889 if $cust_pkg_svc->date_inserted >= $age_threshold;
2897 my($xls_r,$xls_c) = (0,0);
2900 my @fields = qw( countrycode phonenum pin sip_password phone_name );
2901 if($p->{'format'} eq 'csv') {
2902 $csv = new Text::CSV_XS { 'always_quote' => 1,
2905 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2906 $content .= $csv->string;
2908 elsif($p->{'format'} eq 'xls') {
2909 my $XLS1 = new IO::Scalar \$content;
2910 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
2911 or return { 'error' => "Error opening .xls file: $!" };
2912 $xls = $xls_workbook->add_worksheet('DIDs');
2913 foreach ( @fields ) {
2914 $xls->write(0,$xls_c++,$_);
2919 foreach my $svc_phone ( @svc_phone ) {
2920 my @cols = map { $svc_phone->$_ } @fields;
2921 if($p->{'format'} eq 'csv') {
2922 return { 'error' => 'Unable to create CSV' }
2923 unless $csv->combine(@cols);
2924 $content .= $csv->string;
2926 elsif($p->{'format'} eq 'xls') {
2929 $xls->write($xls_r,$xls_c++,$_);
2935 $xls_workbook->close() if $p->{'format'} eq 'xls';
2937 { content => $content, format => $p->{'format'}, };
2942 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2943 return { 'error' => $session } if $context eq 'error';
2945 warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2946 FS::TicketSystem->init();
2947 return { 'error' => 'get_ticket configuration error' }
2948 if $FS::TicketSystem::system ne 'RT_Internal';
2950 # check existence and ownership as part of this
2951 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2952 my $rt_session = FS::TicketSystem->session('');
2953 my $Ticket = FS::TicketSystem->get_ticket_object(
2955 ticket_id => $p->{'ticket_id'},
2958 return { 'error' => 'ticket not found' } if !$Ticket;
2960 if ( length( $p->{'subject'} || '' ) ) {
2962 if ( $p->{'subject'} ne $Ticket->Subject ) {
2963 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2964 return { 'error' => "unable to set subject: $msg" } if !$val;
2968 if(length($p->{'reply'})) {
2969 my @err_or_res = FS::TicketSystem->correspond_ticket(
2971 'ticket_id' => $p->{'ticket_id'},
2972 'content' => $p->{'reply'},
2975 return { 'error' => 'unable to reply to ticket' }
2976 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2979 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2980 my $err_or_ticket = FS::TicketSystem->get_ticket(
2982 'ticket_id' => $p->{'ticket_id'},
2985 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2986 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2988 return { 'error' => $err_or_ticket };
2991 my @custs = @{$err_or_ticket->{'custs'}};
2992 my @txns = @{$err_or_ticket->{'txns'}};
2995 # superseded by check in get_ticket_object
2996 #return { 'error' => 'invalid ticket requested' }
2997 #unless grep($_ eq $custnum, @custs);
2999 foreach my $txn ( @txns ) {
3000 push @filtered_txns, $txn
3001 if ($txn->{'type'} eq 'EmailRecord'
3002 || $txn->{'type'} eq 'Correspond'
3003 || $txn->{'type'} eq 'Create');
3006 warn "$me get_ticket: successful: \n"
3008 return { 'error' => '',
3009 'transactions' => \@filtered_txns,
3010 'ticket_fields' => $err_or_ticket->{'fields'},
3011 'ticket_id' => $p->{'ticket_id'},
3015 sub adjust_ticket_priority {
3017 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3018 return { 'error' => $session } if $context eq 'error';
3020 warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3021 FS::TicketSystem->init;
3022 my $ss_priority = FS::TicketSystem->selfservice_priority;
3024 return { 'error' => 'adjust_ticket_priority configuration error' }
3025 if $FS::TicketSystem::system ne 'RT_Internal'
3028 my $values = $p->{'values'}; #hashref, id => priority value
3031 foreach my $id (keys %$values) {
3032 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3033 my $Ticket = FS::TicketSystem->get_ticket_object('',
3035 'custnum' => $custnum,
3038 $ticket_error{$id} = 'ticket not found';
3042 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3043 # We're not going to implement it for RT_External.
3044 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3045 my $new_value = $values->{$id};
3046 next if $old_value eq $new_value;
3048 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3050 # AddCustomFieldValue works fine (replacing any existing value) if it's
3051 # a single-valued custom field, which it should be. If it's not, you're
3052 # doing something wrong.
3054 if ( length($new_value) ) {
3055 ($val, $msg) = $Ticket->AddCustomFieldValue(
3056 Field => $ss_priority,
3057 Value => $new_value,
3061 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3062 Field => $ss_priority,
3063 Value => $old_value,
3067 $ticket_error{$id} = $msg if !$val;
3068 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3070 return { 'error' => '',
3071 'ticket_error' => \%ticket_error,
3072 %{ customer_info($p) } # send updated customer info back
3078 sub _custoragent_session_custnum {
3081 my($context, $session, $custnum);
3082 if ( $p->{'session_id'} ) {
3084 $context = 'customer';
3085 $session = _cache->get($p->{'session_id'})
3086 or return ( 'error' => "Can't resume session" ); #better error message
3087 $custnum = $session->{'custnum'};
3089 } elsif ( $p->{'agent_session_id'} ) {
3092 my $agent_cache = new FS::ClientAPI_SessionCache( {
3093 'namespace' => 'FS::ClientAPI::Agent',
3095 $session = $agent_cache->get($p->{'agent_session_id'})
3096 or return ( 'error' => "Can't resume session" ); #better error message
3097 $custnum = $p->{'custnum'};
3101 return ( 'error' => "Can't resume session" ); #better error message
3104 ($context, $session, $custnum);