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},'case_insensitive'))
243 if ($conf->exists('username-uppercase') || $conf->exists('username-uppercase', $contact->cust_main->agentnum)) {
244 $contact = FS::contact->by_selfservice_email_custnum($p->{email}, $contact->custnum);
247 return { error => 'Email '.$p->{email}.' not found!'}
250 return { error => 'Incorrect contact password.' }
251 unless $contact->authenticate_password($p->{'password'});
253 $session->{'contactnum'} = $contact->contactnum;
255 $session->{'custnum'} = $contact->custnum;
259 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
261 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
262 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
264 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
265 'domsvc' => $svc_domain->svcnum, }
268 if ( $conf->exists('selfservice_server-login_svcpart') ) {
269 my @svcpart = $conf->config('selfservice_server-login_svcpart');
270 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
271 scalar( grep( $_ eq $svcpart, @svcpart ) );
276 if ( $conf->exists('selfservice_server-primary_only') ) {
279 my $cust_svc = $_->cust_svc;
280 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
281 == $cust_svc->svcpart
286 return { error => 'User not found.' } unless @svc_acct;
288 #return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
290 my $svc_acct = $svc_acct[0];
292 if ( $conf->exists('selfservice_server-login_svcpart') ) {
293 my @svcpart = $conf->config('selfservice_server-login_svcpart');
294 my $svcpart = $svc_acct->cust_svc->svcpart;
295 return { error => 'Invalid user.' }
296 unless grep($_ eq $svcpart, @svcpart);
299 return { error => 'Incorrect password.' }
300 unless $svc_acct->check_password($p->{'password'});
308 $session->{'svcnum'} = $svc_x->svcnum;
310 my $cust_svc = $svc_x->cust_svc;
311 my $cust_pkg = $cust_svc->cust_pkg;
313 my $cust_main = $cust_pkg->cust_main;
314 $session->{'custnum'} = $cust_main->custnum;
315 if ( $conf->exists('pkg-balances') ) {
316 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
317 $cust_main->ncancelled_pkgs;
318 $session->{'pkgnum'} = $cust_pkg->pkgnum
319 if scalar(@cust_pkg) > 1;
323 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
324 #return { error => 'Only primary user may log in.' }
325 # if $conf->exists('selfservice_server-primary_only')
326 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
327 my $part_pkg = $cust_pkg->part_pkg;
328 return { error => 'Only primary user may log in.' }
329 if $conf->exists('selfservice_server-primary_only')
330 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
336 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
337 } until ( ! defined _cache->get($session_id) ); #just in case
339 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
340 _cache->set( $session_id, $session, $timeout );
342 return { 'error' => '',
343 'session_id' => $session_id,
350 my $skin_info = skin_info($p);
351 if ( $p->{'session_id'} ) {
352 _cache->remove($p->{'session_id'});
353 return { %$skin_info, 'error' => '' };
355 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
362 my($context, $session, $custnum) = _custoragent_session_custnum($p);
363 return { 'error' => $session } if $context eq 'error';
365 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
366 or return { 'error' => "Service not found" };
368 $session->{'svcnum'} = $svc_acct->svcnum;
370 my $conf = new FS::Conf;
371 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
372 _cache->set( $p->{'session_id'}, $session, $timeout );
374 return { 'error' => '' };
378 sub payment_gateway {
380 # takes a cust_main and a cust_payby entry, returns the payment_gateway
381 my $conf = new FS::Conf;
382 my $cust_main = shift;
383 my $cust_payby = shift;
384 my $gatewaynum = $conf->config('selfservice-payment_gateway');
386 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
387 die "configured gatewaynum $gatewaynum not found!" if !$pg;
391 return '' if ! FS::payby->realtime($cust_payby);
392 my $pg = $cust_main->agent->payment_gateway(
393 'method' => FS::payby->payby2bop($cust_payby),
403 my $conf = new FS::Conf;
405 my $info = skin_info($p);
407 use vars qw( $cust_paybys ); #cache for performance
408 unless ( $cust_paybys ) {
410 my %cust_paybys = map { $_ => 1 }
411 map { FS::payby->payby2payment($_) }
412 $conf->config('signup_server-payby');
414 $cust_paybys = [ keys %cust_paybys ];
417 $info->{'cust_paybys'} = $cust_paybys;
419 my($context, $session, $custnum) = _custoragent_session_custnum($p);
420 return { 'error' => $session } if $context eq 'error';
422 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
423 or return { 'error' => "unknown custnum $custnum" };
425 $info->{'hide_payment_fields'} = [
427 my $pg = payment_gateway($cust_main, $_);
428 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
429 } @{ $info->{cust_paybys} }
432 $info->{'self_suspend_reason'} =
433 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
435 $info->{'edit_ticket_subject'} =
436 $conf->exists('ticket_system-selfservice_edit_subject') &&
437 $cust_main->edit_subject;
439 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
441 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
444 'custnum' => $custnum,
445 'access_pkgnum' => $session->{'pkgnum'},
446 'access_svcnum' => $session->{'svcnum'},
453 my($context, $session, $custnum) = _custoragent_session_custnum($p);
454 return { 'error' => $session } if $context eq 'error';
458 my $conf = new FS::Conf;
459 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
461 # if ( $FS::TicketSystem::system ) {
462 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
463 # FS::TicketSystem->init();
466 if ( $custnum ) { #customer record
468 %return = ( %return, %{ customer_info_short($p) } );
470 #redundant with customer_info_short, but we need it for several things below
471 my $search = { 'custnum' => $custnum };
472 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
473 my $cust_main = qsearchs('cust_main', $search )
474 or return { 'error' => "unknown custnum $custnum" };
476 my $list_tickets = list_tickets($p);
477 $return{'tickets'} = $list_tickets->{'tickets'};
479 if ( $session->{'pkgnum'} ) {
480 #XXX open invoices in the pkg-balances case
482 $return{'money_char'} = $conf->config("money_char") || '$';
485 invnum => $_->invnum,
486 date => time2str("%b %o, %Y", $_->_date),
488 charged => $_->charged,
490 } $cust_main->open_cust_bill;
491 $return{open_invoices} = \@open;
493 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
494 my $sth = dbh->prepare($sql) or die dbh->errstr;
495 $sth->execute($custnum) or die $sth->errstr;
496 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
497 $return{'last_invoice_date_pretty'} =
498 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
501 #customer_info_short always has nobalance on..
502 $return{small_custview} =
503 small_custview( $cust_main,
504 $return{countrydefault},
505 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
508 $return{has_ship_address} = $cust_main->has_ship_address;
509 $return{status} = $cust_main->status;
510 $return{statuscolor} = $cust_main->statuscolor;
512 # compatibility: some places in selfservice use this to determine
513 # if there's a ship address
514 if ( $return{has_ship_address} ) {
515 $return{ship_last} = $cust_main->last;
516 $return{ship_first} = $cust_main->first;
519 if (scalar($conf->config('support_packages'))) {
520 my @support_services = ();
521 foreach ($cust_main->support_services) {
522 my $seconds = $_->svc_x->seconds || 0;
523 my $time_remaining = (($seconds < 0) ? '-' : '' ).
524 int(abs($seconds)/3600)."h".
525 sprintf("%02d",(abs($seconds)%3600)/60)."m";
526 my $cust_pkg = $_->cust_pkg;
529 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
530 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
531 push @support_services, { svcnum => $_->svcnum,
532 time => $time_remaining,
537 $return{support_services} = \@support_services;
540 if ( $conf->config('prepayment_discounts-credit_type') ) {
542 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
545 } elsif ( $session->{'svcnum'} ) { #no customer record
547 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
548 or die "unknown svcnum";
549 $return{name} = $svc_acct->email;
553 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
557 return { 'error' => '',
558 'custnum' => $custnum,
564 sub customer_info_short {
567 my($context, $session, $custnum) = _custoragent_session_custnum($p);
568 return { 'error' => $session } if $context eq 'error';
572 my $conf = new FS::Conf;
574 if ( $custnum ) { #customer record
576 my $search = { 'custnum' => $custnum };
577 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
578 my $cust_main = qsearchs('cust_main', $search )
579 or return { 'error' => "unknown custnum $custnum" };
581 $return{display_custnum} = $cust_main->display_custnum;
583 if ( $session->{'pkgnum'} ) {
584 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
585 #next_bill_date from cust_pkg?
587 $return{balance} = $cust_main->balance;
588 $return{next_bill_date} = $cust_main->next_bill_date;
589 $return{next_bill_date_pretty} =
590 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
593 $return{balance_pretty} = money_pretty($return{balance});
595 $return{countrydefault} = scalar($conf->config('countrydefault'));
597 $return{small_custview} =
598 small_custview( $cust_main,
599 $return{countrydefault},
603 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
605 $return{payby} = $cust_main->payby;
607 #none of these are terribly expensive if we want 'em...
608 for (@cust_main_editable_fields) {
609 $return{$_} = $cust_main->get($_);
611 $return{$_} = $cust_main->masked($_) for qw/ss stateid/;
613 #maybe a little more expensive, but it should be cached by now
614 for (@location_editable_fields) {
615 $return{$_} = $cust_main->bill_location->get($_);
616 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
619 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
620 $return{payinfo} = $cust_main->paymask;
621 @return{'month', 'year'} = $cust_main->paydate_monthyear;
623 else { delete $return{'payinfo'}; }
625 my @invoicing_list = $cust_main->invoicing_list;
626 $return{'invoicing_list'} =
627 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
628 $return{'postal_invoicing'} =
629 0 < ( grep { $_ eq 'POST' } @invoicing_list );
631 if ( $session->{'svcnum'} ) {
632 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
633 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
634 $return{'svcnum'} = $session->{'svcnum'};
637 } elsif ( $session->{'svcnum'} ) { #no customer record
639 #uuh, not supproted yet... die?
640 return { 'error' => 'customer_info_short not yet supported as agent' };
644 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
648 # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
649 # it is not customer-specific, though it is only shown to authenticated customers
650 # it is not currently agent-specific, though at some point it might be
651 $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
653 return { 'error' => '',
654 'custnum' => $custnum,
659 sub customer_recurring {
662 my($context, $session, $custnum) = _custoragent_session_custnum($p);
663 return { 'error' => $session } if $context eq 'error';
667 my $conf = new FS::Conf;
669 my $search = { 'custnum' => $custnum };
670 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
671 my $cust_main = qsearchs('cust_main', $search )
672 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
674 $return{'display_recurring'} = [ $cust_main->display_recurring ];
676 return { 'error' => '',
677 'custnum' => $custnum,
682 sub billing_history {
685 my($context, $session, $custnum) = _custoragent_session_custnum($p);
686 return { 'error' => $session } if $context eq 'error';
688 return { 'error' => 'No customer' } unless $custnum;
690 my $search = { 'custnum' => $custnum };
691 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
692 my $cust_main = qsearchs('cust_main', $search )
693 or return { 'error' => "unknown custnum $custnum" };
697 if ( $session->{'pkgnum'} ) {
698 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
699 #next_bill_date from cust_pkg?
700 return { 'error' => 'No history for package' };
703 $return{balance} = $cust_main->balance;
704 $return{balance_pretty} = money_pretty($return{balance});
705 $return{next_bill_date} = $cust_main->next_bill_date;
706 $return{next_bill_date_pretty} =
707 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
710 my $conf = new FS::Conf;
712 $return{'history'} = [
713 $cust_main->payment_history(
714 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
719 $return{'money_char'} = $conf->config("money_char") || '$',
727 my $session = _cache->get($p->{'session_id'})
728 or return { 'error' => "Can't resume session" }; #better error message
730 my $custnum = $session->{'custnum'}
731 or return { 'error' => "no customer record" };
733 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
734 or return { 'error' => "unknown custnum $custnum" };
736 my $conf = new FS::Conf;
737 if (($p->{payby} eq "CHEK" || $p->{payby} eq "DCHK") && $conf->exists('selfservice-ACH_info_readonly')) {
738 return { 'error' => "You do not have authority to add a bank account" };
741 my $new = new FS::cust_main { $cust_main->hash };
743 $new->set( $_ => $p->{$_} )
744 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
746 if ( exists($p->{address1}) ) {
747 my $bill_location = FS::cust_location->new({
748 map { $_ => $p->{$_} } @location_editable_fields
750 # if this is unchanged from before, cust_main::replace will ignore it
751 $new->set('bill_location' => $bill_location);
754 if ( exists($p->{ship_address1}) ) {
755 my $ship_location = FS::cust_location->new({
756 map { $_ => $p->{"ship_$_"} } @location_editable_fields
758 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
759 # Selfservice unfortunately tries to indicate "same as billing
760 # address" by sending all fields empty. Did this ever work?
761 $ship_location = $cust_main->bill_location;
763 $new->set('ship_location' => $ship_location);
765 # but if it hasn't been passed in at all, leave ship_location alone--
766 # DON'T change it to match bill_location.
769 if (exists($p->{'payby'})) {
770 $p->{'payby'} =~ /^([A-Z]{4})$/
771 or return { 'error' => "illegal_payby " . $p->{'payby'} };
775 if ( $payby =~ /^(CARD|DCRD)$/ ) {
777 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
779 if ( $new->payinfo eq $cust_main->paymask ) {
780 $new->payinfo($cust_main->payinfo);
781 $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
783 $new->payinfo($p->{'payinfo'});
784 return { 'error' => 'CVV2 is required' }
785 if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
786 $new->paycvv( $p->{'paycvv'} )
789 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
791 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
794 $p->{'payinfo1'} =~ /^([\dx]+)$/
795 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
797 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
798 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
800 $payinfo = $payinfo1. '@'. $payinfo2;
802 $new->payinfo( ($payinfo eq $cust_main->paymask)
803 ? $cust_main->payinfo
807 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
809 } elsif ( $payby =~ /^(BILL)$/ ) {
811 } elsif ( $payby ) { #notyet ready
812 return { 'error' => "unknown payby $payby" };
816 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
817 #false laziness with httemplate/edit/process/cust_main.cgi
818 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
819 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
821 @invoicing_list = $cust_main->invoicing_list;
824 my $error = $new->replace($cust_main, \@invoicing_list);
825 return { 'error' => $error } if $error;
828 return { 'error' => '' };
833 my $session = _cache->get($p->{'session_id'})
834 or return { 'error' => "Can't resume session" }; #better error message
840 my $conf = new FS::Conf;
841 use vars qw($payment_info); #cache for performance
842 unless ( $payment_info ) {
844 my %states = map { $_->state => 1 }
845 qsearch('cust_main_county', {
846 'country' => $conf->config('countrydefault') || 'US'
849 my %cust_paybys = map { $_ => 1 }
850 map { FS::payby->payby2payment($_) }
851 $conf->config('signup_server-payby');
853 my @cust_paybys = keys %cust_paybys;
857 #list all counties/states/countries
858 'cust_main_county' =>
859 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
861 #shortcut for one-country folks
863 [ sort { $a cmp $b } keys %states ],
865 'card_types' => card_types(),
867 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
868 'require_cvv' => $conf->exists('selfservice-require_cvv'),
869 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
871 'paytypes' => [ @FS::cust_main::paytypes ],
873 'paybys' => [ $conf->config('signup_server-payby') ],
874 'cust_paybys' => \@cust_paybys,
876 'stateid_label' => FS::Msgcat::_gettext('stateid'),
877 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
879 'show_ss' => $conf->exists('show_ss'),
880 'show_stateid' => $conf->exists('show_stateid'),
881 'show_paystate' => $conf->exists('show_bankstate'),
883 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
884 'ach_read_only' => $conf->exists('selfservice-ACH_info_readonly'),
894 my %return = %$payment_info;
896 delete $return{'cust_main_county'} if $p->{'omit_cust_main_county'};
898 my $custnum = $session->{'custnum'};
900 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
901 or return { 'error' => "unknown custnum $custnum" };
903 $return{'hide_payment_fields'} = [
905 my $pg = payment_gateway($cust_main, $_);
906 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
907 } @{ $return{cust_paybys} }
910 $return{balance} = $cust_main->balance; #XXX pkg-balances?
912 $return{payname} = $cust_main->payname
913 || ( $cust_main->first. ' '. $cust_main->get('last') );
915 $return{$_} = $cust_main->bill_location->get($_)
916 for qw(address1 address2 city state zip);
918 $return{payby} = $cust_main->payby;
919 $return{stateid_state} = $cust_main->stateid_state;
921 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
922 $return{card_type} = cardtype($cust_main->payinfo);
923 $return{payinfo} = $cust_main->paymask;
925 @return{'month', 'year'} = $cust_main->paydate_monthyear;
929 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
930 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
931 $return{payinfo1} = $payinfo1;
932 $return{payinfo2} = $payinfo2;
933 $return{paytype} = $cust_main->paytype;
934 $return{paystate} = $cust_main->paystate;
935 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
938 if ( $conf->config('prepayment_discounts-credit_type') ) {
940 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
943 #doubleclick protection
945 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
946 $return{paybatch} = $return{payunique}; #back compat
948 $return{credit_card_surcharge_percentage} = $conf->config('credit-card-surcharge-percentage', $cust_main->agentnum);
949 $return{credit_card_surcharge_flatfee} = $conf->config('credit-card-surcharge-flatfee', $cust_main->agentnum);
951 return { 'error' => '',
957 #some false laziness with httemplate/process/payment.cgi - look there for
958 #ACH and CVV support stuff
960 sub validate_payment {
963 my $session = _cache->get($p->{'session_id'})
964 or return { 'error' => "Can't resume session" }; #better error message
966 my $custnum = $session->{'custnum'};
968 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
969 or return { 'error' => "unknown custnum $custnum" };
971 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
972 or return { 'error' => gettext('illegal_amount') };
974 return { error => 'Amount must be greater than 0' } unless $amount > 0;
976 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
977 #changing the hidden form values
978 my $conf = new FS::Conf;
979 my $fee_display = $conf->config('selfservice_process-display') || 'add';
980 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
981 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
982 if ( $fee_display eq 'add'
984 and ! $fee_skip_first || scalar($cust_main->cust_pay)
987 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
988 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
991 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
992 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
993 my $discount_term = $1;
995 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
996 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
999 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1000 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
1003 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1004 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
1007 $payunique = $paybatch if ! length($payunique) && length($paybatch);
1009 $p->{'payby'} ||= 'CARD';
1010 $p->{'payby'} =~ /^([A-Z]{4})$/
1011 or return { 'error' => "illegal_payby " . $p->{'payby'} };
1014 #false laziness w/process/payment.cgi
1017 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1019 $p->{'payinfo1'} =~ /^([\dx]+)$/
1020 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1022 $p->{'payinfo2'} =~ /^([\dx]+)$/
1023 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1025 $payinfo = $payinfo1. '@'. $payinfo2;
1028 if ( $cust_main->paymask eq $payinfo ) {
1029 $payinfo = $cust_main->payinfo;
1033 if ($conf->exists('selfservice-ACH_info_readonly') && !$achonfile) {
1034 return { 'error' => "You are not allowed to change your payment information." };
1037 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1039 $payinfo = $p->{'payinfo'};
1043 #more intelligent matching will be needed here if you change
1044 #card_masking_method and don't remove existing paymasks
1045 if ( $cust_main->paymask eq $payinfo ) {
1046 $payinfo = $cust_main->payinfo;
1050 $payinfo =~ s/\D//g;
1051 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1052 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1056 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1057 return { 'error' => gettext('unknown_card_type') }
1058 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1060 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1061 if ( cardtype($payinfo) eq 'American Express card' ) {
1062 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1063 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1066 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1067 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1070 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1071 return { 'error' => 'CVV2 is required' };
1072 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1073 return { 'error' => 'CVV2 is required' };
1077 die "unknown payby $payby";
1080 my %payby2fields = (
1081 'CARD' => [ qw( paystart_month paystart_year payissue payip
1082 address1 address2 city state zip country ) ],
1083 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1087 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1090 'cust_main' => $cust_main, #XXX or just custnum??
1091 'amount' => sprintf('%.2f', $amount),
1093 'payinfo' => $payinfo,
1094 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1095 'card_type' => $card_type,
1096 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1097 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1098 'month' => $p->{'month'},
1099 'year' => $p->{'year'},
1100 'payname' => $payname,
1101 'payunique' => $payunique,
1102 'paybatch' => $paybatch,
1103 'paycvv' => $paycvv,
1104 'payname' => $payname,
1105 'discount_term' => $discount_term,
1106 'pkgnum' => $session->{'pkgnum'},
1107 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1117 my $validate = validate_payment($p);
1118 return $validate if $validate->{'error'};
1120 my $conf = new FS::Conf;
1121 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1122 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1124 +{ map { $_=>$validate->{$_} }
1125 qw( card_type paymask payname paydate_pretty month year amount
1126 address1 address2 city state zip country
1132 sub process_stored_payment {
1135 my $session_id = $p->{'session_id'};
1137 my $payment_info = _cache->get( "payment_$session_id" )
1138 or return { 'error' => "Can't resume session" }; #better error message
1140 do_process_payment($payment_info);
1144 sub process_payment {
1147 my $payment_info = validate_payment($p);
1148 return $payment_info if $payment_info->{'error'};
1150 do_process_payment($payment_info);
1154 sub do_process_payment {
1155 my $validate = shift;
1157 my $cust_main = $validate->{'cust_main'};
1159 my $amount = delete $validate->{'amount'};
1162 my $payby = delete $validate->{'payby'};
1164 if ( $validate->{'save'} ) {
1165 my $new = new FS::cust_main { $cust_main->hash };
1166 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1167 $new->set( $_ => $validate->{$_} )
1168 foreach qw( payname paystart_month paystart_year payissue payip );
1169 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1171 my $bill_location = FS::cust_location->new({
1172 map { $_ => $validate->{$_} }
1173 qw(address1 address2 city state country zip)
1175 $new->set('bill_location' => $bill_location);
1176 # but don't allow the service address to change this way.
1178 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1179 $new->set( $_ => $validate->{$_} )
1180 foreach qw( payname payip paytype paystate
1181 stateid stateid_state );
1182 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1184 $new->payinfo( $validate->{'payinfo'} ); #to properly set paymask
1185 $new->set( 'paydate' => $validate->{'paydate'} );
1186 my $error = $new->replace($cust_main);
1188 #no, this causes customers to process their payments again
1189 #return { 'error' => $error };
1190 #XXX just warn verosely for now so i can figure out how these happen in
1191 # the first place, eventually should redirect them to the "change
1192 #address" page but indicate if the payment processed?
1193 delete($validate->{'payinfo'}); #don't want to log this!
1194 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1195 "NEW: ". Dumper($new)."\n".
1196 "OLD: ". Dumper($cust_main)."\n".
1197 "PACKET: ". Dumper($validate)."\n";
1203 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1207 'paynum_ref' => \$paynum,
1210 return { 'error' => $error } if $error;
1212 #no error, so order the fee package if applicable...
1213 my $conf = new FS::Conf;
1214 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1215 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1217 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1219 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1221 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1222 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1225 #and generate an invoice for it now too
1226 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1227 return { 'error' => "payment processed and fee ordered successfully, but error billing fee: $error" }
1232 $cust_main->apply_payments;
1235 my $receipt_html = '';
1237 # currently supported for realtime CC only; send receipt data to SS
1238 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1241 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1244 <TD ALIGN="right">Payment#</TD>
1245 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1249 <TD ALIGN="right">Date</TD>
1251 <TD BGCOLOR="#FFFFFF"><B>! .
1252 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1258 <TD ALIGN="right">Amount</TD>
1259 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1264 <TD ALIGN="right">Payment method</TD>
1265 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1278 'amount' => sprintf('%.2f', $cust_pay->paid),
1279 'date' => $cust_pay->_date,
1280 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1281 'time_pretty' => time2str('%T', $cust_pay->_date),
1282 'auth_num' => $cust_pay->auth,
1283 'order_num' => $cust_pay->order_number,
1284 'receipt_html' => $receipt_html,
1291 'receipt_html' => '',
1298 sub realtime_collect {
1301 my $session = _cache->get($p->{'session_id'})
1302 or return { 'error' => "Can't resume session" }; #better error message
1304 my $custnum = $session->{'custnum'};
1306 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1307 or return { 'error' => "unknown custnum $custnum" };
1310 if ( $p->{'amount'} ) {
1311 $amount = $p->{'amount'};
1313 elsif ( $session->{'pkgnum'} ) {
1314 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1317 $amount = $cust_main->balance;
1320 my $error = $cust_main->realtime_collect(
1321 'method' => $p->{'method'},
1322 'amount' => $amount,
1323 'pkgnum' => $session->{'pkgnum'},
1324 'session_id' => $p->{'session_id'},
1328 return { 'error' => $error } unless ref( $error );
1330 return { 'error' => '', amount => $amount, %$error };
1333 sub start_thirdparty {
1335 my $session = _cache->get($p->{'session_id'})
1336 or return { 'error' => "Can't resume session" }; #better error message
1337 my $custnum = $session->{'custnum'};
1338 my $cust_main = FS::cust_main->by_key($custnum);
1340 my $amount = $p->{'amount'}
1341 or return { error => 'no amount' };
1343 my $result = $cust_main->create_payment(
1344 'method' => $p->{'method'},
1345 'amount' => $p->{'amount'},
1346 'pkgnum' => $session->{'pkgnum'},
1347 'session_id' => $p->{'session_id'},
1350 if ( ref($result) ) { # hashref or error
1353 return { error => $result };
1357 sub finish_thirdparty {
1359 my $session_id = delete $p->{'session_id'};
1360 my $session = _cache->get($session_id)
1361 or return { 'error' => "Can't resume session" };
1362 my $custnum = $session->{'custnum'};
1363 my $cust_main = FS::cust_main->by_key($custnum);
1365 if ( $p->{_cancel} ) {
1366 # customer backed out of making a payment
1367 return $cust_main->cancel_payment( $session_id );
1369 my $result = $cust_main->execute_payment( $session_id, %$p );
1370 if ( ref($result) ) {
1373 return { error => $result };
1377 sub process_payment_order_pkg {
1380 my $hr = process_payment($p);
1381 return $hr if $hr->{'error'};
1386 sub process_payment_order_renew {
1389 my $hr = process_payment($p);
1390 return $hr if $hr->{'error'};
1395 sub process_prepay {
1399 my $session = _cache->get($p->{'session_id'})
1400 or return { 'error' => "Can't resume session" }; #better error message
1404 my $custnum = $session->{'custnum'};
1406 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1407 or return { 'error' => "unknown custnum $custnum" };
1409 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1410 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1418 return { 'error' => $error } if $error;
1420 return { 'error' => '',
1421 'amount' => $amount,
1422 'seconds' => $seconds,
1423 'duration' => duration_exact($seconds),
1424 'upbytes' => $upbytes,
1425 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1426 'downbytes' => $downbytes,
1427 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1428 'totalbytes'=> $totalbytes,
1429 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1436 my $session = _cache->get($p->{'session_id'})
1437 or return { 'error' => "Can't resume session" }; #better error message
1439 my $custnum = $session->{'custnum'};
1441 my $invnum = $p->{'invnum'};
1443 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1444 'custnum' => $custnum } )
1445 or return { 'error' => "Can't find invnum" };
1449 return { 'error' => '',
1450 'invnum' => $invnum,
1451 'invoice_text' => join('', $cust_bill->print_text ),
1452 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1459 my $session = _cache->get($p->{'session_id'})
1460 or return { 'error' => "Can't resume session" }; #better error message
1462 my $custnum = $session->{'custnum'};
1464 my $invnum = $p->{'invnum'};
1466 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1467 'custnum' => $custnum } )
1468 or return { 'error' => "Can't find invnum" };
1472 return { 'error' => '',
1473 'invnum' => $invnum,
1474 'invoice_pdf' => $cust_bill->print_pdf({
1475 'unsquelch_cdr' => 1,
1476 'locale' => $p->{'locale'},
1482 sub legacy_invoice {
1484 my $session = _cache->get($p->{'session_id'})
1485 or return { 'error' => "Can't resume session" }; #better error message
1487 my $custnum = $session->{'custnum'};
1489 my $legacyinvnum = $p->{'legacyinvnum'};
1492 'legacyinvnum' => $legacyinvnum,
1493 'custnum' => $custnum,
1496 my $legacy_cust_bill =
1497 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1498 || qsearchs('legacy_cust_bill', \%hash )
1499 or return { 'error' => "Can't find legacyinvnum" };
1503 return { 'error' => '',
1504 'legacyinvnum' => $legacyinvnum,
1505 'legacyid' => $legacy_cust_bill->legacyid,
1506 'invoice_html' => $legacy_cust_bill->content_html,
1511 sub legacy_invoice_pdf {
1513 my $session = _cache->get($p->{'session_id'})
1514 or return { 'error' => "Can't resume session" }; #better error message
1516 my $custnum = $session->{'custnum'};
1518 my $legacyinvnum = $p->{'legacyinvnum'};
1520 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1521 'legacyinvnum' => $legacyinvnum,
1522 'custnum' => $custnum,
1523 }) or return { 'error' => "Can't find legacyinvnum" };
1527 return { 'error' => '',
1528 'legacyinvnum' => $legacyinvnum,
1529 'legacyid' => $legacy_cust_bill->legacyid,
1530 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1538 #sessioning for this? how do we get the session id to the backend invoice
1539 # template so it can add it to the link, blah
1542 if ( $p->{'invnum'} ) {
1543 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1544 or return { 'error' => 'unknown invnum' };
1545 $agentnum = $cust_bill->cust_main->agentnum;
1548 my $templatename = $p->{'template'} || $p->{'templatename'};
1550 #false laziness-ish w/view/cust_bill-logo.cgi
1552 my $conf = new FS::Conf;
1553 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1554 $templatename = "_$1";
1559 my $filename = "logo$templatename.png";
1561 return { 'error' => '',
1562 'logo' => $conf->config_binary($filename, $agentnum),
1563 'content_type' => 'image/png', #should allow gif, jpg too
1570 my $session = _cache->get($p->{'session_id'})
1571 or return { 'error' => "Can't resume session" }; #better error message
1573 my $custnum = $session->{'custnum'};
1575 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1576 or return { 'error' => "unknown custnum $custnum" };
1578 my $conf = new FS::Conf;
1580 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1582 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1587 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1588 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1589 my $owed = $_->owed;
1591 +{ 'invnum' => $_->invnum,
1592 '_date' => $_->_date,
1593 'date' => time2str("%b %o, %Y", $_->_date),
1594 'date_short' => time2str("%m-%d-%Y", $_->_date),
1595 'previous' => sprintf('%.2f', ($_->previous)[0]),
1596 'charged' => sprintf('%.2f', $_->charged),
1597 'owed' => sprintf('%.2f', $owed),
1598 'balance' => sprintf('%.2f', $balance),
1599 'lastpay' => @payments_and_credits
1600 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1606 return { 'error' => '',
1607 'balance' => $cust_main->balance,
1608 'money_char' => $conf->config("money_char") || '$',
1609 'invoices' => $invoices,
1610 'legacy_invoices' => [
1612 +{ 'legacyinvnum' => $_->legacyinvnum,
1613 'legacyid' => $_->legacyid,
1614 '_date' => $_->_date,
1615 'date' => time2str("%b %o, %Y", $_->_date),
1616 'date_short' => time2str("%m-%d-%Y", $_->_date),
1617 'charged' => sprintf('%.2f', $_->charged),
1618 'has_content' => ( length($_->content_pdf)
1619 || length($_->content_html) ),
1629 my $session = _cache->get($p->{'session_id'})
1630 or return { 'error' => "Can't resume session" }; #better error message
1632 my $custnum = $session->{'custnum'};
1634 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1635 or return { 'error' => "unknown custnum $custnum" };
1637 return { 'error' => '',
1638 'balance' => $cust_main->balance,
1639 'money_char' => FS::Conf->new->config("money_char") || '$',
1640 'payments' => [ map $_->SSAPI_getinfo, $cust_main->cust_pay ],
1644 sub payment_receipt {
1646 my $session = _cache->get($p->{'session_id'})
1647 or return { 'error' => "Can't resume session" }; #better error message
1649 my $custnum = $session->{'custnum'};
1651 my $cust_pay = qsearchs('cust_pay', { 'custnum' => $custnum,
1652 'paynum' => $p->{'paynum'},
1655 or return { 'error' => "unknown payment ". $p->{'paynum'} };
1659 %{ $cust_pay->SSAPI_getinfo },
1665 my $session = _cache->get($p->{'session_id'})
1666 or return { 'error' => "Can't resume session" }; #better error message
1668 my $custnum = $session->{'custnum'};
1670 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1671 or return { 'error' => "unknown custnum $custnum" };
1673 my @errors = $cust_main->cancel( 'quiet'=>1 );
1675 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1677 return { 'error' => $error };
1684 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1685 return { 'error' => $session } if $context eq 'error';
1687 my $pkg = qsearchs({
1688 'table' => 'cust_pkg',
1689 'addl_from' => 'LEFT JOIN part_pkg USING ( pkgpart )',
1691 'custnum' => $custnum,
1692 'pkgnum' => $p->{'pkgnum'},
1695 or return {'error' => 'unknown pkg num $pkgnum'};
1698 pkg_label => $pkg->pkg,
1699 pkgpart => $pkg->pkgpart,
1700 classnum => $pkg->classnum,
1708 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1709 return { 'error' => $session } if $context eq 'error';
1711 my $search = { 'custnum' => $custnum };
1712 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1713 my $cust_main = qsearchs('cust_main', $search )
1714 or return { 'error' => "unknown custnum $custnum" };
1716 my $conf = new FS::Conf;
1717 my $immutable = $conf->exists('selfservice_immutable-package');
1719 # the duplication below is necessary:
1720 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1721 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1722 # non-backwards-compatible change breaking the software of anyone using the API
1723 # instead of the stock selfservice
1724 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1725 if( $conf->exists('selfservice_server-view-wholesale') ) {
1726 return { 'svcnum' => $session->{'svcnum'},
1727 'custnum' => $custnum,
1728 'cust_pkg' => [ map {
1730 immutable => $immutable,
1731 part_pkg => [ map $_->hashref, $_->part_pkg ],
1733 [ map $_->hashref, $_->available_part_svc ],
1735 [ map { my $ref = { $_->hash,
1736 label => [ $_->label ],
1738 $ref->{_password} = $_->svc_x->_password
1739 if $context eq 'agent'
1740 && $conf->exists('agent-showpasswords')
1741 && $_->part_svc->svcdb eq 'svc_acct';
1746 } $cust_main->cust_pkg
1749 small_custview( $cust_main, $conf->config('countrydefault') ),
1750 'wholesale_view' => 1,
1751 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1752 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1753 'lnp' => $conf->exists('svc_phone-lnp'),
1757 { 'svcnum' => $session->{'svcnum'},
1758 'custnum' => $custnum,
1759 'cust_pkg' => [ map {
1760 my $primary_cust_svc = $_->primary_cust_svc;
1763 immutable => $immutable,
1764 pkg_label => $_->pkg_locale,
1765 status => $_->status,
1766 statuscolor => $_->statuscolor,
1768 [ map { $_->hashref }
1769 grep { $_->selfservice_access ne 'hidden' }
1770 $_->available_part_svc
1773 [ map { my $ref = { $_->hash,
1774 label => [ $_->label ],
1776 $ref->{_password} = $_->svc_x->_password
1777 if $context eq 'agent'
1778 && $conf->exists('agent-showpasswords')
1779 && $_->part_svc->svcdb eq 'svc_acct';
1780 $ref->{svchash} = { $_->svc_x->hash } if
1781 $_->part_svc->svcdb eq 'svc_phone';
1782 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1783 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1786 grep { $_->part_svc->selfservice_access ne 'hidden' }
1791 ? { $primary_cust_svc->hash,
1792 label => [ $primary_cust_svc->label ],
1793 finger => $primary_cust_svc->svc_x->finger, #uuh
1794 $primary_cust_svc->part_svc->hash,
1798 } $cust_main->ncancelled_pkgs
1801 small_custview( $cust_main, $conf->config('countrydefault') ),
1802 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1810 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1811 return { 'error' => $session } if $context eq 'error';
1813 my $conf = new FS::Conf;
1815 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1816 my $search = { 'custnum' => $custnum };
1817 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1818 my $cust_main = qsearchs('cust_main', $search )
1819 or return { 'error' => "unknown custnum $custnum" };
1821 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1822 if ( ! $pkgnum && $p->{'svcnum'} ) {
1823 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1824 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1828 my @cust_pkg_usage = ();
1829 foreach my $cust_pkg ( $p->{'ncancelled'}
1830 ? $cust_main->ncancelled_pkgs
1831 : $cust_main->unsuspended_pkgs ) {
1832 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1833 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1834 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1837 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1840 foreach (@cust_pkg_usage) {
1841 my $part = $_->part_pkg_usage;
1842 my $tag = $part->description . ($part->shared ? 1 : 0);
1843 my $row = $usage_pools{$tag}
1844 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1845 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1846 $row->[2] += $part->minutes; # minutes total
1848 } # otherwise just leave them empty
1850 if ( $p->{'svcdb'} ) {
1851 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1853 : ref($p->{'svcdb'}) eq 'ARRAY'
1854 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1855 : { $p->{'svcdb'} => 1 };
1856 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1859 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1862 my @svcs; # stuff to return to the client
1863 my %bytes_used_total; # for _used columns only
1864 foreach my $cust_svc (@cust_svc) {
1865 my $svc_x = $cust_svc->svc_x;
1866 my($label, $value) = $cust_svc->label;
1867 my $part_svc = $cust_svc->part_svc;
1868 my $svcdb = $part_svc->svcdb;
1869 my $cust_pkg = $cust_svc->cust_pkg;
1870 my $part_pkg = $cust_pkg->part_pkg;
1873 'svcnum' => $cust_svc->svcnum,
1874 'display_svcnum' => $cust_svc->display_svcnum,
1878 'pkg_label' => $cust_pkg->pkg_locale,
1879 'pkg_status' => $cust_pkg->status,
1880 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1883 # would it make sense to put this in a svc_* method?
1885 if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
1886 my $last_bill = $cust_pkg->last_bill || 0;
1888 my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
1889 my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
1892 'seconds_used' => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
1893 'upbytes_used' => display_bytecount($up_used),
1894 'downbytes_used' => display_bytecount($down_used),
1895 'totalbytes_used' => display_bytecount($up_used + $down_used)
1897 $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
1898 $bytes_used_total{'upbytes_used'} += $up_used;
1899 $bytes_used_total{'downbytes_used'} += $down_used;
1900 $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
1903 if ( $svcdb eq 'svc_acct' ) {
1904 foreach (qw(username email finger seconds)) {
1905 $hash{$_} = $svc_x->$_;
1911 'upbytes' => display_bytecount($svc_x->upbytes),
1912 'downbytes' => display_bytecount($svc_x->downbytes),
1913 'totalbytes' => display_bytecount($svc_x->totalbytes),
1915 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1916 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1917 'recharge_upbytes' =>
1918 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1919 'recharge_downbytes' =>
1920 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1921 'recharge_totalbytes' =>
1922 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1927 } elsif ( $svcdb eq 'svc_dsl' ) {
1929 $hash{'phonenum'} = $svc_x->phonenum;
1930 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1931 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1932 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1935 $hash{'name'} = $cust_main->name;
1937 # no usage to hide here
1939 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1941 # could potentially show lots of things...
1942 $hash{'outbound'} = 1;
1943 $hash{'inbound'} = 0;
1944 if ( $svcdb eq 'svc_phone' ) {
1945 if ( $part_pkg->plan eq 'voip_inbound' ) {
1946 $hash{'outbound'} = 0;
1947 $hash{'inbound'} = 1;
1948 } elsif ( $part_pkg->option('selfservice_inbound_format')
1949 or $conf->config('selfservice-default_inbound_cdr_format')
1951 $hash{'inbound'} = 1;
1954 foreach (qw(inbound outbound)) {
1955 # hmm...we can't filter by status here, because there might
1956 # not be cdr_terminations at all. have to go by date.
1957 # find all since the last bill date.
1958 # XXX cdr types? we are going to need them.
1960 my $sum_cdr = $svc_x->sum_cdrs(
1961 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1962 'begin' => ($cust_pkg->last_bill || 0),
1964 'disable_charged_party' => 1,
1966 $hash{$_} = $sum_cdr->hashref;
1969 } # not hiding usage
1973 } # foreach $cust_svc
1975 foreach my $field (keys %bytes_used_total) {
1976 if ($field =~ /bytes/) {
1977 $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
1982 'svcnum' => $session->{'svcnum'},
1983 'custnum' => $custnum,
1984 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1985 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1987 'bytes_used_total' => \%bytes_used_total,
1989 map { $usage_pools{$_} }
1993 'hide_usage' => $hide_usage,
1998 sub _customer_svc_x {
1999 my($custnum, $svcnum, $table) = (shift, shift, shift);
2000 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
2002 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2003 my $search = " AND custnum = $1";
2004 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2007 'table' => ($table || 'svc_acct'),
2008 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2009 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
2010 #'LEFT JOIN cust_main USING ( custnum ) ',
2011 'hashref' => $hashref,
2012 'extra_sql' => $search, #important
2017 sub svc_status_html {
2020 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2021 return { 'error' => $session } if $context eq 'error';
2023 #XXX only svc_dsl for now
2024 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2025 or return { 'error' => "Service not found" };
2027 my $html = $svc_x->getstatus_html;
2029 return { 'html' => $html };
2033 sub svc_status_hash {
2036 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2037 return { 'error' => $session } if $context eq 'error';
2039 #XXX only svc_acct for now
2040 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2041 or return { 'error' => "Service not found" };
2043 my ( $html, $hashref ) = $svc_x->export_getstatus;
2048 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
2049 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2050 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2051 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2052 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2055 my( $p, $method ) = @_;
2057 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2058 return { 'error' => $session } if $context eq 'error';
2060 #XXX only svc_acct for now
2061 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2062 or return { 'error' => "Service not found" };
2064 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2066 my $error = $svc_x->$method($p); #$p? returns error?
2067 return { 'error' => $error } if $error;
2069 return {}; #? { 'error' => '' }
2073 sub acct_forward_info {
2076 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2077 return { 'error' => $session } if $context eq 'error';
2079 my $svc_forward = _customer_svc_x( $custnum,
2080 { 'srcsvc' => $p->{'svcnum'} },
2083 or return { 'error' => '',
2087 return { 'error' => '',
2088 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2093 sub process_acct_forward {
2095 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2096 return { 'error' => $session } if $context eq 'error';
2098 my $old = _customer_svc_x( $custnum,
2099 { 'srcsvc' => $p->{'svcnum'} },
2103 if ( $p->{'dst'} eq '' ) {
2105 my $error = $old->delete;
2106 return { 'error' => $error };
2108 return { 'error' => '' };
2111 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2112 'dst' => $p->{'dst'},
2117 $new->svcnum($old->svcnum);
2118 my $cust_svc = $old->cust_svc;
2119 $new->svcpart($old->svcpart);
2120 $new->pkgnuym($old->pkgnum);
2121 $error = $new->replace($old);
2123 my $conf = new FS::Conf;
2124 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2126 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2127 or return { 'error' => 'No service' }; #how would we even get here?
2129 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2131 $error = $new->insert;
2134 return { 'error' => $error };
2138 sub list_dsl_devices {
2141 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2142 return { 'error' => $session } if $context eq 'error';
2144 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2145 or return { 'error' => "Service not found" };
2148 'devices' => [ map {
2149 +{ 'mac_addr' => $_->mac_addr };
2150 } $svc_dsl->dsl_device
2156 sub add_dsl_device {
2159 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2160 return { 'error' => $session } if $context eq 'error';
2162 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2163 or return { 'error' => "Service not found" };
2165 return { 'error' => 'No MAC address supplied' }
2166 unless length($p->{'mac_addr'});
2168 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2169 'mac_addr' => scalar($p->{'mac_addr'}),
2171 my $error = $dsl_device->insert;
2172 return { 'error' => $error };
2176 sub delete_dsl_device {
2179 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2180 return { 'error' => $session } if $context eq 'error';
2182 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2183 or return { 'error' => "Service not found" };
2185 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2186 'mac_addr' => scalar($p->{'mac_addr'}),
2189 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2191 my $error = $dsl_device->delete;
2192 return { 'error' => $error };
2198 _usage_details( \&_port_graph, $p,
2199 'svcdb' => 'svc_port',
2204 my($svc_port, $begin, $end) = @_;
2206 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2207 push @usage, { 'png' => $pngOrError };
2211 sub _list_svc_usage {
2212 my($svc_acct, $begin, $end) = @_;
2214 foreach my $part_export (
2215 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2216 qw( sqlradius sqlradius_withdomain )
2218 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2223 sub list_svc_usage {
2224 _usage_details(\&_list_svc_usage, @_);
2227 sub _list_support_usage {
2228 my($svc_acct, $begin, $end) = @_;
2230 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2231 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2233 push @usage, { 'seconds' => $_->seconds,
2234 'support' => $_->support,
2235 '_date' => $_->_date,
2236 'id' => $_->transaction_id,
2237 'creator' => $_->creator,
2238 'subject' => $_->subject,
2239 'status' => $_->status,
2240 'ticketid' => $_->ticketid,
2246 sub list_support_usage {
2247 _usage_details(\&_list_support_usage, @_);
2250 sub _list_cdr_usage {
2251 # XXX CDR type support...
2252 # XXX any way to do a paged search on this?
2253 # we have to return the results all at once...
2254 my($svc_x, $begin, $end, %opt) = @_;
2255 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2259 'disable_charged_party' => 1,
2264 sub list_cdr_usage {
2266 _usage_details( \&_list_cdr_usage, $p );
2269 sub _usage_details {
2270 my($callback, $p, %opt) = @_;
2271 my $conf = FS::Conf->new;
2273 if ( $conf->exists('selfservice_hide-usage') ) {
2274 return { 'error' => 'Viewing usage is not allowed.' };
2277 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2278 return { 'error' => $session } if $context eq 'error';
2280 my $search = { 'svcnum' => $p->{'svcnum'} };
2281 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2283 my $cust_svc = qsearchs( 'cust_svc', $search );
2284 return { 'error' => 'No service selected in list_svc_usage' }
2287 my $svc_x = $cust_svc->svc_x;
2288 my $svcdb = $svc_x->table;
2289 my $cust_pkg = $cust_svc->cust_pkg;
2290 my $freq = $cust_pkg->part_pkg->freq;
2293 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2295 if ( $p->{inbound} ) {
2296 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2297 || $conf->config('selfservice-default_inbound_cdr_format')
2298 || 'source_default';
2299 $callback_opt{inbound} = 1;
2301 $format = $cust_pkg->part_pkg->option('selfservice_format')
2302 || $conf->config('selfservice-default_cdr_format')
2306 $callback_opt{format} = $format;
2307 $callback_opt{use_clid} = 1;
2308 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2311 my $start = $cust_pkg->setup;
2312 #my $end = $cust_pkg->bill; # or time?
2315 unless ( $p->{beginning} ) {
2316 $p->{beginning} = $cust_pkg->last_bill;
2317 $p->{ending} = $end;
2320 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2321 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2323 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2327 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2328 # ugly kludge, I know
2329 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2330 if (defined $delete_col) {
2331 delete($_->[$delete_col]) foreach ($header, @usage);
2335 #kinda false laziness with FS::cust_main::bill, but perhaps
2336 #we should really change this bit to DateTime and DateTime::Duration
2338 #change this bit to use Date::Manip? CAREFUL with timezones (see
2339 # mailing list archive)
2340 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2341 (localtime($p->{ending}) )[0,1,2,3,4,5];
2342 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2343 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2345 if ( $freq =~ /^\d+$/ ) {
2347 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2349 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2350 } elsif ( $freq =~ /^(\d+)w$/ ) {
2352 $nmday += $weeks * 7;
2353 $pmday -= $weeks * 7;
2354 } elsif ( $freq =~ /^(\d+)d$/ ) {
2358 } elsif ( $freq =~ /^(\d+)h$/ ) {
2363 return { 'error' => "unparsable frequency: ". $freq };
2366 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2367 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2371 'svcnum' => $p->{svcnum},
2372 'beginning' => $p->{beginning},
2373 'ending' => $p->{ending},
2374 'inbound' => $p->{inbound},
2375 'previous' => ($previous > $start) ? $previous : $start,
2376 'next' => ($next < $end) ? $next : $end,
2377 'header' => $header,
2385 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2386 return { 'error' => $session } if $context eq 'error';
2388 my $search = { 'custnum' => $custnum };
2389 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2390 my $cust_main = qsearchs('cust_main', $search )
2391 or return { 'error' => "unknown custnum $custnum" };
2393 my $status = $cust_main->status;
2395 my %order_pkg_options = ();
2396 if ( $p->{locationnum} > 0 ) {
2397 $order_pkg_options{locationnum} = delete($p->{locationnum});
2398 } elsif ( $p->{address1} ) {
2399 $order_pkg_options{'cust_location'} = new FS::cust_location {
2400 map { $_ => $p->{$_} }
2401 qw( address1 address2 city county state zip country )
2405 #false laziness w/ClientAPI/Signup.pm
2407 my $cust_pkg = new FS::cust_pkg ( {
2408 'custnum' => $custnum,
2409 'pkgpart' => $p->{'pkgpart'},
2410 'quantity' => $p->{'quantity'} || 1,
2412 my $error = $cust_pkg->check;
2413 return { 'error' => $error } if $error;
2416 unless ( $p->{'svcpart'} eq 'none' ) {
2420 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2422 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2423 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2424 $svcdb = $part_svc->svcdb;
2426 $svcdb = 'svc_acct';
2428 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2431 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2432 'svc_domain' => [ qw( domain ) ],
2433 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2434 'svc_external' => [ qw( id title ) ],
2435 'svc_pbx' => [ qw( id title ) ],
2438 my $svc_x = "FS::$svcdb"->new( {
2439 'svcpart' => $svcpart,
2440 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2443 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2446 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2447 my $acct_snarf = new FS::acct_snarf ( {
2448 'machine' => $p->{"snarf_machine$snarfnum"},
2449 'protocol' => $p->{"snarf_protocol$snarfnum"},
2450 'username' => $p->{"snarf_username$snarfnum"},
2451 '_password' => $p->{"snarf_password$snarfnum"},
2454 push @acct_snarf, $acct_snarf;
2456 $svc_x->child_objects( \@acct_snarf );
2459 my $y = $svc_x->setdefault; # arguably should be in new method
2460 return { 'error' => $y } if $y && !ref($y);
2462 $error = $svc_x->check;
2463 return { 'error' => $error } if $error;
2469 $error = $cust_main->order_pkg(
2470 'cust_pkg' => $cust_pkg,
2475 return { 'error' => $error } if $error;
2477 my $conf = new FS::Conf;
2478 if ( $conf->exists('signup_server-realtime') ) {
2480 my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2483 $cust_pkg->cancel('quiet'=>1);
2486 $cust_pkg->reexport;
2490 $cust_pkg->reexport;
2493 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2495 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2502 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2503 return { 'error' => $session } if $context eq 'error';
2505 my $conf = new FS::Conf;
2506 my $immutable = $conf->exists('selfservice_immutable-package');
2507 return { 'error' => "Package modification disabled" } if $immutable;
2509 my $search = { 'custnum' => $custnum };
2510 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2511 my $cust_main = qsearchs('cust_main', $search )
2512 or return { 'error' => "unknown custnum $custnum" };
2514 my $status = $cust_main->status;
2515 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2516 or return { 'error' => "unknown package $p->{pkgnum}" };
2518 #if someone does need self-service package change of suspended packages,
2519 # figure out how to be more discriminating
2520 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2521 if $cust_pkg->status eq 'suspended';
2523 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2524 'quantity' => $p->{'quantity'} || 1,
2527 my $new_pkg = qsearchs('part_pkg', { 'pkgpart' => $p->{pkgpart} } )
2528 or return { 'error' => "unknown package $p->{pkgpart}" };
2530 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2531 unless ref($err_or_cust_pkg);
2534 if ( $conf->exists('signup_server-realtime') ) {
2536 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2539 $err_or_cust_pkg->suspend;
2542 $err_or_cust_pkg->reexport;
2546 $err_or_cust_pkg->reexport;
2549 return { error => '', pkg => $new_pkg->pkg, pkgnum => $err_or_cust_pkg->pkgnum };
2553 sub order_recharge {
2556 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2557 return { 'error' => $session } if $context eq 'error';
2559 my $search = { 'custnum' => $custnum };
2560 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2561 my $cust_main = qsearchs('cust_main', $search )
2562 or return { 'error' => "unknown custnum $custnum" };
2564 my $status = $cust_main->status;
2565 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2566 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2568 my $svc_x = $cust_svc->svc_x;
2569 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2572 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2573 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2574 recharge_totalbytes );
2575 my $amount = $part_pkg->option('recharge_amount', 1);
2577 my ($l, $v, $d) = $cust_svc->label; # blah
2578 my $pkg = "Recharge $v";
2580 my $bill_error = $cust_main->charge($amount, $pkg,
2581 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2582 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2583 $part_pkg->taxclass); #meh
2585 my $conf = new FS::Conf;
2586 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2588 $bill_error = _do_bop_realtime( $cust_main, $status );
2593 my $error = $svc_x->recharge (\%vhash);
2594 return { 'error' => $error } if $error;
2598 my $error = $bill_error;
2599 $error ||= $svc_x->recharge (\%vhash);
2600 return { 'error' => $error } if $error;
2603 return { error => '', svc => $cust_svc->part_svc->svc };
2607 sub _do_bop_realtime {
2608 my ($cust_main, $status, %opt) = @_;
2610 my $old_balance = $cust_main->balance;
2613 my $bill_error = $cust_main->bill(
2614 'return_bill' => \@cust_bill,
2617 $bill_error ||= $cust_main->apply_payments_and_credits;
2619 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2620 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2622 if ( $cust_main->balance > $old_balance
2623 && $cust_main->balance > 0
2624 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2625 || $status eq 'suspended'
2629 unless ( $opt{'no_invoice_void'} ) {
2631 #this used to apply a credit, but now we can void invoices...
2632 foreach my $cust_bill (@cust_bill) {
2633 my $voiderror = $cust_bill->void('automatic payment failed');
2634 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2639 return { 'error' => '_decline', 'bill_error' => $bill_error };
2642 if ( $opt{'collect'} ) {
2643 my $collect_error = $cust_main->collect();
2644 return { 'error' => '_decline', 'bill_error' => $collect_error }
2645 if $collect_error; #?
2654 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2655 return { 'error' => $session } if $context eq 'error';
2657 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2658 or return { 'error' => "unknown custnum $custnum" };
2660 my @cust_pkg = sort { $a->bill <=> $b->bill }
2661 grep { $_->part_pkg->freq ne '0' }
2662 $cust_main->ncancelled_pkgs;
2664 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2666 my $total = $cust_main->balance;
2669 my $bill = $_->bill;
2670 $total += $_->part_pkg->base_recur($_, \$bill);
2671 my $renew_date = $_->part_pkg->add_freq($_->bill);
2673 'pkgnum' => $_->pkgnum,
2674 'amount' => sprintf('%.2f', $total),
2675 'bill_date' => $_->bill,
2676 'bill_date_pretty' => time2str('%x', $_->bill),
2677 'renew_date' => $renew_date,
2678 'renew_date_pretty' => time2str('%x', $renew_date),
2679 'expire_date' => $_->expire,
2680 'expire_date_pretty' => time2str('%x', $_->expire),
2685 return { 'dates' => \@array };
2689 sub payment_info_renew_info {
2691 my $renew_info = renew_info($p);
2692 my $payment_info = payment_info($p);
2693 return { %$renew_info,
2701 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2702 return { 'error' => $session } if $context eq 'error';
2704 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2705 or return { 'error' => "unknown custnum $custnum" };
2707 my $date = $p->{'date'};
2711 #freeside-daily -n -d $date fs_daily $custnum
2712 $cust_main->bill_and_collect( 'time' => $date,
2713 'invoice_time' => $now,
2714 'actual_time' => $now,
2715 'check_freq' => '1d',
2718 return { 'error' => '' };
2724 my $session = _cache->get($p->{'session_id'})
2725 or return { 'error' => "Can't resume session" }; #better error message
2727 my $custnum = $session->{'custnum'};
2729 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2730 or return { 'error' => "unknown custnum $custnum" };
2732 my $conf = new FS::Conf;
2734 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2735 or return { 'error' => 'Permission denied' };
2737 my $pkgnum = $p->{'pkgnum'};
2739 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2740 'pkgnum' => $pkgnum, } )
2741 or return { 'error' => "unknown pkgnum $pkgnum" };
2743 my $error = $cust_pkg->suspend(reason => $reasonnum);
2744 return { 'error' => $error };
2750 my $session = _cache->get($p->{'session_id'})
2751 or return { 'error' => "Can't resume session" }; #better error message
2753 my $custnum = $session->{'custnum'};
2754 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2755 or return { 'error' => "unknown custnum $custnum" };
2757 my $pkgnum = $p->{'pkgnum'};
2758 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2759 'pkgnum' => $pkgnum, } )
2760 or return { 'error' => "unknown pkgnum $pkgnum" };
2762 my $error = $cust_pkg->cancel( 'quiet' => 1,
2763 'date' => $p->{'date'},
2765 return { 'error' => $error };
2768 sub provision_phone {
2771 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2773 #editing an existing phone number
2774 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2775 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2776 return { 'error' => $session } if $context eq 'error';
2778 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2779 return { 'error' => 'service not found' } unless $svc_phone;
2780 return { 'error' => 'invalid svcnum' }
2781 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2783 $svc_phone->email($p->{'email'})
2784 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2785 $svc_phone->forwarddst($p->{'forwarddst'})
2786 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2787 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2788 return { 'error' => $svc_phone->replace };
2792 unless ( $p->{'lnp'} ) {
2793 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2794 $p->{'lnp_status'} = "portingin";
2795 return _provision( 'FS::svc_phone',
2796 [qw(lnp_desired_due_date lnp_other_provider
2797 lnp_other_provider_account phonenum countrycode lnp_status)],
2798 [qw(phonenum countrycode)],
2804 # single DID order (the usual case)
2805 unless (scalar(@bulkdid)) {
2806 return _provision( 'FS::svc_phone',
2807 [qw(phonenum countrycode)],
2808 [qw(phonenum countrycode)],
2814 # bulk DID order case
2816 foreach my $did ( @bulkdid ) {
2817 $did =~ s/[^0-9]//g;
2818 $error = _provision( 'FS::svc_phone',
2819 [qw(phonenum countrycode)],
2820 [qw(phonenum countrycode)],
2822 'pkgnum' => $p->{'pkgnum'},
2823 'svcpart' => $p->{'svcpart'},
2825 'countrycode' => $p->{'countrycode'},
2826 'session_id' => $p->{'session_id'},
2829 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2831 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2836 warn "provision_pbx called\n"
2839 warn "provision_pbx calling _provision\n"
2841 _provision( 'FS::svc_pbx',
2842 [qw(id title max_extensions max_simultaneous ip_addr)],
2843 [qw(id title max_extensions max_simultaneous ip_addr)],
2849 sub provision_acct {
2851 warn "provision_acct called\n"
2854 return { 'error' => gettext('passwords_dont_match') }
2855 if $p->{'_password'} ne $p->{'_password2'};
2856 return { 'error' => gettext('empty_password') }
2857 unless length($p->{'_password'});
2859 if ($p->{'domsvc'}) {
2860 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2861 qw ( svcpart pkgnum ) );
2862 return { 'error' => gettext('invalid_domain') }
2863 unless ($domains{$p->{'domsvc'}});
2866 warn "provision_acct calling _provision\n"
2868 _provision( 'FS::svc_acct',
2869 [qw(username _password domsvc)],
2870 [qw(username _password domsvc)],
2876 sub provision_external {
2878 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2879 _provision( 'FS::svc_external',
2887 sub provision_forward {
2889 _provision( 'FS::svc_forward',
2890 ['srcsvc','src','dstsvc','dst'],
2897 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2898 warn "_provision called for $class\n"
2901 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2902 return { 'error' => $session } if $context eq 'error';
2904 my $search = { 'custnum' => $custnum };
2905 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2906 my $cust_main = qsearchs('cust_main', $search )
2907 or return { 'error' => "unknown custnum $custnum" };
2909 my $pkgnum = $p->{'pkgnum'};
2911 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2913 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2914 'pkgnum' => $pkgnum,
2916 or return { 'error' => "unknown pkgnum $pkgnum" };
2918 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2920 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2921 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2923 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2924 if $class ne 'FS::'. $part_svc->svcdb;
2926 warn "creating $class record\n"
2928 my $svc_x = $class->new( {
2929 'pkgnum' => $p->{'pkgnum'},
2930 'svcpart' => $p->{'svcpart'},
2931 map { $_ => $p->{$_} } @$fields
2934 my %insert_args = ();
2935 #i shouldn't be a special case here (pass an option or something)
2936 if ( $class eq 'FS::svc_phone'
2937 && grep length($p->{$_}), @location_editable_fields
2940 $insert_args{'cust_location'} = new FS::cust_location {
2941 map { $_ => $p->{$_} } @location_editable_fields
2945 warn "inserting $class record\n"
2947 my $error = $svc_x->insert(%insert_args);
2950 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2952 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2955 my $return = { 'svc' => $part_svc->svc,
2957 map { $_ => $svc_x->get($_) } @$return_fields
2959 warn "_provision returning ". Dumper($return). "\n"
2968 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2969 return { 'error' => $session } if $context eq 'error';
2971 my $search = { 'custnum' => $custnum };
2972 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2973 my $cust_main = qsearchs('cust_main', $search )
2974 or return { 'error' => "unknown custnum $custnum" };
2976 my $pkgnum = $p->{'pkgnum'};
2978 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2979 'pkgnum' => $pkgnum,
2981 or return { 'error' => "unknown pkgnum $pkgnum" };
2983 my $svcpart = $p->{'svcpart'};
2985 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2986 'svcpart' => $svcpart, } )
2987 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2988 my $part_svc = $pkg_svc->part_svc;
2990 my $conf = new FS::Conf;
2993 'svc' => $part_svc->svc,
2994 'svcdb' => $part_svc->svcdb,
2995 'pkgnum' => $pkgnum,
2996 'svcpart' => $svcpart,
2997 'custnum' => $custnum,
2999 'security_phrase' => 0, #XXX !
3000 'svc_acct_pop' => [], #XXX !
3002 'init_popstate' => '',
3007 small_custview( $cust_main, $conf->config('countrydefault') ),
3011 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
3012 && $ret->{'svcdb'} eq 'svc_phone') {
3013 $ret->{'svcnum'} = $p->{'svcnum'};
3014 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3015 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3016 $ret->{'email'} = $svc_phone->email;
3017 $ret->{'forwarddst'} = $svc_phone->forwarddst;
3021 if ($ret->{'svcdb'} eq 'svc_forward') {
3022 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3028 sub unprovision_svc {
3031 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3032 return { 'error' => $session } if $context eq 'error';
3034 my $search = { 'custnum' => $custnum };
3035 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3036 my $cust_main = qsearchs('cust_main', $search )
3037 or return { 'error' => "unknown custnum $custnum" };
3039 my $svcnum = $p->{'svcnum'};
3041 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
3042 or return { 'error' => "unknown svcnum $svcnum" };
3044 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3045 unless $cust_svc->cust_pkg->custnum == $custnum;
3047 my $conf = new FS::Conf;
3049 return { 'svc' => $cust_svc->part_svc->svc,
3050 'error' => $cust_svc->cancel,
3052 small_custview( $cust_main, $conf->config('countrydefault') ),
3057 sub myaccount_passwd {
3059 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3060 return { 'error' => $session } if $context eq 'error';
3062 return { 'error' => "New passwords don't match." }
3063 if $p->{'new_password'} ne $p->{'new_password2'};
3065 return { 'error' => 'Enter new password' }
3066 unless length($p->{'new_password'});
3068 #my $search = { 'custnum' => $custnum };
3069 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3070 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3071 my $search = " AND custnum = $1";
3072 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3074 my $svc_acct = qsearchs( {
3075 'table' => 'svc_acct',
3076 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3077 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3078 'LEFT JOIN cust_main USING ( custnum ) ',
3079 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3080 'extra_sql' => $search, #important
3082 or return { 'error' => "Service not found" };
3086 my $conf = new FS::Conf;
3088 return { 'error' => 'Incorrect current password.' }
3089 if ( exists($p->{'old_password'})
3090 || $conf->exists('selfservice-password_change_oldpass')
3092 && ! $svc_acct->check_password($p->{'old_password'});
3094 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3095 || $svc_acct->set_password($p->{'new_password'})
3096 || $svc_acct->replace();
3098 #regular pw change in self-service should change contact pw too, otherwise its
3099 #way too confusing. hell its confusing they're separate at all, but alas.
3100 #need to support the "ISP provides email that's used as a contact email" case
3102 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3103 if ( $contact && $contact->custnum == $custnum ) {
3104 #svc_acct was successful but this one returns an error? "shouldn't happen"
3105 #don't recheck is_password_allowed here; if the svc_acct password was
3106 #legal, that's good enough
3107 $error ||= $contact->change_password($p->{'new_password'});
3110 my($label, $value) = $svc_acct->cust_svc->label;
3112 return { 'error' => $error,
3122 my $info = skin_info($p);
3124 my $conf = new FS::Conf;
3125 my $verification = $conf->config('selfservice-password_reset_verification')
3126 or return { %$info, 'error' => 'Password resets disabled' };
3131 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3133 $contact = FS::contact->by_selfservice_email($p->{'email'});
3135 $cust_main = $contact->cust_main if $contact;
3137 #also look for an svc_acct, otherwise it would be super confusing
3139 my($username, $domain) = split('@', $p->{'email'});
3140 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3141 if ( $svc_domain ) {
3142 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3143 'domsvc' => $svc_domain->svcnum }
3146 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3147 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3149 #precaution: don't change svc_acct password not part of the same
3150 # customer as contact
3151 $svc_acct = '' if ! $cust_pkg
3152 || $cust_pkg->custnum != $cust_main->custnum;
3157 return { %$info, 'error' => 'Email address not found' }
3158 unless $contact || $svc_acct;
3160 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3162 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3163 or return { %$info, 'error' => 'Account not found' };
3165 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3166 'domsvc' => $svc_domain->svcnum }
3168 or return { %$info, 'error' => 'Account not found' };
3170 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3171 or return { %$info, 'error' => 'Account not found' };
3173 $cust_main = $cust_pkg->cust_main;
3178 'email' => sub { 1; },
3180 my( $p, $cust_main ) = @_;
3181 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3182 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3185 my( $p, $cust_main ) = @_;
3186 my $cust_pay = qsearchs({
3187 'table' => 'cust_pay',
3188 'hashref' => { 'custnum' => $cust_main->custnum },
3189 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3193 $p->{'amount'} == $cust_pay->paid;
3196 my( $p, $cust_main ) = @_;
3197 $p->{'zip'} eq $cust_main->zip
3198 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3202 foreach my $verify ( split(',', $verification) ) {
3204 &{ $verify{$verify} }( $p, $cust_main )
3205 or return { %$info, 'error' => 'Account not found' };
3209 #okay, we're verified
3213 my $error = $contact->send_reset_email(
3214 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3218 return { %$info, 'error' => $error }; #????
3221 } elsif ( $svc_acct ) {
3223 #create a unique session
3225 my $reset_session = {
3226 'svcnum' => $svc_acct->svcnum,
3227 'agentnum' => $svc_acct->cust_main->agentnum,
3230 my $timeout = '1 hour'; #?
3232 my $reset_session_id;
3234 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3235 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3238 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3242 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3243 $cust_main->agentnum);
3244 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3245 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3247 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3248 my $error = $msg_template->send( 'cust_main' => $cust_main,
3249 'object' => $svc_acct,
3250 'substitutions' => {
3251 'session_id' => $reset_session_id,
3255 return { %$info, 'error' => $error }; #????
3260 return { %$info, 'error' => '' };
3263 sub check_reset_passwd {
3266 my $conf = new FS::Conf;
3267 my $verification = $conf->config('selfservice-password_reset_verification')
3268 or return { 'error' => 'Password resets disabled' };
3270 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3271 or return { 'error' => "Can't resume session" }; #better error message
3273 if ( $reset_session->{'svcnum'} ) {
3275 my $svcnum = $reset_session->{'svcnum'};
3277 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3278 or return { 'error' => "Service not found" };
3280 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3281 my $info = skin_info($p);
3285 'session_id' => $p->{'session_id'},
3286 'username' => $svc_acct->username,
3289 } elsif ( $reset_session->{'contactnum'} ) {
3291 my $contactnum = $reset_session->{'contactnum'};
3293 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3294 or return { 'error' => "Contact not found" };
3296 my @contact_email = $contact->contact_email;
3297 return { 'error' => 'No contact email' } unless @contact_email;
3299 $p->{'agentnum'} = $contact->cust_main->agentnum;
3300 my $info = skin_info($p);
3304 'session_id' => $p->{'session_id'},
3305 'email' => $contact_email[0]->email, #the first?
3310 return { 'error' => 'No svcnum or contactnum in session' }; #??
3316 sub process_reset_passwd {
3319 my $conf = new FS::Conf;
3320 my $verification = $conf->config('selfservice-password_reset_verification')
3321 or return { 'error' => 'Password resets disabled' };
3323 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3324 or return { 'error' => "Can't resume session" }; #better error message
3329 if ( $reset_session->{'svcnum'} ) {
3331 my $svcnum = $reset_session->{'svcnum'};
3333 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3334 or return { 'error' => "Service not found" };
3336 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3337 $info ||= skin_info($p);
3342 if ( $reset_session->{'contactnum'} ) {
3344 my $contactnum = $reset_session->{'contactnum'};
3346 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3347 or return { 'error' => "Contact not found" };
3349 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3350 $info ||= skin_info($p);
3354 return { %$info, 'error' => "New passwords don't match." }
3355 if $p->{'new_password'} ne $p->{'new_password2'};
3357 return { %$info, 'error' => 'Enter new password' }
3358 unless length($p->{'new_password'});
3362 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3363 || $svc_acct->set_password($p->{'new_password'})
3364 || $svc_acct->replace();
3366 return { %$info, 'error' => $error } if $error;
3368 #my($label, $value) = $svc_acct->cust_svc->label;
3369 #return { 'error' => $error,
3370 # #'label' => $label,
3371 # #'value' => $value,
3378 my $error = $contact->is_password_allowed($p->{'new_password'})
3379 || $contact->change_password($p->{'new_password'});
3381 return { %$info, 'error' => $error }; # if $error;
3385 #password changed ,so remove session, don't want it reused
3386 _cache->remove($p->{'session_id'});
3388 return { %$info, 'error' => '' };
3392 sub validate_passwd {
3396 %result = ( 'fieldid' => $p->{'fieldid'} )
3397 if $p->{'fieldid'} =~ /^\w+$/;
3399 return { %result, 'password_invalid' => 'Enter new password' }
3400 unless length($p->{'check_password'});
3403 if ($p->{'svcnum'}) {
3404 # false laziness with myaccount_passwd
3405 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3406 return { %result, 'error' => $session } if $context eq 'error';
3408 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3409 my $search = " AND custnum = $1";
3410 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3412 $svc_acct = qsearchs( {
3413 'table' => 'svc_acct',
3414 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3415 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3416 'LEFT JOIN cust_main USING ( custnum ) ',
3417 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3418 'extra_sql' => $search, #important
3420 or return { %result, 'error' => "Service not found" };
3421 # end false laziness
3424 unless ($svc_acct) {
3425 my $conf = new FS::Conf;
3426 my $agentnum = $p->{'agentnum'};
3427 return { %result, 'password_valid' => 1 }
3428 if $conf->config_bool('password-insecure', $p->{'agentnum'});
3431 $svc_acct ||= new FS::svc_acct {};
3433 my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3434 return { %result, 'password_invalid' => $error } if $error;
3435 return { %result, 'password_valid' => 1 };
3440 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3441 return { 'error' => $session } if $context eq 'error';
3444 if ( $session->{'pkgnum'} ) {
3446 #tickets for specific service with pkg-balances on
3447 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3448 'pkgnum' => $session->{'pkgnum'} })
3449 or return { 'error' => 'unknown package' };
3450 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3451 push @tickets, $cust_svc->tickets( $p->{status} );
3456 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3457 or return { 'error' => "unknown custnum $custnum" };
3459 @tickets = $cust_main->tickets( $p->{status} );
3462 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3463 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3464 my $conf = new FS::Conf;
3465 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3469 ($a->{'_selfservice_priority'} eq '') <=>
3470 ($b->{'_selfservice_priority'} eq '')
3473 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3479 +{ tickets => \@tickets };
3486 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3487 return { 'error' => $session } if $context eq 'error';
3489 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3490 FS::TicketSystem->init();
3492 my $conf = new FS::Conf;
3493 my $queue = $p->{'queue'}
3494 || $conf->config('ticket_system-selfservice_queueid')
3495 || $conf->config('ticket_system-default_queueid');
3497 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3498 my $err_or_ticket = FS::TicketSystem->create_ticket(
3499 '', #create RT session based on FS CurrentUser (fs_selfservice)
3501 'custnum' => $custnum,
3502 'svcnum' => $session->{'svcnum'},
3503 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3506 if ( ref($err_or_ticket) ) {
3507 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3509 return { 'error' => '',
3510 'ticket_id' => $err_or_ticket->id,
3513 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3515 return { 'error' => $err_or_ticket };
3523 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3524 return { 'error' => $session } if $context eq 'error';
3526 return { error => 'requested format not implemented' }
3527 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3529 my $conf = new FS::Conf;
3530 my $age_threshold = 0;
3531 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3532 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3534 my $search = { 'custnum' => $custnum };
3535 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3536 my $cust_main = qsearchs('cust_main', $search )
3537 or return { 'error' => "unknown custnum $custnum" };
3539 # does it make more sense to just run one sql query for this instead of all the
3540 # insanity below? would increase performance greately for large data sets?
3542 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3543 my @part_svc = $cust_pkg->part_svc;
3544 foreach my $part_svc ( @part_svc ) {
3545 if($part_svc->svcdb eq 'svc_phone'){
3546 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3547 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3548 push @svc_phone, $cust_pkg_svc->svc_x
3549 if $cust_pkg_svc->date_inserted >= $age_threshold;
3557 my($xls_r,$xls_c) = (0,0);
3560 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3561 if($p->{'format'} eq 'csv') {
3562 $csv = new Text::CSV_XS { 'always_quote' => 1,
3565 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3566 $content .= $csv->string;
3568 elsif($p->{'format'} eq 'xls') {
3569 my $XLS1 = new IO::Scalar \$content;
3570 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3571 or return { 'error' => "Error opening .xls file: $!" };
3572 $xls = $xls_workbook->add_worksheet('DIDs');
3573 foreach ( @fields ) {
3574 $xls->write(0,$xls_c++,$_);
3579 foreach my $svc_phone ( @svc_phone ) {
3580 my @cols = map { $svc_phone->$_ } @fields;
3581 if($p->{'format'} eq 'csv') {
3582 return { 'error' => 'Unable to create CSV' }
3583 unless $csv->combine(@cols);
3584 $content .= $csv->string;
3586 elsif($p->{'format'} eq 'xls') {
3589 $xls->write($xls_r,$xls_c++,$_);
3595 $xls_workbook->close() if $p->{'format'} eq 'xls';
3597 { content => $content, format => $p->{'format'}, };
3602 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3603 return { 'error' => $session } if $context eq 'error';
3605 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3606 # FS::TicketSystem->init();
3607 # return { 'error' => 'get_ticket configuration error' }
3608 # if $FS::TicketSystem::system ne 'RT_Internal';
3610 # check existence and ownership as part of this
3611 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3612 my $rt_session = FS::TicketSystem->session('');
3613 my $Ticket = FS::TicketSystem->get_ticket_object(
3615 ticket_id => $p->{'ticket_id'},
3618 return { 'error' => 'ticket not found' } if !$Ticket;
3620 if ( length( $p->{'subject'} || '' ) ) {
3622 if ( $p->{'subject'} ne $Ticket->Subject ) {
3623 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3624 return { 'error' => "unable to set subject: $msg" } if !$val;
3628 if(length($p->{'reply'})) {
3629 my @err_or_res = FS::TicketSystem->correspond_ticket(
3631 'ticket_id' => $p->{'ticket_id'},
3632 'content' => $p->{'reply'},
3635 return { 'error' => 'unable to reply to ticket' }
3636 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3639 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3640 my $err_or_ticket = FS::TicketSystem->get_ticket(
3642 'ticket_id' => $p->{'ticket_id'},
3645 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3646 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3648 return { 'error' => $err_or_ticket };
3651 my @custs = @{$err_or_ticket->{'custs'}};
3652 my @txns = @{$err_or_ticket->{'txns'}};
3655 # superseded by check in get_ticket_object
3656 #return { 'error' => 'invalid ticket requested' }
3657 #unless grep($_ eq $custnum, @custs);
3659 foreach my $txn ( @txns ) {
3660 push @filtered_txns, $txn
3661 if ($txn->{'type'} eq 'EmailRecord'
3662 || $txn->{'type'} eq 'Correspond'
3663 || $txn->{'type'} eq 'Create');
3666 warn "$me get_ticket: successful: \n"
3668 return { 'error' => '',
3669 'transactions' => \@filtered_txns,
3670 'ticket_fields' => $err_or_ticket->{'fields'},
3671 'ticket_id' => $p->{'ticket_id'},
3675 sub adjust_ticket_priority {
3677 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3678 return { 'error' => $session } if $context eq 'error';
3680 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3681 # FS::TicketSystem->init;
3682 my $ss_priority = FS::TicketSystem->selfservice_priority;
3684 return { 'error' => 'adjust_ticket_priority configuration error' }
3685 if $FS::TicketSystem::system ne 'RT_Internal'
3688 my $values = $p->{'values'}; #hashref, id => priority value
3691 foreach my $id (keys %$values) {
3692 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3693 my $Ticket = FS::TicketSystem->get_ticket_object('',
3695 'custnum' => $custnum,
3698 $ticket_error{$id} = 'ticket not found';
3702 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3703 # We're not going to implement it for RT_External.
3704 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3705 my $new_value = $values->{$id};
3706 next if $old_value eq $new_value;
3708 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3710 # AddCustomFieldValue works fine (replacing any existing value) if it's
3711 # a single-valued custom field, which it should be. If it's not, you're
3712 # doing something wrong.
3714 if ( length($new_value) ) {
3715 ($val, $msg) = $Ticket->AddCustomFieldValue(
3716 Field => $ss_priority,
3717 Value => $new_value,
3721 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3722 Field => $ss_priority,
3723 Value => $old_value,
3727 $ticket_error{$id} = $msg if !$val;
3728 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3730 return { 'error' => '',
3731 'ticket_error' => \%ticket_error,
3732 %{ customer_info($p) } # send updated customer info back
3738 sub _custoragent_session_custnum {
3741 my($context, $session, $custnum);
3742 if ( $p->{'session_id'} ) {
3744 $context = 'customer';
3745 $session = _cache->get($p->{'session_id'})
3746 or return ( 'error' => "Can't resume session" ); #better error message
3747 $custnum = $session->{'custnum'};
3749 } elsif ( $p->{'agent_session_id'} ) {
3752 my $agent_cache = new FS::ClientAPI_SessionCache( {
3753 'namespace' => 'FS::ClientAPI::Agent',
3755 $session = $agent_cache->get($p->{'agent_session_id'})
3756 or return ( 'error' => "Can't resume session" ); #better error message
3757 $custnum = $p->{'custnum'};
3761 return ( 'error' => "Can't resume session" ); #better error message
3764 ($context, $session, $custnum);