1 package FS::ClientAPI::MyAccount;
3 use 5.008; #require 5.8+ for Time::Local 1.05+
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard 0.35;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
21 use FS::UI::bytecount qw( display_bytecount );
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types money_pretty);
27 use FS::Misc::DateTime qw(parse_datetime);
29 use FS::ClientAPI_SessionCache;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
46 use FS::acct_rt_transaction;
49 use FS::cust_location;
51 # for code organization
52 use FS::ClientAPI::MyAccount::contact;
53 use FS::ClientAPI::MyAccount::quotation;
56 $me = '[FS::ClientAPI::MyAccount]';
58 use vars qw( @cust_main_editable_fields @location_editable_fields );
59 @cust_main_editable_fields = qw(
60 first last company daytime night fax mobile
62 payby payinfo payname paystart_month paystart_year payissue payip
63 ss paytype paystate stateid stateid_state
65 @location_editable_fields = qw(
66 address1 address2 city county state zip country
70 BEGIN { #preload to reduce time customer_info takes
71 if ( $FS::TicketSystem::system ) {
72 warn "$me: initializing ticket system\n" if $DEBUG;
73 FS::TicketSystem->init();
78 $cache ||= new FS::ClientAPI_SessionCache( {
79 'namespace' => 'FS::ClientAPI::MyAccount',
86 my($context, $session, $custnum) = _custoragent_session_custnum($p);
87 #return { 'error' => $session } if $context eq 'error';
90 if ( $context eq 'customer' ) {
92 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
95 $sth->execute($custnum) or die $sth->errstr;
97 $agentnum = $sth->fetchrow_arrayref->[0]
98 or die "no agentnum for custnum $custnum";
100 #} elsif ( $context eq 'agent' ) {
101 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
104 $p->{'agentnum'} = $agentnum;
106 my $conf = new FS::Conf;
108 #false laziness w/Signup.pm
110 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
112 if ( $skin_info_cache_agent ) {
114 warn "$me loading cached skin info for agentnum $agentnum\n"
119 warn "$me populating skin info cache for agentnum $agentnum\n"
122 $skin_info_cache_agent = {
123 'agentnum' => $agentnum,
124 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
125 qw( company_name date_format ) ),
126 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
127 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
128 text_color link_color vlink_color hlink_color alink_color
129 font title_color title_align title_size menu_bgcolor menu_fontsize
132 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
133 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
134 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
136 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
137 qw( title_left_image title_right_image
138 menu_top_image menu_body_image menu_bottom_image
141 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
142 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
143 qw( head body_header body_footer company_address ) ),
144 'money_char' => $conf->config("money_char") || '$',
145 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
148 services.php Services
149 services.php My Services
150 services_new.php Order a new service
153 personal.php Personal Information
154 password.php Change Password
157 payment_cc.php Credit Card Payment
158 payment_ach.php Electronic Check Payment
159 payment_paypal.php PayPal Payment
160 payment_webpay.php Webpay Payments
163 usage_data.php Data usage
164 usage_cdr.php Call usage
166 tickets.php Help Desk
167 tickets.php Open Tickets
168 tickets_resolved.php Resolved Tickets
169 ticket_create.php Create a new ticket
177 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
181 #{ %$skin_info_cache_agent };
182 $skin_info_cache_agent;
189 my $conf = new FS::Conf;
193 'phone_login' => $conf->exists('selfservice_server-phone_login'),
194 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
195 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
196 'banner_image_md5' =>
197 md5_hex($conf->config_binary('selfservice-login_banner_image')),
204 sub login_banner_image {
206 my $conf = new FS::Conf;
207 my $image = $conf->config_binary('selfservice-login_banner_image');
209 'md5' => md5_hex($image),
214 #false laziness w/FS::ClientAPI::passwd::passwd
218 my $conf = new FS::Conf;
222 if ( $p->{'domain'} eq 'svc_phone'
223 && $conf->exists('selfservice_server-phone_login') ) {
225 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
226 return { error => 'Number not found.' } unless $svc_phone;
229 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
230 #return { error => 'Only primary user may log in.' }
231 # if $conf->exists('selfservice_server-primary_only')
232 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
234 return { error => 'Incorrect PIN.' }
235 unless $svc_phone->check_pin($p->{'password'});
239 } elsif ( $p->{email}
240 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
243 return { error => 'Incorrect contact password.' }
244 unless $contact->authenticate_password($p->{'password'});
246 $session->{'contactnum'} = $contact->contactnum;
248 $session->{'custnum'} = $contact->custnum;
252 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
254 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
255 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
257 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
258 'domsvc' => $svc_domain->svcnum, }
261 if ( $conf->exists('selfservice_server-login_svcpart') ) {
262 my @svcpart = $conf->config('selfservice_server-login_svcpart');
263 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
264 scalar( grep( $_ eq $svcpart, @svcpart ) );
269 if ( $conf->exists('selfservice_server-primary_only') ) {
272 my $cust_svc = $_->cust_svc;
273 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
274 == $cust_svc->svcpart
279 return { error => 'User not found.' } unless @svc_acct;
281 #return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
283 my $svc_acct = $svc_acct[0];
285 if ( $conf->exists('selfservice_server-login_svcpart') ) {
286 my @svcpart = $conf->config('selfservice_server-login_svcpart');
287 my $svcpart = $svc_acct->cust_svc->svcpart;
288 return { error => 'Invalid user.' }
289 unless grep($_ eq $svcpart, @svcpart);
292 return { error => 'Incorrect password.' }
293 unless $svc_acct->check_password($p->{'password'});
301 $session->{'svcnum'} = $svc_x->svcnum;
303 my $cust_svc = $svc_x->cust_svc;
304 my $cust_pkg = $cust_svc->cust_pkg;
306 my $cust_main = $cust_pkg->cust_main;
307 $session->{'custnum'} = $cust_main->custnum;
308 if ( $conf->exists('pkg-balances') ) {
309 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
310 $cust_main->ncancelled_pkgs;
311 $session->{'pkgnum'} = $cust_pkg->pkgnum
312 if scalar(@cust_pkg) > 1;
316 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
317 #return { error => 'Only primary user may log in.' }
318 # if $conf->exists('selfservice_server-primary_only')
319 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
320 my $part_pkg = $cust_pkg->part_pkg;
321 return { error => 'Only primary user may log in.' }
322 if $conf->exists('selfservice_server-primary_only')
323 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
329 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
330 } until ( ! defined _cache->get($session_id) ); #just in case
332 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
333 _cache->set( $session_id, $session, $timeout );
335 return { 'error' => '',
336 'session_id' => $session_id,
343 my $skin_info = skin_info($p);
344 if ( $p->{'session_id'} ) {
345 _cache->remove($p->{'session_id'});
346 return { %$skin_info, 'error' => '' };
348 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
355 my($context, $session, $custnum) = _custoragent_session_custnum($p);
356 return { 'error' => $session } if $context eq 'error';
358 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
359 or return { 'error' => "Service not found" };
361 $session->{'svcnum'} = $svc_acct->svcnum;
363 my $conf = new FS::Conf;
364 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
365 _cache->set( $p->{'session_id'}, $session, $timeout );
367 return { 'error' => '' };
371 sub payment_gateway {
373 # takes a cust_main and a cust_payby entry, returns the payment_gateway
374 my $conf = new FS::Conf;
375 my $cust_main = shift;
376 my $cust_payby = shift;
377 my $gatewaynum = $conf->config('selfservice-payment_gateway');
379 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
380 die "configured gatewaynum $gatewaynum not found!" if !$pg;
384 return '' if ! FS::payby->realtime($cust_payby);
385 my $pg = $cust_main->agent->payment_gateway(
386 'method' => FS::payby->payby2bop($cust_payby),
396 my $conf = new FS::Conf;
398 my $info = skin_info($p);
400 use vars qw( $cust_paybys ); #cache for performance
401 unless ( $cust_paybys ) {
403 my %cust_paybys = map { $_ => 1 }
404 map { FS::payby->payby2payment($_) }
405 $conf->config('signup_server-payby');
407 $cust_paybys = [ keys %cust_paybys ];
410 $info->{'cust_paybys'} = $cust_paybys;
412 my($context, $session, $custnum) = _custoragent_session_custnum($p);
413 return { 'error' => $session } if $context eq 'error';
415 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
416 or return { 'error' => "unknown custnum $custnum" };
418 $info->{'hide_payment_fields'} = [
420 my $pg = payment_gateway($cust_main, $_);
421 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
422 } @{ $info->{cust_paybys} }
425 $info->{'self_suspend_reason'} =
426 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
428 $info->{'edit_ticket_subject'} =
429 $conf->exists('ticket_system-selfservice_edit_subject') &&
430 $cust_main->edit_subject;
432 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
434 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
437 'custnum' => $custnum,
438 'access_pkgnum' => $session->{'pkgnum'},
439 'access_svcnum' => $session->{'svcnum'},
446 my($context, $session, $custnum) = _custoragent_session_custnum($p);
447 return { 'error' => $session } if $context eq 'error';
451 my $conf = new FS::Conf;
452 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
454 # if ( $FS::TicketSystem::system ) {
455 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
456 # FS::TicketSystem->init();
459 if ( $custnum ) { #customer record
461 %return = ( %return, %{ customer_info_short($p) } );
463 #redundant with customer_info_short, but we need it for several things below
464 my $search = { 'custnum' => $custnum };
465 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
466 my $cust_main = qsearchs('cust_main', $search )
467 or return { 'error' => "unknown custnum $custnum" };
469 my $list_tickets = list_tickets($p);
470 $return{'tickets'} = $list_tickets->{'tickets'};
472 if ( $session->{'pkgnum'} ) {
473 #XXX open invoices in the pkg-balances case
475 $return{'money_char'} = $conf->config("money_char") || '$';
478 invnum => $_->invnum,
479 date => time2str("%b %o, %Y", $_->_date),
481 charged => $_->charged,
483 } $cust_main->open_cust_bill;
484 $return{open_invoices} = \@open;
486 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
487 my $sth = dbh->prepare($sql) or die dbh->errstr;
488 $sth->execute($custnum) or die $sth->errstr;
489 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
490 $return{'last_invoice_date_pretty'} =
491 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
494 #customer_info_short always has nobalance on..
495 $return{small_custview} =
496 small_custview( $cust_main,
497 $return{countrydefault},
498 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
501 $return{has_ship_address} = $cust_main->has_ship_address;
502 $return{status} = $cust_main->status;
503 $return{statuscolor} = $cust_main->statuscolor;
505 # compatibility: some places in selfservice use this to determine
506 # if there's a ship address
507 if ( $return{has_ship_address} ) {
508 $return{ship_last} = $cust_main->last;
509 $return{ship_first} = $cust_main->first;
512 if (scalar($conf->config('support_packages'))) {
513 my @support_services = ();
514 foreach ($cust_main->support_services) {
515 my $seconds = $_->svc_x->seconds || 0;
516 my $time_remaining = (($seconds < 0) ? '-' : '' ).
517 int(abs($seconds)/3600)."h".
518 sprintf("%02d",(abs($seconds)%3600)/60)."m";
519 my $cust_pkg = $_->cust_pkg;
522 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
523 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
524 push @support_services, { svcnum => $_->svcnum,
525 time => $time_remaining,
530 $return{support_services} = \@support_services;
533 if ( $conf->config('prepayment_discounts-credit_type') ) {
535 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
538 } elsif ( $session->{'svcnum'} ) { #no customer record
540 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
541 or die "unknown svcnum";
542 $return{name} = $svc_acct->email;
546 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
550 return { 'error' => '',
551 'custnum' => $custnum,
557 sub customer_info_short {
560 my($context, $session, $custnum) = _custoragent_session_custnum($p);
561 return { 'error' => $session } if $context eq 'error';
565 my $conf = new FS::Conf;
567 if ( $custnum ) { #customer record
569 my $search = { 'custnum' => $custnum };
570 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
571 my $cust_main = qsearchs('cust_main', $search )
572 or return { 'error' => "unknown custnum $custnum" };
574 $return{display_custnum} = $cust_main->display_custnum;
576 if ( $session->{'pkgnum'} ) {
577 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
578 #next_bill_date from cust_pkg?
580 $return{balance} = $cust_main->balance;
581 $return{next_bill_date} = $cust_main->next_bill_date;
582 $return{next_bill_date_pretty} =
583 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
586 $return{balance_pretty} = money_pretty($return{balance});
588 $return{countrydefault} = scalar($conf->config('countrydefault'));
590 $return{small_custview} =
591 small_custview( $cust_main,
592 $return{countrydefault},
596 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
598 $return{payby} = $cust_main->payby;
600 #none of these are terribly expensive if we want 'em...
601 for (@cust_main_editable_fields) {
602 $return{$_} = $cust_main->get($_);
604 $return{$_} = $cust_main->masked($_) for qw/ss stateid/;
606 #maybe a little more expensive, but it should be cached by now
607 for (@location_editable_fields) {
608 $return{$_} = $cust_main->bill_location->get($_);
609 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
612 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
613 $return{payinfo} = $cust_main->paymask;
614 @return{'month', 'year'} = $cust_main->paydate_monthyear;
617 my @invoicing_list = $cust_main->invoicing_list;
618 $return{'invoicing_list'} =
619 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
620 $return{'postal_invoicing'} =
621 0 < ( grep { $_ eq 'POST' } @invoicing_list );
623 if ( $session->{'svcnum'} ) {
624 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
625 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
626 $return{'svcnum'} = $session->{'svcnum'};
629 } elsif ( $session->{'svcnum'} ) { #no customer record
631 #uuh, not supproted yet... die?
632 return { 'error' => 'customer_info_short not yet supported as agent' };
636 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
640 # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
641 # it is not customer-specific, though it is only shown to authenticated customers
642 # it is not currently agent-specific, though at some point it might be
643 $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
645 return { 'error' => '',
646 'custnum' => $custnum,
651 sub customer_recurring {
654 my($context, $session, $custnum) = _custoragent_session_custnum($p);
655 return { 'error' => $session } if $context eq 'error';
659 my $conf = new FS::Conf;
661 my $search = { 'custnum' => $custnum };
662 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
663 my $cust_main = qsearchs('cust_main', $search )
664 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
666 $return{'display_recurring'} = [ $cust_main->display_recurring ];
668 return { 'error' => '',
669 'custnum' => $custnum,
674 sub billing_history {
677 my($context, $session, $custnum) = _custoragent_session_custnum($p);
678 return { 'error' => $session } if $context eq 'error';
680 return { 'error' => 'No customer' } unless $custnum;
682 my $search = { 'custnum' => $custnum };
683 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
684 my $cust_main = qsearchs('cust_main', $search )
685 or return { 'error' => "unknown custnum $custnum" };
689 if ( $session->{'pkgnum'} ) {
690 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
691 #next_bill_date from cust_pkg?
692 return { 'error' => 'No history for package' };
695 $return{balance} = $cust_main->balance;
696 $return{balance_pretty} = money_pretty($return{balance});
697 $return{next_bill_date} = $cust_main->next_bill_date;
698 $return{next_bill_date_pretty} =
699 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
702 my $conf = new FS::Conf;
704 $return{'history'} = [
705 $cust_main->payment_history(
706 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
711 $return{'money_char'} = $conf->config("money_char") || '$',
719 my $session = _cache->get($p->{'session_id'})
720 or return { 'error' => "Can't resume session" }; #better error message
722 my $custnum = $session->{'custnum'}
723 or return { 'error' => "no customer record" };
725 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
726 or return { 'error' => "unknown custnum $custnum" };
728 my $conf = new FS::Conf;
729 if (($p->{payby} eq "CHEK" || $p->{payby} eq "DCHK") && $conf->exists('selfservice-ACH_info_readonly')) {
730 return { 'error' => "You do not have authority to add a bank account" };
733 my $new = new FS::cust_main { $cust_main->hash };
735 $new->set( $_ => $p->{$_} )
736 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
738 if ( exists($p->{address1}) ) {
739 my $bill_location = FS::cust_location->new({
740 map { $_ => $p->{$_} } @location_editable_fields
742 # if this is unchanged from before, cust_main::replace will ignore it
743 $new->set('bill_location' => $bill_location);
746 if ( exists($p->{ship_address1}) ) {
747 my $ship_location = FS::cust_location->new({
748 map { $_ => $p->{"ship_$_"} } @location_editable_fields
750 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
751 # Selfservice unfortunately tries to indicate "same as billing
752 # address" by sending all fields empty. Did this ever work?
753 $ship_location = $cust_main->bill_location;
755 $new->set('ship_location' => $ship_location);
757 # but if it hasn't been passed in at all, leave ship_location alone--
758 # DON'T change it to match bill_location.
761 if (exists($p->{'payby'})) {
762 $p->{'payby'} =~ /^([A-Z]{4})$/
763 or return { 'error' => "illegal_payby " . $p->{'payby'} };
767 if ( $payby =~ /^(CARD|DCRD)$/ ) {
769 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
771 if ( $new->payinfo eq $cust_main->paymask ) {
772 $new->payinfo($cust_main->payinfo);
773 $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
775 $new->payinfo($p->{'payinfo'});
776 return { 'error' => 'CVV2 is required' }
777 if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
778 $new->paycvv( $p->{'paycvv'} )
781 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
783 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
786 $p->{'payinfo1'} =~ /^([\dx]+)$/
787 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
789 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
790 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
792 $payinfo = $payinfo1. '@'. $payinfo2;
794 $new->payinfo( ($payinfo eq $cust_main->paymask)
795 ? $cust_main->payinfo
799 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
801 } elsif ( $payby =~ /^(BILL)$/ ) {
803 } elsif ( $payby ) { #notyet ready
804 return { 'error' => "unknown payby $payby" };
808 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
809 #false laziness with httemplate/edit/process/cust_main.cgi
810 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
811 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
813 @invoicing_list = $cust_main->invoicing_list;
816 my $error = $new->replace($cust_main, \@invoicing_list);
817 return { 'error' => $error } if $error;
820 return { 'error' => '' };
825 my $session = _cache->get($p->{'session_id'})
826 or return { 'error' => "Can't resume session" }; #better error message
832 my $conf = new FS::Conf;
833 use vars qw($payment_info); #cache for performance
834 unless ( $payment_info ) {
836 my %states = map { $_->state => 1 }
837 qsearch('cust_main_county', {
838 'country' => $conf->config('countrydefault') || 'US'
841 my %cust_paybys = map { $_ => 1 }
842 map { FS::payby->payby2payment($_) }
843 $conf->config('signup_server-payby');
845 my @cust_paybys = keys %cust_paybys;
849 #list all counties/states/countries
850 'cust_main_county' =>
851 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
853 #shortcut for one-country folks
855 [ sort { $a cmp $b } keys %states ],
857 'card_types' => card_types(),
859 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
860 'require_cvv' => $conf->exists('selfservice-require_cvv'),
861 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
863 'paytypes' => [ @FS::cust_main::paytypes ],
865 'paybys' => [ $conf->config('signup_server-payby') ],
866 'cust_paybys' => \@cust_paybys,
868 'stateid_label' => FS::Msgcat::_gettext('stateid'),
869 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
871 'show_ss' => $conf->exists('show_ss'),
872 'show_stateid' => $conf->exists('show_stateid'),
873 'show_paystate' => $conf->exists('show_bankstate'),
875 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
876 'ach_read_only' => $conf->exists('selfservice-ACH_info_readonly'),
886 my %return = %$payment_info;
888 delete $return{'cust_main_county'} if $p->{'omit_cust_main_county'};
890 my $custnum = $session->{'custnum'};
892 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
893 or return { 'error' => "unknown custnum $custnum" };
895 $return{'hide_payment_fields'} = [
897 my $pg = payment_gateway($cust_main, $_);
898 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
899 } @{ $return{cust_paybys} }
902 $return{balance} = $cust_main->balance; #XXX pkg-balances?
904 $return{payname} = $cust_main->payname
905 || ( $cust_main->first. ' '. $cust_main->get('last') );
907 $return{$_} = $cust_main->bill_location->get($_)
908 for qw(address1 address2 city state zip);
910 $return{payby} = $cust_main->payby;
911 $return{stateid_state} = $cust_main->stateid_state;
913 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
914 $return{card_type} = cardtype($cust_main->payinfo);
915 $return{payinfo} = $cust_main->paymask;
917 @return{'month', 'year'} = $cust_main->paydate_monthyear;
921 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
922 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
923 $return{payinfo1} = $payinfo1;
924 $return{payinfo2} = $payinfo2;
925 $return{paytype} = $cust_main->paytype;
926 $return{paystate} = $cust_main->paystate;
927 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
930 if ( $conf->config('prepayment_discounts-credit_type') ) {
932 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
935 #doubleclick protection
937 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
938 $return{paybatch} = $return{payunique}; #back compat
940 $return{credit_card_surcharge_percentage} = $conf->config('credit-card-surcharge-percentage', $cust_main->agentnum);
941 $return{credit_card_surcharge_flatfee} = $conf->config('credit-card-surcharge-flatfee', $cust_main->agentnum);
943 return { 'error' => '',
949 #some false laziness with httemplate/process/payment.cgi - look there for
950 #ACH and CVV support stuff
952 sub validate_payment {
955 my $session = _cache->get($p->{'session_id'})
956 or return { 'error' => "Can't resume session" }; #better error message
958 my $custnum = $session->{'custnum'};
960 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
961 or return { 'error' => "unknown custnum $custnum" };
963 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
964 or return { 'error' => gettext('illegal_amount') };
966 return { error => 'Amount must be greater than 0' } unless $amount > 0;
968 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
969 #changing the hidden form values
970 my $conf = new FS::Conf;
971 my $fee_display = $conf->config('selfservice_process-display') || 'add';
972 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
973 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
974 if ( $fee_display eq 'add'
976 and ! $fee_skip_first || scalar($cust_main->cust_pay)
979 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
980 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
983 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
984 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
985 my $discount_term = $1;
987 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
988 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
991 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
992 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
995 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
996 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
999 $payunique = $paybatch if ! length($payunique) && length($paybatch);
1001 $p->{'payby'} ||= 'CARD';
1002 $p->{'payby'} =~ /^([A-Z]{4})$/
1003 or return { 'error' => "illegal_payby " . $p->{'payby'} };
1006 #false laziness w/process/payment.cgi
1009 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1011 $p->{'payinfo1'} =~ /^([\dx]+)$/
1012 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1014 $p->{'payinfo2'} =~ /^([\dx]+)$/
1015 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1017 $payinfo = $payinfo1. '@'. $payinfo2;
1020 if ( $cust_main->paymask eq $payinfo ) {
1021 $payinfo = $cust_main->payinfo;
1025 if ($conf->exists('selfservice-ACH_info_readonly') && !$achonfile) {
1026 return { 'error' => "You are not allowed to change your payment information." };
1029 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1031 $payinfo = $p->{'payinfo'};
1035 #more intelligent matching will be needed here if you change
1036 #card_masking_method and don't remove existing paymasks
1037 if ( $cust_main->paymask eq $payinfo ) {
1038 $payinfo = $cust_main->payinfo;
1042 $payinfo =~ s/\D//g;
1043 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1044 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1048 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1049 return { 'error' => gettext('unknown_card_type') }
1050 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1052 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1053 if ( cardtype($payinfo) eq 'American Express card' ) {
1054 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1055 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1058 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1059 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1062 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1063 return { 'error' => 'CVV2 is required' };
1064 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1065 return { 'error' => 'CVV2 is required' };
1069 die "unknown payby $payby";
1072 my %payby2fields = (
1073 'CARD' => [ qw( paystart_month paystart_year payissue payip
1074 address1 address2 city state zip country ) ],
1075 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1079 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1082 'cust_main' => $cust_main, #XXX or just custnum??
1083 'amount' => sprintf('%.2f', $amount),
1085 'payinfo' => $payinfo,
1086 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1087 'card_type' => $card_type,
1088 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1089 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1090 'month' => $p->{'month'},
1091 'year' => $p->{'year'},
1092 'payname' => $payname,
1093 'payunique' => $payunique,
1094 'paybatch' => $paybatch,
1095 'paycvv' => $paycvv,
1096 'payname' => $payname,
1097 'discount_term' => $discount_term,
1098 'pkgnum' => $session->{'pkgnum'},
1099 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1109 my $validate = validate_payment($p);
1110 return $validate if $validate->{'error'};
1112 my $conf = new FS::Conf;
1113 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1114 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1116 +{ map { $_=>$validate->{$_} }
1117 qw( card_type paymask payname paydate_pretty month year amount
1118 address1 address2 city state zip country
1124 sub process_stored_payment {
1127 my $session_id = $p->{'session_id'};
1129 my $payment_info = _cache->get( "payment_$session_id" )
1130 or return { 'error' => "Can't resume session" }; #better error message
1132 do_process_payment($payment_info);
1136 sub process_payment {
1139 my $payment_info = validate_payment($p);
1140 return $payment_info if $payment_info->{'error'};
1142 do_process_payment($payment_info);
1146 sub do_process_payment {
1147 my $validate = shift;
1149 my $cust_main = $validate->{'cust_main'};
1151 my $amount = delete $validate->{'amount'};
1154 my $payby = delete $validate->{'payby'};
1156 if ( $validate->{'save'} ) {
1157 my $new = new FS::cust_main { $cust_main->hash };
1158 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1159 $new->set( $_ => $validate->{$_} )
1160 foreach qw( payname paystart_month paystart_year payissue payip );
1161 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1163 my $bill_location = FS::cust_location->new({
1164 map { $_ => $validate->{$_} }
1165 qw(address1 address2 city state country zip)
1167 $new->set('bill_location' => $bill_location);
1168 # but don't allow the service address to change this way.
1170 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1171 $new->set( $_ => $validate->{$_} )
1172 foreach qw( payname payip paytype paystate
1173 stateid stateid_state );
1174 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1176 $new->payinfo( $validate->{'payinfo'} ); #to properly set paymask
1177 $new->set( 'paydate' => $validate->{'paydate'} );
1178 my $error = $new->replace($cust_main);
1180 #no, this causes customers to process their payments again
1181 #return { 'error' => $error };
1182 #XXX just warn verosely for now so i can figure out how these happen in
1183 # the first place, eventually should redirect them to the "change
1184 #address" page but indicate if the payment processed?
1185 delete($validate->{'payinfo'}); #don't want to log this!
1186 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1187 "NEW: ". Dumper($new)."\n".
1188 "OLD: ". Dumper($cust_main)."\n".
1189 "PACKET: ". Dumper($validate)."\n";
1195 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1199 'paynum_ref' => \$paynum,
1202 return { 'error' => $error } if $error;
1204 #no error, so order the fee package if applicable...
1205 my $conf = new FS::Conf;
1206 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1207 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1209 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1211 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1213 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1214 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1217 #and generate an invoice for it now too
1218 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1219 return { 'error' => "payment processed and fee ordered successfully, but error billing fee: $error" }
1224 $cust_main->apply_payments;
1227 my $receipt_html = '';
1229 # currently supported for realtime CC only; send receipt data to SS
1230 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1233 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1236 <TD ALIGN="right">Payment#</TD>
1237 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1241 <TD ALIGN="right">Date</TD>
1243 <TD BGCOLOR="#FFFFFF"><B>! .
1244 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1250 <TD ALIGN="right">Amount</TD>
1251 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1256 <TD ALIGN="right">Payment method</TD>
1257 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1270 'amount' => sprintf('%.2f', $cust_pay->paid),
1271 'date' => $cust_pay->_date,
1272 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1273 'time_pretty' => time2str('%T', $cust_pay->_date),
1274 'auth_num' => $cust_pay->auth,
1275 'order_num' => $cust_pay->order_number,
1276 'receipt_html' => $receipt_html,
1283 'receipt_html' => '',
1290 sub realtime_collect {
1293 my $session = _cache->get($p->{'session_id'})
1294 or return { 'error' => "Can't resume session" }; #better error message
1296 my $custnum = $session->{'custnum'};
1298 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1299 or return { 'error' => "unknown custnum $custnum" };
1302 if ( $p->{'amount'} ) {
1303 $amount = $p->{'amount'};
1305 elsif ( $session->{'pkgnum'} ) {
1306 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1309 $amount = $cust_main->balance;
1312 my $error = $cust_main->realtime_collect(
1313 'method' => $p->{'method'},
1314 'amount' => $amount,
1315 'pkgnum' => $session->{'pkgnum'},
1316 'session_id' => $p->{'session_id'},
1320 return { 'error' => $error } unless ref( $error );
1322 return { 'error' => '', amount => $amount, %$error };
1325 sub start_thirdparty {
1327 my $session = _cache->get($p->{'session_id'})
1328 or return { 'error' => "Can't resume session" }; #better error message
1329 my $custnum = $session->{'custnum'};
1330 my $cust_main = FS::cust_main->by_key($custnum);
1332 my $amount = $p->{'amount'}
1333 or return { error => 'no amount' };
1335 my $result = $cust_main->create_payment(
1336 'method' => $p->{'method'},
1337 'amount' => $p->{'amount'},
1338 'pkgnum' => $session->{'pkgnum'},
1339 'session_id' => $p->{'session_id'},
1342 if ( ref($result) ) { # hashref or error
1345 return { error => $result };
1349 sub finish_thirdparty {
1351 my $session_id = delete $p->{'session_id'};
1352 my $session = _cache->get($session_id)
1353 or return { 'error' => "Can't resume session" };
1354 my $custnum = $session->{'custnum'};
1355 my $cust_main = FS::cust_main->by_key($custnum);
1357 if ( $p->{_cancel} ) {
1358 # customer backed out of making a payment
1359 return $cust_main->cancel_payment( $session_id );
1361 my $result = $cust_main->execute_payment( $session_id, %$p );
1362 if ( ref($result) ) {
1365 return { error => $result };
1369 sub process_payment_order_pkg {
1372 my $hr = process_payment($p);
1373 return $hr if $hr->{'error'};
1378 sub process_payment_order_renew {
1381 my $hr = process_payment($p);
1382 return $hr if $hr->{'error'};
1387 sub process_prepay {
1391 my $session = _cache->get($p->{'session_id'})
1392 or return { 'error' => "Can't resume session" }; #better error message
1396 my $custnum = $session->{'custnum'};
1398 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1399 or return { 'error' => "unknown custnum $custnum" };
1401 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1402 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1410 return { 'error' => $error } if $error;
1412 return { 'error' => '',
1413 'amount' => $amount,
1414 'seconds' => $seconds,
1415 'duration' => duration_exact($seconds),
1416 'upbytes' => $upbytes,
1417 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1418 'downbytes' => $downbytes,
1419 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1420 'totalbytes'=> $totalbytes,
1421 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1428 my $session = _cache->get($p->{'session_id'})
1429 or return { 'error' => "Can't resume session" }; #better error message
1431 my $custnum = $session->{'custnum'};
1433 my $invnum = $p->{'invnum'};
1435 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1436 'custnum' => $custnum } )
1437 or return { 'error' => "Can't find invnum" };
1441 return { 'error' => '',
1442 'invnum' => $invnum,
1443 'invoice_text' => join('', $cust_bill->print_text ),
1444 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1451 my $session = _cache->get($p->{'session_id'})
1452 or return { 'error' => "Can't resume session" }; #better error message
1454 my $custnum = $session->{'custnum'};
1456 my $invnum = $p->{'invnum'};
1458 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1459 'custnum' => $custnum } )
1460 or return { 'error' => "Can't find invnum" };
1464 return { 'error' => '',
1465 'invnum' => $invnum,
1466 'invoice_pdf' => $cust_bill->print_pdf({
1467 'unsquelch_cdr' => 1,
1468 'locale' => $p->{'locale'},
1474 sub legacy_invoice {
1476 my $session = _cache->get($p->{'session_id'})
1477 or return { 'error' => "Can't resume session" }; #better error message
1479 my $custnum = $session->{'custnum'};
1481 my $legacyinvnum = $p->{'legacyinvnum'};
1484 'legacyinvnum' => $legacyinvnum,
1485 'custnum' => $custnum,
1488 my $legacy_cust_bill =
1489 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1490 || qsearchs('legacy_cust_bill', \%hash )
1491 or return { 'error' => "Can't find legacyinvnum" };
1495 return { 'error' => '',
1496 'legacyinvnum' => $legacyinvnum,
1497 'legacyid' => $legacy_cust_bill->legacyid,
1498 'invoice_html' => $legacy_cust_bill->content_html,
1503 sub legacy_invoice_pdf {
1505 my $session = _cache->get($p->{'session_id'})
1506 or return { 'error' => "Can't resume session" }; #better error message
1508 my $custnum = $session->{'custnum'};
1510 my $legacyinvnum = $p->{'legacyinvnum'};
1512 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1513 'legacyinvnum' => $legacyinvnum,
1514 'custnum' => $custnum,
1515 }) or return { 'error' => "Can't find legacyinvnum" };
1519 return { 'error' => '',
1520 'legacyinvnum' => $legacyinvnum,
1521 'legacyid' => $legacy_cust_bill->legacyid,
1522 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1530 #sessioning for this? how do we get the session id to the backend invoice
1531 # template so it can add it to the link, blah
1534 if ( $p->{'invnum'} ) {
1535 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1536 or return { 'error' => 'unknown invnum' };
1537 $agentnum = $cust_bill->cust_main->agentnum;
1540 my $templatename = $p->{'template'} || $p->{'templatename'};
1542 #false laziness-ish w/view/cust_bill-logo.cgi
1544 my $conf = new FS::Conf;
1545 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1546 $templatename = "_$1";
1551 my $filename = "logo$templatename.png";
1553 return { 'error' => '',
1554 'logo' => $conf->config_binary($filename, $agentnum),
1555 'content_type' => 'image/png', #should allow gif, jpg too
1562 my $session = _cache->get($p->{'session_id'})
1563 or return { 'error' => "Can't resume session" }; #better error message
1565 my $custnum = $session->{'custnum'};
1567 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1568 or return { 'error' => "unknown custnum $custnum" };
1570 my $conf = new FS::Conf;
1572 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1574 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1579 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1580 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1581 my $owed = $_->owed;
1583 +{ 'invnum' => $_->invnum,
1584 '_date' => $_->_date,
1585 'date' => time2str("%b %o, %Y", $_->_date),
1586 'date_short' => time2str("%m-%d-%Y", $_->_date),
1587 'previous' => sprintf('%.2f', ($_->previous)[0]),
1588 'charged' => sprintf('%.2f', $_->charged),
1589 'owed' => sprintf('%.2f', $owed),
1590 'balance' => sprintf('%.2f', $balance),
1591 'lastpay' => @payments_and_credits
1592 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1598 return { 'error' => '',
1599 'balance' => $cust_main->balance,
1600 'money_char' => $conf->config("money_char") || '$',
1601 'invoices' => $invoices,
1602 'legacy_invoices' => [
1604 +{ 'legacyinvnum' => $_->legacyinvnum,
1605 'legacyid' => $_->legacyid,
1606 '_date' => $_->_date,
1607 'date' => time2str("%b %o, %Y", $_->_date),
1608 'date_short' => time2str("%m-%d-%Y", $_->_date),
1609 'charged' => sprintf('%.2f', $_->charged),
1610 'has_content' => ( length($_->content_pdf)
1611 || length($_->content_html) ),
1621 my $session = _cache->get($p->{'session_id'})
1622 or return { 'error' => "Can't resume session" }; #better error message
1624 my $custnum = $session->{'custnum'};
1626 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1627 or return { 'error' => "unknown custnum $custnum" };
1629 return { 'error' => '',
1630 'balance' => $cust_main->balance,
1631 'money_char' => FS::Conf->new->config("money_char") || '$',
1632 'payments' => [ map $_->SSAPI_getinfo, $cust_main->cust_pay ],
1636 sub payment_receipt {
1638 my $session = _cache->get($p->{'session_id'})
1639 or return { 'error' => "Can't resume session" }; #better error message
1641 my $custnum = $session->{'custnum'};
1643 my $cust_pay = qsearchs('cust_pay', { 'custnum' => $custnum,
1644 'paynum' => $p->{'paynum'},
1647 or return { 'error' => "unknown payment ". $p->{'paynum'} };
1651 %{ $cust_pay->SSAPI_getinfo },
1657 my $session = _cache->get($p->{'session_id'})
1658 or return { 'error' => "Can't resume session" }; #better error message
1660 my $custnum = $session->{'custnum'};
1662 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1663 or return { 'error' => "unknown custnum $custnum" };
1665 my @errors = $cust_main->cancel( 'quiet'=>1 );
1667 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1669 return { 'error' => $error };
1676 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1677 return { 'error' => $session } if $context eq 'error';
1679 my $pkg = qsearchs({
1680 'table' => 'cust_pkg',
1681 'addl_from' => 'LEFT JOIN part_pkg USING ( pkgpart )',
1683 'custnum' => $custnum,
1684 'pkgnum' => $p->{'pkgnum'},
1687 or return {'error' => 'unknown pkg num $pkgnum'};
1690 pkg_label => $pkg->pkg,
1691 pkgpart => $pkg->pkgpart,
1692 classnum => $pkg->classnum,
1700 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1701 return { 'error' => $session } if $context eq 'error';
1703 my $search = { 'custnum' => $custnum };
1704 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1705 my $cust_main = qsearchs('cust_main', $search )
1706 or return { 'error' => "unknown custnum $custnum" };
1708 my $conf = new FS::Conf;
1709 my $immutable = $conf->exists('selfservice_immutable-package');
1711 # the duplication below is necessary:
1712 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1713 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1714 # non-backwards-compatible change breaking the software of anyone using the API
1715 # instead of the stock selfservice
1716 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1717 if( $conf->exists('selfservice_server-view-wholesale') ) {
1718 return { 'svcnum' => $session->{'svcnum'},
1719 'custnum' => $custnum,
1720 'cust_pkg' => [ map {
1722 immutable => $immutable,
1723 part_pkg => [ map $_->hashref, $_->part_pkg ],
1725 [ map $_->hashref, $_->available_part_svc ],
1727 [ map { my $ref = { $_->hash,
1728 label => [ $_->label ],
1730 $ref->{_password} = $_->svc_x->_password
1731 if $context eq 'agent'
1732 && $conf->exists('agent-showpasswords')
1733 && $_->part_svc->svcdb eq 'svc_acct';
1738 } $cust_main->cust_pkg
1741 small_custview( $cust_main, $conf->config('countrydefault') ),
1742 'wholesale_view' => 1,
1743 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1744 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1745 'lnp' => $conf->exists('svc_phone-lnp'),
1749 { 'svcnum' => $session->{'svcnum'},
1750 'custnum' => $custnum,
1751 'cust_pkg' => [ map {
1752 my $primary_cust_svc = $_->primary_cust_svc;
1755 immutable => $immutable,
1756 pkg_label => $_->pkg_locale,
1757 status => $_->status,
1758 statuscolor => $_->statuscolor,
1760 [ map { $_->hashref }
1761 grep { $_->selfservice_access ne 'hidden' }
1762 $_->available_part_svc
1765 [ map { my $ref = { $_->hash,
1766 label => [ $_->label ],
1768 $ref->{_password} = $_->svc_x->_password
1769 if $context eq 'agent'
1770 && $conf->exists('agent-showpasswords')
1771 && $_->part_svc->svcdb eq 'svc_acct';
1772 $ref->{svchash} = { $_->svc_x->hash } if
1773 $_->part_svc->svcdb eq 'svc_phone';
1774 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1775 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1778 grep { $_->part_svc->selfservice_access ne 'hidden' }
1783 ? { $primary_cust_svc->hash,
1784 label => [ $primary_cust_svc->label ],
1785 finger => $primary_cust_svc->svc_x->finger, #uuh
1786 $primary_cust_svc->part_svc->hash,
1790 } $cust_main->ncancelled_pkgs
1793 small_custview( $cust_main, $conf->config('countrydefault') ),
1794 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1802 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1803 return { 'error' => $session } if $context eq 'error';
1805 my $conf = new FS::Conf;
1807 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1808 my $search = { 'custnum' => $custnum };
1809 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1810 my $cust_main = qsearchs('cust_main', $search )
1811 or return { 'error' => "unknown custnum $custnum" };
1813 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1814 if ( ! $pkgnum && $p->{'svcnum'} ) {
1815 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1816 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1820 my @cust_pkg_usage = ();
1821 foreach my $cust_pkg ( $p->{'ncancelled'}
1822 ? $cust_main->ncancelled_pkgs
1823 : $cust_main->unsuspended_pkgs ) {
1824 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1825 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1826 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1829 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1832 foreach (@cust_pkg_usage) {
1833 my $part = $_->part_pkg_usage;
1834 my $tag = $part->description . ($part->shared ? 1 : 0);
1835 my $row = $usage_pools{$tag}
1836 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1837 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1838 $row->[2] += $part->minutes; # minutes total
1840 } # otherwise just leave them empty
1842 if ( $p->{'svcdb'} ) {
1843 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1845 : ref($p->{'svcdb'}) eq 'ARRAY'
1846 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1847 : { $p->{'svcdb'} => 1 };
1848 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1851 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1854 my @svcs; # stuff to return to the client
1855 my %bytes_used_total; # for _used columns only
1856 foreach my $cust_svc (@cust_svc) {
1857 my $svc_x = $cust_svc->svc_x;
1858 my($label, $value) = $cust_svc->label;
1859 my $part_svc = $cust_svc->part_svc;
1860 my $svcdb = $part_svc->svcdb;
1861 my $cust_pkg = $cust_svc->cust_pkg;
1862 my $part_pkg = $cust_pkg->part_pkg;
1865 'svcnum' => $cust_svc->svcnum,
1866 'display_svcnum' => $cust_svc->display_svcnum,
1870 'pkg_label' => $cust_pkg->pkg_locale,
1871 'pkg_status' => $cust_pkg->status,
1872 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1875 # would it make sense to put this in a svc_* method?
1877 if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
1878 my $last_bill = $cust_pkg->last_bill || 0;
1880 my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
1881 my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
1884 'seconds_used' => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
1885 'upbytes_used' => display_bytecount($up_used),
1886 'downbytes_used' => display_bytecount($down_used),
1887 'totalbytes_used' => display_bytecount($up_used + $down_used)
1889 $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
1890 $bytes_used_total{'upbytes_used'} += $up_used;
1891 $bytes_used_total{'downbytes_used'} += $down_used;
1892 $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
1895 if ( $svcdb eq 'svc_acct' ) {
1896 foreach (qw(username email finger seconds)) {
1897 $hash{$_} = $svc_x->$_;
1903 'upbytes' => display_bytecount($svc_x->upbytes),
1904 'downbytes' => display_bytecount($svc_x->downbytes),
1905 'totalbytes' => display_bytecount($svc_x->totalbytes),
1907 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1908 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1909 'recharge_upbytes' =>
1910 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1911 'recharge_downbytes' =>
1912 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1913 'recharge_totalbytes' =>
1914 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1919 } elsif ( $svcdb eq 'svc_dsl' ) {
1921 $hash{'phonenum'} = $svc_x->phonenum;
1922 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1923 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1924 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1927 $hash{'name'} = $cust_main->name;
1929 # no usage to hide here
1931 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1933 # could potentially show lots of things...
1934 $hash{'outbound'} = 1;
1935 $hash{'inbound'} = 0;
1936 if ( $svcdb eq 'svc_phone' ) {
1937 if ( $part_pkg->plan eq 'voip_inbound' ) {
1938 $hash{'outbound'} = 0;
1939 $hash{'inbound'} = 1;
1940 } elsif ( $part_pkg->option('selfservice_inbound_format')
1941 or $conf->config('selfservice-default_inbound_cdr_format')
1943 $hash{'inbound'} = 1;
1946 foreach (qw(inbound outbound)) {
1947 # hmm...we can't filter by status here, because there might
1948 # not be cdr_terminations at all. have to go by date.
1949 # find all since the last bill date.
1950 # XXX cdr types? we are going to need them.
1952 my $sum_cdr = $svc_x->sum_cdrs(
1953 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1954 'begin' => ($cust_pkg->last_bill || 0),
1956 'disable_charged_party' => 1,
1958 $hash{$_} = $sum_cdr->hashref;
1961 } # not hiding usage
1965 } # foreach $cust_svc
1967 foreach my $field (keys %bytes_used_total) {
1968 if ($field =~ /bytes/) {
1969 $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
1974 'svcnum' => $session->{'svcnum'},
1975 'custnum' => $custnum,
1976 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1977 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1979 'bytes_used_total' => \%bytes_used_total,
1981 map { $usage_pools{$_} }
1985 'hide_usage' => $hide_usage,
1990 sub _customer_svc_x {
1991 my($custnum, $svcnum, $table) = (shift, shift, shift);
1992 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1994 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1995 my $search = " AND custnum = $1";
1996 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1999 'table' => ($table || 'svc_acct'),
2000 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2001 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
2002 #'LEFT JOIN cust_main USING ( custnum ) ',
2003 'hashref' => $hashref,
2004 'extra_sql' => $search, #important
2009 sub svc_status_html {
2012 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2013 return { 'error' => $session } if $context eq 'error';
2015 #XXX only svc_dsl for now
2016 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2017 or return { 'error' => "Service not found" };
2019 my $html = $svc_x->getstatus_html;
2021 return { 'html' => $html };
2025 sub svc_status_hash {
2028 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2029 return { 'error' => $session } if $context eq 'error';
2031 #XXX only svc_acct for now
2032 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2033 or return { 'error' => "Service not found" };
2035 my ( $html, $hashref ) = $svc_x->export_getstatus;
2040 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
2041 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2042 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2043 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2044 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2047 my( $p, $method ) = @_;
2049 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2050 return { 'error' => $session } if $context eq 'error';
2052 #XXX only svc_acct for now
2053 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2054 or return { 'error' => "Service not found" };
2056 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2058 my $error = $svc_x->$method($p); #$p? returns error?
2059 return { 'error' => $error } if $error;
2061 return {}; #? { 'error' => '' }
2065 sub acct_forward_info {
2068 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2069 return { 'error' => $session } if $context eq 'error';
2071 my $svc_forward = _customer_svc_x( $custnum,
2072 { 'srcsvc' => $p->{'svcnum'} },
2075 or return { 'error' => '',
2079 return { 'error' => '',
2080 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2085 sub process_acct_forward {
2087 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2088 return { 'error' => $session } if $context eq 'error';
2090 my $old = _customer_svc_x( $custnum,
2091 { 'srcsvc' => $p->{'svcnum'} },
2095 if ( $p->{'dst'} eq '' ) {
2097 my $error = $old->delete;
2098 return { 'error' => $error };
2100 return { 'error' => '' };
2103 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2104 'dst' => $p->{'dst'},
2109 $new->svcnum($old->svcnum);
2110 my $cust_svc = $old->cust_svc;
2111 $new->svcpart($old->svcpart);
2112 $new->pkgnuym($old->pkgnum);
2113 $error = $new->replace($old);
2115 my $conf = new FS::Conf;
2116 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2118 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2119 or return { 'error' => 'No service' }; #how would we even get here?
2121 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2123 $error = $new->insert;
2126 return { 'error' => $error };
2130 sub list_dsl_devices {
2133 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2134 return { 'error' => $session } if $context eq 'error';
2136 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2137 or return { 'error' => "Service not found" };
2140 'devices' => [ map {
2141 +{ 'mac_addr' => $_->mac_addr };
2142 } $svc_dsl->dsl_device
2148 sub add_dsl_device {
2151 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2152 return { 'error' => $session } if $context eq 'error';
2154 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2155 or return { 'error' => "Service not found" };
2157 return { 'error' => 'No MAC address supplied' }
2158 unless length($p->{'mac_addr'});
2160 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2161 'mac_addr' => scalar($p->{'mac_addr'}),
2163 my $error = $dsl_device->insert;
2164 return { 'error' => $error };
2168 sub delete_dsl_device {
2171 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2172 return { 'error' => $session } if $context eq 'error';
2174 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2175 or return { 'error' => "Service not found" };
2177 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2178 'mac_addr' => scalar($p->{'mac_addr'}),
2181 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2183 my $error = $dsl_device->delete;
2184 return { 'error' => $error };
2190 _usage_details( \&_port_graph, $p,
2191 'svcdb' => 'svc_port',
2196 my($svc_port, $begin, $end) = @_;
2198 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2199 push @usage, { 'png' => $pngOrError };
2203 sub _list_svc_usage {
2204 my($svc_acct, $begin, $end) = @_;
2206 foreach my $part_export (
2207 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2208 qw( sqlradius sqlradius_withdomain )
2210 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2215 sub list_svc_usage {
2216 _usage_details(\&_list_svc_usage, @_);
2219 sub _list_support_usage {
2220 my($svc_acct, $begin, $end) = @_;
2222 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2223 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2225 push @usage, { 'seconds' => $_->seconds,
2226 'support' => $_->support,
2227 '_date' => $_->_date,
2228 'id' => $_->transaction_id,
2229 'creator' => $_->creator,
2230 'subject' => $_->subject,
2231 'status' => $_->status,
2232 'ticketid' => $_->ticketid,
2238 sub list_support_usage {
2239 _usage_details(\&_list_support_usage, @_);
2242 sub _list_cdr_usage {
2243 # XXX CDR type support...
2244 # XXX any way to do a paged search on this?
2245 # we have to return the results all at once...
2246 my($svc_x, $begin, $end, %opt) = @_;
2247 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2251 'disable_charged_party' => 1,
2256 sub list_cdr_usage {
2258 _usage_details( \&_list_cdr_usage, $p );
2261 sub _usage_details {
2262 my($callback, $p, %opt) = @_;
2263 my $conf = FS::Conf->new;
2265 if ( $conf->exists('selfservice_hide-usage') ) {
2266 return { 'error' => 'Viewing usage is not allowed.' };
2269 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2270 return { 'error' => $session } if $context eq 'error';
2272 my $search = { 'svcnum' => $p->{'svcnum'} };
2273 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2275 my $cust_svc = qsearchs( 'cust_svc', $search );
2276 return { 'error' => 'No service selected in list_svc_usage' }
2279 my $svc_x = $cust_svc->svc_x;
2280 my $svcdb = $svc_x->table;
2281 my $cust_pkg = $cust_svc->cust_pkg;
2282 my $freq = $cust_pkg->part_pkg->freq;
2285 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2287 if ( $p->{inbound} ) {
2288 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2289 || $conf->config('selfservice-default_inbound_cdr_format')
2290 || 'source_default';
2291 $callback_opt{inbound} = 1;
2293 $format = $cust_pkg->part_pkg->option('selfservice_format')
2294 || $conf->config('selfservice-default_cdr_format')
2298 $callback_opt{format} = $format;
2299 $callback_opt{use_clid} = 1;
2300 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2303 my $start = $cust_pkg->setup;
2304 #my $end = $cust_pkg->bill; # or time?
2307 unless ( $p->{beginning} ) {
2308 $p->{beginning} = $cust_pkg->last_bill;
2309 $p->{ending} = $end;
2312 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2313 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2315 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2319 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2320 # ugly kludge, I know
2321 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2322 if (defined $delete_col) {
2323 delete($_->[$delete_col]) foreach ($header, @usage);
2327 #kinda false laziness with FS::cust_main::bill, but perhaps
2328 #we should really change this bit to DateTime and DateTime::Duration
2330 #change this bit to use Date::Manip? CAREFUL with timezones (see
2331 # mailing list archive)
2332 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2333 (localtime($p->{ending}) )[0,1,2,3,4,5];
2334 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2335 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2337 if ( $freq =~ /^\d+$/ ) {
2339 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2341 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2342 } elsif ( $freq =~ /^(\d+)w$/ ) {
2344 $nmday += $weeks * 7;
2345 $pmday -= $weeks * 7;
2346 } elsif ( $freq =~ /^(\d+)d$/ ) {
2350 } elsif ( $freq =~ /^(\d+)h$/ ) {
2355 return { 'error' => "unparsable frequency: ". $freq };
2358 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2359 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2363 'svcnum' => $p->{svcnum},
2364 'beginning' => $p->{beginning},
2365 'ending' => $p->{ending},
2366 'inbound' => $p->{inbound},
2367 'previous' => ($previous > $start) ? $previous : $start,
2368 'next' => ($next < $end) ? $next : $end,
2369 'header' => $header,
2377 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2378 return { 'error' => $session } if $context eq 'error';
2380 my $search = { 'custnum' => $custnum };
2381 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2382 my $cust_main = qsearchs('cust_main', $search )
2383 or return { 'error' => "unknown custnum $custnum" };
2385 my $status = $cust_main->status;
2387 my %order_pkg_options = ();
2388 if ( $p->{locationnum} > 0 ) {
2389 $order_pkg_options{locationnum} = delete($p->{locationnum});
2390 } elsif ( $p->{address1} ) {
2391 $order_pkg_options{'cust_location'} = new FS::cust_location {
2392 map { $_ => $p->{$_} }
2393 qw( address1 address2 city county state zip country )
2397 #false laziness w/ClientAPI/Signup.pm
2399 my $cust_pkg = new FS::cust_pkg ( {
2400 'custnum' => $custnum,
2401 'pkgpart' => $p->{'pkgpart'},
2402 'quantity' => $p->{'quantity'} || 1,
2404 my $error = $cust_pkg->check;
2405 return { 'error' => $error } if $error;
2408 unless ( $p->{'svcpart'} eq 'none' ) {
2412 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2414 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2415 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2416 $svcdb = $part_svc->svcdb;
2418 $svcdb = 'svc_acct';
2420 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2423 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2424 'svc_domain' => [ qw( domain ) ],
2425 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2426 'svc_external' => [ qw( id title ) ],
2427 'svc_pbx' => [ qw( id title ) ],
2430 my $svc_x = "FS::$svcdb"->new( {
2431 'svcpart' => $svcpart,
2432 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2435 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2438 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2439 my $acct_snarf = new FS::acct_snarf ( {
2440 'machine' => $p->{"snarf_machine$snarfnum"},
2441 'protocol' => $p->{"snarf_protocol$snarfnum"},
2442 'username' => $p->{"snarf_username$snarfnum"},
2443 '_password' => $p->{"snarf_password$snarfnum"},
2446 push @acct_snarf, $acct_snarf;
2448 $svc_x->child_objects( \@acct_snarf );
2451 my $y = $svc_x->setdefault; # arguably should be in new method
2452 return { 'error' => $y } if $y && !ref($y);
2454 $error = $svc_x->check;
2455 return { 'error' => $error } if $error;
2461 $error = $cust_main->order_pkg(
2462 'cust_pkg' => $cust_pkg,
2467 return { 'error' => $error } if $error;
2469 my $conf = new FS::Conf;
2470 if ( $conf->exists('signup_server-realtime') ) {
2472 my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2475 $cust_pkg->cancel('quiet'=>1);
2478 $cust_pkg->reexport;
2482 $cust_pkg->reexport;
2485 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2487 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2494 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2495 return { 'error' => $session } if $context eq 'error';
2497 my $conf = new FS::Conf;
2498 my $immutable = $conf->exists('selfservice_immutable-package');
2499 return { 'error' => "Package modification disabled" } if $immutable;
2501 my $search = { 'custnum' => $custnum };
2502 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2503 my $cust_main = qsearchs('cust_main', $search )
2504 or return { 'error' => "unknown custnum $custnum" };
2506 my $status = $cust_main->status;
2507 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2508 or return { 'error' => "unknown package $p->{pkgnum}" };
2510 #if someone does need self-service package change of suspended packages,
2511 # figure out how to be more discriminating
2512 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2513 if $cust_pkg->status eq 'suspended';
2515 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2516 'quantity' => $p->{'quantity'} || 1,
2519 my $new_pkg = qsearchs('part_pkg', { 'pkgpart' => $p->{pkgpart} } )
2520 or return { 'error' => "unknown package $p->{pkgpart}" };
2522 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2523 unless ref($err_or_cust_pkg);
2526 if ( $conf->exists('signup_server-realtime') ) {
2528 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2531 $err_or_cust_pkg->suspend;
2534 $err_or_cust_pkg->reexport;
2538 $err_or_cust_pkg->reexport;
2541 return { error => '', pkg => $new_pkg->pkg, pkgnum => $err_or_cust_pkg->pkgnum };
2545 sub order_recharge {
2548 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2549 return { 'error' => $session } if $context eq 'error';
2551 my $search = { 'custnum' => $custnum };
2552 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2553 my $cust_main = qsearchs('cust_main', $search )
2554 or return { 'error' => "unknown custnum $custnum" };
2556 my $status = $cust_main->status;
2557 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2558 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2560 my $svc_x = $cust_svc->svc_x;
2561 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2564 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2565 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2566 recharge_totalbytes );
2567 my $amount = $part_pkg->option('recharge_amount', 1);
2569 my ($l, $v, $d) = $cust_svc->label; # blah
2570 my $pkg = "Recharge $v";
2572 my $bill_error = $cust_main->charge($amount, $pkg,
2573 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2574 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2575 $part_pkg->taxclass); #meh
2577 my $conf = new FS::Conf;
2578 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2580 $bill_error = _do_bop_realtime( $cust_main, $status );
2585 my $error = $svc_x->recharge (\%vhash);
2586 return { 'error' => $error } if $error;
2590 my $error = $bill_error;
2591 $error ||= $svc_x->recharge (\%vhash);
2592 return { 'error' => $error } if $error;
2595 return { error => '', svc => $cust_svc->part_svc->svc };
2599 sub _do_bop_realtime {
2600 my ($cust_main, $status, %opt) = @_;
2602 my $old_balance = $cust_main->balance;
2605 my $bill_error = $cust_main->bill(
2606 'return_bill' => \@cust_bill,
2609 $bill_error ||= $cust_main->apply_payments_and_credits;
2611 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2612 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2614 if ( $cust_main->balance > $old_balance
2615 && $cust_main->balance > 0
2616 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2617 || $status eq 'suspended'
2621 unless ( $opt{'no_invoice_void'} ) {
2623 #this used to apply a credit, but now we can void invoices...
2624 foreach my $cust_bill (@cust_bill) {
2625 my $voiderror = $cust_bill->void('automatic payment failed');
2626 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2631 return { 'error' => '_decline', 'bill_error' => $bill_error };
2634 if ( $opt{'collect'} ) {
2635 my $collect_error = $cust_main->collect();
2636 return { 'error' => '_decline', 'bill_error' => $collect_error }
2637 if $collect_error; #?
2646 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2647 return { 'error' => $session } if $context eq 'error';
2649 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2650 or return { 'error' => "unknown custnum $custnum" };
2652 my @cust_pkg = sort { $a->bill <=> $b->bill }
2653 grep { $_->part_pkg->freq ne '0' }
2654 $cust_main->ncancelled_pkgs;
2656 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2658 my $total = $cust_main->balance;
2661 my $bill = $_->bill;
2662 $total += $_->part_pkg->base_recur($_, \$bill);
2663 my $renew_date = $_->part_pkg->add_freq($_->bill);
2665 'pkgnum' => $_->pkgnum,
2666 'amount' => sprintf('%.2f', $total),
2667 'bill_date' => $_->bill,
2668 'bill_date_pretty' => time2str('%x', $_->bill),
2669 'renew_date' => $renew_date,
2670 'renew_date_pretty' => time2str('%x', $renew_date),
2671 'expire_date' => $_->expire,
2672 'expire_date_pretty' => time2str('%x', $_->expire),
2677 return { 'dates' => \@array };
2681 sub payment_info_renew_info {
2683 my $renew_info = renew_info($p);
2684 my $payment_info = payment_info($p);
2685 return { %$renew_info,
2693 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2694 return { 'error' => $session } if $context eq 'error';
2696 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2697 or return { 'error' => "unknown custnum $custnum" };
2699 my $date = $p->{'date'};
2703 #freeside-daily -n -d $date fs_daily $custnum
2704 $cust_main->bill_and_collect( 'time' => $date,
2705 'invoice_time' => $now,
2706 'actual_time' => $now,
2707 'check_freq' => '1d',
2710 return { 'error' => '' };
2716 my $session = _cache->get($p->{'session_id'})
2717 or return { 'error' => "Can't resume session" }; #better error message
2719 my $custnum = $session->{'custnum'};
2721 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2722 or return { 'error' => "unknown custnum $custnum" };
2724 my $conf = new FS::Conf;
2726 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2727 or return { 'error' => 'Permission denied' };
2729 my $pkgnum = $p->{'pkgnum'};
2731 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2732 'pkgnum' => $pkgnum, } )
2733 or return { 'error' => "unknown pkgnum $pkgnum" };
2735 my $error = $cust_pkg->suspend(reason => $reasonnum);
2736 return { 'error' => $error };
2742 my $session = _cache->get($p->{'session_id'})
2743 or return { 'error' => "Can't resume session" }; #better error message
2745 my $custnum = $session->{'custnum'};
2746 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2747 or return { 'error' => "unknown custnum $custnum" };
2749 my $pkgnum = $p->{'pkgnum'};
2750 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2751 'pkgnum' => $pkgnum, } )
2752 or return { 'error' => "unknown pkgnum $pkgnum" };
2754 my $error = $cust_pkg->cancel( 'quiet' => 1,
2755 'date' => $p->{'date'},
2757 return { 'error' => $error };
2760 sub provision_phone {
2763 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2765 #editing an existing phone number
2766 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2767 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2768 return { 'error' => $session } if $context eq 'error';
2770 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2771 return { 'error' => 'service not found' } unless $svc_phone;
2772 return { 'error' => 'invalid svcnum' }
2773 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2775 $svc_phone->email($p->{'email'})
2776 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2777 $svc_phone->forwarddst($p->{'forwarddst'})
2778 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2779 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2780 return { 'error' => $svc_phone->replace };
2784 unless ( $p->{'lnp'} ) {
2785 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2786 $p->{'lnp_status'} = "portingin";
2787 return _provision( 'FS::svc_phone',
2788 [qw(lnp_desired_due_date lnp_other_provider
2789 lnp_other_provider_account phonenum countrycode lnp_status)],
2790 [qw(phonenum countrycode)],
2796 # single DID order (the usual case)
2797 unless (scalar(@bulkdid)) {
2798 return _provision( 'FS::svc_phone',
2799 [qw(phonenum countrycode)],
2800 [qw(phonenum countrycode)],
2806 # bulk DID order case
2808 foreach my $did ( @bulkdid ) {
2809 $did =~ s/[^0-9]//g;
2810 $error = _provision( 'FS::svc_phone',
2811 [qw(phonenum countrycode)],
2812 [qw(phonenum countrycode)],
2814 'pkgnum' => $p->{'pkgnum'},
2815 'svcpart' => $p->{'svcpart'},
2817 'countrycode' => $p->{'countrycode'},
2818 'session_id' => $p->{'session_id'},
2821 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2823 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2828 warn "provision_pbx called\n"
2831 warn "provision_pbx calling _provision\n"
2833 _provision( 'FS::svc_pbx',
2834 [qw(id title max_extensions max_simultaneous ip_addr)],
2835 [qw(id title max_extensions max_simultaneous ip_addr)],
2841 sub provision_acct {
2843 warn "provision_acct called\n"
2846 return { 'error' => gettext('passwords_dont_match') }
2847 if $p->{'_password'} ne $p->{'_password2'};
2848 return { 'error' => gettext('empty_password') }
2849 unless length($p->{'_password'});
2851 if ($p->{'domsvc'}) {
2852 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2853 qw ( svcpart pkgnum ) );
2854 return { 'error' => gettext('invalid_domain') }
2855 unless ($domains{$p->{'domsvc'}});
2858 warn "provision_acct calling _provision\n"
2860 _provision( 'FS::svc_acct',
2861 [qw(username _password domsvc)],
2862 [qw(username _password domsvc)],
2868 sub provision_external {
2870 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2871 _provision( 'FS::svc_external',
2879 sub provision_forward {
2881 _provision( 'FS::svc_forward',
2882 ['srcsvc','src','dstsvc','dst'],
2889 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2890 warn "_provision called for $class\n"
2893 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2894 return { 'error' => $session } if $context eq 'error';
2896 my $search = { 'custnum' => $custnum };
2897 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2898 my $cust_main = qsearchs('cust_main', $search )
2899 or return { 'error' => "unknown custnum $custnum" };
2901 my $pkgnum = $p->{'pkgnum'};
2903 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2905 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2906 'pkgnum' => $pkgnum,
2908 or return { 'error' => "unknown pkgnum $pkgnum" };
2910 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2912 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2913 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2915 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2916 if $class ne 'FS::'. $part_svc->svcdb;
2918 warn "creating $class record\n"
2920 my $svc_x = $class->new( {
2921 'pkgnum' => $p->{'pkgnum'},
2922 'svcpart' => $p->{'svcpart'},
2923 map { $_ => $p->{$_} } @$fields
2926 my %insert_args = ();
2927 #i shouldn't be a special case here (pass an option or something)
2928 if ( $class eq 'FS::svc_phone'
2929 && grep length($p->{$_}), @location_editable_fields
2932 $insert_args{'cust_location'} = new FS::cust_location {
2933 map { $_ => $p->{$_} } @location_editable_fields
2937 warn "inserting $class record\n"
2939 my $error = $svc_x->insert(%insert_args);
2942 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2944 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2947 my $return = { 'svc' => $part_svc->svc,
2949 map { $_ => $svc_x->get($_) } @$return_fields
2951 warn "_provision returning ". Dumper($return). "\n"
2960 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2961 return { 'error' => $session } if $context eq 'error';
2963 my $search = { 'custnum' => $custnum };
2964 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2965 my $cust_main = qsearchs('cust_main', $search )
2966 or return { 'error' => "unknown custnum $custnum" };
2968 my $pkgnum = $p->{'pkgnum'};
2970 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2971 'pkgnum' => $pkgnum,
2973 or return { 'error' => "unknown pkgnum $pkgnum" };
2975 my $svcpart = $p->{'svcpart'};
2977 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2978 'svcpart' => $svcpart, } )
2979 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2980 my $part_svc = $pkg_svc->part_svc;
2982 my $conf = new FS::Conf;
2985 'svc' => $part_svc->svc,
2986 'svcdb' => $part_svc->svcdb,
2987 'pkgnum' => $pkgnum,
2988 'svcpart' => $svcpart,
2989 'custnum' => $custnum,
2991 'security_phrase' => 0, #XXX !
2992 'svc_acct_pop' => [], #XXX !
2994 'init_popstate' => '',
2999 small_custview( $cust_main, $conf->config('countrydefault') ),
3003 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
3004 && $ret->{'svcdb'} eq 'svc_phone') {
3005 $ret->{'svcnum'} = $p->{'svcnum'};
3006 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3007 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3008 $ret->{'email'} = $svc_phone->email;
3009 $ret->{'forwarddst'} = $svc_phone->forwarddst;
3013 if ($ret->{'svcdb'} eq 'svc_forward') {
3014 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3020 sub unprovision_svc {
3023 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3024 return { 'error' => $session } if $context eq 'error';
3026 my $search = { 'custnum' => $custnum };
3027 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3028 my $cust_main = qsearchs('cust_main', $search )
3029 or return { 'error' => "unknown custnum $custnum" };
3031 my $svcnum = $p->{'svcnum'};
3033 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
3034 or return { 'error' => "unknown svcnum $svcnum" };
3036 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3037 unless $cust_svc->cust_pkg->custnum == $custnum;
3039 my $conf = new FS::Conf;
3041 return { 'svc' => $cust_svc->part_svc->svc,
3042 'error' => $cust_svc->cancel,
3044 small_custview( $cust_main, $conf->config('countrydefault') ),
3049 sub myaccount_passwd {
3051 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3052 return { 'error' => $session } if $context eq 'error';
3054 return { 'error' => "New passwords don't match." }
3055 if $p->{'new_password'} ne $p->{'new_password2'};
3057 return { 'error' => 'Enter new password' }
3058 unless length($p->{'new_password'});
3060 #my $search = { 'custnum' => $custnum };
3061 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3062 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3063 my $search = " AND custnum = $1";
3064 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3066 my $svc_acct = qsearchs( {
3067 'table' => 'svc_acct',
3068 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3069 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3070 'LEFT JOIN cust_main USING ( custnum ) ',
3071 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3072 'extra_sql' => $search, #important
3074 or return { 'error' => "Service not found" };
3078 my $conf = new FS::Conf;
3080 return { 'error' => 'Incorrect current password.' }
3081 if ( exists($p->{'old_password'})
3082 || $conf->exists('selfservice-password_change_oldpass')
3084 && ! $svc_acct->check_password($p->{'old_password'});
3086 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3087 || $svc_acct->set_password($p->{'new_password'})
3088 || $svc_acct->replace();
3090 #regular pw change in self-service should change contact pw too, otherwise its
3091 #way too confusing. hell its confusing they're separate at all, but alas.
3092 #need to support the "ISP provides email that's used as a contact email" case
3094 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3095 if ( $contact && $contact->custnum == $custnum ) {
3096 #svc_acct was successful but this one returns an error? "shouldn't happen"
3097 #don't recheck is_password_allowed here; if the svc_acct password was
3098 #legal, that's good enough
3099 $error ||= $contact->change_password($p->{'new_password'});
3102 my($label, $value) = $svc_acct->cust_svc->label;
3104 return { 'error' => $error,
3114 my $info = skin_info($p);
3116 my $conf = new FS::Conf;
3117 my $verification = $conf->config('selfservice-password_reset_verification')
3118 or return { %$info, 'error' => 'Password resets disabled' };
3123 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3125 $contact = FS::contact->by_selfservice_email($p->{'email'});
3127 $cust_main = $contact->cust_main if $contact;
3129 #also look for an svc_acct, otherwise it would be super confusing
3131 my($username, $domain) = split('@', $p->{'email'});
3132 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3133 if ( $svc_domain ) {
3134 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3135 'domsvc' => $svc_domain->svcnum }
3138 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3139 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3141 #precaution: don't change svc_acct password not part of the same
3142 # customer as contact
3143 $svc_acct = '' if ! $cust_pkg
3144 || $cust_pkg->custnum != $cust_main->custnum;
3149 return { %$info, 'error' => 'Email address not found' }
3150 unless $contact || $svc_acct;
3152 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3154 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3155 or return { %$info, 'error' => 'Account not found' };
3157 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3158 'domsvc' => $svc_domain->svcnum }
3160 or return { %$info, 'error' => 'Account not found' };
3162 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3163 or return { %$info, 'error' => 'Account not found' };
3165 $cust_main = $cust_pkg->cust_main;
3170 'email' => sub { 1; },
3172 my( $p, $cust_main ) = @_;
3173 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3174 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3177 my( $p, $cust_main ) = @_;
3178 my $cust_pay = qsearchs({
3179 'table' => 'cust_pay',
3180 'hashref' => { 'custnum' => $cust_main->custnum },
3181 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3185 $p->{'amount'} == $cust_pay->paid;
3188 my( $p, $cust_main ) = @_;
3189 $p->{'zip'} eq $cust_main->zip
3190 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3194 foreach my $verify ( split(',', $verification) ) {
3196 &{ $verify{$verify} }( $p, $cust_main )
3197 or return { %$info, 'error' => 'Account not found' };
3201 #okay, we're verified
3205 my $error = $contact->send_reset_email(
3206 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3210 return { %$info, 'error' => $error }; #????
3213 } elsif ( $svc_acct ) {
3215 #create a unique session
3217 my $reset_session = {
3218 'svcnum' => $svc_acct->svcnum,
3219 'agentnum' => $svc_acct->cust_main->agentnum,
3222 my $timeout = '1 hour'; #?
3224 my $reset_session_id;
3226 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3227 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3230 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3234 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3235 $cust_main->agentnum);
3236 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3237 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3239 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3240 my $error = $msg_template->send( 'cust_main' => $cust_main,
3241 'object' => $svc_acct,
3242 'substitutions' => {
3243 'session_id' => $reset_session_id,
3247 return { %$info, 'error' => $error }; #????
3252 return { %$info, 'error' => '' };
3255 sub check_reset_passwd {
3258 my $conf = new FS::Conf;
3259 my $verification = $conf->config('selfservice-password_reset_verification')
3260 or return { 'error' => 'Password resets disabled' };
3262 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3263 or return { 'error' => "Can't resume session" }; #better error message
3265 if ( $reset_session->{'svcnum'} ) {
3267 my $svcnum = $reset_session->{'svcnum'};
3269 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3270 or return { 'error' => "Service not found" };
3272 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3273 my $info = skin_info($p);
3277 'session_id' => $p->{'session_id'},
3278 'username' => $svc_acct->username,
3281 } elsif ( $reset_session->{'contactnum'} ) {
3283 my $contactnum = $reset_session->{'contactnum'};
3285 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3286 or return { 'error' => "Contact not found" };
3288 my @contact_email = $contact->contact_email;
3289 return { 'error' => 'No contact email' } unless @contact_email;
3291 $p->{'agentnum'} = $contact->cust_main->agentnum;
3292 my $info = skin_info($p);
3296 'session_id' => $p->{'session_id'},
3297 'email' => $contact_email[0]->email, #the first?
3302 return { 'error' => 'No svcnum or contactnum in session' }; #??
3308 sub process_reset_passwd {
3311 my $conf = new FS::Conf;
3312 my $verification = $conf->config('selfservice-password_reset_verification')
3313 or return { 'error' => 'Password resets disabled' };
3315 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3316 or return { 'error' => "Can't resume session" }; #better error message
3321 if ( $reset_session->{'svcnum'} ) {
3323 my $svcnum = $reset_session->{'svcnum'};
3325 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3326 or return { 'error' => "Service not found" };
3328 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3329 $info ||= skin_info($p);
3334 if ( $reset_session->{'contactnum'} ) {
3336 my $contactnum = $reset_session->{'contactnum'};
3338 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3339 or return { 'error' => "Contact not found" };
3341 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3342 $info ||= skin_info($p);
3346 return { %$info, 'error' => "New passwords don't match." }
3347 if $p->{'new_password'} ne $p->{'new_password2'};
3349 return { %$info, 'error' => 'Enter new password' }
3350 unless length($p->{'new_password'});
3354 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3355 || $svc_acct->set_password($p->{'new_password'})
3356 || $svc_acct->replace();
3358 return { %$info, 'error' => $error } if $error;
3360 #my($label, $value) = $svc_acct->cust_svc->label;
3361 #return { 'error' => $error,
3362 # #'label' => $label,
3363 # #'value' => $value,
3370 my $error = $contact->is_password_allowed($p->{'new_password'})
3371 || $contact->change_password($p->{'new_password'});
3373 return { %$info, 'error' => $error }; # if $error;
3377 #password changed ,so remove session, don't want it reused
3378 _cache->remove($p->{'session_id'});
3380 return { %$info, 'error' => '' };
3384 sub validate_passwd {
3388 %result = ( 'fieldid' => $p->{'fieldid'} )
3389 if $p->{'fieldid'} =~ /^\w+$/;
3391 return { %result, 'password_invalid' => 'Enter new password' }
3392 unless length($p->{'check_password'});
3395 if ($p->{'svcnum'}) {
3396 # false laziness with myaccount_passwd
3397 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3398 return { %result, 'error' => $session } if $context eq 'error';
3400 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3401 my $search = " AND custnum = $1";
3402 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3404 $svc_acct = qsearchs( {
3405 'table' => 'svc_acct',
3406 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3407 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3408 'LEFT JOIN cust_main USING ( custnum ) ',
3409 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3410 'extra_sql' => $search, #important
3412 or return { %result, 'error' => "Service not found" };
3413 # end false laziness
3416 unless ($svc_acct) {
3417 my $conf = new FS::Conf;
3418 my $agentnum = $p->{'agentnum'};
3419 return { %result, 'password_valid' => 1 }
3420 if $conf->config_bool('password-insecure', $p->{'agentnum'});
3423 $svc_acct ||= new FS::svc_acct {};
3425 my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3426 return { %result, 'password_invalid' => $error } if $error;
3427 return { %result, 'password_valid' => 1 };
3432 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3433 return { 'error' => $session } if $context eq 'error';
3436 if ( $session->{'pkgnum'} ) {
3438 #tickets for specific service with pkg-balances on
3439 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3440 'pkgnum' => $session->{'pkgnum'} })
3441 or return { 'error' => 'unknown package' };
3442 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3443 push @tickets, $cust_svc->tickets( $p->{status} );
3448 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3449 or return { 'error' => "unknown custnum $custnum" };
3451 @tickets = $cust_main->tickets( $p->{status} );
3454 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3455 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3456 my $conf = new FS::Conf;
3457 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3461 ($a->{'_selfservice_priority'} eq '') <=>
3462 ($b->{'_selfservice_priority'} eq '')
3465 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3471 +{ tickets => \@tickets };
3478 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3479 return { 'error' => $session } if $context eq 'error';
3481 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3482 FS::TicketSystem->init();
3484 my $conf = new FS::Conf;
3485 my $queue = $p->{'queue'}
3486 || $conf->config('ticket_system-selfservice_queueid')
3487 || $conf->config('ticket_system-default_queueid');
3489 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3490 my $err_or_ticket = FS::TicketSystem->create_ticket(
3491 '', #create RT session based on FS CurrentUser (fs_selfservice)
3493 'custnum' => $custnum,
3494 'svcnum' => $session->{'svcnum'},
3495 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3498 if ( ref($err_or_ticket) ) {
3499 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3501 return { 'error' => '',
3502 'ticket_id' => $err_or_ticket->id,
3505 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3507 return { 'error' => $err_or_ticket };
3515 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3516 return { 'error' => $session } if $context eq 'error';
3518 return { error => 'requested format not implemented' }
3519 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3521 my $conf = new FS::Conf;
3522 my $age_threshold = 0;
3523 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3524 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3526 my $search = { 'custnum' => $custnum };
3527 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3528 my $cust_main = qsearchs('cust_main', $search )
3529 or return { 'error' => "unknown custnum $custnum" };
3531 # does it make more sense to just run one sql query for this instead of all the
3532 # insanity below? would increase performance greately for large data sets?
3534 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3535 my @part_svc = $cust_pkg->part_svc;
3536 foreach my $part_svc ( @part_svc ) {
3537 if($part_svc->svcdb eq 'svc_phone'){
3538 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3539 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3540 push @svc_phone, $cust_pkg_svc->svc_x
3541 if $cust_pkg_svc->date_inserted >= $age_threshold;
3549 my($xls_r,$xls_c) = (0,0);
3552 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3553 if($p->{'format'} eq 'csv') {
3554 $csv = new Text::CSV_XS { 'always_quote' => 1,
3557 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3558 $content .= $csv->string;
3560 elsif($p->{'format'} eq 'xls') {
3561 my $XLS1 = new IO::Scalar \$content;
3562 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3563 or return { 'error' => "Error opening .xls file: $!" };
3564 $xls = $xls_workbook->add_worksheet('DIDs');
3565 foreach ( @fields ) {
3566 $xls->write(0,$xls_c++,$_);
3571 foreach my $svc_phone ( @svc_phone ) {
3572 my @cols = map { $svc_phone->$_ } @fields;
3573 if($p->{'format'} eq 'csv') {
3574 return { 'error' => 'Unable to create CSV' }
3575 unless $csv->combine(@cols);
3576 $content .= $csv->string;
3578 elsif($p->{'format'} eq 'xls') {
3581 $xls->write($xls_r,$xls_c++,$_);
3587 $xls_workbook->close() if $p->{'format'} eq 'xls';
3589 { content => $content, format => $p->{'format'}, };
3594 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3595 return { 'error' => $session } if $context eq 'error';
3597 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3598 # FS::TicketSystem->init();
3599 # return { 'error' => 'get_ticket configuration error' }
3600 # if $FS::TicketSystem::system ne 'RT_Internal';
3602 # check existence and ownership as part of this
3603 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3604 my $rt_session = FS::TicketSystem->session('');
3605 my $Ticket = FS::TicketSystem->get_ticket_object(
3607 ticket_id => $p->{'ticket_id'},
3610 return { 'error' => 'ticket not found' } if !$Ticket;
3612 if ( length( $p->{'subject'} || '' ) ) {
3614 if ( $p->{'subject'} ne $Ticket->Subject ) {
3615 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3616 return { 'error' => "unable to set subject: $msg" } if !$val;
3620 if(length($p->{'reply'})) {
3621 my @err_or_res = FS::TicketSystem->correspond_ticket(
3623 'ticket_id' => $p->{'ticket_id'},
3624 'content' => $p->{'reply'},
3627 return { 'error' => 'unable to reply to ticket' }
3628 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3631 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3632 my $err_or_ticket = FS::TicketSystem->get_ticket(
3634 'ticket_id' => $p->{'ticket_id'},
3637 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3638 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3640 return { 'error' => $err_or_ticket };
3643 my @custs = @{$err_or_ticket->{'custs'}};
3644 my @txns = @{$err_or_ticket->{'txns'}};
3647 # superseded by check in get_ticket_object
3648 #return { 'error' => 'invalid ticket requested' }
3649 #unless grep($_ eq $custnum, @custs);
3651 foreach my $txn ( @txns ) {
3652 push @filtered_txns, $txn
3653 if ($txn->{'type'} eq 'EmailRecord'
3654 || $txn->{'type'} eq 'Correspond'
3655 || $txn->{'type'} eq 'Create');
3658 warn "$me get_ticket: successful: \n"
3660 return { 'error' => '',
3661 'transactions' => \@filtered_txns,
3662 'ticket_fields' => $err_or_ticket->{'fields'},
3663 'ticket_id' => $p->{'ticket_id'},
3667 sub adjust_ticket_priority {
3669 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3670 return { 'error' => $session } if $context eq 'error';
3672 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3673 # FS::TicketSystem->init;
3674 my $ss_priority = FS::TicketSystem->selfservice_priority;
3676 return { 'error' => 'adjust_ticket_priority configuration error' }
3677 if $FS::TicketSystem::system ne 'RT_Internal'
3680 my $values = $p->{'values'}; #hashref, id => priority value
3683 foreach my $id (keys %$values) {
3684 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3685 my $Ticket = FS::TicketSystem->get_ticket_object('',
3687 'custnum' => $custnum,
3690 $ticket_error{$id} = 'ticket not found';
3694 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3695 # We're not going to implement it for RT_External.
3696 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3697 my $new_value = $values->{$id};
3698 next if $old_value eq $new_value;
3700 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3702 # AddCustomFieldValue works fine (replacing any existing value) if it's
3703 # a single-valued custom field, which it should be. If it's not, you're
3704 # doing something wrong.
3706 if ( length($new_value) ) {
3707 ($val, $msg) = $Ticket->AddCustomFieldValue(
3708 Field => $ss_priority,
3709 Value => $new_value,
3713 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3714 Field => $ss_priority,
3715 Value => $old_value,
3719 $ticket_error{$id} = $msg if !$val;
3720 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3722 return { 'error' => '',
3723 'ticket_error' => \%ticket_error,
3724 %{ customer_info($p) } # send updated customer info back
3730 sub _custoragent_session_custnum {
3733 my($context, $session, $custnum);
3734 if ( $p->{'session_id'} ) {
3736 $context = 'customer';
3737 $session = _cache->get($p->{'session_id'})
3738 or return ( 'error' => "Can't resume session" ); #better error message
3739 $custnum = $session->{'custnum'};
3741 } elsif ( $p->{'agent_session_id'} ) {
3744 my $agent_cache = new FS::ClientAPI_SessionCache( {
3745 'namespace' => 'FS::ClientAPI::Agent',
3747 $session = $agent_cache->get($p->{'agent_session_id'})
3748 or return ( 'error' => "Can't resume session" ); #better error message
3749 $custnum = $p->{'custnum'};
3753 return ( 'error' => "Can't resume session" ); #better error message
3756 ($context, $session, $custnum);