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;
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);
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;
51 $me = '[FS::ClientAPI::MyAccount]';
53 use vars qw( @cust_main_editable_fields @location_editable_fields );
54 @cust_main_editable_fields = qw(
55 first last company daytime night fax mobile
57 payby payinfo payname paystart_month paystart_year payissue payip
58 ss paytype paystate stateid stateid_state
60 @location_editable_fields = qw(
61 address1 address2 city county state zip country
65 BEGIN { #preload to reduce time customer_info takes
66 if ( $FS::TicketSystem::system ) {
67 warn "$me: initializing ticket system\n" if $DEBUG;
68 FS::TicketSystem->init();
73 $cache ||= new FS::ClientAPI_SessionCache( {
74 'namespace' => 'FS::ClientAPI::MyAccount',
81 my($context, $session, $custnum) = _custoragent_session_custnum($p);
82 #return { 'error' => $session } if $context eq 'error';
85 if ( $context eq 'customer' ) {
87 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
90 $sth->execute($custnum) or die $sth->errstr;
92 $agentnum = $sth->fetchrow_arrayref->[0]
93 or die "no agentnum for custnum $custnum";
95 #} elsif ( $context eq 'agent' ) {
96 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
100 my $conf = new FS::Conf;
102 #false laziness w/Signup.pm
104 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
106 if ( $skin_info_cache_agent ) {
108 warn "$me loading cached skin info for agentnum $agentnum\n"
113 warn "$me populating skin info cache for agentnum $agentnum\n"
116 $skin_info_cache_agent = {
117 'agentnum' => $agentnum,
118 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
119 qw( company_name date_format ) ),
120 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
121 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
122 text_color link_color vlink_color hlink_color alink_color
123 font title_color title_align title_size menu_bgcolor menu_fontsize
126 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
127 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
128 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
130 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
131 qw( title_left_image title_right_image
132 menu_top_image menu_body_image menu_bottom_image
135 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
136 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
137 qw( head body_header body_footer company_address ) ),
140 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
144 #{ %$skin_info_cache_agent };
145 $skin_info_cache_agent;
152 my $conf = new FS::Conf;
156 'phone_login' => $conf->exists('selfservice_server-phone_login'),
157 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
158 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
159 'banner_image_md5' =>
160 md5_hex($conf->config_binary('selfservice-login_banner_image')),
167 sub login_banner_image {
169 my $conf = new FS::Conf;
170 my $image = $conf->config_binary('selfservice-login_banner_image');
172 'md5' => md5_hex($image),
177 #false laziness w/FS::ClientAPI::passwd::passwd
181 my $conf = new FS::Conf;
185 if ( $p->{'domain'} eq 'svc_phone'
186 && $conf->exists('selfservice_server-phone_login') ) {
188 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
189 return { error => 'Number not found.' } unless $svc_phone;
192 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
193 #return { error => 'Only primary user may log in.' }
194 # if $conf->exists('selfservice_server-primary_only')
195 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
197 return { error => 'Incorrect PIN.' }
198 unless $svc_phone->check_pin($p->{'password'});
202 } elsif ( $p->{email}
203 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
206 return { error => 'Incorrect password.' }
207 unless $contact->authenticate_password($p->{'password'});
209 $session->{'custnum'} = $contact->custnum;
213 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
215 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
216 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
218 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
219 'domsvc' => $svc_domain->svcnum, }
221 return { error => 'User not found.' } unless $svc_acct;
223 if($conf->exists('selfservice_server-login_svcpart')) {
224 my @svcpart = $conf->config('selfservice_server-login_svcpart');
225 my $svcpart = $svc_acct->cust_svc->svcpart;
226 return { error => 'Invalid user.' }
227 unless grep($_ eq $svcpart, @svcpart);
230 return { error => 'Incorrect password.' }
231 unless $svc_acct->check_password($p->{'password'});
239 $session->{'svcnum'} = $svc_x->svcnum;
241 my $cust_svc = $svc_x->cust_svc;
242 my $cust_pkg = $cust_svc->cust_pkg;
244 my $cust_main = $cust_pkg->cust_main;
245 $session->{'custnum'} = $cust_main->custnum;
246 if ( $conf->exists('pkg-balances') ) {
247 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
248 $cust_main->ncancelled_pkgs;
249 $session->{'pkgnum'} = $cust_pkg->pkgnum
250 if scalar(@cust_pkg) > 1;
254 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
255 #return { error => 'Only primary user may log in.' }
256 # if $conf->exists('selfservice_server-primary_only')
257 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
258 my $part_pkg = $cust_pkg->part_pkg;
259 return { error => 'Only primary user may log in.' }
260 if $conf->exists('selfservice_server-primary_only')
261 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
267 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
268 } until ( ! defined _cache->get($session_id) ); #just in case
270 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
271 _cache->set( $session_id, $session, $timeout );
273 return { 'error' => '',
274 'session_id' => $session_id,
280 if ( $p->{'session_id'} ) {
281 _cache->remove($p->{'session_id'});
282 return { %{ skin_info($p) }, 'error' => '' };
284 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
291 my($context, $session, $custnum) = _custoragent_session_custnum($p);
292 return { 'error' => $session } if $context eq 'error';
294 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
295 or return { 'error' => "Service not found" };
297 $session->{'svcnum'} = $svc_acct->svcnum;
299 my $conf = new FS::Conf;
300 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
301 _cache->set( $p->{'session_id'}, $session, $timeout );
303 return { 'error' => '' };
307 sub payment_gateway {
309 # takes a cust_main and a cust_payby entry, returns the payment_gateway
310 my $conf = new FS::Conf;
311 my $cust_main = shift;
312 my $cust_payby = shift;
313 my $gatewaynum = $conf->config('selfservice-payment_gateway');
315 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
316 die "configured gatewaynum $gatewaynum not found!" if !$pg;
320 return '' if ! FS::payby->realtime($cust_payby);
321 my $pg = $cust_main->agent->payment_gateway(
322 'method' => FS::payby->payby2bop($cust_payby),
332 my $conf = new FS::Conf;
334 my $info = skin_info($p);
336 use vars qw( $cust_paybys ); #cache for performance
337 unless ( $cust_paybys ) {
339 my %cust_paybys = map { $_ => 1 }
340 map { FS::payby->payby2payment($_) }
341 $conf->config('signup_server-payby');
343 $cust_paybys = [ keys %cust_paybys ];
346 $info->{'cust_paybys'} = $cust_paybys;
348 my($context, $session, $custnum) = _custoragent_session_custnum($p);
349 return { 'error' => $session } if $context eq 'error';
351 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
352 or return { 'error' => "unknown custnum $custnum" };
354 $info->{'hide_payment_fields'} = [
356 my $pg = payment_gateway($cust_main, $_);
357 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
358 } @{ $info->{cust_paybys} }
361 $info->{'self_suspend_reason'} =
362 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
364 $info->{'edit_ticket_subject'} =
365 $conf->exists('ticket_system-selfservice_edit_subject') &&
366 $cust_main->edit_subject;
368 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
371 'custnum' => $custnum,
372 'access_pkgnum' => $session->{'pkgnum'},
373 'access_svcnum' => $session->{'svcnum'},
380 my($context, $session, $custnum) = _custoragent_session_custnum($p);
381 return { 'error' => $session } if $context eq 'error';
385 my $conf = new FS::Conf;
386 if ($conf->exists('cust_main-require_address2')) {
387 $return{'require_address2'} = '1';
389 $return{'require_address2'} = '';
392 if ( $FS::TicketSystem::system ) {
393 warn "$me customer_info: initializing ticket system\n" if $DEBUG;
394 FS::TicketSystem->init();
397 if ( $custnum ) { #customer record
399 my $search = { 'custnum' => $custnum };
400 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
401 my $cust_main = qsearchs('cust_main', $search )
402 or return { 'error' => "unknown custnum $custnum" };
404 $return{display_custnum} = $cust_main->display_custnum;
406 if ( $session->{'pkgnum'} ) {
407 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
408 #next_bill_date from cust_pkg?
410 $return{balance} = $cust_main->balance;
411 $return{next_bill_date} = $cust_main->next_bill_date;
412 $return{next_bill_date_pretty} =
413 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
417 my @tickets = $cust_main->tickets;
418 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
419 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
420 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
424 ($a->{'_selfservice_priority'} eq '') <=>
425 ($b->{'_selfservice_priority'} eq '')
428 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
434 $return{tickets} = \@tickets;
437 unless ( $session->{'pkgnum'} ) {
440 invnum => $_->invnum,
441 date => time2str("%b %o, %Y", $_->_date),
444 } $cust_main->open_cust_bill;
445 $return{open_invoices} = \@open;
447 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
448 my $sth = dbh->prepare($sql) or die dbh->errstr;
449 $sth->execute($custnum) or die $sth->errstr;
450 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
451 $return{'last_invoice_date_pretty'} =
452 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
455 $return{countrydefault} = scalar($conf->config('countrydefault'));
457 $return{small_custview} =
458 small_custview( $cust_main,
459 $return{countrydefault},
460 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
463 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
465 $return{has_ship_address} = $cust_main->has_ship_address;
466 $return{status} = $cust_main->status;
467 $return{statuscolor} = $cust_main->statuscolor;
469 for (@cust_main_editable_fields) {
470 $return{$_} = $cust_main->get($_);
473 for (@location_editable_fields) {
474 $return{$_} = $cust_main->bill_location->get($_);
475 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
477 $return{has_ship_address} = $cust_main->has_ship_address;
478 # compatibility: some places in selfservice use this to determine
479 # if there's a ship address
480 if ( $return{has_ship_address} ) {
481 $return{ship_last} = $cust_main->last;
482 $return{ship_first} = $cust_main->first;
485 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
486 $return{payinfo} = $cust_main->paymask;
487 @return{'month', 'year'} = $cust_main->paydate_monthyear;
490 $return{'invoicing_list'} =
491 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
492 $return{'postal_invoicing'} =
493 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
495 if (scalar($conf->config('support_packages'))) {
496 my @support_services = ();
497 foreach ($cust_main->support_services) {
498 my $seconds = $_->svc_x->seconds || 0;
499 my $time_remaining = (($seconds < 0) ? '-' : '' ).
500 int(abs($seconds)/3600)."h".
501 sprintf("%02d",(abs($seconds)%3600)/60)."m";
502 my $cust_pkg = $_->cust_pkg;
505 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
506 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
507 push @support_services, { svcnum => $_->svcnum,
508 time => $time_remaining,
513 $return{support_services} = \@support_services;
516 if ( $conf->config('prepayment_discounts-credit_type') ) {
518 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
521 if ( $session->{'svcnum'} ) {
522 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
523 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
524 $return{'svcnum'} = $session->{'svcnum'};
527 } elsif ( $session->{'svcnum'} ) { #no customer record
529 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
530 or die "unknown svcnum";
531 $return{name} = $svc_acct->email;
535 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
539 return { 'error' => '',
540 'custnum' => $custnum,
546 sub customer_info_short {
549 my($context, $session, $custnum) = _custoragent_session_custnum($p);
550 return { 'error' => $session } if $context eq 'error';
554 my $conf = new FS::Conf;
556 if ( $custnum ) { #customer record
558 my $search = { 'custnum' => $custnum };
559 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
560 my $cust_main = qsearchs('cust_main', $search )
561 or return { 'error' => "unknown custnum $custnum" };
563 $return{display_custnum} = $cust_main->display_custnum;
565 $return{countrydefault} = scalar($conf->config('countrydefault'));
567 $return{small_custview} =
568 small_custview( $cust_main,
569 $return{countrydefault},
573 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
575 $return{payby} = $cust_main->payby;
577 #none of these are terribly expensive if we want 'em...
578 for (@cust_main_editable_fields) {
579 $return{$_} = $cust_main->get($_);
581 #maybe a little more expensive, but it should be cached by now
582 for (@location_editable_fields) {
583 $return{$_} = $cust_main->bill_location->get($_);
584 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
587 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
588 $return{payinfo} = $cust_main->paymask;
589 @return{'month', 'year'} = $cust_main->paydate_monthyear;
592 $return{'invoicing_list'} =
593 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
594 #$return{'postal_invoicing'} =
595 # 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
597 if ( $session->{'svcnum'} ) {
598 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
599 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
600 $return{'svcnum'} = $session->{'svcnum'};
603 } elsif ( $session->{'svcnum'} ) { #no customer record
605 #uuh, not supproted yet... die?
606 return { 'error' => 'customer_info_short not yet supported as agent' };
610 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
614 return { 'error' => '',
615 'custnum' => $custnum,
620 sub billing_history {
623 my($context, $session, $custnum) = _custoragent_session_custnum($p);
624 return { 'error' => $session } if $context eq 'error';
626 return { 'error' => 'No customer' } unless $custnum;
628 my $search = { 'custnum' => $custnum };
629 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
630 my $cust_main = qsearchs('cust_main', $search )
631 or return { 'error' => "unknown custnum $custnum" };
635 if ( $session->{'pkgnum'} ) {
636 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
637 #next_bill_date from cust_pkg?
638 return { 'error' => 'No history for package' };
641 $return{balance} = $cust_main->balance;
642 $return{next_bill_date} = $cust_main->next_bill_date;
643 $return{next_bill_date_pretty} =
644 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
649 my $conf = new FS::Conf;
651 if ( $conf->exists('selfservice-billing_history-line_items') ) {
653 foreach my $cust_bill ( $cust_main->cust_bill ) {
656 'type' => 'Line item',
657 'description' => $_->desc( $cust_main->locale ).
658 ( $_->sdate && $_->edate
659 ? ' '. time2str('%d-%b-%Y', $_->sdate).
660 ' To '. time2str('%d-%b-%Y', $_->edate)
663 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
664 'date' => $cust_bill->_date,
665 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
667 foreach $cust_bill->cust_bill_pkg;
675 'description' => 'Invoice #'. $_->display_invnum,
676 'amount' => sprintf('%.2f', $_->charged ),
678 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
680 foreach $cust_main->cust_bill;
686 'description' => 'Payment', #XXX type
687 'amount' => sprintf('%.2f', 0 - $_->paid ),
689 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
691 foreach $cust_main->cust_pay;
695 'description' => 'Credit', #more info?
696 'amount' => sprintf('%.2f', 0 -$_->amount ),
698 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
700 foreach $cust_main->cust_credit;
704 'description' => 'Refund', #more info? type, like payment?
705 'amount' => $_->refund,
707 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
709 foreach $cust_main->cust_refund;
711 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
713 $return{'history'} = \@history;
721 my $session = _cache->get($p->{'session_id'})
722 or return { 'error' => "Can't resume session" }; #better error message
724 my $custnum = $session->{'custnum'}
725 or return { 'error' => "no customer record" };
727 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
728 or return { 'error' => "unknown custnum $custnum" };
730 my $new = new FS::cust_main { $cust_main->hash };
732 $new->set( $_ => $p->{$_} )
733 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
735 if ( exists($p->{address1}) ) {
736 my $bill_location = FS::cust_location->new({
737 map { $_ => $p->{$_} } @location_editable_fields
739 # if this is unchanged from before, cust_main::replace will ignore it
740 $new->set('bill_location' => $bill_location);
743 if ( exists($p->{ship_address1}) ) {
744 my $ship_location = FS::cust_location->new({
745 map { $_ => $p->{"ship_$_"} } @location_editable_fields
747 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
748 # Selfservice unfortunately tries to indicate "same as billing
749 # address" by sending all fields empty. Did this ever work?
750 $ship_location = $cust_main->bill_location;
752 $new->set('ship_location' => $ship_location);
754 # but if it hasn't been passed in at all, leave ship_location alone--
755 # DON'T change it to match bill_location.
758 if (exists($p->{'payby'})) {
759 $p->{'payby'} =~ /^([A-Z]{4})$/
760 or return { 'error' => "illegal_payby " . $p->{'payby'} };
764 if ( $payby =~ /^(CARD|DCRD)$/ ) {
766 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
768 if ( $new->payinfo eq $cust_main->paymask ) {
769 $new->payinfo($cust_main->payinfo);
771 $new->payinfo($p->{'payinfo'});
774 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
776 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
779 $p->{'payinfo1'} =~ /^([\dx]+)$/
780 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
782 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
783 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
785 $payinfo = $payinfo1. '@'. $payinfo2;
787 $new->payinfo( ($payinfo eq $cust_main->paymask)
788 ? $cust_main->payinfo
792 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
794 } elsif ( $payby =~ /^(BILL)$/ ) {
796 } elsif ( $payby ) { #notyet ready
797 return { 'error' => "unknown payby $payby" };
801 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
802 #false laziness with httemplate/edit/process/cust_main.cgi
803 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
804 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
806 @invoicing_list = $cust_main->invoicing_list;
809 my $error = $new->replace($cust_main, \@invoicing_list);
810 return { 'error' => $error } if $error;
813 return { 'error' => '' };
818 my $session = _cache->get($p->{'session_id'})
819 or return { 'error' => "Can't resume session" }; #better error message
825 my $conf = new FS::Conf;
826 use vars qw($payment_info); #cache for performance
827 unless ( $payment_info ) {
829 my %states = map { $_->state => 1 }
830 qsearch('cust_main_county', {
831 'country' => $conf->config('countrydefault') || 'US'
834 my %cust_paybys = map { $_ => 1 }
835 map { FS::payby->payby2payment($_) }
836 $conf->config('signup_server-payby');
838 my @cust_paybys = keys %cust_paybys;
842 #list all counties/states/countries
843 'cust_main_county' =>
844 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
846 #shortcut for one-country folks
848 [ sort { $a cmp $b } keys %states ],
850 'card_types' => card_types(),
852 'paytypes' => [ @FS::cust_main::paytypes ],
854 'paybys' => [ $conf->config('signup_server-payby') ],
855 'cust_paybys' => \@cust_paybys,
857 'stateid_label' => FS::Msgcat::_gettext('stateid'),
858 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
860 'show_ss' => $conf->exists('show_ss'),
861 'show_stateid' => $conf->exists('show_stateid'),
862 'show_paystate' => $conf->exists('show_bankstate'),
864 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
866 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
875 my %return = %$payment_info;
877 my $custnum = $session->{'custnum'};
879 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
880 or return { 'error' => "unknown custnum $custnum" };
882 $return{'hide_payment_fields'} = [
884 my $pg = payment_gateway($cust_main, $_);
885 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
886 } @{ $return{cust_paybys} }
889 $return{balance} = $cust_main->balance; #XXX pkg-balances?
891 $return{payname} = $cust_main->payname
892 || ( $cust_main->first. ' '. $cust_main->get('last') );
894 $return{$_} = $cust_main->bill_location->get($_)
895 for qw(address1 address2 city state zip);
897 $return{payby} = $cust_main->payby;
898 $return{stateid_state} = $cust_main->stateid_state;
900 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
901 $return{card_type} = cardtype($cust_main->payinfo);
902 $return{payinfo} = $cust_main->paymask;
904 @return{'month', 'year'} = $cust_main->paydate_monthyear;
908 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
909 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
910 $return{payinfo1} = $payinfo1;
911 $return{payinfo2} = $payinfo2;
912 $return{paytype} = $cust_main->paytype;
913 $return{paystate} = $cust_main->paystate;
914 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
917 if ( $conf->config('prepayment_discounts-credit_type') ) {
919 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
922 #doubleclick protection
924 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
926 return { 'error' => '',
932 #some false laziness with httemplate/process/payment.cgi - look there for
933 #ACH and CVV support stuff
935 sub validate_payment {
938 my $session = _cache->get($p->{'session_id'})
939 or return { 'error' => "Can't resume session" }; #better error message
941 my $custnum = $session->{'custnum'};
943 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
944 or return { 'error' => "unknown custnum $custnum" };
946 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
947 or return { 'error' => gettext('illegal_amount') };
949 return { error => 'Amount must be greater than 0' } unless $amount > 0;
951 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
952 #changing the hidden form values
953 my $conf = new FS::Conf;
954 my $fee_display = $conf->config('selfservice_process-display') || 'add';
955 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
956 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
957 if ( $fee_display eq 'add'
959 and ! $fee_skip_first || scalar($cust_main->cust_pay)
962 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
963 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
966 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
967 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
968 my $discount_term = $1;
970 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
971 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
974 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
975 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
978 $p->{'payby'} ||= 'CARD';
979 $p->{'payby'} =~ /^([A-Z]{4})$/
980 or return { 'error' => "illegal_payby " . $p->{'payby'} };
983 #false laziness w/process/payment.cgi
986 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
988 $p->{'payinfo1'} =~ /^([\dx]+)$/
989 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
991 $p->{'payinfo2'} =~ /^([\dx]+)$/
992 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
994 $payinfo = $payinfo1. '@'. $payinfo2;
996 $payinfo = $cust_main->payinfo
997 if $cust_main->paymask eq $payinfo;
999 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1001 $payinfo = $p->{'payinfo'};
1003 #more intelligent matching will be needed here if you change
1004 #card_masking_method and don't remove existing paymasks
1005 $payinfo = $cust_main->payinfo
1006 if $cust_main->paymask eq $payinfo;
1008 $payinfo =~ s/\D//g;
1009 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1010 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1014 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1015 return { 'error' => gettext('unknown_card_type') }
1016 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1018 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1019 if ( cardtype($payinfo) eq 'American Express card' ) {
1020 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1021 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1024 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1025 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1031 die "unknown payby $payby";
1034 my %payby2fields = (
1035 'CARD' => [ qw( paystart_month paystart_year payissue payip
1036 address1 address2 city state zip country ) ],
1037 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1041 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1044 'cust_main' => $cust_main, #XXX or just custnum??
1045 'amount' => sprintf('%.2f', $amount),
1047 'payinfo' => $payinfo,
1048 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1049 'card_type' => $card_type,
1050 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1051 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1052 'month' => $p->{'month'},
1053 'year' => $p->{'year'},
1054 'payname' => $payname,
1055 'paybatch' => $paybatch, #this doesn't actually do anything
1056 'paycvv' => $paycvv,
1057 'payname' => $payname,
1058 'discount_term' => $discount_term,
1059 'pkgnum' => $session->{'pkgnum'},
1060 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1070 my $validate = validate_payment($p);
1071 return $validate if $validate->{'error'};
1073 my $conf = new FS::Conf;
1074 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1075 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1077 +{ map { $_=>$validate->{$_} }
1078 qw( card_type paymask payname paydate_pretty month year amount
1079 address1 address2 city state zip country
1085 sub process_stored_payment {
1088 my $session_id = $p->{'session_id'};
1090 my $payment_info = _cache->get( "payment_$session_id" )
1091 or return { 'error' => "Can't resume session" }; #better error message
1093 do_process_payment($payment_info);
1097 sub process_payment {
1100 my $payment_info = validate_payment($p);
1101 return $payment_info if $payment_info->{'error'};
1103 do_process_payment($payment_info);
1107 sub do_process_payment {
1108 my $validate = shift;
1110 my $cust_main = $validate->{'cust_main'};
1112 my $amount = delete $validate->{'amount'};
1115 my $payby = delete $validate->{'payby'};
1117 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1120 'paynum_ref' => \$paynum,
1123 return { 'error' => $error } if $error;
1125 #no error, so order the fee package if applicable...
1126 my $conf = new FS::Conf;
1127 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1128 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1130 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1132 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1134 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1135 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1138 #and generate an invoice for it now too
1139 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1140 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1145 $cust_main->apply_payments;
1147 if ( $validate->{'save'} ) {
1148 my $new = new FS::cust_main { $cust_main->hash };
1149 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1150 $new->set( $_ => $validate->{$_} )
1151 foreach qw( payname paystart_month paystart_year payissue payip );
1152 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1154 my $bill_location = FS::cust_location->new({
1155 map { $_ => $validate->{$_} }
1156 qw(address1 address2 city state country zip)
1158 $new->set('bill_location' => $bill_location);
1159 # but don't allow the service address to change this way.
1161 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1162 $new->set( $_ => $validate->{$_} )
1163 foreach qw( payname payip paytype paystate
1164 stateid stateid_state );
1165 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1167 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1168 $new->set( 'paydate' => $validate->{'paydate'} );
1169 my $error = $new->replace($cust_main);
1171 #no, this causes customers to process their payments again
1172 #return { 'error' => $error };
1173 #XXX just warn verosely for now so i can figure out how these happen in
1174 # the first place, eventually should redirect them to the "change
1175 #address" page but indicate the payment did process??
1176 delete($validate->{'payinfo'}); #don't want to log this!
1177 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1178 "NEW: ". Dumper($new)."\n".
1179 "OLD: ". Dumper($cust_main)."\n".
1180 "PACKET: ". Dumper($validate)."\n";
1188 my $receipt_html = '';
1190 # currently supported for realtime CC only; send receipt data to SS
1191 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1194 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1197 <TD ALIGN="right">Payment#</TD>
1198 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1202 <TD ALIGN="right">Date</TD>
1204 <TD BGCOLOR="#FFFFFF"><B>! .
1205 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1211 <TD ALIGN="right">Amount</TD>
1212 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1217 <TD ALIGN="right">Payment method</TD>
1218 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1229 my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
1233 'amount' => sprintf('%.2f', $cust_pay->paid),
1234 'date' => $cust_pay->_date,
1235 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1236 'time_pretty' => time2str('%T', $cust_pay->_date),
1237 'auth_num' => $auth,
1238 'order_num' => $order,
1239 'receipt_html' => $receipt_html,
1246 'receipt_html' => '',
1253 sub realtime_collect {
1256 my $session = _cache->get($p->{'session_id'})
1257 or return { 'error' => "Can't resume session" }; #better error message
1259 my $custnum = $session->{'custnum'};
1261 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1262 or return { 'error' => "unknown custnum $custnum" };
1265 if ( $p->{'amount'} ) {
1266 $amount = $p->{'amount'};
1268 elsif ( $session->{'pkgnum'} ) {
1269 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1272 $amount = $cust_main->balance;
1275 my $error = $cust_main->realtime_collect(
1276 'method' => $p->{'method'},
1277 'amount' => $amount,
1278 'pkgnum' => $session->{'pkgnum'},
1279 'session_id' => $p->{'session_id'},
1283 return { 'error' => $error } unless ref( $error );
1285 return { 'error' => '', amount => $amount, %$error };
1288 sub start_thirdparty {
1290 my $session = _cache->get($p->{'session_id'})
1291 or return { 'error' => "Can't resume session" }; #better error message
1292 my $custnum = $session->{'custnum'};
1293 my $cust_main = FS::cust_main->by_key($custnum);
1295 my $amount = $p->{'amount'}
1296 or return { error => 'no amount' };
1298 my $result = $cust_main->create_payment(
1299 'method' => $p->{'method'},
1300 'amount' => $p->{'amount'},
1301 'pkgnum' => $session->{'pkgnum'},
1302 'session_id' => $p->{'session_id'},
1305 if ( ref($result) ) { # hashref or error
1308 return { error => $result };
1312 sub finish_thirdparty {
1314 my $session_id = delete $p->{'session_id'};
1315 my $session = _cache->get($session_id)
1316 or return { 'error' => "Can't resume session" };
1317 my $custnum = $session->{'custnum'};
1318 my $cust_main = FS::cust_main->by_key($custnum);
1320 if ( $p->{_cancel} ) {
1321 # customer backed out of making a payment
1322 return $cust_main->cancel_payment( $session_id );
1324 my $result = $cust_main->execute_payment( $session_id, %$p );
1325 if ( ref($result) ) {
1328 return { error => $result };
1332 sub process_payment_order_pkg {
1335 my $hr = process_payment($p);
1336 return $hr if $hr->{'error'};
1341 sub process_payment_order_renew {
1344 my $hr = process_payment($p);
1345 return $hr if $hr->{'error'};
1350 sub process_prepay {
1354 my $session = _cache->get($p->{'session_id'})
1355 or return { 'error' => "Can't resume session" }; #better error message
1359 my $custnum = $session->{'custnum'};
1361 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1362 or return { 'error' => "unknown custnum $custnum" };
1364 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1365 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1373 return { 'error' => $error } if $error;
1375 return { 'error' => '',
1376 'amount' => $amount,
1377 'seconds' => $seconds,
1378 'duration' => duration_exact($seconds),
1379 'upbytes' => $upbytes,
1380 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1381 'downbytes' => $downbytes,
1382 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1383 'totalbytes'=> $totalbytes,
1384 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1391 my $session = _cache->get($p->{'session_id'})
1392 or return { 'error' => "Can't resume session" }; #better error message
1394 my $custnum = $session->{'custnum'};
1396 my $invnum = $p->{'invnum'};
1398 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1399 'custnum' => $custnum } )
1400 or return { 'error' => "Can't find invnum" };
1404 return { 'error' => '',
1405 'invnum' => $invnum,
1406 'invoice_text' => join('', $cust_bill->print_text ),
1407 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1414 my $session = _cache->get($p->{'session_id'})
1415 or return { 'error' => "Can't resume session" }; #better error message
1417 my $custnum = $session->{'custnum'};
1419 my $invnum = $p->{'invnum'};
1421 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1422 'custnum' => $custnum } )
1423 or return { 'error' => "Can't find invnum" };
1427 return { 'error' => '',
1428 'invnum' => $invnum,
1429 'invoice_pdf' => $cust_bill->print_pdf({
1430 'unsquelch_cdr' => 1,
1431 'locale' => $p->{'locale'},
1437 sub legacy_invoice {
1439 my $session = _cache->get($p->{'session_id'})
1440 or return { 'error' => "Can't resume session" }; #better error message
1442 my $custnum = $session->{'custnum'};
1444 my $legacyinvnum = $p->{'legacyinvnum'};
1447 'legacyinvnum' => $legacyinvnum,
1448 'custnum' => $custnum,
1451 my $legacy_cust_bill =
1452 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1453 || qsearchs('legacy_cust_bill', \%hash )
1454 or return { 'error' => "Can't find legacyinvnum" };
1458 return { 'error' => '',
1459 'legacyinvnum' => $legacyinvnum,
1460 'legacyid' => $legacy_cust_bill->legacyid,
1461 'invoice_html' => $legacy_cust_bill->content_html,
1466 sub legacy_invoice_pdf {
1468 my $session = _cache->get($p->{'session_id'})
1469 or return { 'error' => "Can't resume session" }; #better error message
1471 my $custnum = $session->{'custnum'};
1473 my $legacyinvnum = $p->{'legacyinvnum'};
1475 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1476 'legacyinvnum' => $legacyinvnum,
1477 'custnum' => $custnum,
1478 }) or return { 'error' => "Can't find legacyinvnum" };
1482 return { 'error' => '',
1483 'legacyinvnum' => $legacyinvnum,
1484 'legacyid' => $legacy_cust_bill->legacyid,
1485 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1493 #sessioning for this? how do we get the session id to the backend invoice
1494 # template so it can add it to the link, blah
1497 if ( $p->{'invnum'} ) {
1498 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1499 or return { 'error' => 'unknown invnum' };
1500 $agentnum = $cust_bill->cust_main->agentnum;
1503 my $templatename = $p->{'template'} || $p->{'templatename'};
1505 #false laziness-ish w/view/cust_bill-logo.cgi
1507 my $conf = new FS::Conf;
1508 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1509 $templatename = "_$1";
1514 my $filename = "logo$templatename.png";
1516 return { 'error' => '',
1517 'logo' => $conf->config_binary($filename, $agentnum),
1518 'content_type' => 'image/png', #should allow gif, jpg too
1525 my $session = _cache->get($p->{'session_id'})
1526 or return { 'error' => "Can't resume session" }; #better error message
1528 my $custnum = $session->{'custnum'};
1530 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1531 or return { 'error' => "unknown custnum $custnum" };
1533 my $conf = new FS::Conf;
1535 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1537 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1541 return { 'error' => '',
1542 'balance' => $cust_main->balance,
1545 my $owed = $_->owed;
1547 +{ 'invnum' => $_->invnum,
1548 '_date' => $_->_date,
1549 'date' => time2str("%b %o, %Y", $_->_date),
1550 'date_short' => time2str("%m-%d-%Y", $_->_date),
1551 'previous' => sprintf('%.2f', ($_->previous)[0]),
1552 'charged' => sprintf('%.2f', $_->charged),
1553 'owed' => sprintf('%.2f', $owed),
1554 'balance' => sprintf('%.2f', $balance),
1559 'legacy_invoices' => [
1561 +{ 'legacyinvnum' => $_->legacyinvnum,
1562 'legacyid' => $_->legacyid,
1563 '_date' => $_->_date,
1564 'date' => time2str("%b %o, %Y", $_->_date),
1565 'date_short' => time2str("%m-%d-%Y", $_->_date),
1566 'charged' => sprintf('%.2f', $_->charged),
1567 'has_content' => ( length($_->content_pdf)
1568 || length($_->content_html) ),
1578 my $session = _cache->get($p->{'session_id'})
1579 or return { 'error' => "Can't resume session" }; #better error message
1581 my $custnum = $session->{'custnum'};
1583 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1584 or return { 'error' => "unknown custnum $custnum" };
1586 my @errors = $cust_main->cancel( 'quiet'=>1 );
1588 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1590 return { 'error' => $error };
1597 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1598 return { 'error' => $session } if $context eq 'error';
1600 my $search = { 'custnum' => $custnum };
1601 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1602 my $cust_main = qsearchs('cust_main', $search )
1603 or return { 'error' => "unknown custnum $custnum" };
1605 my $conf = new FS::Conf;
1607 # the duplication below is necessary:
1608 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1609 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1610 # non-backwards-compatible change breaking the software of anyone using the API
1611 # instead of the stock selfservice
1612 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1613 if( $conf->exists('selfservice_server-view-wholesale') ) {
1614 return { 'svcnum' => $session->{'svcnum'},
1615 'custnum' => $custnum,
1616 'cust_pkg' => [ map {
1618 part_pkg => [ map $_->hashref, $_->part_pkg ],
1620 [ map $_->hashref, $_->available_part_svc ],
1622 [ map { my $ref = { $_->hash,
1623 label => [ $_->label ],
1625 $ref->{_password} = $_->svc_x->_password
1626 if $context eq 'agent'
1627 && $conf->exists('agent-showpasswords')
1628 && $_->part_svc->svcdb eq 'svc_acct';
1633 } $cust_main->cust_pkg
1636 small_custview( $cust_main, $conf->config('countrydefault') ),
1637 'wholesale_view' => 1,
1638 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1639 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1640 'lnp' => $conf->exists('svc_phone-lnp'),
1644 { 'svcnum' => $session->{'svcnum'},
1645 'custnum' => $custnum,
1646 'cust_pkg' => [ map {
1647 my $primary_cust_svc = $_->primary_cust_svc;
1650 pkg_label => $_->pkg_locale,
1651 status => $_->status,
1653 [ map { $_->hashref }
1654 grep { $_->selfservice_access ne 'hidden' }
1655 $_->available_part_svc
1658 [ map { my $ref = { $_->hash,
1659 label => [ $_->label ],
1661 $ref->{_password} = $_->svc_x->_password
1662 if $context eq 'agent'
1663 && $conf->exists('agent-showpasswords')
1664 && $_->part_svc->svcdb eq 'svc_acct';
1665 $ref->{svchash} = { $_->svc_x->hash } if
1666 $_->part_svc->svcdb eq 'svc_phone';
1667 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1668 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1671 grep { $_->part_svc->selfservice_access ne 'hidden' }
1676 ? { $primary_cust_svc->hash,
1677 label => [ $primary_cust_svc->label ],
1678 finger => $primary_cust_svc->svc_x->finger, #uuh
1679 $primary_cust_svc->part_svc->hash,
1683 } $cust_main->ncancelled_pkgs
1686 small_custview( $cust_main, $conf->config('countrydefault') ),
1694 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1695 return { 'error' => $session } if $context eq 'error';
1697 my $search = { 'custnum' => $custnum };
1698 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1699 my $cust_main = qsearchs('cust_main', $search )
1700 or return { 'error' => "unknown custnum $custnum" };
1702 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1703 if ( ! $pkgnum && $p->{'svcnum'} ) {
1704 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1705 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1709 my @cust_pkg_usage = ();
1710 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1711 foreach my $cust_pkg ( $p->{'ncancelled'}
1712 ? $cust_main->ncancelled_pkgs
1713 : $cust_main->unsuspended_pkgs ) {
1714 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1715 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1716 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1719 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1721 foreach (@cust_pkg_usage) {
1722 my $part = $_->part_pkg_usage;
1723 my $tag = $part->description . ($part->shared ? 1 : 0);
1724 my $row = $usage_pools{$tag}
1725 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1726 $row->[1] += $_->minutes; # minutes remaining
1727 $row->[2] += $part->minutes; # minutes total
1730 if ( $p->{'svcdb'} ) {
1731 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1733 : ref($p->{'svcdb'}) eq 'ARRAY'
1734 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1735 : { $p->{'svcdb'} => 1 };
1736 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1739 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1742 my $conf = new FS::Conf;
1745 'svcnum' => $session->{'svcnum'},
1746 'custnum' => $custnum,
1747 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1748 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1751 my $svc_x = $_->svc_x;
1752 my($label, $value) = $_->label;
1753 my $part_svc = $_->part_svc;
1754 my $svcdb = $part_svc->svcdb;
1755 my $cust_pkg = $_->cust_pkg;
1756 my $part_pkg = $cust_pkg->part_pkg;
1759 'svcnum' => $_->svcnum,
1760 'display_svcnum' => $_->display_svcnum,
1764 'pkg_label' => $cust_pkg->pkg_locale,
1765 'pkg_status' => $cust_pkg->status,
1766 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1769 if ( $svcdb eq 'svc_acct' ) {
1772 'username' => $svc_x->username,
1773 'email' => $svc_x->email,
1774 'finger' => $svc_x->finger,
1775 'seconds' => $svc_x->seconds,
1776 'upbytes' => display_bytecount($svc_x->upbytes),
1777 'downbytes' => display_bytecount($svc_x->downbytes),
1778 'totalbytes' => display_bytecount($svc_x->totalbytes),
1780 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1781 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1782 'recharge_upbytes' =>
1783 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1784 'recharge_downbytes' =>
1785 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1786 'recharge_totalbytes' =>
1787 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1791 } elsif ( $svcdb eq 'svc_dsl' ) {
1792 $hash{'phonenum'} = $svc_x->phonenum;
1793 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1794 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1795 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1798 $hash{'name'} = $cust_main->name;
1800 } elsif ( $svcdb eq 'svc_phone' ) {
1801 # could potentially show lots of things...
1802 $hash{'outbound'} = 1;
1803 $hash{'inbound'} = 0;
1804 if ( $part_pkg->plan eq 'voip_inbound' ) {
1805 $hash{'outbound'} = 0;
1806 $hash{'inbound'} = 1;
1807 } elsif ( $part_pkg->option('selfservice_inbound_format')
1808 or $conf->config('selfservice-default_inbound_cdr_format')
1810 $hash{'inbound'} = 1;
1812 foreach (qw(inbound outbound)) {
1813 # hmm...we can't filter by status here, because there might
1814 # not be cdr_terminations at all. have to go by date.
1815 # find all since the last bill date.
1816 # XXX cdr types? we are going to need them.
1818 my $sum_cdr = $svc_x->sum_cdrs(
1819 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1820 'begin' => ($cust_pkg->last_bill || 0),
1823 $hash{$_} = $sum_cdr->hashref;
1828 # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1839 map { $usage_pools{$_} }
1847 sub _customer_svc_x {
1848 my($custnum, $svcnum, $table) = (shift, shift, shift);
1849 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1851 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1852 my $search = " AND custnum = $1";
1853 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1856 'table' => ($table || 'svc_acct'),
1857 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1858 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1859 #'LEFT JOIN cust_main USING ( custnum ) ',
1860 'hashref' => $hashref,
1861 'extra_sql' => $search, #important
1866 sub svc_status_html {
1869 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1870 return { 'error' => $session } if $context eq 'error';
1872 #XXX only svc_dsl for now
1873 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1874 or return { 'error' => "Service not found" };
1876 my $html = $svc_x->getstatus_html;
1878 return { 'html' => $html };
1882 sub svc_status_hash {
1885 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1886 return { 'error' => $session } if $context eq 'error';
1888 #XXX only svc_acct for now
1889 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1890 or return { 'error' => "Service not found" };
1892 my ( $html, $hashref ) = $svc_x->export_getstatus;
1897 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1898 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1899 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1900 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1901 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1904 my( $p, $method ) = @_;
1906 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1907 return { 'error' => $session } if $context eq 'error';
1909 #XXX only svc_acct for now
1910 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1911 or return { 'error' => "Service not found" };
1913 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1915 my $error = $svc_x->$method($p); #$p? returns error?
1916 return { 'error' => $error } if $error;
1918 return {}; #? { 'error' => '' }
1922 sub acct_forward_info {
1925 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1926 return { 'error' => $session } if $context eq 'error';
1928 my $svc_forward = _customer_svc_x( $custnum,
1929 { 'srcsvc' => $p->{'svcnum'} },
1932 or return { 'error' => '',
1936 return { 'error' => '',
1937 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1942 sub process_acct_forward {
1944 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1945 return { 'error' => $session } if $context eq 'error';
1947 my $old = _customer_svc_x( $custnum,
1948 { 'srcsvc' => $p->{'svcnum'} },
1952 if ( $p->{'dst'} eq '' ) {
1954 my $error = $old->delete;
1955 return { 'error' => $error };
1957 return { 'error' => '' };
1960 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1961 'dst' => $p->{'dst'},
1966 $new->svcnum($old->svcnum);
1967 my $cust_svc = $old->cust_svc;
1968 $new->svcpart($old->svcpart);
1969 $new->pkgnuym($old->pkgnum);
1970 $error = $new->replace($old);
1972 my $conf = new FS::Conf;
1973 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1975 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1976 or return { 'error' => 'No service' }; #how would we even get here?
1978 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
1980 $error = $new->insert;
1983 return { 'error' => $error };
1987 sub list_dsl_devices {
1990 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1991 return { 'error' => $session } if $context eq 'error';
1993 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1994 or return { 'error' => "Service not found" };
1997 'devices' => [ map {
1998 +{ 'mac_addr' => $_->mac_addr };
1999 } $svc_dsl->dsl_device
2005 sub add_dsl_device {
2008 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2009 return { 'error' => $session } if $context eq 'error';
2011 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2012 or return { 'error' => "Service not found" };
2014 return { 'error' => 'No MAC address supplied' }
2015 unless length($p->{'mac_addr'});
2017 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2018 'mac_addr' => scalar($p->{'mac_addr'}),
2020 my $error = $dsl_device->insert;
2021 return { 'error' => $error };
2025 sub delete_dsl_device {
2028 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2029 return { 'error' => $session } if $context eq 'error';
2031 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2032 or return { 'error' => "Service not found" };
2034 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2035 'mac_addr' => scalar($p->{'mac_addr'}),
2038 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2040 my $error = $dsl_device->delete;
2041 return { 'error' => $error };
2047 _usage_details( \&_port_graph, $p,
2048 'svcdb' => 'svc_port',
2053 my($svc_port, $begin, $end) = @_;
2055 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2056 push @usage, { 'png' => $pngOrError };
2060 sub _list_svc_usage {
2061 my($svc_acct, $begin, $end) = @_;
2063 foreach my $part_export (
2064 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2065 qw( sqlradius sqlradius_withdomain )
2067 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2072 sub list_svc_usage {
2073 _usage_details(\&_list_svc_usage, @_);
2076 sub _list_support_usage {
2077 my($svc_acct, $begin, $end) = @_;
2079 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2080 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2082 push @usage, { 'seconds' => $_->seconds,
2083 'support' => $_->support,
2084 '_date' => $_->_date,
2085 'id' => $_->transaction_id,
2086 'creator' => $_->creator,
2087 'subject' => $_->subject,
2088 'status' => $_->status,
2089 'ticketid' => $_->ticketid,
2095 sub list_support_usage {
2096 _usage_details(\&_list_support_usage, @_);
2099 sub _list_cdr_usage {
2100 # XXX CDR type support...
2101 # XXX any way to do a paged search on this?
2102 # we have to return the results all at once...
2103 my($svc_phone, $begin, $end, %opt) = @_;
2104 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2105 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, %opt );
2108 sub list_cdr_usage {
2110 _usage_details( \&_list_cdr_usage, $p,
2111 'svcdb' => 'svc_phone',
2115 sub _usage_details {
2116 my($callback, $p, %opt) = @_;
2118 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2119 return { 'error' => $session } if $context eq 'error';
2121 my $search = { 'svcnum' => $p->{'svcnum'} };
2122 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2124 my $svcdb = $opt{'svcdb'} || 'svc_acct';
2126 my $svc_x = qsearchs( $svcdb, $search );
2127 return { 'error' => 'No service selected in list_svc_usage' }
2130 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2131 my $freq = $cust_pkg->part_pkg->freq;
2134 if ( $svcdb eq 'svc_phone' ) {
2135 my $conf = FS::Conf->new;
2137 if ( $p->{inbound} ) {
2138 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2139 || $conf->config('selfservice-default_inbound_cdr_format')
2140 || 'source_default';
2141 $callback_opt{inbound} = 1;
2143 $format = $cust_pkg->part_pkg->option('selfservice_format')
2144 || $conf->config('selfservice-default_cdr_format')
2148 $callback_opt{format} = $format;
2149 $callback_opt{use_clid} = 1;
2150 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2153 my $start = $cust_pkg->setup;
2154 #my $end = $cust_pkg->bill; # or time?
2157 unless ( $p->{beginning} ) {
2158 $p->{beginning} = $cust_pkg->last_bill;
2159 $p->{ending} = $end;
2162 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2163 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2165 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2169 #kinda false laziness with FS::cust_main::bill, but perhaps
2170 #we should really change this bit to DateTime and DateTime::Duration
2172 #change this bit to use Date::Manip? CAREFUL with timezones (see
2173 # mailing list archive)
2174 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2175 (localtime($p->{ending}) )[0,1,2,3,4,5];
2176 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2177 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2179 if ( $freq =~ /^\d+$/ ) {
2181 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2183 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2184 } elsif ( $freq =~ /^(\d+)w$/ ) {
2186 $nmday += $weeks * 7;
2187 $pmday -= $weeks * 7;
2188 } elsif ( $freq =~ /^(\d+)d$/ ) {
2192 } elsif ( $freq =~ /^(\d+)h$/ ) {
2197 return { 'error' => "unparsable frequency: ". $freq };
2200 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2201 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2205 'svcnum' => $p->{svcnum},
2206 'beginning' => $p->{beginning},
2207 'ending' => $p->{ending},
2208 'inbound' => $p->{inbound},
2209 'previous' => ($previous > $start) ? $previous : $start,
2210 'next' => ($next < $end) ? $next : $end,
2211 'header' => $header,
2219 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2220 return { 'error' => $session } if $context eq 'error';
2222 my $search = { 'custnum' => $custnum };
2223 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2224 my $cust_main = qsearchs('cust_main', $search )
2225 or return { 'error' => "unknown custnum $custnum" };
2227 my $status = $cust_main->status;
2228 #false laziness w/ClientAPI/Signup.pm
2230 my $cust_pkg = new FS::cust_pkg ( {
2231 'custnum' => $custnum,
2232 'pkgpart' => $p->{'pkgpart'},
2234 my $error = $cust_pkg->check;
2235 return { 'error' => $error } if $error;
2238 unless ( $p->{'svcpart'} eq 'none' ) {
2242 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2244 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2245 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2246 $svcdb = $part_svc->svcdb;
2248 $svcdb = 'svc_acct';
2250 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2253 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2254 'svc_domain' => [ qw( domain ) ],
2255 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2256 'svc_external' => [ qw( id title ) ],
2257 'svc_pbx' => [ qw( id title ) ],
2260 my $svc_x = "FS::$svcdb"->new( {
2261 'svcpart' => $svcpart,
2262 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2265 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2268 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2269 my $acct_snarf = new FS::acct_snarf ( {
2270 'machine' => $p->{"snarf_machine$snarfnum"},
2271 'protocol' => $p->{"snarf_protocol$snarfnum"},
2272 'username' => $p->{"snarf_username$snarfnum"},
2273 '_password' => $p->{"snarf_password$snarfnum"},
2276 push @acct_snarf, $acct_snarf;
2278 $svc_x->child_objects( \@acct_snarf );
2281 my $y = $svc_x->setdefault; # arguably should be in new method
2282 return { 'error' => $y } if $y && !ref($y);
2284 $error = $svc_x->check;
2285 return { 'error' => $error } if $error;
2292 tie my %hash, 'Tie::RefHash';
2293 %hash = ( $cust_pkg => \@svc );
2295 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2296 return { 'error' => $error } if $error;
2298 my $conf = new FS::Conf;
2299 if ( $conf->exists('signup_server-realtime') ) {
2301 my $bill_error = _do_bop_realtime( $cust_main, $status );
2304 $cust_pkg->cancel('quiet'=>1);
2307 $cust_pkg->reexport;
2311 $cust_pkg->reexport;
2314 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2316 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2323 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2324 return { 'error' => $session } if $context eq 'error';
2326 my $search = { 'custnum' => $custnum };
2327 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2328 my $cust_main = qsearchs('cust_main', $search )
2329 or return { 'error' => "unknown custnum $custnum" };
2331 my $status = $cust_main->status;
2332 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2333 or return { 'error' => "unknown package $p->{pkgnum}" };
2335 #if someone does need self-service package change of suspended packages,
2336 # figure out how to be more discriminating
2337 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2338 if $cust_pkg->status eq 'suspended';
2341 my $error = FS::cust_pkg::order( $custnum,
2347 my $conf = new FS::Conf;
2348 if ( $conf->exists('signup_server-realtime') ) {
2350 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2353 $newpkg[0]->suspend;
2356 $newpkg[0]->reexport;
2360 $newpkg[0]->reexport;
2363 return { error => '', pkgnum => $cust_pkg->pkgnum };
2367 sub order_recharge {
2370 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2371 return { 'error' => $session } if $context eq 'error';
2373 my $search = { 'custnum' => $custnum };
2374 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2375 my $cust_main = qsearchs('cust_main', $search )
2376 or return { 'error' => "unknown custnum $custnum" };
2378 my $status = $cust_main->status;
2379 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2380 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2382 my $svc_x = $cust_svc->svc_x;
2383 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2386 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2387 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2388 recharge_totalbytes );
2389 my $amount = $part_pkg->option('recharge_amount', 1);
2391 my ($l, $v, $d) = $cust_svc->label; # blah
2392 my $pkg = "Recharge $v";
2394 my $bill_error = $cust_main->charge($amount, $pkg,
2395 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2396 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2397 $part_pkg->taxclass); #meh
2399 my $conf = new FS::Conf;
2400 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2402 $bill_error = _do_bop_realtime( $cust_main, $status );
2407 my $error = $svc_x->recharge (\%vhash);
2408 return { 'error' => $error } if $error;
2412 my $error = $bill_error;
2413 $error ||= $svc_x->recharge (\%vhash);
2414 return { 'error' => $error } if $error;
2417 return { error => '', svc => $cust_svc->part_svc->svc };
2421 sub _do_bop_realtime {
2422 my ($cust_main, $status, %opt) = @_;
2424 my $old_balance = $cust_main->balance;
2426 my $bill_error = $cust_main->bill
2427 || $cust_main->apply_payments_and_credits;
2429 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2430 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2432 if ( $cust_main->balance > $old_balance
2433 && $cust_main->balance > 0
2434 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2435 || $status eq 'suspended'
2439 unless ( $opt{'no_credit'} ) {
2440 #this makes sense. credit is "un-doing" the invoice
2441 my $conf = new FS::Conf;
2442 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2443 'self-service decline',
2444 reason_type=>$conf->config('signup_credit_type'),
2446 $cust_main->apply_credits( 'order' => 'newest' );
2449 return { 'error' => '_decline', 'bill_error' => $bill_error };
2458 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2459 return { 'error' => $session } if $context eq 'error';
2461 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2462 or return { 'error' => "unknown custnum $custnum" };
2464 my @cust_pkg = sort { $a->bill <=> $b->bill }
2465 grep { $_->part_pkg->freq ne '0' }
2466 $cust_main->ncancelled_pkgs;
2468 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2470 my $total = $cust_main->balance;
2473 my $bill = $_->bill;
2474 $total += $_->part_pkg->base_recur($_, \$bill);
2475 my $renew_date = $_->part_pkg->add_freq($_->bill);
2477 'pkgnum' => $_->pkgnum,
2478 'amount' => sprintf('%.2f', $total),
2479 'bill_date' => $_->bill,
2480 'bill_date_pretty' => time2str('%x', $_->bill),
2481 'renew_date' => $renew_date,
2482 'renew_date_pretty' => time2str('%x', $renew_date),
2483 'expire_date' => $_->expire,
2484 'expire_date_pretty' => time2str('%x', $_->expire),
2489 return { 'dates' => \@array };
2493 sub payment_info_renew_info {
2495 my $renew_info = renew_info($p);
2496 my $payment_info = payment_info($p);
2497 return { %$renew_info,
2505 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2506 return { 'error' => $session } if $context eq 'error';
2508 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2509 or return { 'error' => "unknown custnum $custnum" };
2511 my $date = $p->{'date'};
2515 #freeside-daily -n -d $date fs_daily $custnum
2516 $cust_main->bill_and_collect( 'time' => $date,
2517 'invoice_time' => $now,
2518 'actual_time' => $now,
2519 'check_freq' => '1d',
2522 return { 'error' => '' };
2528 my $session = _cache->get($p->{'session_id'})
2529 or return { 'error' => "Can't resume session" }; #better error message
2531 my $custnum = $session->{'custnum'};
2533 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2534 or return { 'error' => "unknown custnum $custnum" };
2536 my $conf = new FS::Conf;
2538 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2539 or return { 'error' => 'Permission denied' };
2541 my $pkgnum = $p->{'pkgnum'};
2543 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2544 'pkgnum' => $pkgnum, } )
2545 or return { 'error' => "unknown pkgnum $pkgnum" };
2547 my $error = $cust_pkg->suspend(reason => $reasonnum);
2548 return { 'error' => $error };
2554 my $session = _cache->get($p->{'session_id'})
2555 or return { 'error' => "Can't resume session" }; #better error message
2557 my $custnum = $session->{'custnum'};
2559 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2560 or return { 'error' => "unknown custnum $custnum" };
2562 my $pkgnum = $p->{'pkgnum'};
2564 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2565 'pkgnum' => $pkgnum, } )
2566 or return { 'error' => "unknown pkgnum $pkgnum" };
2568 my $error = $cust_pkg->cancel('quiet' => 1);
2569 return { 'error' => $error };
2573 sub provision_phone {
2576 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2578 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2579 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2580 return { 'error' => $session } if $context eq 'error';
2582 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2583 return { 'error' => 'service not found' } unless $svc_phone;
2584 return { 'error' => 'invalid svcnum' }
2585 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2587 $svc_phone->email($p->{'email'})
2588 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2589 $svc_phone->forwarddst($p->{'forwarddst'})
2590 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2591 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2592 return { 'error' => $svc_phone->replace };
2596 unless($p->{'lnp'}) {
2597 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2598 $p->{'lnp_status'} = "portingin";
2599 return _provision( 'FS::svc_phone',
2600 [qw(lnp_desired_due_date lnp_other_provider
2601 lnp_other_provider_account phonenum countrycode lnp_status)],
2602 [qw(phonenum countrycode)],
2609 unless (scalar(@bulkdid)) {
2610 return _provision( 'FS::svc_phone',
2611 [qw(phonenum countrycode)],
2612 [qw(phonenum countrycode)],
2618 # bulk DID order case
2620 foreach my $did ( @bulkdid ) {
2621 $did =~ s/[^0-9]//g;
2622 $error = _provision( 'FS::svc_phone',
2623 [qw(phonenum countrycode)],
2624 [qw(phonenum countrycode)],
2626 'pkgnum' => $p->{'pkgnum'},
2627 'svcpart' => $p->{'svcpart'},
2629 'countrycode' => $p->{'countrycode'},
2630 'session_id' => $p->{'session_id'},
2633 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2635 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2638 sub provision_acct {
2640 warn "provision_acct called\n"
2643 return { 'error' => gettext('passwords_dont_match') }
2644 if $p->{'_password'} ne $p->{'_password2'};
2645 return { 'error' => gettext('empty_password') }
2646 unless length($p->{'_password'});
2648 if ($p->{'domsvc'}) {
2649 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2650 qw ( svcpart pkgnum ) );
2651 return { 'error' => gettext('invalid_domain') }
2652 unless ($domains{$p->{'domsvc'}});
2655 warn "provision_acct calling _provision\n"
2657 _provision( 'FS::svc_acct',
2658 [qw(username _password domsvc)],
2659 [qw(username _password domsvc)],
2665 sub provision_external {
2667 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2668 _provision( 'FS::svc_external',
2677 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2678 warn "_provision called for $class\n"
2681 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2682 return { 'error' => $session } if $context eq 'error';
2684 my $search = { 'custnum' => $custnum };
2685 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2686 my $cust_main = qsearchs('cust_main', $search )
2687 or return { 'error' => "unknown custnum $custnum" };
2689 my $pkgnum = $p->{'pkgnum'};
2691 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2693 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2694 'pkgnum' => $pkgnum,
2696 or return { 'error' => "unknown pkgnum $pkgnum" };
2698 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2700 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2701 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2703 warn "creating $class record\n"
2705 my $svc_x = $class->new( {
2706 'pkgnum' => $p->{'pkgnum'},
2707 'svcpart' => $p->{'svcpart'},
2708 map { $_ => $p->{$_} } @$fields
2710 warn "inserting $class record\n"
2712 my $error = $svc_x->insert;
2715 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2717 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2720 my $return = { 'svc' => $part_svc->svc,
2722 map { $_ => $svc_x->get($_) } @$return_fields
2724 warn "_provision returning ". Dumper($return). "\n"
2733 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2734 return { 'error' => $session } if $context eq 'error';
2736 my $search = { 'custnum' => $custnum };
2737 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2738 my $cust_main = qsearchs('cust_main', $search )
2739 or return { 'error' => "unknown custnum $custnum" };
2741 my $pkgnum = $p->{'pkgnum'};
2743 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2744 'pkgnum' => $pkgnum,
2746 or return { 'error' => "unknown pkgnum $pkgnum" };
2748 my $svcpart = $p->{'svcpart'};
2750 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2751 'svcpart' => $svcpart, } )
2752 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2753 my $part_svc = $pkg_svc->part_svc;
2755 my $conf = new FS::Conf;
2758 'svc' => $part_svc->svc,
2759 'svcdb' => $part_svc->svcdb,
2760 'pkgnum' => $pkgnum,
2761 'svcpart' => $svcpart,
2762 'custnum' => $custnum,
2764 'security_phrase' => 0, #XXX !
2765 'svc_acct_pop' => [], #XXX !
2767 'init_popstate' => '',
2772 small_custview( $cust_main, $conf->config('countrydefault') ),
2776 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2777 && $ret->{'svcdb'} eq 'svc_phone') {
2778 $ret->{'svcnum'} = $p->{'svcnum'};
2779 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2780 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2781 $ret->{'email'} = $svc_phone->email;
2782 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2789 sub unprovision_svc {
2792 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2793 return { 'error' => $session } if $context eq 'error';
2795 my $search = { 'custnum' => $custnum };
2796 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2797 my $cust_main = qsearchs('cust_main', $search )
2798 or return { 'error' => "unknown custnum $custnum" };
2800 my $svcnum = $p->{'svcnum'};
2802 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2803 or return { 'error' => "unknown svcnum $svcnum" };
2805 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2806 unless $cust_svc->cust_pkg->custnum == $custnum;
2808 my $conf = new FS::Conf;
2810 return { 'svc' => $cust_svc->part_svc->svc,
2811 'error' => $cust_svc->cancel,
2813 small_custview( $cust_main, $conf->config('countrydefault') ),
2818 sub myaccount_passwd {
2820 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2821 return { 'error' => $session } if $context eq 'error';
2823 return { 'error' => "New passwords don't match." }
2824 if $p->{'new_password'} ne $p->{'new_password2'};
2826 return { 'error' => 'Enter new password' }
2827 unless length($p->{'new_password'});
2829 #my $search = { 'custnum' => $custnum };
2830 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2831 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2832 my $search = " AND custnum = $1";
2833 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2835 my $svc_acct = qsearchs( {
2836 'table' => 'svc_acct',
2837 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2838 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2839 'LEFT JOIN cust_main USING ( custnum ) ',
2840 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2841 'extra_sql' => $search, #important
2843 or return { 'error' => "Service not found" };
2847 my $conf = new FS::Conf;
2848 $error = 'Password too short.'
2849 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2850 $error = 'Password too long.'
2851 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2853 $svc_acct->set_password($p->{'new_password'});
2854 $error ||= $svc_acct->replace();
2856 my($label, $value) = $svc_acct->cust_svc->label;
2858 return { 'error' => $error,
2865 #regular pw change in self-service should change contact pw too, otherwise its way too confusing. hell its confusing they're separate at all, but alas. need to support the "ISP provides email that's used as a contact email" case as well as we can.
2866 # sub contact_passwd {
2868 # my($context, $session, $custnum) = _custoragent_session_custnum($p);
2869 # return { 'error' => $session } if $context eq 'error';
2871 # return { 'error' => 'Not logged in as a contact.' }
2872 # unless $session->{'contactnum'};
2874 # return { 'error' => "New passwords don't match." }
2875 # if $p->{'new_password'} ne $p->{'new_password2'};
2877 # return { 'error' => 'Enter new password' }
2878 # unless length($p->{'new_password'});
2880 # #my $search = { 'custnum' => $custnum };
2881 # #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2882 # $custnum =~ /^(\d+)$/ or die "illegal custnum";
2883 # my $search = " AND selfservice_access IS NOT NULL ".
2884 # " AND selfservice_access = 'Y' ".
2885 # " AND ( disabled IS NULL OR disabled = '' )".
2886 # " AND custnum IS NOT NULL AND custnum = $1";
2887 # $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2889 # my $contact = qsearchs( {
2890 # 'table' => 'contact',
2891 # 'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
2892 # 'hashref' => { 'contactnum' => $session->{'contactnum'}, },
2893 # 'extra_sql' => $search, #important
2895 # or return { 'error' => "Email not found" }; #? how did we get logged in?
2896 # # deleted since then?
2900 # # use these svc_acct length restrictions??
2901 # my $conf = new FS::Conf;
2902 # $error = 'Password too short.'
2903 # if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2904 # $error = 'Password too long.'
2905 # if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2907 # $error ||= $contact->change_password($p->{'new_password'});
2909 # return { 'error' => $error, };
2916 my $conf = new FS::Conf;
2917 my $verification = $conf->config('selfservice-password_reset_verification')
2918 or return { 'error' => 'Password resets disabled' };
2923 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
2925 $contact = FS::contact->by_selfservice_email($p->{'email'});
2927 $cust_main = $contact->cust_main if $contact;
2929 #also look for an svc_acct, otherwise it would be super confusing
2931 my($username, $domain) = split('@', $p->{'email'});
2932 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
2933 if ( $svc_domain ) {
2934 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2935 'domsvc' => $svc_domain->svcnum }
2938 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
2939 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
2941 #precaution: don't change svc_acct password not part of the same
2942 # customer as contact
2943 $svc_acct = '' if ! $cust_pkg
2944 || $cust_pkg->custnum != $cust_main->custnum;
2949 return { 'error' => 'Email address not found' }
2950 unless $contact || $svc_acct;
2952 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
2954 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2955 or return { 'error' => 'Account not found' };
2957 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2958 'domsvc' => $svc_domain->svcnum }
2960 or return { 'error' => 'Account not found' };
2962 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2963 or return { 'error' => 'Account not found' };
2965 $cust_main = $cust_pkg->cust_main;
2970 'email' => sub { 1; },
2972 my( $p, $cust_main ) = @_;
2973 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2974 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2977 my( $p, $cust_main ) = @_;
2978 my $cust_pay = qsearchs({
2979 'table' => 'cust_pay',
2980 'hashref' => { 'custnum' => $cust_main->custnum },
2981 'order_by' => 'ORDER BY _date DESC LIMIT 1',
2985 $p->{'amount'} == $cust_pay->paid;
2988 my( $p, $cust_main ) = @_;
2989 $p->{'zip'} eq $cust_main->zip
2990 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2994 foreach my $verify ( split(',', $verification) ) {
2996 &{ $verify{$verify} }( $p, $cust_main )
2997 or return { 'error' => 'Account not found' };
3001 #okay, we're verified
3005 my $error = $contact->send_reset_email(
3006 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3010 return { 'error' => $error }; #????
3013 } elsif ( $svc_acct ) {
3015 #create a unique session
3017 my $reset_session = {
3018 'svcnum' => $svc_acct->svcnum,
3021 my $timeout = '1 hour'; #?
3023 my $reset_session_id;
3025 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3026 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3029 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3033 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3034 $cust_main->agentnum);
3035 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3036 return { 'error' => "selfservice-password_reset_msgnum unset" }
3038 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3039 my $error = $msg_template->send( 'cust_main' => $cust_main,
3040 'object' => $svc_acct,
3041 'substitutions' => {
3042 'session_id' => $reset_session_id,
3046 return { 'error' => $error }; #????
3051 return { 'error' => '' };
3054 sub check_reset_passwd {
3057 my $conf = new FS::Conf;
3058 my $verification = $conf->config('selfservice-password_reset_verification')
3059 or return { 'error' => 'Password resets disabled' };
3061 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3062 or return { 'error' => "Can't resume session" }; #better error message
3064 if ( $reset_session->{'svcnum'} ) {
3066 my $svcnum = $reset_session->{'svcnum'};
3068 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3069 or return { 'error' => "Service not found" };
3071 return { 'error' => '',
3072 'session_id' => $p->{'session_id'},
3073 'username' => $svc_acct->username,
3076 } elsif ( $reset_session->{'contactnum'} ) {
3078 my $contactnum = $reset_session->{'contactnum'};
3080 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3081 or return { 'error' => "Contact not found" };
3083 my @contact_email = $contact->contact_email;
3084 return { 'error' => 'No contact email' } unless @contact_email;
3086 return { 'error' => '',
3087 'session_id' => $p->{'session_id'},
3088 'email' => $contact_email[0]->email, #the first?
3093 return { 'error' => 'No svcnum or contactnum in session' }; #??
3099 sub process_reset_passwd {
3102 my $conf = new FS::Conf;
3103 my $verification = $conf->config('selfservice-password_reset_verification')
3104 or return { 'error' => 'Password resets disabled' };
3106 return { 'error' => "New passwords don't match." }
3107 if $p->{'new_password'} ne $p->{'new_password2'};
3109 return { 'error' => 'Enter new password' }
3110 unless length($p->{'new_password'});
3112 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3113 or return { 'error' => "Can't resume session" }; #better error message
3115 if ( $reset_session->{'svcnum'} ) {
3117 my $svcnum = $reset_session->{'svcnum'};
3119 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3120 or return { 'error' => "Service not found" };
3122 $svc_acct->set_password($p->{'new_password'});
3123 my $error = $svc_acct->replace();
3125 return { 'error' => $error } if $error;
3127 #my($label, $value) = $svc_acct->cust_svc->label;
3128 #return { 'error' => $error,
3129 # #'label' => $label,
3130 # #'value' => $value,
3135 if ( $reset_session->{'contactnum'} ) {
3137 my $contactnum = $reset_session->{'contactnum'};
3139 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3140 or return { 'error' => "Contact not found" };
3142 my $error = $contact->change_password($p->{'new_password'});
3144 return { 'error' => $error }; # if $error;
3148 #password changed ,so remove session, don't want it reused
3149 _cache->remove($p->{'session_id'});
3151 return { 'error' => '' };
3157 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3158 return { 'error' => $session } if $context eq 'error';
3160 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3161 FS::TicketSystem->init();
3163 my $conf = new FS::Conf;
3164 my $queue = $p->{'queue'}
3165 || $conf->config('ticket_system-selfservice_queueid')
3166 || $conf->config('ticket_system-default_queueid');
3168 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3169 my $err_or_ticket = FS::TicketSystem->create_ticket(
3170 '', #create RT session based on FS CurrentUser (fs_selfservice)
3172 'custnum' => $custnum,
3173 'svcnum' => $session->{'svcnum'},
3174 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3177 if ( ref($err_or_ticket) ) {
3178 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3180 return { 'error' => '',
3181 'ticket_id' => $err_or_ticket->id,
3184 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3186 return { 'error' => $err_or_ticket };
3194 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3195 return { 'error' => $session } if $context eq 'error';
3197 return { error => 'requested format not implemented' }
3198 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3200 my $conf = new FS::Conf;
3201 my $age_threshold = 0;
3202 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3203 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3205 my $search = { 'custnum' => $custnum };
3206 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3207 my $cust_main = qsearchs('cust_main', $search )
3208 or return { 'error' => "unknown custnum $custnum" };
3210 # does it make more sense to just run one sql query for this instead of all the
3211 # insanity below? would increase performance greately for large data sets?
3213 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3214 my @part_svc = $cust_pkg->part_svc;
3215 foreach my $part_svc ( @part_svc ) {
3216 if($part_svc->svcdb eq 'svc_phone'){
3217 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3218 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3219 push @svc_phone, $cust_pkg_svc->svc_x
3220 if $cust_pkg_svc->date_inserted >= $age_threshold;
3228 my($xls_r,$xls_c) = (0,0);
3231 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3232 if($p->{'format'} eq 'csv') {
3233 $csv = new Text::CSV_XS { 'always_quote' => 1,
3236 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3237 $content .= $csv->string;
3239 elsif($p->{'format'} eq 'xls') {
3240 my $XLS1 = new IO::Scalar \$content;
3241 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3242 or return { 'error' => "Error opening .xls file: $!" };
3243 $xls = $xls_workbook->add_worksheet('DIDs');
3244 foreach ( @fields ) {
3245 $xls->write(0,$xls_c++,$_);
3250 foreach my $svc_phone ( @svc_phone ) {
3251 my @cols = map { $svc_phone->$_ } @fields;
3252 if($p->{'format'} eq 'csv') {
3253 return { 'error' => 'Unable to create CSV' }
3254 unless $csv->combine(@cols);
3255 $content .= $csv->string;
3257 elsif($p->{'format'} eq 'xls') {
3260 $xls->write($xls_r,$xls_c++,$_);
3266 $xls_workbook->close() if $p->{'format'} eq 'xls';
3268 { content => $content, format => $p->{'format'}, };
3273 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3274 return { 'error' => $session } if $context eq 'error';
3276 warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3277 FS::TicketSystem->init();
3278 return { 'error' => 'get_ticket configuration error' }
3279 if $FS::TicketSystem::system ne 'RT_Internal';
3281 # check existence and ownership as part of this
3282 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3283 my $rt_session = FS::TicketSystem->session('');
3284 my $Ticket = FS::TicketSystem->get_ticket_object(
3286 ticket_id => $p->{'ticket_id'},
3289 return { 'error' => 'ticket not found' } if !$Ticket;
3291 if ( length( $p->{'subject'} || '' ) ) {
3293 if ( $p->{'subject'} ne $Ticket->Subject ) {
3294 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3295 return { 'error' => "unable to set subject: $msg" } if !$val;
3299 if(length($p->{'reply'})) {
3300 my @err_or_res = FS::TicketSystem->correspond_ticket(
3302 'ticket_id' => $p->{'ticket_id'},
3303 'content' => $p->{'reply'},
3306 return { 'error' => 'unable to reply to ticket' }
3307 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3310 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3311 my $err_or_ticket = FS::TicketSystem->get_ticket(
3313 'ticket_id' => $p->{'ticket_id'},
3316 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3317 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3319 return { 'error' => $err_or_ticket };
3322 my @custs = @{$err_or_ticket->{'custs'}};
3323 my @txns = @{$err_or_ticket->{'txns'}};
3326 # superseded by check in get_ticket_object
3327 #return { 'error' => 'invalid ticket requested' }
3328 #unless grep($_ eq $custnum, @custs);
3330 foreach my $txn ( @txns ) {
3331 push @filtered_txns, $txn
3332 if ($txn->{'type'} eq 'EmailRecord'
3333 || $txn->{'type'} eq 'Correspond'
3334 || $txn->{'type'} eq 'Create');
3337 warn "$me get_ticket: successful: \n"
3339 return { 'error' => '',
3340 'transactions' => \@filtered_txns,
3341 'ticket_fields' => $err_or_ticket->{'fields'},
3342 'ticket_id' => $p->{'ticket_id'},
3346 sub adjust_ticket_priority {
3348 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3349 return { 'error' => $session } if $context eq 'error';
3351 warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3352 FS::TicketSystem->init;
3353 my $ss_priority = FS::TicketSystem->selfservice_priority;
3355 return { 'error' => 'adjust_ticket_priority configuration error' }
3356 if $FS::TicketSystem::system ne 'RT_Internal'
3359 my $values = $p->{'values'}; #hashref, id => priority value
3362 foreach my $id (keys %$values) {
3363 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3364 my $Ticket = FS::TicketSystem->get_ticket_object('',
3366 'custnum' => $custnum,
3369 $ticket_error{$id} = 'ticket not found';
3373 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3374 # We're not going to implement it for RT_External.
3375 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3376 my $new_value = $values->{$id};
3377 next if $old_value eq $new_value;
3379 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3381 # AddCustomFieldValue works fine (replacing any existing value) if it's
3382 # a single-valued custom field, which it should be. If it's not, you're
3383 # doing something wrong.
3385 if ( length($new_value) ) {
3386 ($val, $msg) = $Ticket->AddCustomFieldValue(
3387 Field => $ss_priority,
3388 Value => $new_value,
3392 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3393 Field => $ss_priority,
3394 Value => $old_value,
3398 $ticket_error{$id} = $msg if !$val;
3399 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3401 return { 'error' => '',
3402 'ticket_error' => \%ticket_error,
3403 %{ customer_info($p) } # send updated customer info back
3409 sub _custoragent_session_custnum {
3412 my($context, $session, $custnum);
3413 if ( $p->{'session_id'} ) {
3415 $context = 'customer';
3416 $session = _cache->get($p->{'session_id'})
3417 or return ( 'error' => "Can't resume session" ); #better error message
3418 $custnum = $session->{'custnum'};
3420 } elsif ( $p->{'agent_session_id'} ) {
3423 my $agent_cache = new FS::ClientAPI_SessionCache( {
3424 'namespace' => 'FS::ClientAPI::Agent',
3426 $session = $agent_cache->get($p->{'agent_session_id'})
3427 or return ( 'error' => "Can't resume session" ); #better error message
3428 $custnum = $p->{'custnum'};
3432 return ( 'error' => "Can't resume session" ); #better error message
3435 ($context, $session, $custnum);