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;
616 else { delete $return{'payinfo'}; }
618 my @invoicing_list = $cust_main->invoicing_list;
619 $return{'invoicing_list'} =
620 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
621 $return{'postal_invoicing'} =
622 0 < ( grep { $_ eq 'POST' } @invoicing_list );
624 if ( $session->{'svcnum'} ) {
625 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
626 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
627 $return{'svcnum'} = $session->{'svcnum'};
630 } elsif ( $session->{'svcnum'} ) { #no customer record
632 #uuh, not supproted yet... die?
633 return { 'error' => 'customer_info_short not yet supported as agent' };
637 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
641 # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
642 # it is not customer-specific, though it is only shown to authenticated customers
643 # it is not currently agent-specific, though at some point it might be
644 $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
646 return { 'error' => '',
647 'custnum' => $custnum,
652 sub customer_recurring {
655 my($context, $session, $custnum) = _custoragent_session_custnum($p);
656 return { 'error' => $session } if $context eq 'error';
660 my $conf = new FS::Conf;
662 my $search = { 'custnum' => $custnum };
663 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
664 my $cust_main = qsearchs('cust_main', $search )
665 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
667 $return{'display_recurring'} = [ $cust_main->display_recurring ];
669 return { 'error' => '',
670 'custnum' => $custnum,
675 sub billing_history {
678 my($context, $session, $custnum) = _custoragent_session_custnum($p);
679 return { 'error' => $session } if $context eq 'error';
681 return { 'error' => 'No customer' } unless $custnum;
683 my $search = { 'custnum' => $custnum };
684 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
685 my $cust_main = qsearchs('cust_main', $search )
686 or return { 'error' => "unknown custnum $custnum" };
690 if ( $session->{'pkgnum'} ) {
691 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
692 #next_bill_date from cust_pkg?
693 return { 'error' => 'No history for package' };
696 $return{balance} = $cust_main->balance;
697 $return{balance_pretty} = money_pretty($return{balance});
698 $return{next_bill_date} = $cust_main->next_bill_date;
699 $return{next_bill_date_pretty} =
700 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
703 my $conf = new FS::Conf;
705 $return{'history'} = [
706 $cust_main->payment_history(
707 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
712 $return{'money_char'} = $conf->config("money_char") || '$',
720 my $session = _cache->get($p->{'session_id'})
721 or return { 'error' => "Can't resume session" }; #better error message
723 my $custnum = $session->{'custnum'}
724 or return { 'error' => "no customer record" };
726 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
727 or return { 'error' => "unknown custnum $custnum" };
729 my $conf = new FS::Conf;
730 if (($p->{payby} eq "CHEK" || $p->{payby} eq "DCHK") && $conf->exists('selfservice-ACH_info_readonly')) {
731 return { 'error' => "You do not have authority to add a bank account" };
734 my $new = new FS::cust_main { $cust_main->hash };
736 $new->set( $_ => $p->{$_} )
737 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
739 if ( exists($p->{address1}) ) {
740 my $bill_location = FS::cust_location->new({
741 map { $_ => $p->{$_} } @location_editable_fields
743 # if this is unchanged from before, cust_main::replace will ignore it
744 $new->set('bill_location' => $bill_location);
747 if ( exists($p->{ship_address1}) ) {
748 my $ship_location = FS::cust_location->new({
749 map { $_ => $p->{"ship_$_"} } @location_editable_fields
751 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
752 # Selfservice unfortunately tries to indicate "same as billing
753 # address" by sending all fields empty. Did this ever work?
754 $ship_location = $cust_main->bill_location;
756 $new->set('ship_location' => $ship_location);
758 # but if it hasn't been passed in at all, leave ship_location alone--
759 # DON'T change it to match bill_location.
762 if (exists($p->{'payby'})) {
763 $p->{'payby'} =~ /^([A-Z]{4})$/
764 or return { 'error' => "illegal_payby " . $p->{'payby'} };
768 if ( $payby =~ /^(CARD|DCRD)$/ ) {
770 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
772 if ( $new->payinfo eq $cust_main->paymask ) {
773 $new->payinfo($cust_main->payinfo);
774 $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
776 $new->payinfo($p->{'payinfo'});
777 return { 'error' => 'CVV2 is required' }
778 if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
779 $new->paycvv( $p->{'paycvv'} )
782 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
784 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
787 $p->{'payinfo1'} =~ /^([\dx]+)$/
788 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
790 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
791 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
793 $payinfo = $payinfo1. '@'. $payinfo2;
795 $new->payinfo( ($payinfo eq $cust_main->paymask)
796 ? $cust_main->payinfo
800 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
802 } elsif ( $payby =~ /^(BILL)$/ ) {
804 } elsif ( $payby ) { #notyet ready
805 return { 'error' => "unknown payby $payby" };
809 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
810 #false laziness with httemplate/edit/process/cust_main.cgi
811 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
812 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
814 @invoicing_list = $cust_main->invoicing_list;
817 my $error = $new->replace($cust_main, \@invoicing_list);
818 return { 'error' => $error } if $error;
821 return { 'error' => '' };
826 my $session = _cache->get($p->{'session_id'})
827 or return { 'error' => "Can't resume session" }; #better error message
833 my $conf = new FS::Conf;
834 use vars qw($payment_info); #cache for performance
835 unless ( $payment_info ) {
837 my %states = map { $_->state => 1 }
838 qsearch('cust_main_county', {
839 'country' => $conf->config('countrydefault') || 'US'
842 my %cust_paybys = map { $_ => 1 }
843 map { FS::payby->payby2payment($_) }
844 $conf->config('signup_server-payby');
846 my @cust_paybys = keys %cust_paybys;
850 #list all counties/states/countries
851 'cust_main_county' =>
852 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
854 #shortcut for one-country folks
856 [ sort { $a cmp $b } keys %states ],
858 'card_types' => card_types(),
860 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
861 'require_cvv' => $conf->exists('selfservice-require_cvv'),
862 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
864 'paytypes' => [ @FS::cust_main::paytypes ],
866 'paybys' => [ $conf->config('signup_server-payby') ],
867 'cust_paybys' => \@cust_paybys,
869 'stateid_label' => FS::Msgcat::_gettext('stateid'),
870 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
872 'show_ss' => $conf->exists('show_ss'),
873 'show_stateid' => $conf->exists('show_stateid'),
874 'show_paystate' => $conf->exists('show_bankstate'),
876 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
877 'ach_read_only' => $conf->exists('selfservice-ACH_info_readonly'),
887 my %return = %$payment_info;
889 delete $return{'cust_main_county'} if $p->{'omit_cust_main_county'};
891 my $custnum = $session->{'custnum'};
893 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
894 or return { 'error' => "unknown custnum $custnum" };
896 $return{'hide_payment_fields'} = [
898 my $pg = payment_gateway($cust_main, $_);
899 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
900 } @{ $return{cust_paybys} }
903 $return{balance} = $cust_main->balance; #XXX pkg-balances?
905 $return{payname} = $cust_main->payname
906 || ( $cust_main->first. ' '. $cust_main->get('last') );
908 $return{$_} = $cust_main->bill_location->get($_)
909 for qw(address1 address2 city state zip);
911 $return{payby} = $cust_main->payby;
912 $return{stateid_state} = $cust_main->stateid_state;
914 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
915 $return{card_type} = cardtype($cust_main->payinfo);
916 $return{payinfo} = $cust_main->paymask;
918 @return{'month', 'year'} = $cust_main->paydate_monthyear;
922 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
923 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
924 $return{payinfo1} = $payinfo1;
925 $return{payinfo2} = $payinfo2;
926 $return{paytype} = $cust_main->paytype;
927 $return{paystate} = $cust_main->paystate;
928 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
931 if ( $conf->config('prepayment_discounts-credit_type') ) {
933 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
936 #doubleclick protection
938 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
939 $return{paybatch} = $return{payunique}; #back compat
941 $return{credit_card_surcharge_percentage} = $conf->config('credit-card-surcharge-percentage', $cust_main->agentnum);
942 $return{credit_card_surcharge_flatfee} = $conf->config('credit-card-surcharge-flatfee', $cust_main->agentnum);
944 return { 'error' => '',
950 #some false laziness with httemplate/process/payment.cgi - look there for
951 #ACH and CVV support stuff
953 sub validate_payment {
956 my $session = _cache->get($p->{'session_id'})
957 or return { 'error' => "Can't resume session" }; #better error message
959 my $custnum = $session->{'custnum'};
961 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
962 or return { 'error' => "unknown custnum $custnum" };
964 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
965 or return { 'error' => gettext('illegal_amount') };
967 return { error => 'Amount must be greater than 0' } unless $amount > 0;
969 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
970 #changing the hidden form values
971 my $conf = new FS::Conf;
972 my $fee_display = $conf->config('selfservice_process-display') || 'add';
973 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
974 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
975 if ( $fee_display eq 'add'
977 and ! $fee_skip_first || scalar($cust_main->cust_pay)
980 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
981 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
984 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
985 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
986 my $discount_term = $1;
988 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
989 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
992 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
993 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
996 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
997 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
1000 $payunique = $paybatch if ! length($payunique) && length($paybatch);
1002 $p->{'payby'} ||= 'CARD';
1003 $p->{'payby'} =~ /^([A-Z]{4})$/
1004 or return { 'error' => "illegal_payby " . $p->{'payby'} };
1007 #false laziness w/process/payment.cgi
1010 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1012 $p->{'payinfo1'} =~ /^([\dx]+)$/
1013 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1015 $p->{'payinfo2'} =~ /^([\dx]+)$/
1016 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1018 $payinfo = $payinfo1. '@'. $payinfo2;
1021 if ( $cust_main->paymask eq $payinfo ) {
1022 $payinfo = $cust_main->payinfo;
1026 if ($conf->exists('selfservice-ACH_info_readonly') && !$achonfile) {
1027 return { 'error' => "You are not allowed to change your payment information." };
1030 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1032 $payinfo = $p->{'payinfo'};
1036 #more intelligent matching will be needed here if you change
1037 #card_masking_method and don't remove existing paymasks
1038 if ( $cust_main->paymask eq $payinfo ) {
1039 $payinfo = $cust_main->payinfo;
1043 $payinfo =~ s/\D//g;
1044 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1045 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1049 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1050 return { 'error' => gettext('unknown_card_type') }
1051 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1053 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1054 if ( cardtype($payinfo) eq 'American Express card' ) {
1055 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1056 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1059 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1060 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1063 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1064 return { 'error' => 'CVV2 is required' };
1065 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1066 return { 'error' => 'CVV2 is required' };
1070 die "unknown payby $payby";
1073 my %payby2fields = (
1074 'CARD' => [ qw( paystart_month paystart_year payissue payip
1075 address1 address2 city state zip country ) ],
1076 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1080 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1083 'cust_main' => $cust_main, #XXX or just custnum??
1084 'amount' => sprintf('%.2f', $amount),
1086 'payinfo' => $payinfo,
1087 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1088 'card_type' => $card_type,
1089 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1090 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1091 'month' => $p->{'month'},
1092 'year' => $p->{'year'},
1093 'payname' => $payname,
1094 'payunique' => $payunique,
1095 'paybatch' => $paybatch,
1096 'paycvv' => $paycvv,
1097 'payname' => $payname,
1098 'discount_term' => $discount_term,
1099 'pkgnum' => $session->{'pkgnum'},
1100 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1110 my $validate = validate_payment($p);
1111 return $validate if $validate->{'error'};
1113 my $conf = new FS::Conf;
1114 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1115 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1117 +{ map { $_=>$validate->{$_} }
1118 qw( card_type paymask payname paydate_pretty month year amount
1119 address1 address2 city state zip country
1125 sub process_stored_payment {
1128 my $session_id = $p->{'session_id'};
1130 my $payment_info = _cache->get( "payment_$session_id" )
1131 or return { 'error' => "Can't resume session" }; #better error message
1133 do_process_payment($payment_info);
1137 sub process_payment {
1140 my $payment_info = validate_payment($p);
1141 return $payment_info if $payment_info->{'error'};
1143 do_process_payment($payment_info);
1147 sub do_process_payment {
1148 my $validate = shift;
1150 my $cust_main = $validate->{'cust_main'};
1152 my $amount = delete $validate->{'amount'};
1155 my $payby = delete $validate->{'payby'};
1157 if ( $validate->{'save'} ) {
1158 my $new = new FS::cust_main { $cust_main->hash };
1159 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1160 $new->set( $_ => $validate->{$_} )
1161 foreach qw( payname paystart_month paystart_year payissue payip );
1162 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1164 my $bill_location = FS::cust_location->new({
1165 map { $_ => $validate->{$_} }
1166 qw(address1 address2 city state country zip)
1168 $new->set('bill_location' => $bill_location);
1169 # but don't allow the service address to change this way.
1171 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1172 $new->set( $_ => $validate->{$_} )
1173 foreach qw( payname payip paytype paystate
1174 stateid stateid_state );
1175 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1177 $new->payinfo( $validate->{'payinfo'} ); #to properly set paymask
1178 $new->set( 'paydate' => $validate->{'paydate'} );
1179 my $error = $new->replace($cust_main);
1181 #no, this causes customers to process their payments again
1182 #return { 'error' => $error };
1183 #XXX just warn verosely for now so i can figure out how these happen in
1184 # the first place, eventually should redirect them to the "change
1185 #address" page but indicate if the payment processed?
1186 delete($validate->{'payinfo'}); #don't want to log this!
1187 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1188 "NEW: ". Dumper($new)."\n".
1189 "OLD: ". Dumper($cust_main)."\n".
1190 "PACKET: ". Dumper($validate)."\n";
1196 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1200 'paynum_ref' => \$paynum,
1203 return { 'error' => $error } if $error;
1205 #no error, so order the fee package if applicable...
1206 my $conf = new FS::Conf;
1207 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1208 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1210 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1212 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1214 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1215 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1218 #and generate an invoice for it now too
1219 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1220 return { 'error' => "payment processed and fee ordered successfully, but error billing fee: $error" }
1225 $cust_main->apply_payments;
1228 my $receipt_html = '';
1230 # currently supported for realtime CC only; send receipt data to SS
1231 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1234 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1237 <TD ALIGN="right">Payment#</TD>
1238 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1242 <TD ALIGN="right">Date</TD>
1244 <TD BGCOLOR="#FFFFFF"><B>! .
1245 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1251 <TD ALIGN="right">Amount</TD>
1252 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1257 <TD ALIGN="right">Payment method</TD>
1258 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1271 'amount' => sprintf('%.2f', $cust_pay->paid),
1272 'date' => $cust_pay->_date,
1273 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1274 'time_pretty' => time2str('%T', $cust_pay->_date),
1275 'auth_num' => $cust_pay->auth,
1276 'order_num' => $cust_pay->order_number,
1277 'receipt_html' => $receipt_html,
1284 'receipt_html' => '',
1291 sub realtime_collect {
1294 my $session = _cache->get($p->{'session_id'})
1295 or return { 'error' => "Can't resume session" }; #better error message
1297 my $custnum = $session->{'custnum'};
1299 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1300 or return { 'error' => "unknown custnum $custnum" };
1303 if ( $p->{'amount'} ) {
1304 $amount = $p->{'amount'};
1306 elsif ( $session->{'pkgnum'} ) {
1307 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1310 $amount = $cust_main->balance;
1313 my $error = $cust_main->realtime_collect(
1314 'method' => $p->{'method'},
1315 'amount' => $amount,
1316 'pkgnum' => $session->{'pkgnum'},
1317 'session_id' => $p->{'session_id'},
1321 return { 'error' => $error } unless ref( $error );
1323 return { 'error' => '', amount => $amount, %$error };
1326 sub start_thirdparty {
1328 my $session = _cache->get($p->{'session_id'})
1329 or return { 'error' => "Can't resume session" }; #better error message
1330 my $custnum = $session->{'custnum'};
1331 my $cust_main = FS::cust_main->by_key($custnum);
1333 my $amount = $p->{'amount'}
1334 or return { error => 'no amount' };
1336 my $result = $cust_main->create_payment(
1337 'method' => $p->{'method'},
1338 'amount' => $p->{'amount'},
1339 'pkgnum' => $session->{'pkgnum'},
1340 'session_id' => $p->{'session_id'},
1343 if ( ref($result) ) { # hashref or error
1346 return { error => $result };
1350 sub finish_thirdparty {
1352 my $session_id = delete $p->{'session_id'};
1353 my $session = _cache->get($session_id)
1354 or return { 'error' => "Can't resume session" };
1355 my $custnum = $session->{'custnum'};
1356 my $cust_main = FS::cust_main->by_key($custnum);
1358 if ( $p->{_cancel} ) {
1359 # customer backed out of making a payment
1360 return $cust_main->cancel_payment( $session_id );
1362 my $result = $cust_main->execute_payment( $session_id, %$p );
1363 if ( ref($result) ) {
1366 return { error => $result };
1370 sub process_payment_order_pkg {
1373 my $hr = process_payment($p);
1374 return $hr if $hr->{'error'};
1379 sub process_payment_order_renew {
1382 my $hr = process_payment($p);
1383 return $hr if $hr->{'error'};
1388 sub process_prepay {
1392 my $session = _cache->get($p->{'session_id'})
1393 or return { 'error' => "Can't resume session" }; #better error message
1397 my $custnum = $session->{'custnum'};
1399 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1400 or return { 'error' => "unknown custnum $custnum" };
1402 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1403 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1411 return { 'error' => $error } if $error;
1413 return { 'error' => '',
1414 'amount' => $amount,
1415 'seconds' => $seconds,
1416 'duration' => duration_exact($seconds),
1417 'upbytes' => $upbytes,
1418 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1419 'downbytes' => $downbytes,
1420 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1421 'totalbytes'=> $totalbytes,
1422 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1429 my $session = _cache->get($p->{'session_id'})
1430 or return { 'error' => "Can't resume session" }; #better error message
1432 my $custnum = $session->{'custnum'};
1434 my $invnum = $p->{'invnum'};
1436 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1437 'custnum' => $custnum } )
1438 or return { 'error' => "Can't find invnum" };
1442 return { 'error' => '',
1443 'invnum' => $invnum,
1444 'invoice_text' => join('', $cust_bill->print_text ),
1445 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1452 my $session = _cache->get($p->{'session_id'})
1453 or return { 'error' => "Can't resume session" }; #better error message
1455 my $custnum = $session->{'custnum'};
1457 my $invnum = $p->{'invnum'};
1459 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1460 'custnum' => $custnum } )
1461 or return { 'error' => "Can't find invnum" };
1465 return { 'error' => '',
1466 'invnum' => $invnum,
1467 'invoice_pdf' => $cust_bill->print_pdf({
1468 'unsquelch_cdr' => 1,
1469 'locale' => $p->{'locale'},
1475 sub legacy_invoice {
1477 my $session = _cache->get($p->{'session_id'})
1478 or return { 'error' => "Can't resume session" }; #better error message
1480 my $custnum = $session->{'custnum'};
1482 my $legacyinvnum = $p->{'legacyinvnum'};
1485 'legacyinvnum' => $legacyinvnum,
1486 'custnum' => $custnum,
1489 my $legacy_cust_bill =
1490 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1491 || qsearchs('legacy_cust_bill', \%hash )
1492 or return { 'error' => "Can't find legacyinvnum" };
1496 return { 'error' => '',
1497 'legacyinvnum' => $legacyinvnum,
1498 'legacyid' => $legacy_cust_bill->legacyid,
1499 'invoice_html' => $legacy_cust_bill->content_html,
1504 sub legacy_invoice_pdf {
1506 my $session = _cache->get($p->{'session_id'})
1507 or return { 'error' => "Can't resume session" }; #better error message
1509 my $custnum = $session->{'custnum'};
1511 my $legacyinvnum = $p->{'legacyinvnum'};
1513 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1514 'legacyinvnum' => $legacyinvnum,
1515 'custnum' => $custnum,
1516 }) or return { 'error' => "Can't find legacyinvnum" };
1520 return { 'error' => '',
1521 'legacyinvnum' => $legacyinvnum,
1522 'legacyid' => $legacy_cust_bill->legacyid,
1523 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1531 #sessioning for this? how do we get the session id to the backend invoice
1532 # template so it can add it to the link, blah
1535 if ( $p->{'invnum'} ) {
1536 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1537 or return { 'error' => 'unknown invnum' };
1538 $agentnum = $cust_bill->cust_main->agentnum;
1541 my $templatename = $p->{'template'} || $p->{'templatename'};
1543 #false laziness-ish w/view/cust_bill-logo.cgi
1545 my $conf = new FS::Conf;
1546 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1547 $templatename = "_$1";
1552 my $filename = "logo$templatename.png";
1554 return { 'error' => '',
1555 'logo' => $conf->config_binary($filename, $agentnum),
1556 'content_type' => 'image/png', #should allow gif, jpg too
1563 my $session = _cache->get($p->{'session_id'})
1564 or return { 'error' => "Can't resume session" }; #better error message
1566 my $custnum = $session->{'custnum'};
1568 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1569 or return { 'error' => "unknown custnum $custnum" };
1571 my $conf = new FS::Conf;
1573 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1575 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1580 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1581 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1582 my $owed = $_->owed;
1584 +{ 'invnum' => $_->invnum,
1585 '_date' => $_->_date,
1586 'date' => time2str("%b %o, %Y", $_->_date),
1587 'date_short' => time2str("%m-%d-%Y", $_->_date),
1588 'previous' => sprintf('%.2f', ($_->previous)[0]),
1589 'charged' => sprintf('%.2f', $_->charged),
1590 'owed' => sprintf('%.2f', $owed),
1591 'balance' => sprintf('%.2f', $balance),
1592 'lastpay' => @payments_and_credits
1593 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1599 return { 'error' => '',
1600 'balance' => $cust_main->balance,
1601 'money_char' => $conf->config("money_char") || '$',
1602 'invoices' => $invoices,
1603 'legacy_invoices' => [
1605 +{ 'legacyinvnum' => $_->legacyinvnum,
1606 'legacyid' => $_->legacyid,
1607 '_date' => $_->_date,
1608 'date' => time2str("%b %o, %Y", $_->_date),
1609 'date_short' => time2str("%m-%d-%Y", $_->_date),
1610 'charged' => sprintf('%.2f', $_->charged),
1611 'has_content' => ( length($_->content_pdf)
1612 || length($_->content_html) ),
1622 my $session = _cache->get($p->{'session_id'})
1623 or return { 'error' => "Can't resume session" }; #better error message
1625 my $custnum = $session->{'custnum'};
1627 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1628 or return { 'error' => "unknown custnum $custnum" };
1630 return { 'error' => '',
1631 'balance' => $cust_main->balance,
1632 'money_char' => FS::Conf->new->config("money_char") || '$',
1633 'payments' => [ map $_->SSAPI_getinfo, $cust_main->cust_pay ],
1637 sub payment_receipt {
1639 my $session = _cache->get($p->{'session_id'})
1640 or return { 'error' => "Can't resume session" }; #better error message
1642 my $custnum = $session->{'custnum'};
1644 my $cust_pay = qsearchs('cust_pay', { 'custnum' => $custnum,
1645 'paynum' => $p->{'paynum'},
1648 or return { 'error' => "unknown payment ". $p->{'paynum'} };
1652 %{ $cust_pay->SSAPI_getinfo },
1658 my $session = _cache->get($p->{'session_id'})
1659 or return { 'error' => "Can't resume session" }; #better error message
1661 my $custnum = $session->{'custnum'};
1663 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1664 or return { 'error' => "unknown custnum $custnum" };
1666 my @errors = $cust_main->cancel( 'quiet'=>1 );
1668 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1670 return { 'error' => $error };
1677 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1678 return { 'error' => $session } if $context eq 'error';
1680 my $pkg = qsearchs({
1681 'table' => 'cust_pkg',
1682 'addl_from' => 'LEFT JOIN part_pkg USING ( pkgpart )',
1684 'custnum' => $custnum,
1685 'pkgnum' => $p->{'pkgnum'},
1688 or return {'error' => 'unknown pkg num $pkgnum'};
1691 pkg_label => $pkg->pkg,
1692 pkgpart => $pkg->pkgpart,
1693 classnum => $pkg->classnum,
1701 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1702 return { 'error' => $session } if $context eq 'error';
1704 my $search = { 'custnum' => $custnum };
1705 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1706 my $cust_main = qsearchs('cust_main', $search )
1707 or return { 'error' => "unknown custnum $custnum" };
1709 my $conf = new FS::Conf;
1710 my $immutable = $conf->exists('selfservice_immutable-package');
1712 # the duplication below is necessary:
1713 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1714 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1715 # non-backwards-compatible change breaking the software of anyone using the API
1716 # instead of the stock selfservice
1717 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1718 if( $conf->exists('selfservice_server-view-wholesale') ) {
1719 return { 'svcnum' => $session->{'svcnum'},
1720 'custnum' => $custnum,
1721 'cust_pkg' => [ map {
1723 immutable => $immutable,
1724 part_pkg => [ map $_->hashref, $_->part_pkg ],
1726 [ map $_->hashref, $_->available_part_svc ],
1728 [ map { my $ref = { $_->hash,
1729 label => [ $_->label ],
1731 $ref->{_password} = $_->svc_x->_password
1732 if $context eq 'agent'
1733 && $conf->exists('agent-showpasswords')
1734 && $_->part_svc->svcdb eq 'svc_acct';
1739 } $cust_main->cust_pkg
1742 small_custview( $cust_main, $conf->config('countrydefault') ),
1743 'wholesale_view' => 1,
1744 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1745 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1746 'lnp' => $conf->exists('svc_phone-lnp'),
1750 { 'svcnum' => $session->{'svcnum'},
1751 'custnum' => $custnum,
1752 'cust_pkg' => [ map {
1753 my $primary_cust_svc = $_->primary_cust_svc;
1756 immutable => $immutable,
1757 pkg_label => $_->pkg_locale,
1758 status => $_->status,
1759 statuscolor => $_->statuscolor,
1761 [ map { $_->hashref }
1762 grep { $_->selfservice_access ne 'hidden' }
1763 $_->available_part_svc
1766 [ map { my $ref = { $_->hash,
1767 label => [ $_->label ],
1769 $ref->{_password} = $_->svc_x->_password
1770 if $context eq 'agent'
1771 && $conf->exists('agent-showpasswords')
1772 && $_->part_svc->svcdb eq 'svc_acct';
1773 $ref->{svchash} = { $_->svc_x->hash } if
1774 $_->part_svc->svcdb eq 'svc_phone';
1775 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1776 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1779 grep { $_->part_svc->selfservice_access ne 'hidden' }
1784 ? { $primary_cust_svc->hash,
1785 label => [ $primary_cust_svc->label ],
1786 finger => $primary_cust_svc->svc_x->finger, #uuh
1787 $primary_cust_svc->part_svc->hash,
1791 } $cust_main->ncancelled_pkgs
1794 small_custview( $cust_main, $conf->config('countrydefault') ),
1795 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1803 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1804 return { 'error' => $session } if $context eq 'error';
1806 my $conf = new FS::Conf;
1808 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1809 my $search = { 'custnum' => $custnum };
1810 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1811 my $cust_main = qsearchs('cust_main', $search )
1812 or return { 'error' => "unknown custnum $custnum" };
1814 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1815 if ( ! $pkgnum && $p->{'svcnum'} ) {
1816 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1817 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1821 my @cust_pkg_usage = ();
1822 foreach my $cust_pkg ( $p->{'ncancelled'}
1823 ? $cust_main->ncancelled_pkgs
1824 : $cust_main->unsuspended_pkgs ) {
1825 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1826 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1827 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1830 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1833 foreach (@cust_pkg_usage) {
1834 my $part = $_->part_pkg_usage;
1835 my $tag = $part->description . ($part->shared ? 1 : 0);
1836 my $row = $usage_pools{$tag}
1837 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1838 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1839 $row->[2] += $part->minutes; # minutes total
1841 } # otherwise just leave them empty
1843 if ( $p->{'svcdb'} ) {
1844 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1846 : ref($p->{'svcdb'}) eq 'ARRAY'
1847 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1848 : { $p->{'svcdb'} => 1 };
1849 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1852 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1855 my @svcs; # stuff to return to the client
1856 my %bytes_used_total; # for _used columns only
1857 foreach my $cust_svc (@cust_svc) {
1858 my $svc_x = $cust_svc->svc_x;
1859 my($label, $value) = $cust_svc->label;
1860 my $part_svc = $cust_svc->part_svc;
1861 my $svcdb = $part_svc->svcdb;
1862 my $cust_pkg = $cust_svc->cust_pkg;
1863 my $part_pkg = $cust_pkg->part_pkg;
1866 'svcnum' => $cust_svc->svcnum,
1867 'display_svcnum' => $cust_svc->display_svcnum,
1871 'pkg_label' => $cust_pkg->pkg_locale,
1872 'pkg_status' => $cust_pkg->status,
1873 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1876 # would it make sense to put this in a svc_* method?
1878 if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
1879 my $last_bill = $cust_pkg->last_bill || 0;
1881 my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
1882 my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
1885 'seconds_used' => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
1886 'upbytes_used' => display_bytecount($up_used),
1887 'downbytes_used' => display_bytecount($down_used),
1888 'totalbytes_used' => display_bytecount($up_used + $down_used)
1890 $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
1891 $bytes_used_total{'upbytes_used'} += $up_used;
1892 $bytes_used_total{'downbytes_used'} += $down_used;
1893 $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
1896 if ( $svcdb eq 'svc_acct' ) {
1897 foreach (qw(username email finger seconds)) {
1898 $hash{$_} = $svc_x->$_;
1904 'upbytes' => display_bytecount($svc_x->upbytes),
1905 'downbytes' => display_bytecount($svc_x->downbytes),
1906 'totalbytes' => display_bytecount($svc_x->totalbytes),
1908 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1909 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1910 'recharge_upbytes' =>
1911 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1912 'recharge_downbytes' =>
1913 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1914 'recharge_totalbytes' =>
1915 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1920 } elsif ( $svcdb eq 'svc_dsl' ) {
1922 $hash{'phonenum'} = $svc_x->phonenum;
1923 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1924 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1925 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1928 $hash{'name'} = $cust_main->name;
1930 # no usage to hide here
1932 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1934 # could potentially show lots of things...
1935 $hash{'outbound'} = 1;
1936 $hash{'inbound'} = 0;
1937 if ( $svcdb eq 'svc_phone' ) {
1938 if ( $part_pkg->plan eq 'voip_inbound' ) {
1939 $hash{'outbound'} = 0;
1940 $hash{'inbound'} = 1;
1941 } elsif ( $part_pkg->option('selfservice_inbound_format')
1942 or $conf->config('selfservice-default_inbound_cdr_format')
1944 $hash{'inbound'} = 1;
1947 foreach (qw(inbound outbound)) {
1948 # hmm...we can't filter by status here, because there might
1949 # not be cdr_terminations at all. have to go by date.
1950 # find all since the last bill date.
1951 # XXX cdr types? we are going to need them.
1953 my $sum_cdr = $svc_x->sum_cdrs(
1954 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1955 'begin' => ($cust_pkg->last_bill || 0),
1957 'disable_charged_party' => 1,
1959 $hash{$_} = $sum_cdr->hashref;
1962 } # not hiding usage
1966 } # foreach $cust_svc
1968 foreach my $field (keys %bytes_used_total) {
1969 if ($field =~ /bytes/) {
1970 $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
1975 'svcnum' => $session->{'svcnum'},
1976 'custnum' => $custnum,
1977 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1978 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1980 'bytes_used_total' => \%bytes_used_total,
1982 map { $usage_pools{$_} }
1986 'hide_usage' => $hide_usage,
1991 sub _customer_svc_x {
1992 my($custnum, $svcnum, $table) = (shift, shift, shift);
1993 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1995 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1996 my $search = " AND custnum = $1";
1997 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2000 'table' => ($table || 'svc_acct'),
2001 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2002 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
2003 #'LEFT JOIN cust_main USING ( custnum ) ',
2004 'hashref' => $hashref,
2005 'extra_sql' => $search, #important
2010 sub svc_status_html {
2013 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2014 return { 'error' => $session } if $context eq 'error';
2016 #XXX only svc_dsl for now
2017 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2018 or return { 'error' => "Service not found" };
2020 my $html = $svc_x->getstatus_html;
2022 return { 'html' => $html };
2026 sub svc_status_hash {
2029 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2030 return { 'error' => $session } if $context eq 'error';
2032 #XXX only svc_acct for now
2033 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2034 or return { 'error' => "Service not found" };
2036 my ( $html, $hashref ) = $svc_x->export_getstatus;
2041 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
2042 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2043 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2044 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2045 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2048 my( $p, $method ) = @_;
2050 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2051 return { 'error' => $session } if $context eq 'error';
2053 #XXX only svc_acct for now
2054 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2055 or return { 'error' => "Service not found" };
2057 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2059 my $error = $svc_x->$method($p); #$p? returns error?
2060 return { 'error' => $error } if $error;
2062 return {}; #? { 'error' => '' }
2066 sub acct_forward_info {
2069 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2070 return { 'error' => $session } if $context eq 'error';
2072 my $svc_forward = _customer_svc_x( $custnum,
2073 { 'srcsvc' => $p->{'svcnum'} },
2076 or return { 'error' => '',
2080 return { 'error' => '',
2081 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2086 sub process_acct_forward {
2088 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2089 return { 'error' => $session } if $context eq 'error';
2091 my $old = _customer_svc_x( $custnum,
2092 { 'srcsvc' => $p->{'svcnum'} },
2096 if ( $p->{'dst'} eq '' ) {
2098 my $error = $old->delete;
2099 return { 'error' => $error };
2101 return { 'error' => '' };
2104 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2105 'dst' => $p->{'dst'},
2110 $new->svcnum($old->svcnum);
2111 my $cust_svc = $old->cust_svc;
2112 $new->svcpart($old->svcpart);
2113 $new->pkgnuym($old->pkgnum);
2114 $error = $new->replace($old);
2116 my $conf = new FS::Conf;
2117 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2119 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2120 or return { 'error' => 'No service' }; #how would we even get here?
2122 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2124 $error = $new->insert;
2127 return { 'error' => $error };
2131 sub list_dsl_devices {
2134 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2135 return { 'error' => $session } if $context eq 'error';
2137 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2138 or return { 'error' => "Service not found" };
2141 'devices' => [ map {
2142 +{ 'mac_addr' => $_->mac_addr };
2143 } $svc_dsl->dsl_device
2149 sub add_dsl_device {
2152 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2153 return { 'error' => $session } if $context eq 'error';
2155 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2156 or return { 'error' => "Service not found" };
2158 return { 'error' => 'No MAC address supplied' }
2159 unless length($p->{'mac_addr'});
2161 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2162 'mac_addr' => scalar($p->{'mac_addr'}),
2164 my $error = $dsl_device->insert;
2165 return { 'error' => $error };
2169 sub delete_dsl_device {
2172 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2173 return { 'error' => $session } if $context eq 'error';
2175 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2176 or return { 'error' => "Service not found" };
2178 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2179 'mac_addr' => scalar($p->{'mac_addr'}),
2182 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2184 my $error = $dsl_device->delete;
2185 return { 'error' => $error };
2191 _usage_details( \&_port_graph, $p,
2192 'svcdb' => 'svc_port',
2197 my($svc_port, $begin, $end) = @_;
2199 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2200 push @usage, { 'png' => $pngOrError };
2204 sub _list_svc_usage {
2205 my($svc_acct, $begin, $end) = @_;
2207 foreach my $part_export (
2208 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2209 qw( sqlradius sqlradius_withdomain )
2211 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2216 sub list_svc_usage {
2217 _usage_details(\&_list_svc_usage, @_);
2220 sub _list_support_usage {
2221 my($svc_acct, $begin, $end) = @_;
2223 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2224 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2226 push @usage, { 'seconds' => $_->seconds,
2227 'support' => $_->support,
2228 '_date' => $_->_date,
2229 'id' => $_->transaction_id,
2230 'creator' => $_->creator,
2231 'subject' => $_->subject,
2232 'status' => $_->status,
2233 'ticketid' => $_->ticketid,
2239 sub list_support_usage {
2240 _usage_details(\&_list_support_usage, @_);
2243 sub _list_cdr_usage {
2244 # XXX CDR type support...
2245 # XXX any way to do a paged search on this?
2246 # we have to return the results all at once...
2247 my($svc_x, $begin, $end, %opt) = @_;
2248 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2252 'disable_charged_party' => 1,
2257 sub list_cdr_usage {
2259 _usage_details( \&_list_cdr_usage, $p );
2262 sub _usage_details {
2263 my($callback, $p, %opt) = @_;
2264 my $conf = FS::Conf->new;
2266 if ( $conf->exists('selfservice_hide-usage') ) {
2267 return { 'error' => 'Viewing usage is not allowed.' };
2270 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2271 return { 'error' => $session } if $context eq 'error';
2273 my $search = { 'svcnum' => $p->{'svcnum'} };
2274 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2276 my $cust_svc = qsearchs( 'cust_svc', $search );
2277 return { 'error' => 'No service selected in list_svc_usage' }
2280 my $svc_x = $cust_svc->svc_x;
2281 my $svcdb = $svc_x->table;
2282 my $cust_pkg = $cust_svc->cust_pkg;
2283 my $freq = $cust_pkg->part_pkg->freq;
2286 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2288 if ( $p->{inbound} ) {
2289 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2290 || $conf->config('selfservice-default_inbound_cdr_format')
2291 || 'source_default';
2292 $callback_opt{inbound} = 1;
2294 $format = $cust_pkg->part_pkg->option('selfservice_format')
2295 || $conf->config('selfservice-default_cdr_format')
2299 $callback_opt{format} = $format;
2300 $callback_opt{use_clid} = 1;
2301 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2304 my $start = $cust_pkg->setup;
2305 #my $end = $cust_pkg->bill; # or time?
2308 unless ( $p->{beginning} ) {
2309 $p->{beginning} = $cust_pkg->last_bill;
2310 $p->{ending} = $end;
2313 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2314 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2316 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2320 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2321 # ugly kludge, I know
2322 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2323 if (defined $delete_col) {
2324 delete($_->[$delete_col]) foreach ($header, @usage);
2328 #kinda false laziness with FS::cust_main::bill, but perhaps
2329 #we should really change this bit to DateTime and DateTime::Duration
2331 #change this bit to use Date::Manip? CAREFUL with timezones (see
2332 # mailing list archive)
2333 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2334 (localtime($p->{ending}) )[0,1,2,3,4,5];
2335 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2336 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2338 if ( $freq =~ /^\d+$/ ) {
2340 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2342 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2343 } elsif ( $freq =~ /^(\d+)w$/ ) {
2345 $nmday += $weeks * 7;
2346 $pmday -= $weeks * 7;
2347 } elsif ( $freq =~ /^(\d+)d$/ ) {
2351 } elsif ( $freq =~ /^(\d+)h$/ ) {
2356 return { 'error' => "unparsable frequency: ". $freq };
2359 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2360 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2364 'svcnum' => $p->{svcnum},
2365 'beginning' => $p->{beginning},
2366 'ending' => $p->{ending},
2367 'inbound' => $p->{inbound},
2368 'previous' => ($previous > $start) ? $previous : $start,
2369 'next' => ($next < $end) ? $next : $end,
2370 'header' => $header,
2378 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2379 return { 'error' => $session } if $context eq 'error';
2381 my $search = { 'custnum' => $custnum };
2382 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2383 my $cust_main = qsearchs('cust_main', $search )
2384 or return { 'error' => "unknown custnum $custnum" };
2386 my $status = $cust_main->status;
2388 my %order_pkg_options = ();
2389 if ( $p->{locationnum} > 0 ) {
2390 $order_pkg_options{locationnum} = delete($p->{locationnum});
2391 } elsif ( $p->{address1} ) {
2392 $order_pkg_options{'cust_location'} = new FS::cust_location {
2393 map { $_ => $p->{$_} }
2394 qw( address1 address2 city county state zip country )
2398 #false laziness w/ClientAPI/Signup.pm
2400 my $cust_pkg = new FS::cust_pkg ( {
2401 'custnum' => $custnum,
2402 'pkgpart' => $p->{'pkgpart'},
2403 'quantity' => $p->{'quantity'} || 1,
2405 my $error = $cust_pkg->check;
2406 return { 'error' => $error } if $error;
2409 unless ( $p->{'svcpart'} eq 'none' ) {
2413 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2415 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2416 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2417 $svcdb = $part_svc->svcdb;
2419 $svcdb = 'svc_acct';
2421 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2424 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2425 'svc_domain' => [ qw( domain ) ],
2426 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2427 'svc_external' => [ qw( id title ) ],
2428 'svc_pbx' => [ qw( id title ) ],
2431 my $svc_x = "FS::$svcdb"->new( {
2432 'svcpart' => $svcpart,
2433 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2436 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2439 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2440 my $acct_snarf = new FS::acct_snarf ( {
2441 'machine' => $p->{"snarf_machine$snarfnum"},
2442 'protocol' => $p->{"snarf_protocol$snarfnum"},
2443 'username' => $p->{"snarf_username$snarfnum"},
2444 '_password' => $p->{"snarf_password$snarfnum"},
2447 push @acct_snarf, $acct_snarf;
2449 $svc_x->child_objects( \@acct_snarf );
2452 my $y = $svc_x->setdefault; # arguably should be in new method
2453 return { 'error' => $y } if $y && !ref($y);
2455 $error = $svc_x->check;
2456 return { 'error' => $error } if $error;
2462 $error = $cust_main->order_pkg(
2463 'cust_pkg' => $cust_pkg,
2468 return { 'error' => $error } if $error;
2470 my $conf = new FS::Conf;
2471 if ( $conf->exists('signup_server-realtime') ) {
2473 my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2476 $cust_pkg->cancel('quiet'=>1);
2479 $cust_pkg->reexport;
2483 $cust_pkg->reexport;
2486 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2488 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2495 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2496 return { 'error' => $session } if $context eq 'error';
2498 my $conf = new FS::Conf;
2499 my $immutable = $conf->exists('selfservice_immutable-package');
2500 return { 'error' => "Package modification disabled" } if $immutable;
2502 my $search = { 'custnum' => $custnum };
2503 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2504 my $cust_main = qsearchs('cust_main', $search )
2505 or return { 'error' => "unknown custnum $custnum" };
2507 my $status = $cust_main->status;
2508 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2509 or return { 'error' => "unknown package $p->{pkgnum}" };
2511 #if someone does need self-service package change of suspended packages,
2512 # figure out how to be more discriminating
2513 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2514 if $cust_pkg->status eq 'suspended';
2516 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2517 'quantity' => $p->{'quantity'} || 1,
2520 my $new_pkg = qsearchs('part_pkg', { 'pkgpart' => $p->{pkgpart} } )
2521 or return { 'error' => "unknown package $p->{pkgpart}" };
2523 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2524 unless ref($err_or_cust_pkg);
2527 if ( $conf->exists('signup_server-realtime') ) {
2529 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2532 $err_or_cust_pkg->suspend;
2535 $err_or_cust_pkg->reexport;
2539 $err_or_cust_pkg->reexport;
2542 return { error => '', pkg => $new_pkg->pkg, pkgnum => $err_or_cust_pkg->pkgnum };
2546 sub order_recharge {
2549 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2550 return { 'error' => $session } if $context eq 'error';
2552 my $search = { 'custnum' => $custnum };
2553 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2554 my $cust_main = qsearchs('cust_main', $search )
2555 or return { 'error' => "unknown custnum $custnum" };
2557 my $status = $cust_main->status;
2558 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2559 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2561 my $svc_x = $cust_svc->svc_x;
2562 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2565 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2566 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2567 recharge_totalbytes );
2568 my $amount = $part_pkg->option('recharge_amount', 1);
2570 my ($l, $v, $d) = $cust_svc->label; # blah
2571 my $pkg = "Recharge $v";
2573 my $bill_error = $cust_main->charge($amount, $pkg,
2574 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2575 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2576 $part_pkg->taxclass); #meh
2578 my $conf = new FS::Conf;
2579 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2581 $bill_error = _do_bop_realtime( $cust_main, $status );
2586 my $error = $svc_x->recharge (\%vhash);
2587 return { 'error' => $error } if $error;
2591 my $error = $bill_error;
2592 $error ||= $svc_x->recharge (\%vhash);
2593 return { 'error' => $error } if $error;
2596 return { error => '', svc => $cust_svc->part_svc->svc };
2600 sub _do_bop_realtime {
2601 my ($cust_main, $status, %opt) = @_;
2603 my $old_balance = $cust_main->balance;
2606 my $bill_error = $cust_main->bill(
2607 'return_bill' => \@cust_bill,
2610 $bill_error ||= $cust_main->apply_payments_and_credits;
2612 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2613 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2615 if ( $cust_main->balance > $old_balance
2616 && $cust_main->balance > 0
2617 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2618 || $status eq 'suspended'
2622 unless ( $opt{'no_invoice_void'} ) {
2624 #this used to apply a credit, but now we can void invoices...
2625 foreach my $cust_bill (@cust_bill) {
2626 my $voiderror = $cust_bill->void('automatic payment failed');
2627 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2632 return { 'error' => '_decline', 'bill_error' => $bill_error };
2635 if ( $opt{'collect'} ) {
2636 my $collect_error = $cust_main->collect();
2637 return { 'error' => '_decline', 'bill_error' => $collect_error }
2638 if $collect_error; #?
2647 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2648 return { 'error' => $session } if $context eq 'error';
2650 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2651 or return { 'error' => "unknown custnum $custnum" };
2653 my @cust_pkg = sort { $a->bill <=> $b->bill }
2654 grep { $_->part_pkg->freq ne '0' }
2655 $cust_main->ncancelled_pkgs;
2657 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2659 my $total = $cust_main->balance;
2662 my $bill = $_->bill;
2663 $total += $_->part_pkg->base_recur($_, \$bill);
2664 my $renew_date = $_->part_pkg->add_freq($_->bill);
2666 'pkgnum' => $_->pkgnum,
2667 'amount' => sprintf('%.2f', $total),
2668 'bill_date' => $_->bill,
2669 'bill_date_pretty' => time2str('%x', $_->bill),
2670 'renew_date' => $renew_date,
2671 'renew_date_pretty' => time2str('%x', $renew_date),
2672 'expire_date' => $_->expire,
2673 'expire_date_pretty' => time2str('%x', $_->expire),
2678 return { 'dates' => \@array };
2682 sub payment_info_renew_info {
2684 my $renew_info = renew_info($p);
2685 my $payment_info = payment_info($p);
2686 return { %$renew_info,
2694 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2695 return { 'error' => $session } if $context eq 'error';
2697 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2698 or return { 'error' => "unknown custnum $custnum" };
2700 my $date = $p->{'date'};
2704 #freeside-daily -n -d $date fs_daily $custnum
2705 $cust_main->bill_and_collect( 'time' => $date,
2706 'invoice_time' => $now,
2707 'actual_time' => $now,
2708 'check_freq' => '1d',
2711 return { 'error' => '' };
2717 my $session = _cache->get($p->{'session_id'})
2718 or return { 'error' => "Can't resume session" }; #better error message
2720 my $custnum = $session->{'custnum'};
2722 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2723 or return { 'error' => "unknown custnum $custnum" };
2725 my $conf = new FS::Conf;
2727 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2728 or return { 'error' => 'Permission denied' };
2730 my $pkgnum = $p->{'pkgnum'};
2732 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2733 'pkgnum' => $pkgnum, } )
2734 or return { 'error' => "unknown pkgnum $pkgnum" };
2736 my $error = $cust_pkg->suspend(reason => $reasonnum);
2737 return { 'error' => $error };
2743 my $session = _cache->get($p->{'session_id'})
2744 or return { 'error' => "Can't resume session" }; #better error message
2746 my $custnum = $session->{'custnum'};
2747 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2748 or return { 'error' => "unknown custnum $custnum" };
2750 my $pkgnum = $p->{'pkgnum'};
2751 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2752 'pkgnum' => $pkgnum, } )
2753 or return { 'error' => "unknown pkgnum $pkgnum" };
2755 my $error = $cust_pkg->cancel( 'quiet' => 1,
2756 'date' => $p->{'date'},
2758 return { 'error' => $error };
2761 sub provision_phone {
2764 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2766 #editing an existing phone number
2767 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2768 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2769 return { 'error' => $session } if $context eq 'error';
2771 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2772 return { 'error' => 'service not found' } unless $svc_phone;
2773 return { 'error' => 'invalid svcnum' }
2774 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2776 $svc_phone->email($p->{'email'})
2777 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2778 $svc_phone->forwarddst($p->{'forwarddst'})
2779 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2780 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2781 return { 'error' => $svc_phone->replace };
2785 unless ( $p->{'lnp'} ) {
2786 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2787 $p->{'lnp_status'} = "portingin";
2788 return _provision( 'FS::svc_phone',
2789 [qw(lnp_desired_due_date lnp_other_provider
2790 lnp_other_provider_account phonenum countrycode lnp_status)],
2791 [qw(phonenum countrycode)],
2797 # single DID order (the usual case)
2798 unless (scalar(@bulkdid)) {
2799 return _provision( 'FS::svc_phone',
2800 [qw(phonenum countrycode)],
2801 [qw(phonenum countrycode)],
2807 # bulk DID order case
2809 foreach my $did ( @bulkdid ) {
2810 $did =~ s/[^0-9]//g;
2811 $error = _provision( 'FS::svc_phone',
2812 [qw(phonenum countrycode)],
2813 [qw(phonenum countrycode)],
2815 'pkgnum' => $p->{'pkgnum'},
2816 'svcpart' => $p->{'svcpart'},
2818 'countrycode' => $p->{'countrycode'},
2819 'session_id' => $p->{'session_id'},
2822 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2824 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2829 warn "provision_pbx called\n"
2832 warn "provision_pbx calling _provision\n"
2834 _provision( 'FS::svc_pbx',
2835 [qw(id title max_extensions max_simultaneous ip_addr)],
2836 [qw(id title max_extensions max_simultaneous ip_addr)],
2842 sub provision_acct {
2844 warn "provision_acct called\n"
2847 return { 'error' => gettext('passwords_dont_match') }
2848 if $p->{'_password'} ne $p->{'_password2'};
2849 return { 'error' => gettext('empty_password') }
2850 unless length($p->{'_password'});
2852 if ($p->{'domsvc'}) {
2853 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2854 qw ( svcpart pkgnum ) );
2855 return { 'error' => gettext('invalid_domain') }
2856 unless ($domains{$p->{'domsvc'}});
2859 warn "provision_acct calling _provision\n"
2861 _provision( 'FS::svc_acct',
2862 [qw(username _password domsvc)],
2863 [qw(username _password domsvc)],
2869 sub provision_external {
2871 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2872 _provision( 'FS::svc_external',
2880 sub provision_forward {
2882 _provision( 'FS::svc_forward',
2883 ['srcsvc','src','dstsvc','dst'],
2890 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2891 warn "_provision called for $class\n"
2894 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2895 return { 'error' => $session } if $context eq 'error';
2897 my $search = { 'custnum' => $custnum };
2898 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2899 my $cust_main = qsearchs('cust_main', $search )
2900 or return { 'error' => "unknown custnum $custnum" };
2902 my $pkgnum = $p->{'pkgnum'};
2904 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2906 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2907 'pkgnum' => $pkgnum,
2909 or return { 'error' => "unknown pkgnum $pkgnum" };
2911 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2913 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2914 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2916 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2917 if $class ne 'FS::'. $part_svc->svcdb;
2919 warn "creating $class record\n"
2921 my $svc_x = $class->new( {
2922 'pkgnum' => $p->{'pkgnum'},
2923 'svcpart' => $p->{'svcpart'},
2924 map { $_ => $p->{$_} } @$fields
2927 my %insert_args = ();
2928 #i shouldn't be a special case here (pass an option or something)
2929 if ( $class eq 'FS::svc_phone'
2930 && grep length($p->{$_}), @location_editable_fields
2933 $insert_args{'cust_location'} = new FS::cust_location {
2934 map { $_ => $p->{$_} } @location_editable_fields
2938 warn "inserting $class record\n"
2940 my $error = $svc_x->insert(%insert_args);
2943 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2945 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2948 my $return = { 'svc' => $part_svc->svc,
2950 map { $_ => $svc_x->get($_) } @$return_fields
2952 warn "_provision returning ". Dumper($return). "\n"
2961 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2962 return { 'error' => $session } if $context eq 'error';
2964 my $search = { 'custnum' => $custnum };
2965 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2966 my $cust_main = qsearchs('cust_main', $search )
2967 or return { 'error' => "unknown custnum $custnum" };
2969 my $pkgnum = $p->{'pkgnum'};
2971 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2972 'pkgnum' => $pkgnum,
2974 or return { 'error' => "unknown pkgnum $pkgnum" };
2976 my $svcpart = $p->{'svcpart'};
2978 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2979 'svcpart' => $svcpart, } )
2980 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2981 my $part_svc = $pkg_svc->part_svc;
2983 my $conf = new FS::Conf;
2986 'svc' => $part_svc->svc,
2987 'svcdb' => $part_svc->svcdb,
2988 'pkgnum' => $pkgnum,
2989 'svcpart' => $svcpart,
2990 'custnum' => $custnum,
2992 'security_phrase' => 0, #XXX !
2993 'svc_acct_pop' => [], #XXX !
2995 'init_popstate' => '',
3000 small_custview( $cust_main, $conf->config('countrydefault') ),
3004 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
3005 && $ret->{'svcdb'} eq 'svc_phone') {
3006 $ret->{'svcnum'} = $p->{'svcnum'};
3007 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3008 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3009 $ret->{'email'} = $svc_phone->email;
3010 $ret->{'forwarddst'} = $svc_phone->forwarddst;
3014 if ($ret->{'svcdb'} eq 'svc_forward') {
3015 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3021 sub unprovision_svc {
3024 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3025 return { 'error' => $session } if $context eq 'error';
3027 my $search = { 'custnum' => $custnum };
3028 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3029 my $cust_main = qsearchs('cust_main', $search )
3030 or return { 'error' => "unknown custnum $custnum" };
3032 my $svcnum = $p->{'svcnum'};
3034 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
3035 or return { 'error' => "unknown svcnum $svcnum" };
3037 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3038 unless $cust_svc->cust_pkg->custnum == $custnum;
3040 my $conf = new FS::Conf;
3042 return { 'svc' => $cust_svc->part_svc->svc,
3043 'error' => $cust_svc->cancel,
3045 small_custview( $cust_main, $conf->config('countrydefault') ),
3050 sub myaccount_passwd {
3052 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3053 return { 'error' => $session } if $context eq 'error';
3055 return { 'error' => "New passwords don't match." }
3056 if $p->{'new_password'} ne $p->{'new_password2'};
3058 return { 'error' => 'Enter new password' }
3059 unless length($p->{'new_password'});
3061 #my $search = { 'custnum' => $custnum };
3062 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3063 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3064 my $search = " AND custnum = $1";
3065 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3067 my $svc_acct = qsearchs( {
3068 'table' => 'svc_acct',
3069 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3070 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3071 'LEFT JOIN cust_main USING ( custnum ) ',
3072 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3073 'extra_sql' => $search, #important
3075 or return { 'error' => "Service not found" };
3079 my $conf = new FS::Conf;
3081 return { 'error' => 'Incorrect current password.' }
3082 if ( exists($p->{'old_password'})
3083 || $conf->exists('selfservice-password_change_oldpass')
3085 && ! $svc_acct->check_password($p->{'old_password'});
3087 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3088 || $svc_acct->set_password($p->{'new_password'})
3089 || $svc_acct->replace();
3091 #regular pw change in self-service should change contact pw too, otherwise its
3092 #way too confusing. hell its confusing they're separate at all, but alas.
3093 #need to support the "ISP provides email that's used as a contact email" case
3095 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3096 if ( $contact && $contact->custnum == $custnum ) {
3097 #svc_acct was successful but this one returns an error? "shouldn't happen"
3098 #don't recheck is_password_allowed here; if the svc_acct password was
3099 #legal, that's good enough
3100 $error ||= $contact->change_password($p->{'new_password'});
3103 my($label, $value) = $svc_acct->cust_svc->label;
3105 return { 'error' => $error,
3115 my $info = skin_info($p);
3117 my $conf = new FS::Conf;
3118 my $verification = $conf->config('selfservice-password_reset_verification')
3119 or return { %$info, 'error' => 'Password resets disabled' };
3124 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3126 $contact = FS::contact->by_selfservice_email($p->{'email'});
3128 $cust_main = $contact->cust_main if $contact;
3130 #also look for an svc_acct, otherwise it would be super confusing
3132 my($username, $domain) = split('@', $p->{'email'});
3133 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3134 if ( $svc_domain ) {
3135 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3136 'domsvc' => $svc_domain->svcnum }
3139 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3140 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3142 #precaution: don't change svc_acct password not part of the same
3143 # customer as contact
3144 $svc_acct = '' if ! $cust_pkg
3145 || $cust_pkg->custnum != $cust_main->custnum;
3150 return { %$info, 'error' => 'Email address not found' }
3151 unless $contact || $svc_acct;
3153 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3155 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3156 or return { %$info, 'error' => 'Account not found' };
3158 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3159 'domsvc' => $svc_domain->svcnum }
3161 or return { %$info, 'error' => 'Account not found' };
3163 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3164 or return { %$info, 'error' => 'Account not found' };
3166 $cust_main = $cust_pkg->cust_main;
3171 'email' => sub { 1; },
3173 my( $p, $cust_main ) = @_;
3174 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3175 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3178 my( $p, $cust_main ) = @_;
3179 my $cust_pay = qsearchs({
3180 'table' => 'cust_pay',
3181 'hashref' => { 'custnum' => $cust_main->custnum },
3182 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3186 $p->{'amount'} == $cust_pay->paid;
3189 my( $p, $cust_main ) = @_;
3190 $p->{'zip'} eq $cust_main->zip
3191 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3195 foreach my $verify ( split(',', $verification) ) {
3197 &{ $verify{$verify} }( $p, $cust_main )
3198 or return { %$info, 'error' => 'Account not found' };
3202 #okay, we're verified
3206 my $error = $contact->send_reset_email(
3207 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3211 return { %$info, 'error' => $error }; #????
3214 } elsif ( $svc_acct ) {
3216 #create a unique session
3218 my $reset_session = {
3219 'svcnum' => $svc_acct->svcnum,
3220 'agentnum' => $svc_acct->cust_main->agentnum,
3223 my $timeout = '1 hour'; #?
3225 my $reset_session_id;
3227 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3228 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3231 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3235 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3236 $cust_main->agentnum);
3237 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3238 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3240 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3241 my $error = $msg_template->send( 'cust_main' => $cust_main,
3242 'object' => $svc_acct,
3243 'substitutions' => {
3244 'session_id' => $reset_session_id,
3248 return { %$info, 'error' => $error }; #????
3253 return { %$info, 'error' => '' };
3256 sub check_reset_passwd {
3259 my $conf = new FS::Conf;
3260 my $verification = $conf->config('selfservice-password_reset_verification')
3261 or return { 'error' => 'Password resets disabled' };
3263 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3264 or return { 'error' => "Can't resume session" }; #better error message
3266 if ( $reset_session->{'svcnum'} ) {
3268 my $svcnum = $reset_session->{'svcnum'};
3270 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3271 or return { 'error' => "Service not found" };
3273 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3274 my $info = skin_info($p);
3278 'session_id' => $p->{'session_id'},
3279 'username' => $svc_acct->username,
3282 } elsif ( $reset_session->{'contactnum'} ) {
3284 my $contactnum = $reset_session->{'contactnum'};
3286 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3287 or return { 'error' => "Contact not found" };
3289 my @contact_email = $contact->contact_email;
3290 return { 'error' => 'No contact email' } unless @contact_email;
3292 $p->{'agentnum'} = $contact->cust_main->agentnum;
3293 my $info = skin_info($p);
3297 'session_id' => $p->{'session_id'},
3298 'email' => $contact_email[0]->email, #the first?
3303 return { 'error' => 'No svcnum or contactnum in session' }; #??
3309 sub process_reset_passwd {
3312 my $conf = new FS::Conf;
3313 my $verification = $conf->config('selfservice-password_reset_verification')
3314 or return { 'error' => 'Password resets disabled' };
3316 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3317 or return { 'error' => "Can't resume session" }; #better error message
3322 if ( $reset_session->{'svcnum'} ) {
3324 my $svcnum = $reset_session->{'svcnum'};
3326 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3327 or return { 'error' => "Service not found" };
3329 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3330 $info ||= skin_info($p);
3335 if ( $reset_session->{'contactnum'} ) {
3337 my $contactnum = $reset_session->{'contactnum'};
3339 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3340 or return { 'error' => "Contact not found" };
3342 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3343 $info ||= skin_info($p);
3347 return { %$info, 'error' => "New passwords don't match." }
3348 if $p->{'new_password'} ne $p->{'new_password2'};
3350 return { %$info, 'error' => 'Enter new password' }
3351 unless length($p->{'new_password'});
3355 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3356 || $svc_acct->set_password($p->{'new_password'})
3357 || $svc_acct->replace();
3359 return { %$info, 'error' => $error } if $error;
3361 #my($label, $value) = $svc_acct->cust_svc->label;
3362 #return { 'error' => $error,
3363 # #'label' => $label,
3364 # #'value' => $value,
3371 my $error = $contact->is_password_allowed($p->{'new_password'})
3372 || $contact->change_password($p->{'new_password'});
3374 return { %$info, 'error' => $error }; # if $error;
3378 #password changed ,so remove session, don't want it reused
3379 _cache->remove($p->{'session_id'});
3381 return { %$info, 'error' => '' };
3385 sub validate_passwd {
3389 %result = ( 'fieldid' => $p->{'fieldid'} )
3390 if $p->{'fieldid'} =~ /^\w+$/;
3392 return { %result, 'password_invalid' => 'Enter new password' }
3393 unless length($p->{'check_password'});
3396 if ($p->{'svcnum'}) {
3397 # false laziness with myaccount_passwd
3398 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3399 return { %result, 'error' => $session } if $context eq 'error';
3401 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3402 my $search = " AND custnum = $1";
3403 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3405 $svc_acct = qsearchs( {
3406 'table' => 'svc_acct',
3407 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3408 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3409 'LEFT JOIN cust_main USING ( custnum ) ',
3410 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3411 'extra_sql' => $search, #important
3413 or return { %result, 'error' => "Service not found" };
3414 # end false laziness
3417 unless ($svc_acct) {
3418 my $conf = new FS::Conf;
3419 my $agentnum = $p->{'agentnum'};
3420 return { %result, 'password_valid' => 1 }
3421 if $conf->config_bool('password-insecure', $p->{'agentnum'});
3424 $svc_acct ||= new FS::svc_acct {};
3426 my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3427 return { %result, 'password_invalid' => $error } if $error;
3428 return { %result, 'password_valid' => 1 };
3433 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3434 return { 'error' => $session } if $context eq 'error';
3437 if ( $session->{'pkgnum'} ) {
3439 #tickets for specific service with pkg-balances on
3440 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3441 'pkgnum' => $session->{'pkgnum'} })
3442 or return { 'error' => 'unknown package' };
3443 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3444 push @tickets, $cust_svc->tickets( $p->{status} );
3449 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3450 or return { 'error' => "unknown custnum $custnum" };
3452 @tickets = $cust_main->tickets( $p->{status} );
3455 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3456 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3457 my $conf = new FS::Conf;
3458 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3462 ($a->{'_selfservice_priority'} eq '') <=>
3463 ($b->{'_selfservice_priority'} eq '')
3466 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3472 +{ tickets => \@tickets };
3479 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3480 return { 'error' => $session } if $context eq 'error';
3482 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3483 FS::TicketSystem->init();
3485 my $conf = new FS::Conf;
3486 my $queue = $p->{'queue'}
3487 || $conf->config('ticket_system-selfservice_queueid')
3488 || $conf->config('ticket_system-default_queueid');
3490 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3491 my $err_or_ticket = FS::TicketSystem->create_ticket(
3492 '', #create RT session based on FS CurrentUser (fs_selfservice)
3494 'custnum' => $custnum,
3495 'svcnum' => $session->{'svcnum'},
3496 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3499 if ( ref($err_or_ticket) ) {
3500 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3502 return { 'error' => '',
3503 'ticket_id' => $err_or_ticket->id,
3506 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3508 return { 'error' => $err_or_ticket };
3516 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3517 return { 'error' => $session } if $context eq 'error';
3519 return { error => 'requested format not implemented' }
3520 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3522 my $conf = new FS::Conf;
3523 my $age_threshold = 0;
3524 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3525 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3527 my $search = { 'custnum' => $custnum };
3528 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3529 my $cust_main = qsearchs('cust_main', $search )
3530 or return { 'error' => "unknown custnum $custnum" };
3532 # does it make more sense to just run one sql query for this instead of all the
3533 # insanity below? would increase performance greately for large data sets?
3535 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3536 my @part_svc = $cust_pkg->part_svc;
3537 foreach my $part_svc ( @part_svc ) {
3538 if($part_svc->svcdb eq 'svc_phone'){
3539 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3540 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3541 push @svc_phone, $cust_pkg_svc->svc_x
3542 if $cust_pkg_svc->date_inserted >= $age_threshold;
3550 my($xls_r,$xls_c) = (0,0);
3553 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3554 if($p->{'format'} eq 'csv') {
3555 $csv = new Text::CSV_XS { 'always_quote' => 1,
3558 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3559 $content .= $csv->string;
3561 elsif($p->{'format'} eq 'xls') {
3562 my $XLS1 = new IO::Scalar \$content;
3563 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3564 or return { 'error' => "Error opening .xls file: $!" };
3565 $xls = $xls_workbook->add_worksheet('DIDs');
3566 foreach ( @fields ) {
3567 $xls->write(0,$xls_c++,$_);
3572 foreach my $svc_phone ( @svc_phone ) {
3573 my @cols = map { $svc_phone->$_ } @fields;
3574 if($p->{'format'} eq 'csv') {
3575 return { 'error' => 'Unable to create CSV' }
3576 unless $csv->combine(@cols);
3577 $content .= $csv->string;
3579 elsif($p->{'format'} eq 'xls') {
3582 $xls->write($xls_r,$xls_c++,$_);
3588 $xls_workbook->close() if $p->{'format'} eq 'xls';
3590 { content => $content, format => $p->{'format'}, };
3595 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3596 return { 'error' => $session } if $context eq 'error';
3598 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3599 # FS::TicketSystem->init();
3600 # return { 'error' => 'get_ticket configuration error' }
3601 # if $FS::TicketSystem::system ne 'RT_Internal';
3603 # check existence and ownership as part of this
3604 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3605 my $rt_session = FS::TicketSystem->session('');
3606 my $Ticket = FS::TicketSystem->get_ticket_object(
3608 ticket_id => $p->{'ticket_id'},
3611 return { 'error' => 'ticket not found' } if !$Ticket;
3613 if ( length( $p->{'subject'} || '' ) ) {
3615 if ( $p->{'subject'} ne $Ticket->Subject ) {
3616 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3617 return { 'error' => "unable to set subject: $msg" } if !$val;
3621 if(length($p->{'reply'})) {
3622 my @err_or_res = FS::TicketSystem->correspond_ticket(
3624 'ticket_id' => $p->{'ticket_id'},
3625 'content' => $p->{'reply'},
3628 return { 'error' => 'unable to reply to ticket' }
3629 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3632 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3633 my $err_or_ticket = FS::TicketSystem->get_ticket(
3635 'ticket_id' => $p->{'ticket_id'},
3638 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3639 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3641 return { 'error' => $err_or_ticket };
3644 my @custs = @{$err_or_ticket->{'custs'}};
3645 my @txns = @{$err_or_ticket->{'txns'}};
3648 # superseded by check in get_ticket_object
3649 #return { 'error' => 'invalid ticket requested' }
3650 #unless grep($_ eq $custnum, @custs);
3652 foreach my $txn ( @txns ) {
3653 push @filtered_txns, $txn
3654 if ($txn->{'type'} eq 'EmailRecord'
3655 || $txn->{'type'} eq 'Correspond'
3656 || $txn->{'type'} eq 'Create');
3659 warn "$me get_ticket: successful: \n"
3661 return { 'error' => '',
3662 'transactions' => \@filtered_txns,
3663 'ticket_fields' => $err_or_ticket->{'fields'},
3664 'ticket_id' => $p->{'ticket_id'},
3668 sub adjust_ticket_priority {
3670 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3671 return { 'error' => $session } if $context eq 'error';
3673 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3674 # FS::TicketSystem->init;
3675 my $ss_priority = FS::TicketSystem->selfservice_priority;
3677 return { 'error' => 'adjust_ticket_priority configuration error' }
3678 if $FS::TicketSystem::system ne 'RT_Internal'
3681 my $values = $p->{'values'}; #hashref, id => priority value
3684 foreach my $id (keys %$values) {
3685 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3686 my $Ticket = FS::TicketSystem->get_ticket_object('',
3688 'custnum' => $custnum,
3691 $ticket_error{$id} = 'ticket not found';
3695 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3696 # We're not going to implement it for RT_External.
3697 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3698 my $new_value = $values->{$id};
3699 next if $old_value eq $new_value;
3701 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3703 # AddCustomFieldValue works fine (replacing any existing value) if it's
3704 # a single-valued custom field, which it should be. If it's not, you're
3705 # doing something wrong.
3707 if ( length($new_value) ) {
3708 ($val, $msg) = $Ticket->AddCustomFieldValue(
3709 Field => $ss_priority,
3710 Value => $new_value,
3714 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3715 Field => $ss_priority,
3716 Value => $old_value,
3720 $ticket_error{$id} = $msg if !$val;
3721 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3723 return { 'error' => '',
3724 'ticket_error' => \%ticket_error,
3725 %{ customer_info($p) } # send updated customer info back
3731 sub _custoragent_session_custnum {
3734 my($context, $session, $custnum);
3735 if ( $p->{'session_id'} ) {
3737 $context = 'customer';
3738 $session = _cache->get($p->{'session_id'})
3739 or return ( 'error' => "Can't resume session" ); #better error message
3740 $custnum = $session->{'custnum'};
3742 } elsif ( $p->{'agent_session_id'} ) {
3745 my $agent_cache = new FS::ClientAPI_SessionCache( {
3746 'namespace' => 'FS::ClientAPI::Agent',
3748 $session = $agent_cache->get($p->{'agent_session_id'})
3749 or return ( 'error' => "Can't resume session" ); #better error message
3750 $custnum = $p->{'custnum'};
3754 return ( 'error' => "Can't resume session" ); #better error message
3757 ($context, $session, $custnum);