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;
50 $me = '[FS::ClientAPI::MyAccount]';
52 use vars qw( @cust_main_editable_fields @location_editable_fields );
53 @cust_main_editable_fields = qw(
54 first last company daytime night fax mobile
56 payby payinfo payname paystart_month paystart_year payissue payip
57 ss paytype paystate stateid stateid_state
59 @location_editable_fields = qw(
60 address1 address2 city county state zip country
64 BEGIN { #preload to reduce time customer_info takes
65 if ( $FS::TicketSystem::system ) {
66 warn "$me: initializing ticket system\n" if $DEBUG;
67 FS::TicketSystem->init();
72 $cache ||= new FS::ClientAPI_SessionCache( {
73 'namespace' => 'FS::ClientAPI::MyAccount',
80 my($context, $session, $custnum) = _custoragent_session_custnum($p);
81 #return { 'error' => $session } if $context eq 'error';
84 if ( $context eq 'customer' ) {
86 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
89 $sth->execute($custnum) or die $sth->errstr;
91 $agentnum = $sth->fetchrow_arrayref->[0]
92 or die "no agentnum for custnum $custnum";
94 #} elsif ( $context eq 'agent' ) {
95 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
99 my $conf = new FS::Conf;
101 #false laziness w/Signup.pm
103 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
105 if ( $skin_info_cache_agent ) {
107 warn "$me loading cached skin info for agentnum $agentnum\n"
112 warn "$me populating skin info cache for agentnum $agentnum\n"
115 $skin_info_cache_agent = {
116 'agentnum' => $agentnum,
117 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
118 qw( company_name date_format ) ),
119 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
120 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
121 text_color link_color vlink_color hlink_color alink_color
122 font title_color title_align title_size menu_bgcolor menu_fontsize
125 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
126 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
127 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
129 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
130 qw( title_left_image title_right_image
131 menu_top_image menu_body_image menu_bottom_image
134 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
135 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
136 qw( head body_header body_footer company_address ) ),
137 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
140 services.php Services
141 services.php My Services
142 services_new.php Order a new service
145 personal.php Personal Information
146 password.php Change Password
149 payment_cc.php Credit Card Payment
150 payment_ach.php Electronic Check Payment
151 payment_paypal.php PayPal Payment
152 payment_webpay.php Webpay Payments
155 usage_data.php Data usage
156 usage_cdr.php Call usage
158 tickets.php Help Desk
159 tickets.php Open Tickets
160 tickets_resolved.php Resolved Tickets
161 ticket_create.php Create a new ticket
169 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
173 #{ %$skin_info_cache_agent };
174 $skin_info_cache_agent;
181 my $conf = new FS::Conf;
185 'phone_login' => $conf->exists('selfservice_server-phone_login'),
186 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
187 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
188 'banner_image_md5' =>
189 md5_hex($conf->config_binary('selfservice-login_banner_image')),
196 sub login_banner_image {
198 my $conf = new FS::Conf;
199 my $image = $conf->config_binary('selfservice-login_banner_image');
201 'md5' => md5_hex($image),
206 #false laziness w/FS::ClientAPI::passwd::passwd
210 my $conf = new FS::Conf;
213 if ( $p->{'domain'} eq 'svc_phone'
214 && $conf->exists('selfservice_server-phone_login') ) {
216 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
217 return { error => 'Number not found.' } unless $svc_phone;
220 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
221 #return { error => 'Only primary user may log in.' }
222 # if $conf->exists('selfservice_server-primary_only')
223 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
225 return { error => 'Incorrect PIN.' }
226 unless $svc_phone->check_pin($p->{'password'});
232 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
233 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
235 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
236 'domsvc' => $svc_domain->svcnum, }
238 return { error => 'User not found.' } unless $svc_acct;
240 if($conf->exists('selfservice_server-login_svcpart')) {
241 my @svcpart = $conf->config('selfservice_server-login_svcpart');
242 my $svcpart = $svc_acct->cust_svc->svcpart;
243 return { error => 'Invalid user.' }
244 unless grep($_ eq $svcpart, @svcpart);
247 return { error => 'Incorrect password.' }
248 unless $svc_acct->check_password($p->{'password'});
255 'svcnum' => $svc_x->svcnum,
258 my $cust_svc = $svc_x->cust_svc;
259 my $cust_pkg = $cust_svc->cust_pkg;
261 my $cust_main = $cust_pkg->cust_main;
262 $session->{'custnum'} = $cust_main->custnum;
263 if ( $conf->exists('pkg-balances') ) {
264 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
265 $cust_main->ncancelled_pkgs;
266 $session->{'pkgnum'} = $cust_pkg->pkgnum
267 if scalar(@cust_pkg) > 1;
271 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
272 #return { error => 'Only primary user may log in.' }
273 # if $conf->exists('selfservice_server-primary_only')
274 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
275 my $part_pkg = $cust_pkg->part_pkg;
276 return { error => 'Only primary user may log in.' }
277 if $conf->exists('selfservice_server-primary_only')
278 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
282 $session_id = sha512_hex(time(). {}. rand(). $$)
283 } until ( ! defined _cache->get($session_id) ); #just in case
285 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
286 _cache->set( $session_id, $session, $timeout );
288 return { 'error' => '',
289 'session_id' => $session_id,
295 if ( $p->{'session_id'} ) {
296 _cache->remove($p->{'session_id'});
297 return { %{ skin_info($p) }, 'error' => '' };
299 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
306 my($context, $session, $custnum) = _custoragent_session_custnum($p);
307 return { 'error' => $session } if $context eq 'error';
309 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
310 or return { 'error' => "Service not found" };
312 $session->{'svcnum'} = $svc_acct->svcnum;
314 my $conf = new FS::Conf;
315 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
316 _cache->set( $p->{'session_id'}, $session, $timeout );
318 return { 'error' => '' };
322 sub payment_gateway {
324 # takes a cust_main and a cust_payby entry, returns the payment_gateway
325 my $conf = new FS::Conf;
326 my $cust_main = shift;
327 my $cust_payby = shift;
328 my $gatewaynum = $conf->config('selfservice-payment_gateway');
330 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
331 die "configured gatewaynum $gatewaynum not found!" if !$pg;
335 return '' if ! FS::payby->realtime($cust_payby);
336 my $pg = $cust_main->agent->payment_gateway(
337 'method' => FS::payby->payby2bop($cust_payby),
347 my $conf = new FS::Conf;
349 my $info = skin_info($p);
351 use vars qw( $cust_paybys ); #cache for performance
352 unless ( $cust_paybys ) {
354 my %cust_paybys = map { $_ => 1 }
355 map { FS::payby->payby2payment($_) }
356 $conf->config('signup_server-payby');
358 $cust_paybys = [ keys %cust_paybys ];
361 $info->{'cust_paybys'} = $cust_paybys;
363 my($context, $session, $custnum) = _custoragent_session_custnum($p);
364 return { 'error' => $session } if $context eq 'error';
366 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
367 or return { 'error' => "unknown custnum $custnum" };
369 $info->{'hide_payment_fields'} = [
371 my $pg = payment_gateway($cust_main, $_);
372 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
373 } @{ $info->{cust_paybys} }
376 $info->{'self_suspend_reason'} =
377 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
379 $info->{'edit_ticket_subject'} =
380 $conf->exists('ticket_system-selfservice_edit_subject') &&
381 $cust_main->edit_subject;
383 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
386 'custnum' => $custnum,
387 'access_pkgnum' => $session->{'pkgnum'},
388 'access_svcnum' => $session->{'svcnum'},
395 my($context, $session, $custnum) = _custoragent_session_custnum($p);
396 return { 'error' => $session } if $context eq 'error';
400 my $conf = new FS::Conf;
401 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
403 # if ( $FS::TicketSystem::system ) {
404 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
405 # FS::TicketSystem->init();
408 if ( $custnum ) { #customer record
410 %return = ( %return, %{ customer_info_short($p) } );
412 #redundant with customer_info_short, but we need it for several things below
413 my $search = { 'custnum' => $custnum };
414 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
415 my $cust_main = qsearchs('cust_main', $search )
416 or return { 'error' => "unknown custnum $custnum" };
418 my $list_tickets = list_tickets($p);
419 $return{'tickets'} = $list_tickets->{'tickets'};
421 if ( $session->{'pkgnum'} ) {
422 #XXX open invoices in the pkg-balances case
426 invnum => $_->invnum,
427 date => time2str("%b %o, %Y", $_->_date),
430 } $cust_main->open_cust_bill;
431 $return{open_invoices} = \@open;
433 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
434 my $sth = dbh->prepare($sql) or die dbh->errstr;
435 $sth->execute($custnum) or die $sth->errstr;
436 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
437 $return{'last_invoice_date_pretty'} =
438 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
441 #customer_info_short always has nobalance on..
442 $return{small_custview} =
443 small_custview( $cust_main,
444 $return{countrydefault},
445 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
448 $return{has_ship_address} = $cust_main->has_ship_address;
449 $return{status} = $cust_main->status;
450 $return{statuscolor} = $cust_main->statuscolor;
452 # compatibility: some places in selfservice use this to determine
453 # if there's a ship address
454 if ( $return{has_ship_address} ) {
455 $return{ship_last} = $cust_main->last;
456 $return{ship_first} = $cust_main->first;
459 if (scalar($conf->config('support_packages'))) {
460 my @support_services = ();
461 foreach ($cust_main->support_services) {
462 my $seconds = $_->svc_x->seconds || 0;
463 my $time_remaining = (($seconds < 0) ? '-' : '' ).
464 int(abs($seconds)/3600)."h".
465 sprintf("%02d",(abs($seconds)%3600)/60)."m";
466 my $cust_pkg = $_->cust_pkg;
469 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
470 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
471 push @support_services, { svcnum => $_->svcnum,
472 time => $time_remaining,
477 $return{support_services} = \@support_services;
480 if ( $conf->config('prepayment_discounts-credit_type') ) {
482 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
485 } elsif ( $session->{'svcnum'} ) { #no customer record
487 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
488 or die "unknown svcnum";
489 $return{name} = $svc_acct->email;
493 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
497 return { 'error' => '',
498 'custnum' => $custnum,
504 sub customer_info_short {
507 my($context, $session, $custnum) = _custoragent_session_custnum($p);
508 return { 'error' => $session } if $context eq 'error';
512 my $conf = new FS::Conf;
514 if ( $custnum ) { #customer record
516 my $search = { 'custnum' => $custnum };
517 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
518 my $cust_main = qsearchs('cust_main', $search )
519 or return { 'error' => "unknown custnum $custnum" };
521 $return{display_custnum} = $cust_main->display_custnum;
523 if ( $session->{'pkgnum'} ) {
524 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
525 #next_bill_date from cust_pkg?
527 $return{balance} = $cust_main->balance;
528 $return{next_bill_date} = $cust_main->next_bill_date;
529 $return{next_bill_date_pretty} =
530 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
534 $return{countrydefault} = scalar($conf->config('countrydefault'));
536 $return{small_custview} =
537 small_custview( $cust_main,
538 $return{countrydefault},
542 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
544 $return{payby} = $cust_main->payby;
546 #none of these are terribly expensive if we want 'em...
547 for (@cust_main_editable_fields) {
548 $return{$_} = $cust_main->get($_);
550 #maybe a little more expensive, but it should be cached by now
551 for (@location_editable_fields) {
552 $return{$_} = $cust_main->bill_location->get($_);
553 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
556 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
557 $return{payinfo} = $cust_main->paymask;
558 @return{'month', 'year'} = $cust_main->paydate_monthyear;
561 my @invoicing_list = $cust_main->invoicing_list;
562 $return{'invoicing_list'} =
563 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
564 $return{'postal_invoicing'} =
565 0 < ( grep { $_ eq 'POST' } @invoicing_list );
567 if ( $session->{'svcnum'} ) {
568 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
569 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
570 $return{'svcnum'} = $session->{'svcnum'};
573 } elsif ( $session->{'svcnum'} ) { #no customer record
575 #uuh, not supproted yet... die?
576 return { 'error' => 'customer_info_short not yet supported as agent' };
580 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
584 return { 'error' => '',
585 'custnum' => $custnum,
590 sub billing_history {
593 my($context, $session, $custnum) = _custoragent_session_custnum($p);
594 return { 'error' => $session } if $context eq 'error';
596 return { 'error' => 'No customer' } unless $custnum;
598 my $search = { 'custnum' => $custnum };
599 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
600 my $cust_main = qsearchs('cust_main', $search )
601 or return { 'error' => "unknown custnum $custnum" };
605 if ( $session->{'pkgnum'} ) {
606 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
607 #next_bill_date from cust_pkg?
608 return { 'error' => 'No history for package' };
611 $return{balance} = $cust_main->balance;
612 $return{next_bill_date} = $cust_main->next_bill_date;
613 $return{next_bill_date_pretty} =
614 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
619 my $conf = new FS::Conf;
621 if ( $conf->exists('selfservice-billing_history-line_items') ) {
623 foreach my $cust_bill ( $cust_main->cust_bill ) {
626 'type' => 'Line item',
627 'description' => $_->desc( $cust_main->locale ).
628 ( $_->sdate && $_->edate
629 ? ' '. time2str('%d-%b-%Y', $_->sdate).
630 ' To '. time2str('%d-%b-%Y', $_->edate)
633 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
634 'date' => $cust_bill->_date,
635 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
637 foreach $cust_bill->cust_bill_pkg;
645 'description' => 'Invoice #'. $_->display_invnum,
646 'amount' => sprintf('%.2f', $_->charged ),
648 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
650 foreach $cust_main->cust_bill;
656 'description' => 'Payment', #XXX type
657 'amount' => sprintf('%.2f', 0 - $_->paid ),
659 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
661 foreach $cust_main->cust_pay;
665 'description' => 'Credit', #more info?
666 'amount' => sprintf('%.2f', 0 -$_->amount ),
668 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
670 foreach $cust_main->cust_credit;
674 'description' => 'Refund', #more info? type, like payment?
675 'amount' => $_->refund,
677 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
679 foreach $cust_main->cust_refund;
681 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
683 $return{'history'} = \@history;
691 my $session = _cache->get($p->{'session_id'})
692 or return { 'error' => "Can't resume session" }; #better error message
694 my $custnum = $session->{'custnum'}
695 or return { 'error' => "no customer record" };
697 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
698 or return { 'error' => "unknown custnum $custnum" };
700 my $new = new FS::cust_main { $cust_main->hash };
702 $new->set( $_ => $p->{$_} )
703 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
705 if ( exists($p->{address1}) ) {
706 my $bill_location = FS::cust_location->new({
707 map { $_ => $p->{$_} } @location_editable_fields
709 # if this is unchanged from before, cust_main::replace will ignore it
710 $new->set('bill_location' => $bill_location);
713 if ( exists($p->{ship_address1}) ) {
714 my $ship_location = FS::cust_location->new({
715 map { $_ => $p->{"ship_$_"} } @location_editable_fields
717 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
718 # Selfservice unfortunately tries to indicate "same as billing
719 # address" by sending all fields empty. Did this ever work?
720 $ship_location = $cust_main->bill_location;
722 $new->set('ship_location' => $ship_location);
724 # but if it hasn't been passed in at all, leave ship_location alone--
725 # DON'T change it to match bill_location.
728 if (exists($p->{'payby'})) {
729 $p->{'payby'} =~ /^([A-Z]{4})$/
730 or return { 'error' => "illegal_payby " . $p->{'payby'} };
734 if ( $payby =~ /^(CARD|DCRD)$/ ) {
736 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
738 if ( $new->payinfo eq $cust_main->paymask ) {
739 $new->payinfo($cust_main->payinfo);
741 $new->payinfo($p->{'payinfo'});
744 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
746 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
749 $p->{'payinfo1'} =~ /^([\dx]+)$/
750 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
752 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
753 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
755 $payinfo = $payinfo1. '@'. $payinfo2;
757 $new->payinfo( ($payinfo eq $cust_main->paymask)
758 ? $cust_main->payinfo
762 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
764 } elsif ( $payby =~ /^(BILL)$/ ) {
766 } elsif ( $payby ) { #notyet ready
767 return { 'error' => "unknown payby $payby" };
771 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
772 #false laziness with httemplate/edit/process/cust_main.cgi
773 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
774 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
776 @invoicing_list = $cust_main->invoicing_list;
779 my $error = $new->replace($cust_main, \@invoicing_list);
780 return { 'error' => $error } if $error;
783 return { 'error' => '' };
788 my $session = _cache->get($p->{'session_id'})
789 or return { 'error' => "Can't resume session" }; #better error message
795 my $conf = new FS::Conf;
796 use vars qw($payment_info); #cache for performance
797 unless ( $payment_info ) {
799 my %states = map { $_->state => 1 }
800 qsearch('cust_main_county', {
801 'country' => $conf->config('countrydefault') || 'US'
804 my %cust_paybys = map { $_ => 1 }
805 map { FS::payby->payby2payment($_) }
806 $conf->config('signup_server-payby');
808 my @cust_paybys = keys %cust_paybys;
812 #list all counties/states/countries
813 'cust_main_county' =>
814 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
816 #shortcut for one-country folks
818 [ sort { $a cmp $b } keys %states ],
820 'card_types' => card_types(),
822 'paytypes' => [ @FS::cust_main::paytypes ],
824 'paybys' => [ $conf->config('signup_server-payby') ],
825 'cust_paybys' => \@cust_paybys,
827 'stateid_label' => FS::Msgcat::_gettext('stateid'),
828 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
830 'show_ss' => $conf->exists('show_ss'),
831 'show_stateid' => $conf->exists('show_stateid'),
832 'show_paystate' => $conf->exists('show_bankstate'),
834 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
836 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
845 my %return = %$payment_info;
847 my $custnum = $session->{'custnum'};
849 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
850 or return { 'error' => "unknown custnum $custnum" };
852 $return{'hide_payment_fields'} = [
854 my $pg = payment_gateway($cust_main, $_);
855 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
856 } @{ $return{cust_paybys} }
859 $return{balance} = $cust_main->balance; #XXX pkg-balances?
861 $return{payname} = $cust_main->payname
862 || ( $cust_main->first. ' '. $cust_main->get('last') );
864 $return{$_} = $cust_main->bill_location->get($_)
865 for qw(address1 address2 city state zip);
867 $return{payby} = $cust_main->payby;
868 $return{stateid_state} = $cust_main->stateid_state;
870 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
871 $return{card_type} = cardtype($cust_main->payinfo);
872 $return{payinfo} = $cust_main->paymask;
874 @return{'month', 'year'} = $cust_main->paydate_monthyear;
878 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
879 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
880 $return{payinfo1} = $payinfo1;
881 $return{payinfo2} = $payinfo2;
882 $return{paytype} = $cust_main->paytype;
883 $return{paystate} = $cust_main->paystate;
884 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
887 if ( $conf->config('prepayment_discounts-credit_type') ) {
889 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
892 #doubleclick protection
894 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
896 return { 'error' => '',
902 #some false laziness with httemplate/process/payment.cgi - look there for
903 #ACH and CVV support stuff
905 sub validate_payment {
908 my $session = _cache->get($p->{'session_id'})
909 or return { 'error' => "Can't resume session" }; #better error message
911 my $custnum = $session->{'custnum'};
913 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
914 or return { 'error' => "unknown custnum $custnum" };
916 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
917 or return { 'error' => gettext('illegal_amount') };
919 return { error => 'Amount must be greater than 0' } unless $amount > 0;
921 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
922 #changing the hidden form values
923 my $conf = new FS::Conf;
924 my $fee_display = $conf->config('selfservice_process-display') || 'add';
925 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
926 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
927 if ( $fee_display eq 'add'
929 and ! $fee_skip_first || scalar($cust_main->cust_pay)
932 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
933 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
936 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
937 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
938 my $discount_term = $1;
940 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
941 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
944 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
945 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
948 $p->{'payby'} ||= 'CARD';
949 $p->{'payby'} =~ /^([A-Z]{4})$/
950 or return { 'error' => "illegal_payby " . $p->{'payby'} };
953 #false laziness w/process/payment.cgi
956 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
958 $p->{'payinfo1'} =~ /^([\dx]+)$/
959 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
961 $p->{'payinfo2'} =~ /^([\dx]+)$/
962 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
964 $payinfo = $payinfo1. '@'. $payinfo2;
966 $payinfo = $cust_main->payinfo
967 if $cust_main->paymask eq $payinfo;
969 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
971 $payinfo = $p->{'payinfo'};
973 #more intelligent matching will be needed here if you change
974 #card_masking_method and don't remove existing paymasks
975 $payinfo = $cust_main->payinfo
976 if $cust_main->paymask eq $payinfo;
979 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
980 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
984 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
985 return { 'error' => gettext('unknown_card_type') }
986 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
988 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
989 if ( cardtype($payinfo) eq 'American Express card' ) {
990 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
991 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
994 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
995 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1001 die "unknown payby $payby";
1004 my %payby2fields = (
1005 'CARD' => [ qw( paystart_month paystart_year payissue payip
1006 address1 address2 city state zip country ) ],
1007 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1011 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1014 'cust_main' => $cust_main, #XXX or just custnum??
1015 'amount' => sprintf('%.2f', $amount),
1017 'payinfo' => $payinfo,
1018 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1019 'card_type' => $card_type,
1020 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1021 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1022 'month' => $p->{'month'},
1023 'year' => $p->{'year'},
1024 'payname' => $payname,
1025 'paybatch' => $paybatch, #this doesn't actually do anything
1026 'paycvv' => $paycvv,
1027 'payname' => $payname,
1028 'discount_term' => $discount_term,
1029 'pkgnum' => $session->{'pkgnum'},
1030 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1040 my $validate = validate_payment($p);
1041 return $validate if $validate->{'error'};
1043 my $conf = new FS::Conf;
1044 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1045 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1047 +{ map { $_=>$validate->{$_} }
1048 qw( card_type paymask payname paydate_pretty month year amount
1049 address1 address2 city state zip country
1055 sub process_stored_payment {
1058 my $session_id = $p->{'session_id'};
1060 my $payment_info = _cache->get( "payment_$session_id" )
1061 or return { 'error' => "Can't resume session" }; #better error message
1063 do_process_payment($payment_info);
1067 sub process_payment {
1070 my $payment_info = validate_payment($p);
1071 return $payment_info if $payment_info->{'error'};
1073 do_process_payment($payment_info);
1077 sub do_process_payment {
1078 my $validate = shift;
1080 my $cust_main = $validate->{'cust_main'};
1082 my $amount = delete $validate->{'amount'};
1085 my $payby = delete $validate->{'payby'};
1087 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1090 'paynum_ref' => \$paynum,
1093 return { 'error' => $error } if $error;
1095 #no error, so order the fee package if applicable...
1096 my $conf = new FS::Conf;
1097 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1098 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1100 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1102 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1104 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1105 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1108 #and generate an invoice for it now too
1109 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1110 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1115 $cust_main->apply_payments;
1117 if ( $validate->{'save'} ) {
1118 my $new = new FS::cust_main { $cust_main->hash };
1119 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1120 $new->set( $_ => $validate->{$_} )
1121 foreach qw( payname paystart_month paystart_year payissue payip );
1122 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1124 my $bill_location = FS::cust_location->new({
1125 map { $_ => $validate->{$_} }
1126 qw(address1 address2 city state country zip)
1128 $new->set('bill_location' => $bill_location);
1129 # but don't allow the service address to change this way.
1131 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1132 $new->set( $_ => $validate->{$_} )
1133 foreach qw( payname payip paytype paystate
1134 stateid stateid_state );
1135 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1137 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1138 $new->set( 'paydate' => $validate->{'paydate'} );
1139 my $error = $new->replace($cust_main);
1141 #no, this causes customers to process their payments again
1142 #return { 'error' => $error };
1143 #XXX just warn verosely for now so i can figure out how these happen in
1144 # the first place, eventually should redirect them to the "change
1145 #address" page but indicate the payment did process??
1146 delete($validate->{'payinfo'}); #don't want to log this!
1147 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1148 "NEW: ". Dumper($new)."\n".
1149 "OLD: ". Dumper($cust_main)."\n".
1150 "PACKET: ". Dumper($validate)."\n";
1158 my $receipt_html = '';
1160 # currently supported for realtime CC only; send receipt data to SS
1161 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1164 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1167 <TD ALIGN="right">Payment#</TD>
1168 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1172 <TD ALIGN="right">Date</TD>
1174 <TD BGCOLOR="#FFFFFF"><B>! .
1175 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1181 <TD ALIGN="right">Amount</TD>
1182 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1187 <TD ALIGN="right">Payment method</TD>
1188 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1199 my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
1203 'amount' => sprintf('%.2f', $cust_pay->paid),
1204 'date' => $cust_pay->_date,
1205 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1206 'time_pretty' => time2str('%T', $cust_pay->_date),
1207 'auth_num' => $auth,
1208 'order_num' => $order,
1209 'receipt_html' => $receipt_html,
1216 'receipt_html' => '',
1223 sub realtime_collect {
1226 my $session = _cache->get($p->{'session_id'})
1227 or return { 'error' => "Can't resume session" }; #better error message
1229 my $custnum = $session->{'custnum'};
1231 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1232 or return { 'error' => "unknown custnum $custnum" };
1235 if ( $p->{'amount'} ) {
1236 $amount = $p->{'amount'};
1238 elsif ( $session->{'pkgnum'} ) {
1239 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1242 $amount = $cust_main->balance;
1245 my $error = $cust_main->realtime_collect(
1246 'method' => $p->{'method'},
1247 'amount' => $amount,
1248 'pkgnum' => $session->{'pkgnum'},
1249 'session_id' => $p->{'session_id'},
1253 return { 'error' => $error } unless ref( $error );
1255 return { 'error' => '', amount => $amount, %$error };
1258 sub start_thirdparty {
1260 my $session = _cache->get($p->{'session_id'})
1261 or return { 'error' => "Can't resume session" }; #better error message
1262 my $custnum = $session->{'custnum'};
1263 my $cust_main = FS::cust_main->by_key($custnum);
1265 my $amount = $p->{'amount'}
1266 or return { error => 'no amount' };
1268 my $result = $cust_main->create_payment(
1269 'method' => $p->{'method'},
1270 'amount' => $p->{'amount'},
1271 'pkgnum' => $session->{'pkgnum'},
1272 'session_id' => $p->{'session_id'},
1275 if ( ref($result) ) { # hashref or error
1278 return { error => $result };
1282 sub finish_thirdparty {
1284 my $session_id = delete $p->{'session_id'};
1285 my $session = _cache->get($session_id)
1286 or return { 'error' => "Can't resume session" };
1287 my $custnum = $session->{'custnum'};
1288 my $cust_main = FS::cust_main->by_key($custnum);
1290 if ( $p->{_cancel} ) {
1291 # customer backed out of making a payment
1292 return $cust_main->cancel_payment( $session_id );
1294 my $result = $cust_main->execute_payment( $session_id, %$p );
1295 if ( ref($result) ) {
1298 return { error => $result };
1302 sub process_payment_order_pkg {
1305 my $hr = process_payment($p);
1306 return $hr if $hr->{'error'};
1311 sub process_payment_order_renew {
1314 my $hr = process_payment($p);
1315 return $hr if $hr->{'error'};
1320 sub process_prepay {
1324 my $session = _cache->get($p->{'session_id'})
1325 or return { 'error' => "Can't resume session" }; #better error message
1329 my $custnum = $session->{'custnum'};
1331 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1332 or return { 'error' => "unknown custnum $custnum" };
1334 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1335 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1343 return { 'error' => $error } if $error;
1345 return { 'error' => '',
1346 'amount' => $amount,
1347 'seconds' => $seconds,
1348 'duration' => duration_exact($seconds),
1349 'upbytes' => $upbytes,
1350 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1351 'downbytes' => $downbytes,
1352 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1353 'totalbytes'=> $totalbytes,
1354 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1361 my $session = _cache->get($p->{'session_id'})
1362 or return { 'error' => "Can't resume session" }; #better error message
1364 my $custnum = $session->{'custnum'};
1366 my $invnum = $p->{'invnum'};
1368 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1369 'custnum' => $custnum } )
1370 or return { 'error' => "Can't find invnum" };
1374 return { 'error' => '',
1375 'invnum' => $invnum,
1376 'invoice_text' => join('', $cust_bill->print_text ),
1377 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1384 my $session = _cache->get($p->{'session_id'})
1385 or return { 'error' => "Can't resume session" }; #better error message
1387 my $custnum = $session->{'custnum'};
1389 my $invnum = $p->{'invnum'};
1391 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1392 'custnum' => $custnum } )
1393 or return { 'error' => "Can't find invnum" };
1397 return { 'error' => '',
1398 'invnum' => $invnum,
1399 'invoice_pdf' => $cust_bill->print_pdf({
1400 'unsquelch_cdr' => 1,
1401 'locale' => $p->{'locale'},
1407 sub legacy_invoice {
1409 my $session = _cache->get($p->{'session_id'})
1410 or return { 'error' => "Can't resume session" }; #better error message
1412 my $custnum = $session->{'custnum'};
1414 my $legacyinvnum = $p->{'legacyinvnum'};
1417 'legacyinvnum' => $legacyinvnum,
1418 'custnum' => $custnum,
1421 my $legacy_cust_bill =
1422 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1423 || qsearchs('legacy_cust_bill', \%hash )
1424 or return { 'error' => "Can't find legacyinvnum" };
1428 return { 'error' => '',
1429 'legacyinvnum' => $legacyinvnum,
1430 'legacyid' => $legacy_cust_bill->legacyid,
1431 'invoice_html' => $legacy_cust_bill->content_html,
1436 sub legacy_invoice_pdf {
1438 my $session = _cache->get($p->{'session_id'})
1439 or return { 'error' => "Can't resume session" }; #better error message
1441 my $custnum = $session->{'custnum'};
1443 my $legacyinvnum = $p->{'legacyinvnum'};
1445 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1446 'legacyinvnum' => $legacyinvnum,
1447 'custnum' => $custnum,
1448 }) or return { 'error' => "Can't find legacyinvnum" };
1452 return { 'error' => '',
1453 'legacyinvnum' => $legacyinvnum,
1454 'legacyid' => $legacy_cust_bill->legacyid,
1455 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1463 #sessioning for this? how do we get the session id to the backend invoice
1464 # template so it can add it to the link, blah
1467 if ( $p->{'invnum'} ) {
1468 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1469 or return { 'error' => 'unknown invnum' };
1470 $agentnum = $cust_bill->cust_main->agentnum;
1473 my $templatename = $p->{'template'} || $p->{'templatename'};
1475 #false laziness-ish w/view/cust_bill-logo.cgi
1477 my $conf = new FS::Conf;
1478 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1479 $templatename = "_$1";
1484 my $filename = "logo$templatename.png";
1486 return { 'error' => '',
1487 'logo' => $conf->config_binary($filename, $agentnum),
1488 'content_type' => 'image/png', #should allow gif, jpg too
1495 my $session = _cache->get($p->{'session_id'})
1496 or return { 'error' => "Can't resume session" }; #better error message
1498 my $custnum = $session->{'custnum'};
1500 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1501 or return { 'error' => "unknown custnum $custnum" };
1503 my $conf = new FS::Conf;
1505 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1507 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1511 return { 'error' => '',
1512 'balance' => $cust_main->balance,
1515 my $owed = $_->owed;
1517 +{ 'invnum' => $_->invnum,
1518 '_date' => $_->_date,
1519 'date' => time2str("%b %o, %Y", $_->_date),
1520 'date_short' => time2str("%m-%d-%Y", $_->_date),
1521 'previous' => sprintf('%.2f', ($_->previous)[0]),
1522 'charged' => sprintf('%.2f', $_->charged),
1523 'owed' => sprintf('%.2f', $owed),
1524 'balance' => sprintf('%.2f', $balance),
1529 'legacy_invoices' => [
1531 +{ 'legacyinvnum' => $_->legacyinvnum,
1532 'legacyid' => $_->legacyid,
1533 '_date' => $_->_date,
1534 'date' => time2str("%b %o, %Y", $_->_date),
1535 'date_short' => time2str("%m-%d-%Y", $_->_date),
1536 'charged' => sprintf('%.2f', $_->charged),
1537 'has_content' => ( length($_->content_pdf)
1538 || length($_->content_html) ),
1548 my $session = _cache->get($p->{'session_id'})
1549 or return { 'error' => "Can't resume session" }; #better error message
1551 my $custnum = $session->{'custnum'};
1553 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1554 or return { 'error' => "unknown custnum $custnum" };
1556 my @errors = $cust_main->cancel( 'quiet'=>1 );
1558 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1560 return { 'error' => $error };
1567 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1568 return { 'error' => $session } if $context eq 'error';
1570 my $search = { 'custnum' => $custnum };
1571 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1572 my $cust_main = qsearchs('cust_main', $search )
1573 or return { 'error' => "unknown custnum $custnum" };
1575 my $conf = new FS::Conf;
1577 # the duplication below is necessary:
1578 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1579 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1580 # non-backwards-compatible change breaking the software of anyone using the API
1581 # instead of the stock selfservice
1582 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1583 if( $conf->exists('selfservice_server-view-wholesale') ) {
1584 return { 'svcnum' => $session->{'svcnum'},
1585 'custnum' => $custnum,
1586 'cust_pkg' => [ map {
1588 part_pkg => [ map $_->hashref, $_->part_pkg ],
1590 [ map $_->hashref, $_->available_part_svc ],
1592 [ map { my $ref = { $_->hash,
1593 label => [ $_->label ],
1595 $ref->{_password} = $_->svc_x->_password
1596 if $context eq 'agent'
1597 && $conf->exists('agent-showpasswords')
1598 && $_->part_svc->svcdb eq 'svc_acct';
1603 } $cust_main->cust_pkg
1606 small_custview( $cust_main, $conf->config('countrydefault') ),
1607 'wholesale_view' => 1,
1608 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1609 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1610 'lnp' => $conf->exists('svc_phone-lnp'),
1614 { 'svcnum' => $session->{'svcnum'},
1615 'custnum' => $custnum,
1616 'cust_pkg' => [ map {
1617 my $primary_cust_svc = $_->primary_cust_svc;
1620 pkg_label => $_->pkg_locale,
1621 status => $_->status,
1622 statuscolor => $_->statuscolor,
1624 [ map { $_->hashref }
1625 grep { $_->selfservice_access ne 'hidden' }
1626 $_->available_part_svc
1629 [ map { my $ref = { $_->hash,
1630 label => [ $_->label ],
1632 $ref->{_password} = $_->svc_x->_password
1633 if $context eq 'agent'
1634 && $conf->exists('agent-showpasswords')
1635 && $_->part_svc->svcdb eq 'svc_acct';
1636 $ref->{svchash} = { $_->svc_x->hash } if
1637 $_->part_svc->svcdb eq 'svc_phone';
1638 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1639 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1642 grep { $_->part_svc->selfservice_access ne 'hidden' }
1647 ? { $primary_cust_svc->hash,
1648 label => [ $primary_cust_svc->label ],
1649 finger => $primary_cust_svc->svc_x->finger, #uuh
1650 $primary_cust_svc->part_svc->hash,
1654 } $cust_main->ncancelled_pkgs
1657 small_custview( $cust_main, $conf->config('countrydefault') ),
1658 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1666 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1667 return { 'error' => $session } if $context eq 'error';
1669 my $search = { 'custnum' => $custnum };
1670 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1671 my $cust_main = qsearchs('cust_main', $search )
1672 or return { 'error' => "unknown custnum $custnum" };
1674 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1675 if ( ! $pkgnum && $p->{'svcnum'} ) {
1676 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1677 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1681 my @cust_pkg_usage = ();
1682 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1683 foreach my $cust_pkg ( $p->{'ncancelled'}
1684 ? $cust_main->ncancelled_pkgs
1685 : $cust_main->unsuspended_pkgs ) {
1686 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1687 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1688 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1691 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1693 foreach (@cust_pkg_usage) {
1694 my $part = $_->part_pkg_usage;
1695 my $tag = $part->description . ($part->shared ? 1 : 0);
1696 my $row = $usage_pools{$tag}
1697 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1698 $row->[1] += $_->minutes; # minutes remaining
1699 $row->[2] += $part->minutes; # minutes total
1702 if ( $p->{'svcdb'} ) {
1703 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1705 : ref($p->{'svcdb'}) eq 'ARRAY'
1706 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1707 : { $p->{'svcdb'} => 1 };
1708 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1711 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1714 my $conf = new FS::Conf;
1717 'svcnum' => $session->{'svcnum'},
1718 'custnum' => $custnum,
1719 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1720 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1723 my $svc_x = $_->svc_x;
1724 my($label, $value) = $_->label;
1725 my $part_svc = $_->part_svc;
1726 my $svcdb = $part_svc->svcdb;
1727 my $cust_pkg = $_->cust_pkg;
1728 my $part_pkg = $cust_pkg->part_pkg;
1731 'svcnum' => $_->svcnum,
1732 'display_svcnum' => $_->display_svcnum,
1736 'pkg_label' => $cust_pkg->pkg_locale,
1737 'pkg_status' => $cust_pkg->status,
1738 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1741 if ( $svcdb eq 'svc_acct' ) {
1744 'username' => $svc_x->username,
1745 'email' => $svc_x->email,
1746 'finger' => $svc_x->finger,
1747 'seconds' => $svc_x->seconds,
1748 'upbytes' => display_bytecount($svc_x->upbytes),
1749 'downbytes' => display_bytecount($svc_x->downbytes),
1750 'totalbytes' => display_bytecount($svc_x->totalbytes),
1752 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1753 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1754 'recharge_upbytes' =>
1755 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1756 'recharge_downbytes' =>
1757 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1758 'recharge_totalbytes' =>
1759 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1763 } elsif ( $svcdb eq 'svc_dsl' ) {
1764 $hash{'phonenum'} = $svc_x->phonenum;
1765 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1766 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1767 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1770 $hash{'name'} = $cust_main->name;
1772 } elsif ( $svcdb eq 'svc_phone' ) {
1773 # could potentially show lots of things...
1774 $hash{'outbound'} = 1;
1775 $hash{'inbound'} = 0;
1776 if ( $part_pkg->plan eq 'voip_inbound' ) {
1777 $hash{'outbound'} = 0;
1778 $hash{'inbound'} = 1;
1779 } elsif ( $part_pkg->option('selfservice_inbound_format')
1780 or $conf->config('selfservice-default_inbound_cdr_format')
1782 $hash{'inbound'} = 1;
1784 foreach (qw(inbound outbound)) {
1785 # hmm...we can't filter by status here, because there might
1786 # not be cdr_terminations at all. have to go by date.
1787 # find all since the last bill date.
1788 # XXX cdr types? we are going to need them.
1790 my $sum_cdr = $svc_x->sum_cdrs(
1791 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1792 'begin' => ($cust_pkg->last_bill || 0),
1795 $hash{$_} = $sum_cdr->hashref;
1800 # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1811 map { $usage_pools{$_} }
1819 sub _customer_svc_x {
1820 my($custnum, $svcnum, $table) = (shift, shift, shift);
1821 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1823 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1824 my $search = " AND custnum = $1";
1825 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1828 'table' => ($table || 'svc_acct'),
1829 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1830 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1831 #'LEFT JOIN cust_main USING ( custnum ) ',
1832 'hashref' => $hashref,
1833 'extra_sql' => $search, #important
1838 sub svc_status_html {
1841 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1842 return { 'error' => $session } if $context eq 'error';
1844 #XXX only svc_dsl for now
1845 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1846 or return { 'error' => "Service not found" };
1848 my $html = $svc_x->getstatus_html;
1850 return { 'html' => $html };
1854 sub svc_status_hash {
1857 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1858 return { 'error' => $session } if $context eq 'error';
1860 #XXX only svc_acct for now
1861 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1862 or return { 'error' => "Service not found" };
1864 my ( $html, $hashref ) = $svc_x->export_getstatus;
1869 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1870 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1871 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1872 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1873 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1876 my( $p, $method ) = @_;
1878 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1879 return { 'error' => $session } if $context eq 'error';
1881 #XXX only svc_acct for now
1882 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1883 or return { 'error' => "Service not found" };
1885 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1887 my $error = $svc_x->$method($p); #$p? returns error?
1888 return { 'error' => $error } if $error;
1890 return {}; #? { 'error' => '' }
1894 sub acct_forward_info {
1897 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1898 return { 'error' => $session } if $context eq 'error';
1900 my $svc_forward = _customer_svc_x( $custnum,
1901 { 'srcsvc' => $p->{'svcnum'} },
1904 or return { 'error' => '',
1908 return { 'error' => '',
1909 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1914 sub process_acct_forward {
1916 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1917 return { 'error' => $session } if $context eq 'error';
1919 my $old = _customer_svc_x( $custnum,
1920 { 'srcsvc' => $p->{'svcnum'} },
1924 if ( $p->{'dst'} eq '' ) {
1926 my $error = $old->delete;
1927 return { 'error' => $error };
1929 return { 'error' => '' };
1932 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1933 'dst' => $p->{'dst'},
1938 $new->svcnum($old->svcnum);
1939 my $cust_svc = $old->cust_svc;
1940 $new->svcpart($old->svcpart);
1941 $new->pkgnuym($old->pkgnum);
1942 $error = $new->replace($old);
1944 my $conf = new FS::Conf;
1945 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1947 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1948 or return { 'error' => 'No service' }; #how would we even get here?
1950 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
1952 $error = $new->insert;
1955 return { 'error' => $error };
1959 sub list_dsl_devices {
1962 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1963 return { 'error' => $session } if $context eq 'error';
1965 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1966 or return { 'error' => "Service not found" };
1969 'devices' => [ map {
1970 +{ 'mac_addr' => $_->mac_addr };
1971 } $svc_dsl->dsl_device
1977 sub add_dsl_device {
1980 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1981 return { 'error' => $session } if $context eq 'error';
1983 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1984 or return { 'error' => "Service not found" };
1986 return { 'error' => 'No MAC address supplied' }
1987 unless length($p->{'mac_addr'});
1989 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
1990 'mac_addr' => scalar($p->{'mac_addr'}),
1992 my $error = $dsl_device->insert;
1993 return { 'error' => $error };
1997 sub delete_dsl_device {
2000 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2001 return { 'error' => $session } if $context eq 'error';
2003 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2004 or return { 'error' => "Service not found" };
2006 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2007 'mac_addr' => scalar($p->{'mac_addr'}),
2010 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2012 my $error = $dsl_device->delete;
2013 return { 'error' => $error };
2019 _usage_details( \&_port_graph, $p,
2020 'svcdb' => 'svc_port',
2025 my($svc_port, $begin, $end) = @_;
2027 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2028 push @usage, { 'png' => $pngOrError };
2032 sub _list_svc_usage {
2033 my($svc_acct, $begin, $end) = @_;
2035 foreach my $part_export (
2036 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2037 qw( sqlradius sqlradius_withdomain )
2039 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2044 sub list_svc_usage {
2045 _usage_details(\&_list_svc_usage, @_);
2048 sub _list_support_usage {
2049 my($svc_acct, $begin, $end) = @_;
2051 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2052 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2054 push @usage, { 'seconds' => $_->seconds,
2055 'support' => $_->support,
2056 '_date' => $_->_date,
2057 'id' => $_->transaction_id,
2058 'creator' => $_->creator,
2059 'subject' => $_->subject,
2060 'status' => $_->status,
2061 'ticketid' => $_->ticketid,
2067 sub list_support_usage {
2068 _usage_details(\&_list_support_usage, @_);
2071 sub _list_cdr_usage {
2072 # XXX CDR type support...
2073 # XXX any way to do a paged search on this?
2074 # we have to return the results all at once...
2075 my($svc_phone, $begin, $end, %opt) = @_;
2076 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2077 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, %opt );
2080 sub list_cdr_usage {
2082 _usage_details( \&_list_cdr_usage, $p,
2083 'svcdb' => 'svc_phone',
2087 sub _usage_details {
2088 my($callback, $p, %opt) = @_;
2090 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2091 return { 'error' => $session } if $context eq 'error';
2093 my $search = { 'svcnum' => $p->{'svcnum'} };
2094 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2096 my $svcdb = $opt{'svcdb'} || 'svc_acct';
2098 my $svc_x = qsearchs( $svcdb, $search );
2099 return { 'error' => 'No service selected in list_svc_usage' }
2102 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2103 my $freq = $cust_pkg->part_pkg->freq;
2106 if ( $svcdb eq 'svc_phone' ) {
2107 my $conf = FS::Conf->new;
2109 if ( $p->{inbound} ) {
2110 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2111 || $conf->config('selfservice-default_inbound_cdr_format')
2112 || 'source_default';
2113 $callback_opt{inbound} = 1;
2115 $format = $cust_pkg->part_pkg->option('selfservice_format')
2116 || $conf->config('selfservice-default_cdr_format')
2120 $callback_opt{format} = $format;
2121 $callback_opt{use_clid} = 1;
2122 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2125 my $start = $cust_pkg->setup;
2126 #my $end = $cust_pkg->bill; # or time?
2129 unless ( $p->{beginning} ) {
2130 $p->{beginning} = $cust_pkg->last_bill;
2131 $p->{ending} = $end;
2134 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2135 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2137 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2141 #kinda false laziness with FS::cust_main::bill, but perhaps
2142 #we should really change this bit to DateTime and DateTime::Duration
2144 #change this bit to use Date::Manip? CAREFUL with timezones (see
2145 # mailing list archive)
2146 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2147 (localtime($p->{ending}) )[0,1,2,3,4,5];
2148 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2149 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2151 if ( $freq =~ /^\d+$/ ) {
2153 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2155 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2156 } elsif ( $freq =~ /^(\d+)w$/ ) {
2158 $nmday += $weeks * 7;
2159 $pmday -= $weeks * 7;
2160 } elsif ( $freq =~ /^(\d+)d$/ ) {
2164 } elsif ( $freq =~ /^(\d+)h$/ ) {
2169 return { 'error' => "unparsable frequency: ". $freq };
2172 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2173 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2177 'svcnum' => $p->{svcnum},
2178 'beginning' => $p->{beginning},
2179 'ending' => $p->{ending},
2180 'inbound' => $p->{inbound},
2181 'previous' => ($previous > $start) ? $previous : $start,
2182 'next' => ($next < $end) ? $next : $end,
2183 'header' => $header,
2191 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2192 return { 'error' => $session } if $context eq 'error';
2194 my $search = { 'custnum' => $custnum };
2195 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2196 my $cust_main = qsearchs('cust_main', $search )
2197 or return { 'error' => "unknown custnum $custnum" };
2199 my $status = $cust_main->status;
2200 #false laziness w/ClientAPI/Signup.pm
2202 my $cust_pkg = new FS::cust_pkg ( {
2203 'custnum' => $custnum,
2204 'pkgpart' => $p->{'pkgpart'},
2206 my $error = $cust_pkg->check;
2207 return { 'error' => $error } if $error;
2210 unless ( $p->{'svcpart'} eq 'none' ) {
2214 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2216 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2217 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2218 $svcdb = $part_svc->svcdb;
2220 $svcdb = 'svc_acct';
2222 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2225 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2226 'svc_domain' => [ qw( domain ) ],
2227 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2228 'svc_external' => [ qw( id title ) ],
2229 'svc_pbx' => [ qw( id title ) ],
2232 my $svc_x = "FS::$svcdb"->new( {
2233 'svcpart' => $svcpart,
2234 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2237 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2240 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2241 my $acct_snarf = new FS::acct_snarf ( {
2242 'machine' => $p->{"snarf_machine$snarfnum"},
2243 'protocol' => $p->{"snarf_protocol$snarfnum"},
2244 'username' => $p->{"snarf_username$snarfnum"},
2245 '_password' => $p->{"snarf_password$snarfnum"},
2248 push @acct_snarf, $acct_snarf;
2250 $svc_x->child_objects( \@acct_snarf );
2253 my $y = $svc_x->setdefault; # arguably should be in new method
2254 return { 'error' => $y } if $y && !ref($y);
2256 $error = $svc_x->check;
2257 return { 'error' => $error } if $error;
2264 tie my %hash, 'Tie::RefHash';
2265 %hash = ( $cust_pkg => \@svc );
2267 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2268 return { 'error' => $error } if $error;
2270 my $conf = new FS::Conf;
2271 if ( $conf->exists('signup_server-realtime') ) {
2273 my $bill_error = _do_bop_realtime( $cust_main, $status );
2276 $cust_pkg->cancel('quiet'=>1);
2279 $cust_pkg->reexport;
2283 $cust_pkg->reexport;
2286 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2288 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2295 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2296 return { 'error' => $session } if $context eq 'error';
2298 my $search = { 'custnum' => $custnum };
2299 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2300 my $cust_main = qsearchs('cust_main', $search )
2301 or return { 'error' => "unknown custnum $custnum" };
2303 my $status = $cust_main->status;
2304 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2305 or return { 'error' => "unknown package $p->{pkgnum}" };
2307 #if someone does need self-service package change of suspended packages,
2308 # figure out how to be more discriminating
2309 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2310 if $cust_pkg->status eq 'suspended';
2313 my $error = FS::cust_pkg::order( $custnum,
2319 my $conf = new FS::Conf;
2320 if ( $conf->exists('signup_server-realtime') ) {
2322 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2325 $newpkg[0]->suspend;
2328 $newpkg[0]->reexport;
2332 $newpkg[0]->reexport;
2335 return { error => '', pkgnum => $cust_pkg->pkgnum };
2339 sub order_recharge {
2342 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2343 return { 'error' => $session } if $context eq 'error';
2345 my $search = { 'custnum' => $custnum };
2346 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2347 my $cust_main = qsearchs('cust_main', $search )
2348 or return { 'error' => "unknown custnum $custnum" };
2350 my $status = $cust_main->status;
2351 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2352 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2354 my $svc_x = $cust_svc->svc_x;
2355 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2358 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2359 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2360 recharge_totalbytes );
2361 my $amount = $part_pkg->option('recharge_amount', 1);
2363 my ($l, $v, $d) = $cust_svc->label; # blah
2364 my $pkg = "Recharge $v";
2366 my $bill_error = $cust_main->charge($amount, $pkg,
2367 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2368 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2369 $part_pkg->taxclass); #meh
2371 my $conf = new FS::Conf;
2372 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2374 $bill_error = _do_bop_realtime( $cust_main, $status );
2379 my $error = $svc_x->recharge (\%vhash);
2380 return { 'error' => $error } if $error;
2384 my $error = $bill_error;
2385 $error ||= $svc_x->recharge (\%vhash);
2386 return { 'error' => $error } if $error;
2389 return { error => '', svc => $cust_svc->part_svc->svc };
2393 sub _do_bop_realtime {
2394 my ($cust_main, $status, %opt) = @_;
2396 my $old_balance = $cust_main->balance;
2398 my $bill_error = $cust_main->bill
2399 || $cust_main->apply_payments_and_credits;
2401 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2402 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2404 if ( $cust_main->balance > $old_balance
2405 && $cust_main->balance > 0
2406 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2407 || $status eq 'suspended'
2411 unless ( $opt{'no_credit'} ) {
2412 #this makes sense. credit is "un-doing" the invoice
2413 my $conf = new FS::Conf;
2414 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2415 'self-service decline',
2416 reason_type=>$conf->config('signup_credit_type'),
2418 $cust_main->apply_credits( 'order' => 'newest' );
2421 return { 'error' => '_decline', 'bill_error' => $bill_error };
2430 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2431 return { 'error' => $session } if $context eq 'error';
2433 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2434 or return { 'error' => "unknown custnum $custnum" };
2436 my @cust_pkg = sort { $a->bill <=> $b->bill }
2437 grep { $_->part_pkg->freq ne '0' }
2438 $cust_main->ncancelled_pkgs;
2440 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2442 my $total = $cust_main->balance;
2445 my $bill = $_->bill;
2446 $total += $_->part_pkg->base_recur($_, \$bill);
2447 my $renew_date = $_->part_pkg->add_freq($_->bill);
2449 'pkgnum' => $_->pkgnum,
2450 'amount' => sprintf('%.2f', $total),
2451 'bill_date' => $_->bill,
2452 'bill_date_pretty' => time2str('%x', $_->bill),
2453 'renew_date' => $renew_date,
2454 'renew_date_pretty' => time2str('%x', $renew_date),
2455 'expire_date' => $_->expire,
2456 'expire_date_pretty' => time2str('%x', $_->expire),
2461 return { 'dates' => \@array };
2465 sub payment_info_renew_info {
2467 my $renew_info = renew_info($p);
2468 my $payment_info = payment_info($p);
2469 return { %$renew_info,
2477 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2478 return { 'error' => $session } if $context eq 'error';
2480 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2481 or return { 'error' => "unknown custnum $custnum" };
2483 my $date = $p->{'date'};
2487 #freeside-daily -n -d $date fs_daily $custnum
2488 $cust_main->bill_and_collect( 'time' => $date,
2489 'invoice_time' => $now,
2490 'actual_time' => $now,
2491 'check_freq' => '1d',
2494 return { 'error' => '' };
2500 my $session = _cache->get($p->{'session_id'})
2501 or return { 'error' => "Can't resume session" }; #better error message
2503 my $custnum = $session->{'custnum'};
2505 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2506 or return { 'error' => "unknown custnum $custnum" };
2508 my $conf = new FS::Conf;
2510 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2511 or return { 'error' => 'Permission denied' };
2513 my $pkgnum = $p->{'pkgnum'};
2515 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2516 'pkgnum' => $pkgnum, } )
2517 or return { 'error' => "unknown pkgnum $pkgnum" };
2519 my $error = $cust_pkg->suspend(reason => $reasonnum);
2520 return { 'error' => $error };
2526 my $session = _cache->get($p->{'session_id'})
2527 or return { 'error' => "Can't resume session" }; #better error message
2529 my $custnum = $session->{'custnum'};
2531 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2532 or return { 'error' => "unknown custnum $custnum" };
2534 my $pkgnum = $p->{'pkgnum'};
2536 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2537 'pkgnum' => $pkgnum, } )
2538 or return { 'error' => "unknown pkgnum $pkgnum" };
2540 my $error = $cust_pkg->cancel('quiet' => 1);
2541 return { 'error' => $error };
2545 sub provision_phone {
2548 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2550 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2551 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2552 return { 'error' => $session } if $context eq 'error';
2554 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2555 return { 'error' => 'service not found' } unless $svc_phone;
2556 return { 'error' => 'invalid svcnum' }
2557 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2559 $svc_phone->email($p->{'email'})
2560 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2561 $svc_phone->forwarddst($p->{'forwarddst'})
2562 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2563 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2564 return { 'error' => $svc_phone->replace };
2568 unless($p->{'lnp'}) {
2569 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2570 $p->{'lnp_status'} = "portingin";
2571 return _provision( 'FS::svc_phone',
2572 [qw(lnp_desired_due_date lnp_other_provider
2573 lnp_other_provider_account phonenum countrycode lnp_status)],
2574 [qw(phonenum countrycode)],
2581 unless (scalar(@bulkdid)) {
2582 return _provision( 'FS::svc_phone',
2583 [qw(phonenum countrycode)],
2584 [qw(phonenum countrycode)],
2590 # bulk DID order case
2592 foreach my $did ( @bulkdid ) {
2593 $did =~ s/[^0-9]//g;
2594 $error = _provision( 'FS::svc_phone',
2595 [qw(phonenum countrycode)],
2596 [qw(phonenum countrycode)],
2598 'pkgnum' => $p->{'pkgnum'},
2599 'svcpart' => $p->{'svcpart'},
2601 'countrycode' => $p->{'countrycode'},
2602 'session_id' => $p->{'session_id'},
2605 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2607 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2610 sub provision_acct {
2612 warn "provision_acct called\n"
2615 return { 'error' => gettext('passwords_dont_match') }
2616 if $p->{'_password'} ne $p->{'_password2'};
2617 return { 'error' => gettext('empty_password') }
2618 unless length($p->{'_password'});
2620 if ($p->{'domsvc'}) {
2621 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2622 qw ( svcpart pkgnum ) );
2623 return { 'error' => gettext('invalid_domain') }
2624 unless ($domains{$p->{'domsvc'}});
2627 warn "provision_acct calling _provision\n"
2629 _provision( 'FS::svc_acct',
2630 [qw(username _password domsvc)],
2631 [qw(username _password domsvc)],
2637 sub provision_external {
2639 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2640 _provision( 'FS::svc_external',
2649 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2650 warn "_provision called for $class\n"
2653 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2654 return { 'error' => $session } if $context eq 'error';
2656 my $search = { 'custnum' => $custnum };
2657 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2658 my $cust_main = qsearchs('cust_main', $search )
2659 or return { 'error' => "unknown custnum $custnum" };
2661 my $pkgnum = $p->{'pkgnum'};
2663 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2665 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2666 'pkgnum' => $pkgnum,
2668 or return { 'error' => "unknown pkgnum $pkgnum" };
2670 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2672 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2673 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2675 warn "creating $class record\n"
2677 my $svc_x = $class->new( {
2678 'pkgnum' => $p->{'pkgnum'},
2679 'svcpart' => $p->{'svcpart'},
2680 map { $_ => $p->{$_} } @$fields
2682 warn "inserting $class record\n"
2684 my $error = $svc_x->insert;
2687 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2689 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2692 my $return = { 'svc' => $part_svc->svc,
2694 map { $_ => $svc_x->get($_) } @$return_fields
2696 warn "_provision returning ". Dumper($return). "\n"
2705 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2706 return { 'error' => $session } if $context eq 'error';
2708 my $search = { 'custnum' => $custnum };
2709 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2710 my $cust_main = qsearchs('cust_main', $search )
2711 or return { 'error' => "unknown custnum $custnum" };
2713 my $pkgnum = $p->{'pkgnum'};
2715 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2716 'pkgnum' => $pkgnum,
2718 or return { 'error' => "unknown pkgnum $pkgnum" };
2720 my $svcpart = $p->{'svcpart'};
2722 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2723 'svcpart' => $svcpart, } )
2724 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2725 my $part_svc = $pkg_svc->part_svc;
2727 my $conf = new FS::Conf;
2730 'svc' => $part_svc->svc,
2731 'svcdb' => $part_svc->svcdb,
2732 'pkgnum' => $pkgnum,
2733 'svcpart' => $svcpart,
2734 'custnum' => $custnum,
2736 'security_phrase' => 0, #XXX !
2737 'svc_acct_pop' => [], #XXX !
2739 'init_popstate' => '',
2744 small_custview( $cust_main, $conf->config('countrydefault') ),
2748 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2749 && $ret->{'svcdb'} eq 'svc_phone') {
2750 $ret->{'svcnum'} = $p->{'svcnum'};
2751 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2752 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2753 $ret->{'email'} = $svc_phone->email;
2754 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2761 sub unprovision_svc {
2764 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2765 return { 'error' => $session } if $context eq 'error';
2767 my $search = { 'custnum' => $custnum };
2768 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2769 my $cust_main = qsearchs('cust_main', $search )
2770 or return { 'error' => "unknown custnum $custnum" };
2772 my $svcnum = $p->{'svcnum'};
2774 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2775 or return { 'error' => "unknown svcnum $svcnum" };
2777 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2778 unless $cust_svc->cust_pkg->custnum == $custnum;
2780 my $conf = new FS::Conf;
2782 return { 'svc' => $cust_svc->part_svc->svc,
2783 'error' => $cust_svc->cancel,
2785 small_custview( $cust_main, $conf->config('countrydefault') ),
2790 sub myaccount_passwd {
2792 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2793 return { 'error' => $session } if $context eq 'error';
2795 return { 'error' => "New passwords don't match." }
2796 if $p->{'new_password'} ne $p->{'new_password2'};
2798 return { 'error' => 'Enter new password' }
2799 unless length($p->{'new_password'});
2801 #my $search = { 'custnum' => $custnum };
2802 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2803 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2804 my $search = " AND custnum = $1";
2805 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2807 my $svc_acct = qsearchs( {
2808 'table' => 'svc_acct',
2809 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2810 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2811 'LEFT JOIN cust_main USING ( custnum ) ',
2812 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2813 'extra_sql' => $search, #important
2815 or return { 'error' => "Service not found" };
2819 my $conf = new FS::Conf;
2820 $error = 'Password too short.'
2821 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2822 $error = 'Password too long.'
2823 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2825 $svc_acct->set_password($p->{'new_password'});
2826 $error ||= $svc_acct->replace();
2828 my($label, $value) = $svc_acct->cust_svc->label;
2830 return { 'error' => $error,
2840 my $conf = new FS::Conf;
2841 my $verification = $conf->config('selfservice-password_reset_verification')
2842 or return { 'error' => 'Password resets disabled' };
2844 my $username = $p->{'username'};
2846 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2847 or return { 'error' => 'Account not found' };
2849 my $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2850 'domsvc' => $svc_domain->svcnum }
2852 or return { 'error' => 'Account not found' };
2854 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2855 or return { 'error' => 'Account not found' };
2857 my $cust_main = $cust_pkg->cust_main;
2861 my( $p, $cust_main ) = @_;
2862 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2863 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2866 my( $p, $cust_main ) = @_;
2867 my $cust_pay = qsearchs({
2868 'table' => 'cust_pay',
2869 'hashref' => { 'custnum' => $cust_main->custnum },
2870 'order_by' => 'ORDER BY _date DESC LIMIT 1',
2874 $p->{'amount'} == $cust_pay->paid;
2877 my( $p, $cust_main ) = @_;
2878 $p->{'zip'} eq $cust_main->zip
2879 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2883 foreach my $verify ( split(',', $verification) ) {
2885 &{ $verify{$verify} }( $p, $cust_main )
2886 or return { 'error' => 'Account not found' };
2890 #okay, we're verified, now create a unique session
2892 my $reset_session = {
2893 'svcnum' => $svc_acct->svcnum,
2896 my $timeout = '1 hour'; #?
2898 my $reset_session_id;
2900 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
2901 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") ); #just in case
2903 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
2907 my $msgnum = $conf->config('selfservice-password_reset_msgnum', $cust_main->agentnum);
2908 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
2909 return { 'error' => "selfservice-password_reset_msgnum unset" } unless $msgnum;
2910 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
2911 my $error = $msg_template->send( 'cust_main' => $cust_main,
2912 'object' => $svc_acct,
2913 'substitutions' => {
2914 'session_id' => $reset_session_id,
2918 return { 'error' => $error }; #????
2921 return { 'error' => '' };
2924 sub check_reset_passwd {
2927 my $conf = new FS::Conf;
2928 my $verification = $conf->config('selfservice-password_reset_verification')
2929 or return { 'error' => 'Password resets disabled' };
2931 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2932 or return { 'error' => "Can't resume session" }; #better error message
2934 my $svcnum = $reset_session->{'svcnum'};
2936 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2937 or return { 'error' => "Service not found" };
2939 return { 'error' => '',
2940 'username' => $svc_acct->username,
2945 sub process_reset_passwd {
2948 my $conf = new FS::Conf;
2949 my $verification = $conf->config('selfservice-password_reset_verification')
2950 or return { 'error' => 'Password resets disabled' };
2952 return { 'error' => "New passwords don't match." }
2953 if $p->{'new_password'} ne $p->{'new_password2'};
2955 return { 'error' => 'Enter new password' }
2956 unless length($p->{'new_password'});
2958 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2959 or return { 'error' => "Can't resume session" }; #better error message
2961 my $svcnum = $reset_session->{'svcnum'};
2963 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2964 or return { 'error' => "Service not found" };
2966 $svc_acct->set_password($p->{'new_password'});
2967 my $error = $svc_acct->replace();
2969 my($label, $value) = $svc_acct->cust_svc->label;
2971 return { 'error' => $error,
2980 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2981 return { 'error' => $session } if $context eq 'error';
2984 if ( $session->{'pkgnum'} ) {
2986 #tickets for specific service with pkg-balances on
2987 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2988 'pkgnum' => $session->{'pkgnum'} })
2989 or return { 'error' => 'unknown package' };
2990 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
2991 push @tickets, $cust_svc->tickets( $p->{status} );
2996 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2997 or return { 'error' => "unknown custnum $custnum" };
2999 @tickets = $cust_main->tickets( $p->{status} );
3002 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3003 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3004 my $conf = new FS::Conf;
3005 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3009 ($a->{'_selfservice_priority'} eq '') <=>
3010 ($b->{'_selfservice_priority'} eq '')
3013 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3019 +{ tickets => \@tickets };
3026 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3027 return { 'error' => $session } if $context eq 'error';
3029 # warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3030 # FS::TicketSystem->init();
3032 my $conf = new FS::Conf;
3033 my $queue = $p->{'queue'}
3034 || $conf->config('ticket_system-selfservice_queueid')
3035 || $conf->config('ticket_system-default_queueid');
3037 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3038 my $err_or_ticket = FS::TicketSystem->create_ticket(
3039 '', #create RT session based on FS CurrentUser (fs_selfservice)
3041 'custnum' => $custnum,
3042 'svcnum' => $session->{'svcnum'},
3043 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3046 if ( ref($err_or_ticket) ) {
3047 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3049 return { 'error' => '',
3050 'ticket_id' => $err_or_ticket->id,
3053 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3055 return { 'error' => $err_or_ticket };
3063 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3064 return { 'error' => $session } if $context eq 'error';
3066 return { error => 'requested format not implemented' }
3067 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3069 my $conf = new FS::Conf;
3070 my $age_threshold = 0;
3071 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3072 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3074 my $search = { 'custnum' => $custnum };
3075 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3076 my $cust_main = qsearchs('cust_main', $search )
3077 or return { 'error' => "unknown custnum $custnum" };
3079 # does it make more sense to just run one sql query for this instead of all the
3080 # insanity below? would increase performance greately for large data sets?
3082 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3083 my @part_svc = $cust_pkg->part_svc;
3084 foreach my $part_svc ( @part_svc ) {
3085 if($part_svc->svcdb eq 'svc_phone'){
3086 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3087 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3088 push @svc_phone, $cust_pkg_svc->svc_x
3089 if $cust_pkg_svc->date_inserted >= $age_threshold;
3097 my($xls_r,$xls_c) = (0,0);
3100 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3101 if($p->{'format'} eq 'csv') {
3102 $csv = new Text::CSV_XS { 'always_quote' => 1,
3105 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3106 $content .= $csv->string;
3108 elsif($p->{'format'} eq 'xls') {
3109 my $XLS1 = new IO::Scalar \$content;
3110 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3111 or return { 'error' => "Error opening .xls file: $!" };
3112 $xls = $xls_workbook->add_worksheet('DIDs');
3113 foreach ( @fields ) {
3114 $xls->write(0,$xls_c++,$_);
3119 foreach my $svc_phone ( @svc_phone ) {
3120 my @cols = map { $svc_phone->$_ } @fields;
3121 if($p->{'format'} eq 'csv') {
3122 return { 'error' => 'Unable to create CSV' }
3123 unless $csv->combine(@cols);
3124 $content .= $csv->string;
3126 elsif($p->{'format'} eq 'xls') {
3129 $xls->write($xls_r,$xls_c++,$_);
3135 $xls_workbook->close() if $p->{'format'} eq 'xls';
3137 { content => $content, format => $p->{'format'}, };
3142 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3143 return { 'error' => $session } if $context eq 'error';
3145 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3146 # FS::TicketSystem->init();
3147 # return { 'error' => 'get_ticket configuration error' }
3148 # if $FS::TicketSystem::system ne 'RT_Internal';
3150 # check existence and ownership as part of this
3151 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3152 my $rt_session = FS::TicketSystem->session('');
3153 my $Ticket = FS::TicketSystem->get_ticket_object(
3155 ticket_id => $p->{'ticket_id'},
3158 return { 'error' => 'ticket not found' } if !$Ticket;
3160 if ( length( $p->{'subject'} || '' ) ) {
3162 if ( $p->{'subject'} ne $Ticket->Subject ) {
3163 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3164 return { 'error' => "unable to set subject: $msg" } if !$val;
3168 if(length($p->{'reply'})) {
3169 my @err_or_res = FS::TicketSystem->correspond_ticket(
3171 'ticket_id' => $p->{'ticket_id'},
3172 'content' => $p->{'reply'},
3175 return { 'error' => 'unable to reply to ticket' }
3176 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3179 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3180 my $err_or_ticket = FS::TicketSystem->get_ticket(
3182 'ticket_id' => $p->{'ticket_id'},
3185 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3186 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3188 return { 'error' => $err_or_ticket };
3191 my @custs = @{$err_or_ticket->{'custs'}};
3192 my @txns = @{$err_or_ticket->{'txns'}};
3195 # superseded by check in get_ticket_object
3196 #return { 'error' => 'invalid ticket requested' }
3197 #unless grep($_ eq $custnum, @custs);
3199 foreach my $txn ( @txns ) {
3200 push @filtered_txns, $txn
3201 if ($txn->{'type'} eq 'EmailRecord'
3202 || $txn->{'type'} eq 'Correspond'
3203 || $txn->{'type'} eq 'Create');
3206 warn "$me get_ticket: successful: \n"
3208 return { 'error' => '',
3209 'transactions' => \@filtered_txns,
3210 'ticket_fields' => $err_or_ticket->{'fields'},
3211 'ticket_id' => $p->{'ticket_id'},
3215 sub adjust_ticket_priority {
3217 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3218 return { 'error' => $session } if $context eq 'error';
3220 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3221 # FS::TicketSystem->init;
3222 my $ss_priority = FS::TicketSystem->selfservice_priority;
3224 return { 'error' => 'adjust_ticket_priority configuration error' }
3225 if $FS::TicketSystem::system ne 'RT_Internal'
3228 my $values = $p->{'values'}; #hashref, id => priority value
3231 foreach my $id (keys %$values) {
3232 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3233 my $Ticket = FS::TicketSystem->get_ticket_object('',
3235 'custnum' => $custnum,
3238 $ticket_error{$id} = 'ticket not found';
3242 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3243 # We're not going to implement it for RT_External.
3244 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3245 my $new_value = $values->{$id};
3246 next if $old_value eq $new_value;
3248 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3250 # AddCustomFieldValue works fine (replacing any existing value) if it's
3251 # a single-valued custom field, which it should be. If it's not, you're
3252 # doing something wrong.
3254 if ( length($new_value) ) {
3255 ($val, $msg) = $Ticket->AddCustomFieldValue(
3256 Field => $ss_priority,
3257 Value => $new_value,
3261 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3262 Field => $ss_priority,
3263 Value => $old_value,
3267 $ticket_error{$id} = $msg if !$val;
3268 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3270 return { 'error' => '',
3271 'ticket_error' => \%ticket_error,
3272 %{ customer_info($p) } # send updated customer info back
3278 sub _custoragent_session_custnum {
3281 my($context, $session, $custnum);
3282 if ( $p->{'session_id'} ) {
3284 $context = 'customer';
3285 $session = _cache->get($p->{'session_id'})
3286 or return ( 'error' => "Can't resume session" ); #better error message
3287 $custnum = $session->{'custnum'};
3289 } elsif ( $p->{'agent_session_id'} ) {
3292 my $agent_cache = new FS::ClientAPI_SessionCache( {
3293 'namespace' => 'FS::ClientAPI::Agent',
3295 $session = $agent_cache->get($p->{'agent_session_id'})
3296 or return ( 'error' => "Can't resume session" ); #better error message
3297 $custnum = $p->{'custnum'};
3301 return ( 'error' => "Can't resume session" ); #better error message
3304 ($context, $session, $custnum);