add switch_acct and reset_passwd to self-service API, RT#13656
[freeside.git] / FS / FS / ClientAPI / MyAccount.pm
1 package FS::ClientAPI::MyAccount;
2
3 use 5.008; #require 5.8+ for Time::Local 1.05+
4 use strict;
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
7 use Data::Dumper;
8 use Digest::MD5 qw(md5_hex);
9 use Date::Format;
10 use Business::CreditCard;
11 use Time::Duration;
12 use Time::Local qw(timelocal_nocheck);
13 use FS::UI::Web::small_custview qw(small_custview); #less doh
14 use FS::UI::Web;
15 use FS::UI::bytecount qw( display_bytecount );
16 use FS::Conf;
17 #use FS::UID qw(dbh);
18 use FS::Record qw(qsearch qsearchs dbh);
19 use FS::Msgcat qw(gettext);
20 use FS::Misc qw(card_types);
21 use FS::Misc::DateTime qw(parse_datetime);
22 use FS::ClientAPI_SessionCache;
23 use FS::cust_svc;
24 use FS::svc_acct;
25 use FS::svc_domain;
26 use FS::svc_phone;
27 use FS::svc_external;
28 use FS::svc_dsl;
29 use FS::dsl_device;
30 use FS::part_svc;
31 use FS::cust_main;
32 use FS::cust_bill;
33 use FS::cust_main_county;
34 use FS::cust_pkg;
35 use FS::payby;
36 use FS::acct_rt_transaction;
37 use HTML::Entities;
38 use FS::TicketSystem;
39 use Text::CSV_XS;
40 use IO::Scalar;
41 use Spreadsheet::WriteExcel;
42
43 $DEBUG = 0;
44 $me = '[FS::ClientAPI::MyAccount]';
45
46 use vars qw( @cust_main_editable_fields );
47 @cust_main_editable_fields = qw(
48   first last company address1 address2 city
49     county state zip country
50     daytime night fax mobile
51   ship_first ship_last ship_company ship_address1 ship_address2 ship_city
52     ship_state ship_zip ship_country
53     ship_daytime ship_night ship_fax ship_mobile
54   locale
55   payby payinfo payname paystart_month paystart_year payissue payip
56   ss paytype paystate stateid stateid_state
57 );
58
59 BEGIN { #preload to reduce time customer_info takes
60   if ( $FS::TicketSystem::system ) {
61     warn "$me: initializing ticket system\n" if $DEBUG;
62     FS::TicketSystem->init();
63   }
64 }
65
66 sub _cache {
67   $cache ||= new FS::ClientAPI_SessionCache( {
68                'namespace' => 'FS::ClientAPI::MyAccount',
69              } );
70 }
71
72 sub skin_info {
73   my $p = shift;
74
75   my($context, $session, $custnum) = _custoragent_session_custnum($p);
76   #return { 'error' => $session } if $context eq 'error';
77
78   my $agentnum = '';
79   if ( $context eq 'customer' ) {
80
81     my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
82       or die dbh->errstr;
83
84     $sth->execute($custnum) or die $sth->errstr;
85
86     $agentnum = $sth->fetchrow_arrayref->[0]
87       or die "no agentnum for custnum $custnum";
88
89   #} elsif ( $context eq 'agent' ) {
90   } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
91     $agentnum = $1;
92   }
93
94   my $conf = new FS::Conf;
95
96   #false laziness w/Signup.pm
97
98   my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
99
100   if ( $skin_info_cache_agent ) {
101
102     warn "$me loading cached skin info for agentnum $agentnum\n"
103       if $DEBUG > 1;
104
105   } else {
106
107     warn "$me populating skin info cache for agentnum $agentnum\n"
108       if $DEBUG > 1;
109
110     $skin_info_cache_agent = {
111       'agentnum' => $agentnum,
112       ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
113         qw( company_name date_format ) ),
114       ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
115         qw( body_bgcolor box_bgcolor
116             text_color link_color vlink_color hlink_color alink_color
117             font title_color title_align title_size menu_bgcolor menu_fontsize
118           )
119       ),
120       ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
121         qw( menu_skipblanks menu_skipheadings menu_nounderline )
122       ),
123       ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
124         qw( title_left_image title_right_image
125             menu_top_image menu_body_image menu_bottom_image
126           )
127       ),
128       'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
129       ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
130         qw( head body_header body_footer company_address ) ),
131     };
132
133     _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
134
135   }
136
137   #{ %$skin_info_cache_agent };
138   $skin_info_cache_agent;
139
140 }
141
142 sub login_info {
143   my $p = shift;
144
145   my $conf = new FS::Conf;
146
147   my %info = (
148     %{ skin_info($p) },
149     'phone_login'  => $conf->exists('selfservice_server-phone_login'),
150     'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
151   );
152
153   return \%info;
154
155 }
156
157 #false laziness w/FS::ClientAPI::passwd::passwd
158 sub login {
159   my $p = shift;
160
161   my $conf = new FS::Conf;
162
163   my $svc_x = '';
164   if ( $p->{'domain'} eq 'svc_phone'
165        && $conf->exists('selfservice_server-phone_login') ) { 
166
167     my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
168     return { error => 'Number not found.' } unless $svc_phone;
169
170     #XXX?
171     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
172     #return { error => 'Only primary user may log in.' } 
173     #  if $conf->exists('selfservice_server-primary_only')
174     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
175
176     return { error => 'Incorrect PIN.' }
177       unless $svc_phone->check_pin($p->{'password'});
178
179     $svc_x = $svc_phone;
180
181   } else {
182
183     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
184       or return { error => 'Domain '. $p->{'domain'}. ' not found' };
185
186     my $svc_acct = qsearchs( 'svc_acct', { 'username'  => $p->{'username'},
187                                            'domsvc'    => $svc_domain->svcnum, }
188                            );
189     return { error => 'User not found.' } unless $svc_acct;
190
191     if($conf->exists('selfservice_server-login_svcpart')) {
192         my @svcpart = $conf->config('selfservice_server-login_svcpart');
193         my $svcpart = $svc_acct->cust_svc->svcpart;
194         return { error => 'Invalid user.' } 
195             unless grep($_ eq $svcpart, @svcpart);
196     }
197
198     return { error => 'Incorrect password.' }
199       unless $svc_acct->check_password($p->{'password'});
200
201     $svc_x = $svc_acct;
202
203   }
204
205   my $session = {
206     'svcnum' => $svc_x->svcnum,
207   };
208
209   my $cust_svc = $svc_x->cust_svc;
210   my $cust_pkg = $cust_svc->cust_pkg;
211   if ( $cust_pkg ) {
212     my $cust_main = $cust_pkg->cust_main;
213     $session->{'custnum'} = $cust_main->custnum;
214     if ( $conf->exists('pkg-balances') ) {
215       my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
216                           $cust_main->ncancelled_pkgs;
217       $session->{'pkgnum'} = $cust_pkg->pkgnum
218         if scalar(@cust_pkg) > 1;
219     }
220   }
221
222   #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
223   #return { error => 'Only primary user may log in.' } 
224   #  if $conf->exists('selfservice_server-primary_only')
225   #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
226   my $part_pkg = $cust_pkg->part_pkg;
227   return { error => 'Only primary user may log in.' }
228     if $conf->exists('selfservice_server-primary_only')
229        && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
230
231   my $session_id;
232   do {
233     $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
234   } until ( ! defined _cache->get($session_id) ); #just in case
235
236   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
237   _cache->set( $session_id, $session, $timeout );
238
239   return { 'error'      => '',
240            'session_id' => $session_id,
241          };
242 }
243
244 sub logout {
245   my $p = shift;
246   if ( $p->{'session_id'} ) {
247     _cache->remove($p->{'session_id'});
248     return { %{ skin_info($p) }, 'error' => '' };
249   } else {
250     return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
251   }
252 }
253
254 sub switch_acct {
255   my $p = shift;
256
257   my($context, $session, $custnum) = _custoragent_session_custnum($p);
258   return { 'error' => $session } if $context eq 'error';
259
260   my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
261     or return { 'error' => "Service not found" };
262
263   $session->{'svcnum'} = $svc_acct->svcnum;
264
265   my $conf = new FS::Conf;
266   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
267   _cache->set( $p->{'session_id'}, $session, $timeout );
268
269   return { 'error' => '' };
270
271 }
272
273 sub payment_gateway {
274   # internal use only
275   # takes a cust_main and a cust_payby entry, returns the payment_gateway
276   my $conf = new FS::Conf;
277   my $cust_main = shift;
278   my $cust_payby = shift;
279   my $gatewaynum = $conf->config('selfservice-payment_gateway');
280   if ( $gatewaynum ) {
281     my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
282     die "configured gatewaynum $gatewaynum not found!" if !$pg;
283     return $pg;
284   }
285   else {
286     return '' if ! FS::payby->realtime($cust_payby);
287     my $pg = $cust_main->agent->payment_gateway(
288       'method'  => FS::payby->payby2bop($cust_payby),
289       'nofatal' => 1
290     );
291     return $pg;
292   }
293 }
294
295 sub access_info {
296   my $p = shift;
297
298   my $conf = new FS::Conf;
299
300   my $info = skin_info($p);
301
302   use vars qw( $cust_paybys ); #cache for performance
303   unless ( $cust_paybys ) {
304
305     my %cust_paybys = map { $_ => 1 }
306                       map { FS::payby->payby2payment($_) }
307                           $conf->config('signup_server-payby');
308
309     $cust_paybys = [ keys %cust_paybys ];
310
311   }
312   $info->{'cust_paybys'} = $cust_paybys;
313
314   my($context, $session, $custnum) = _custoragent_session_custnum($p);
315   return { 'error' => $session } if $context eq 'error';
316
317   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
318     or return { 'error' => "unknown custnum $custnum" };
319
320   $info->{'hide_payment_fields'} = [ 
321     map { 
322       my $pg = payment_gateway($cust_main, $_);
323       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
324     } @{ $info->{cust_paybys} }
325   ];
326
327   $info->{'self_suspend_reason'} = 
328       $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
329
330   $info->{'edit_ticket_subject'} =
331       $conf->exists('ticket_system-selfservice_edit_subject') && 
332       $cust_main->edit_subject;
333
334   return { %$info,
335            'custnum'       => $custnum,
336            'access_pkgnum' => $session->{'pkgnum'},
337            'access_svcnum' => $session->{'svcnum'},
338          };
339 }
340
341 sub customer_info {
342   my $p = shift;
343
344   my($context, $session, $custnum) = _custoragent_session_custnum($p);
345   return { 'error' => $session } if $context eq 'error';
346
347   my %return;
348
349   my $conf = new FS::Conf;
350   if ($conf->exists('cust_main-require_address2')) {
351     $return{'require_address2'} = '1';
352   }else{
353     $return{'require_address2'} = '';
354   }
355
356   if ( $FS::TicketSystem::system ) {
357     warn "$me customer_info: initializing ticket system\n" if $DEBUG;
358     FS::TicketSystem->init();
359   }
360  
361   if ( $custnum ) { #customer record
362
363     my $search = { 'custnum' => $custnum };
364     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
365     my $cust_main = qsearchs('cust_main', $search )
366       or return { 'error' => "unknown custnum $custnum" };
367
368     if ( $session->{'pkgnum'} ) { 
369       $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
370     } else {
371       $return{balance} = $cust_main->balance;
372     }
373
374     my @tickets = $cust_main->tickets;
375     # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
376     if ( FS::TicketSystem->selfservice_priority ) {
377       my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
378       $return{tickets} = [ 
379         sort { 
380           (
381             ($a->{'_selfservice_priority'} eq '') <=>
382             ($b->{'_selfservice_priority'} eq '')
383           ) ||
384           ( $dir * 
385             ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'}) 
386           )
387         } @tickets
388       ];
389     }
390     else {
391       $return{tickets} = \@tickets;
392     }
393
394     unless ( $session->{'pkgnum'} ) {
395       my @open = map {
396                        {
397                          invnum => $_->invnum,
398                          date   => time2str("%b %o, %Y", $_->_date),
399                          owed   => $_->owed,
400                        };
401                      } $cust_main->open_cust_bill;
402       $return{open_invoices} = \@open;
403     }
404
405     $return{small_custview} =
406       small_custview( $cust_main,
407                       scalar($conf->config('countrydefault')),
408                       ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
409                     );
410
411     $return{name} = $cust_main->first. ' '. $cust_main->get('last');
412     $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
413
414     for (@cust_main_editable_fields) {
415       $return{$_} = $cust_main->get($_);
416     }
417
418     if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
419       $return{payinfo} = $cust_main->paymask;
420       @return{'month', 'year'} = $cust_main->paydate_monthyear;
421     }
422
423     $return{'invoicing_list'} =
424       join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
425     $return{'postal_invoicing'} =
426       0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
427
428     if (scalar($conf->config('support_packages'))) {
429       my @support_services = ();
430       foreach ($cust_main->support_services) {
431         my $seconds = $_->svc_x->seconds;
432         my $time_remaining = (($seconds < 0) ? '-' : '' ).
433                              int(abs($seconds)/3600)."h".
434                              sprintf("%02d",(abs($seconds)%3600)/60)."m";
435         my $cust_pkg = $_->cust_pkg;
436         my $pkgnum = '';
437         my $pkg = '';
438         $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
439         $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
440         push @support_services, { svcnum => $_->svcnum,
441                                   time => $time_remaining,
442                                   pkgnum => $pkgnum,
443                                   pkg => $pkg,
444                                 };
445       }
446       $return{support_services} = \@support_services;
447     }
448
449     if ( $conf->config('prepayment_discounts-credit_type') ) {
450       #need to eval?
451       $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
452     }
453
454     if ( $session->{'svcnum'} ) {
455       my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
456       $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
457       $return{'svcnum'} = $session->{'svcnum'};
458     }
459
460   } elsif ( $session->{'svcnum'} ) { #no customer record
461
462     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
463       or die "unknown svcnum";
464     $return{name} = $svc_acct->email;
465
466   } else {
467
468     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
469
470   }
471
472   return { 'error'          => '',
473            'custnum'        => $custnum,
474            %return,
475          };
476
477 }
478
479 sub customer_info_short {
480   my $p = shift;
481
482   my($context, $session, $custnum) = _custoragent_session_custnum($p);
483   return { 'error' => $session } if $context eq 'error';
484
485   my %return;
486
487   my $conf = new FS::Conf;
488
489   if ( $custnum ) { #customer record
490
491     my $search = { 'custnum' => $custnum };
492     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
493     my $cust_main = qsearchs('cust_main', $search )
494       or return { 'error' => "unknown custnum $custnum" };
495
496     $return{small_custview} =
497       small_custview( $cust_main,
498                       scalar($conf->config('countrydefault')),
499                       1, ##nobalance
500                     );
501
502     $return{name} = $cust_main->first. ' '. $cust_main->get('last');
503     $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
504
505     $return{payby} = $cust_main->payby;
506
507     #none of these are terribly expensive if we want 'em...
508     for (@cust_main_editable_fields) {
509       $return{$_} = $cust_main->get($_);
510     }
511     
512     if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
513       $return{payinfo} = $cust_main->paymask;
514       @return{'month', 'year'} = $cust_main->paydate_monthyear;
515     }
516     
517     $return{'invoicing_list'} =
518       join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
519     #$return{'postal_invoicing'} =
520     #  0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
521
522     if ( $session->{'svcnum'} ) {
523       my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
524       $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
525       $return{'svcnum'} = $session->{'svcnum'};
526     }
527
528   } elsif ( $session->{'svcnum'} ) { #no customer record
529
530     #uuh, not supproted yet... die?
531     return { 'error' => 'customer_info_short not yet supported as agent' };
532
533   } else {
534
535     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
536
537   }
538
539   return { 'error'          => '',
540            'custnum'        => $custnum,
541            %return,
542          };
543 }
544
545 sub edit_info {
546   my $p = shift;
547   my $session = _cache->get($p->{'session_id'})
548     or return { 'error' => "Can't resume session" }; #better error message
549
550   my $custnum = $session->{'custnum'}
551     or return { 'error' => "no customer record" };
552
553   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
554     or return { 'error' => "unknown custnum $custnum" };
555
556   my $new = new FS::cust_main { $cust_main->hash };
557   $new->set( $_ => $p->{$_} )
558     foreach grep { exists $p->{$_} } @cust_main_editable_fields;
559
560   my $payby = '';
561   if (exists($p->{'payby'})) {
562     $p->{'payby'} =~ /^([A-Z]{4})$/
563       or return { 'error' => "illegal_payby " . $p->{'payby'} };
564     $payby = $1;
565   }
566
567   if ( $payby =~ /^(CARD|DCRD)$/ ) {
568
569     $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
570
571     if ( $new->payinfo eq $cust_main->paymask ) {
572       $new->payinfo($cust_main->payinfo);
573     } else {
574       $new->payinfo($p->{'payinfo'});
575     }
576
577     $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
578
579   } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
580
581     my $payinfo;
582     $p->{'payinfo1'} =~ /^([\dx]+)$/
583       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
584     my $payinfo1 = $1;
585      $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by -require-bank-branch?
586       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
587     my $payinfo2 = $1;
588     $payinfo = $payinfo1. '@'. $payinfo2;
589
590     $new->payinfo( ($payinfo eq $cust_main->paymask)
591                      ? $cust_main->payinfo
592                      : $payinfo
593                  );
594
595     $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
596
597   } elsif ( $payby =~ /^(BILL)$/ ) {
598     #no-op
599   } elsif ( $payby ) {  #notyet ready
600     return { 'error' => "unknown payby $payby" };
601   }
602
603   my @invoicing_list;
604   if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
605     #false laziness with httemplate/edit/process/cust_main.cgi
606     @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
607     push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
608   } else {
609     @invoicing_list = $cust_main->invoicing_list;
610   }
611
612   my $error = $new->replace($cust_main, \@invoicing_list);
613   return { 'error' => $error } if $error;
614   #$cust_main = $new;
615   
616   return { 'error' => '' };
617 }
618
619 sub payment_info {
620   my $p = shift;
621   my $session = _cache->get($p->{'session_id'})
622     or return { 'error' => "Can't resume session" }; #better error message
623
624   ##
625   #generic
626   ##
627
628   my $conf = new FS::Conf;
629   use vars qw($payment_info); #cache for performance
630   unless ( $payment_info ) {
631
632     my %states = map { $_->state => 1 }
633                    qsearch('cust_main_county', {
634                      'country' => $conf->config('countrydefault') || 'US'
635                    } );
636
637     my %cust_paybys = map { $_ => 1 }
638                       map { FS::payby->payby2payment($_) }
639                           $conf->config('signup_server-payby');
640
641     my @cust_paybys = keys %cust_paybys;
642
643     $payment_info = {
644
645       #list all counties/states/countries
646       'cust_main_county' => 
647         [ map { $_->hashref } qsearch('cust_main_county', {}) ],
648
649       #shortcut for one-country folks
650       'states' =>
651         [ sort { $a cmp $b } keys %states ],
652
653       'card_types' => card_types(),
654
655       'paytypes' => [ @FS::cust_main::paytypes ],
656
657       'paybys' => [ $conf->config('signup_server-payby') ],
658       'cust_paybys' => \@cust_paybys,
659
660       'stateid_label' => FS::Msgcat::_gettext('stateid'),
661       'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
662
663       'show_ss'  => $conf->exists('show_ss'),
664       'show_stateid' => $conf->exists('show_stateid'),
665       'show_paystate' => $conf->exists('show_bankstate'),
666
667       'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
668
669       'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
670     };
671
672   }
673
674   ##
675   #customer-specific
676   ##
677
678   my %return = %$payment_info;
679
680   my $custnum = $session->{'custnum'};
681
682   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
683     or return { 'error' => "unknown custnum $custnum" };
684
685   $return{'hide_payment_fields'} = [
686     map { 
687       my $pg = payment_gateway($cust_main, $_);
688       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
689     } @{ $return{cust_paybys} }
690   ];
691
692   $return{balance} = $cust_main->balance; #XXX pkg-balances?
693
694   $return{payname} = $cust_main->payname
695                      || ( $cust_main->first. ' '. $cust_main->get('last') );
696
697   $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
698
699   $return{payby} = $cust_main->payby;
700   $return{stateid_state} = $cust_main->stateid_state;
701
702   if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
703     $return{card_type} = cardtype($cust_main->payinfo);
704     $return{payinfo} = $cust_main->paymask;
705
706     @return{'month', 'year'} = $cust_main->paydate_monthyear;
707
708   }
709
710   if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
711     my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
712     $return{payinfo1} = $payinfo1;
713     $return{payinfo2} = $payinfo2;
714     $return{paytype}  = $cust_main->paytype;
715     $return{paystate} = $cust_main->paystate;
716
717   }
718
719   if ( $conf->config('prepayment_discounts-credit_type') ) {
720     #need to eval?
721     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
722   }
723
724   #doubleclick protection
725   my $_date = time;
726   $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
727
728   return { 'error' => '',
729            %return,
730          };
731
732 }
733
734 #some false laziness with httemplate/process/payment.cgi - look there for
735 #ACH and CVV support stuff
736
737 sub validate_payment {
738   my $p = shift;
739
740   my $session = _cache->get($p->{'session_id'})
741     or return { 'error' => "Can't resume session" }; #better error message
742
743   my $custnum = $session->{'custnum'};
744
745   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
746     or return { 'error' => "unknown custnum $custnum" };
747
748   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
749     or return { 'error' => gettext('illegal_amount') };
750   my $amount = $1;
751   return { error => 'Amount must be greater than 0' } unless $amount > 0;
752
753   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
754     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
755   my $discount_term = $1;
756
757   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
758     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
759   my $payname = $1;
760
761   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
762     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
763   my $paybatch = $1;
764
765   $p->{'payby'} ||= 'CARD';
766   $p->{'payby'} =~ /^([A-Z]{4})$/
767     or return { 'error' => "illegal_payby " . $p->{'payby'} };
768   my $payby = $1;
769
770   #false laziness w/process/payment.cgi
771   my $payinfo;
772   my $paycvv = '';
773   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
774   
775     $p->{'payinfo1'} =~ /^([\dx]+)$/
776       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
777     my $payinfo1 = $1;
778      $p->{'payinfo2'} =~ /^([\dx]+)$/
779       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
780     my $payinfo2 = $1;
781     $payinfo = $payinfo1. '@'. $payinfo2;
782
783     $payinfo = $cust_main->payinfo
784       if $cust_main->paymask eq $payinfo;
785    
786   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
787    
788     $payinfo = $p->{'payinfo'};
789
790     #more intelligent mathing will be needed here if you change
791     #card_masking_method and don't remove existing paymasks
792     $payinfo = $cust_main->payinfo
793       if $cust_main->paymask eq $payinfo;
794
795     $payinfo =~ s/\D//g;
796     $payinfo =~ /^(\d{13,16}|\d{8,9})$/
797       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
798     $payinfo = $1;
799
800     validate($payinfo)
801       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
802     return { 'error' => gettext('unknown_card_type') }
803       if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
804
805     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
806       if ( cardtype($payinfo) eq 'American Express card' ) {
807         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
808           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
809         $paycvv = $1;
810       } else {
811         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
812           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
813         $paycvv = $1;
814       }
815     }
816   
817   } else {
818     die "unknown payby $payby";
819   }
820
821   my %payby2fields = (
822     'CARD' => [ qw( paystart_month paystart_year payissue payip
823                     address1 address2 city state zip country    ) ],
824     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
825   );
826
827   my $card_type = '';
828   $card_type = cardtype($payinfo) if $payby eq 'CARD';
829
830   { 
831     'cust_main'      => $cust_main, #XXX or just custnum??
832     'amount'         => $amount,
833     'payby'          => $payby,
834     'payinfo'        => $payinfo,
835     'paymask'        => $cust_main->mask_payinfo( $payby, $payinfo ),
836     'card_type'      => $card_type,
837     'paydate'        => $p->{'year'}. '-'. $p->{'month'}. '-01',
838     'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
839     'payname'        => $payname,
840     'paybatch'       => $paybatch, #this doesn't actually do anything
841     'paycvv'         => $paycvv,
842     'payname'        => $payname,
843     'discount_term'  => $discount_term,
844     'pkgnum'         => $session->{'pkgnum'},
845     map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
846                              qw( save auto ),
847                            )
848   };
849
850 }
851
852 sub store_payment {
853   my $p = shift;
854
855   my $validate = validate_payment($p);
856   return $validate if $validate->{'error'};
857
858   my $conf = new FS::Conf;
859   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
860   _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
861
862   +{ map { $_=>$validate->{$_} }
863       qw( card_type paymask payname paydate_pretty amount )
864   };
865
866 }
867
868 sub process_stored_payment {
869   my $p = shift;
870
871   my $session_id = $p->{'session_id'};
872
873   my $payment_info = _cache->get( "payment_$session_id" )
874     or return { 'error' => "Can't resume session" }; #better error message
875
876   do_process_payment($payment_info);
877
878 }
879
880 sub process_payment {
881   my $p = shift;
882
883   my $payment_info = validate_payment($p);
884   return $payment_info if $payment_info->{'error'};
885
886   do_process_payment($payment_info);
887
888 }
889
890 sub do_process_payment {
891   my $validate = shift;
892
893   my $cust_main = $validate->{'cust_main'};
894
895   my $amount = delete $validate->{'amount'};
896   my $paynum = '';
897
898   my $payby = delete $validate->{'payby'};
899
900   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
901     'quiet'       => 1,
902     'selfservice' => 1,
903     'paynum_ref'  => \$paynum,
904     %$validate,
905   );
906   return { 'error' => $error } if $error;
907
908   $cust_main->apply_payments;
909
910   if ( $validate->{'save'} ) {
911     my $new = new FS::cust_main { $cust_main->hash };
912     if ($validate->{'payby'} eq 'CARD' || $validate->{'payby'} eq 'DCRD') {
913       $new->set( $_ => $validate->{$_} )
914         foreach qw( payname paystart_month paystart_year payissue payip
915                     address1 address2 city state zip country );
916       $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
917     } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
918       $new->set( $_ => $validate->{$_} )
919         foreach qw( payname payip paytype paystate
920                     stateid stateid_state );
921       $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
922     }
923     $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
924     $new->set( 'paydate' => $validate->{'paydate'} );
925     my $error = $new->replace($cust_main);
926     if ( $error ) {
927       #no, this causes customers to process their payments again
928       #return { 'error' => $error };
929       #XXX just warn verosely for now so i can figure out how these happen in
930       # the first place, eventually should redirect them to the "change
931       #address" page but indicate the payment did process??
932       delete($validate->{'payinfo'}); #don't want to log this!
933       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
934            "NEW: ". Dumper($new)."\n".
935            "OLD: ". Dumper($cust_main)."\n".
936            "PACKET: ". Dumper($validate)."\n";
937     #} else {
938       #not needed...
939       #$cust_main = $new;
940     }
941   }
942
943   my $cust_pay = '';
944   my $receipt_html = '';
945   if ($paynum) {
946       # currently supported for realtime CC only; send receipt data to SS
947       $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
948       if($cust_pay) {
949         $receipt_html = qq!
950 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
951
952 <TR>
953   <TD ALIGN="right">Payment#</TD>
954   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
955 </TR>
956
957 <TR>
958   <TD ALIGN="right">Date</TD>
959
960   <TD BGCOLOR="#FFFFFF"><B>! . 
961         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
962                                                             . qq!</B></TD>
963 </TR>
964
965
966 <TR>
967   <TD ALIGN="right">Amount</TD>
968   <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
969
970 </TR>
971
972 <TR>
973   <TD ALIGN="right">Payment method</TD>
974   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
975                                                                 . qq!</B></TD>
976 </TR>
977
978 </TABLE>
979 !;
980       }
981   }
982
983   if ( $cust_pay ) {
984
985     my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
986
987     return {
988       'error'        => '',
989       'amount'       => sprintf('%.2f', $cust_pay->paid),
990       'date'         => $cust_pay->_date,
991       'date_pretty'  => time2str('%Y-%m-%d', $cust_pay->_date),
992       'time_pretty'  => time2str('%T', $cust_pay->_date),
993       'auth_num'     => $auth,
994       'order_num'    => $order,
995       'receipt_html' => $receipt_html,
996     };
997
998   } else {
999
1000     return {
1001       'error'        => '',
1002       'receipt_html' => '',
1003     };
1004
1005   }
1006
1007 }
1008
1009 sub realtime_collect {
1010   my $p = shift;
1011
1012   my $session = _cache->get($p->{'session_id'})
1013     or return { 'error' => "Can't resume session" }; #better error message
1014
1015   my $custnum = $session->{'custnum'};
1016
1017   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1018     or return { 'error' => "unknown custnum $custnum" };
1019
1020   my $amount;
1021   if ( $p->{'amount'} ) {
1022     $amount = $p->{'amount'};
1023   }
1024   elsif ( $session->{'pkgnum'} ) {
1025     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1026   }
1027   else {
1028     $amount = $cust_main->balance;
1029   }
1030
1031   my $error = $cust_main->realtime_collect(
1032     'method'     => $p->{'method'},
1033     'amount'     => $amount,
1034     'pkgnum'     => $session->{'pkgnum'},
1035     'session_id' => $p->{'session_id'},
1036     'apply'      => 1,
1037     'selfservice'=> 1,
1038   );
1039   return { 'error' => $error } unless ref( $error );
1040
1041   return { 'error' => '', amount => $amount, %$error };
1042 }
1043
1044 sub process_payment_order_pkg {
1045   my $p = shift;
1046
1047   my $hr = process_payment($p);
1048   return $hr if $hr->{'error'};
1049
1050   order_pkg($p);
1051 }
1052
1053 sub process_payment_order_renew {
1054   my $p = shift;
1055
1056   my $hr = process_payment($p);
1057   return $hr if $hr->{'error'};
1058
1059   order_renew($p);
1060 }
1061
1062 sub process_prepay {
1063
1064   my $p = shift;
1065
1066   my $session = _cache->get($p->{'session_id'})
1067     or return { 'error' => "Can't resume session" }; #better error message
1068
1069   my %return;
1070
1071   my $custnum = $session->{'custnum'};
1072
1073   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1074     or return { 'error' => "unknown custnum $custnum" };
1075
1076   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1077   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1078                                            \$amount,
1079                                            \$seconds,
1080                                            \$upbytes,
1081                                            \$downbytes,
1082                                            \$totalbytes,
1083                                          );
1084
1085   return { 'error' => $error } if $error;
1086
1087   return { 'error'     => '',
1088            'amount'    => $amount,
1089            'seconds'   => $seconds,
1090            'duration'  => duration_exact($seconds),
1091            'upbytes'   => $upbytes,
1092            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
1093            'downbytes' => $downbytes,
1094            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
1095            'totalbytes'=> $totalbytes,
1096            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1097          };
1098
1099 }
1100
1101 sub invoice {
1102   my $p = shift;
1103   my $session = _cache->get($p->{'session_id'})
1104     or return { 'error' => "Can't resume session" }; #better error message
1105
1106   my $custnum = $session->{'custnum'};
1107
1108   my $invnum = $p->{'invnum'};
1109
1110   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1111                                           'custnum' => $custnum } )
1112     or return { 'error' => "Can't find invnum" };
1113
1114   #my %return;
1115
1116   return { 'error'        => '',
1117            'invnum'       => $invnum,
1118            'invoice_text' => join('', $cust_bill->print_text ),
1119            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1120          };
1121
1122 }
1123
1124 sub invoice_pdf {
1125   my $p = shift;
1126   my $session = _cache->get($p->{'session_id'})
1127     or return { 'error' => "Can't resume session" }; #better error message
1128
1129   my $custnum = $session->{'custnum'};
1130
1131   my $invnum = $p->{'invnum'};
1132
1133   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1134                                           'custnum' => $custnum } )
1135     or return { 'error' => "Can't find invnum" };
1136
1137   #my %return;
1138
1139   return { 'error'       => '',
1140            'invnum'      => $invnum,
1141            'invoice_pdf' => $cust_bill->print_pdf( { unsquelch_cdr => 1 } ),
1142          };
1143
1144 }
1145
1146 sub invoice_logo {
1147   my $p = shift;
1148
1149   #sessioning for this?  how do we get the session id to the backend invoice
1150   # template so it can add it to the link, blah
1151
1152   my $agentnum = '';
1153   if ( $p->{'invnum'} ) {
1154     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1155       or return { 'error' => 'unknown invnum' };
1156     $agentnum = $cust_bill->cust_main->agentnum;
1157   }
1158
1159   my $templatename = $p->{'template'} || $p->{'templatename'};
1160
1161   #false laziness-ish w/view/cust_bill-logo.cgi
1162
1163   my $conf = new FS::Conf;
1164   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1165     $templatename = "_$1";
1166   } else {
1167     $templatename = '';
1168   }
1169
1170   my $filename = "logo$templatename.png";
1171
1172   return { 'error'        => '',
1173            'logo'         => $conf->config_binary($filename, $agentnum),
1174            'content_type' => 'image/png', #should allow gif, jpg too
1175          };
1176 }
1177
1178
1179 sub list_invoices {
1180   my $p = shift;
1181   my $session = _cache->get($p->{'session_id'})
1182     or return { 'error' => "Can't resume session" }; #better error message
1183
1184   my $custnum = $session->{'custnum'};
1185
1186   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1187     or return { 'error' => "unknown custnum $custnum" };
1188
1189   my @cust_bill = $cust_main->cust_bill;
1190
1191   my $balance = 0;
1192
1193   return  { 'error'       => '',
1194             'balance'     => $cust_main->balance,
1195             'invoices'    => [
1196               map {
1197                     my $owed = $_->owed;
1198                     $balance += $owed;
1199                     +{ 'invnum'     => $_->invnum,
1200                        '_date'      => $_->_date,
1201                        'date'       => time2str("%b %o, %Y", $_->_date),
1202                        'date_short' => time2str("%m-%d-%Y",  $_->_date),
1203                        'previous'   => sprintf('%.2f', ($_->previous)[0]),
1204                        'charged'    => sprintf('%.2f', $_->charged),
1205                        'owed'       => sprintf('%.2f', $owed),
1206                        'balance'    => sprintf('%.2f', $balance),
1207                      }
1208                   }
1209                   @cust_bill
1210             ]
1211           };
1212 }
1213
1214 sub cancel {
1215   my $p = shift;
1216   my $session = _cache->get($p->{'session_id'})
1217     or return { 'error' => "Can't resume session" }; #better error message
1218
1219   my $custnum = $session->{'custnum'};
1220
1221   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1222     or return { 'error' => "unknown custnum $custnum" };
1223
1224   my @errors = $cust_main->cancel( 'quiet'=>1 );
1225
1226   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1227
1228   return { 'error' => $error };
1229
1230 }
1231
1232 sub list_pkgs {
1233   my $p = shift;
1234
1235   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1236   return { 'error' => $session } if $context eq 'error';
1237
1238   my $search = { 'custnum' => $custnum };
1239   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1240   my $cust_main = qsearchs('cust_main', $search )
1241     or return { 'error' => "unknown custnum $custnum" };
1242
1243   my $conf = new FS::Conf;
1244   
1245 # the duplication below is necessary:
1246 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1247 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1248 # non-backwards-compatible change breaking the software of anyone using the API
1249 # instead of the stock selfservice
1250 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1251   if( $conf->exists('selfservice_server-view-wholesale') ) {
1252     return { 'svcnum'   => $session->{'svcnum'},
1253             'custnum'  => $custnum,
1254             'cust_pkg' => [ map {
1255                           { $_->hash,
1256                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1257                             part_svc =>
1258                               [ map $_->hashref, $_->available_part_svc ],
1259                             cust_svc => 
1260                               [ map { my $ref = { $_->hash,
1261                                                   label => [ $_->label ],
1262                                                 };
1263                                       $ref->{_password} = $_->svc_x->_password
1264                                         if $context eq 'agent'
1265                                         && $conf->exists('agent-showpasswords')
1266                                         && $_->part_svc->svcdb eq 'svc_acct';
1267                                       $ref;
1268                                     } $_->cust_svc
1269                               ],
1270                           };
1271                         } $cust_main->cust_pkg
1272                   ],
1273     'small_custview' =>
1274       small_custview( $cust_main, $conf->config('countrydefault') ),
1275     'wholesale_view' => 1,
1276     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1277     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1278     'lnp' => $conf->exists('svc_phone-lnp'),
1279       };
1280   }
1281
1282   { 'svcnum'   => $session->{'svcnum'},
1283     'custnum'  => $custnum,
1284     'cust_pkg' => [ map {
1285                           my $primary_cust_svc = $_->primary_cust_svc;
1286                           +{ $_->hash,
1287                             $_->part_pkg->hash,
1288                             status => $_->status,
1289                             part_svc =>
1290                               [ map $_->hashref, $_->available_part_svc ],
1291                             cust_svc => 
1292                               [ map { my $ref = { $_->hash,
1293                                                   label => [ $_->label ],
1294                                                 };
1295                                       $ref->{_password} = $_->svc_x->_password
1296                                         if $context eq 'agent'
1297                                         && $conf->exists('agent-showpasswords')
1298                                         && $_->part_svc->svcdb eq 'svc_acct';
1299                                       $ref->{svchash} = { $_->svc_x->hash } if 
1300                                         $_->part_svc->svcdb eq 'svc_phone';
1301                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1302                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1303                                       $ref;
1304                                     } $_->cust_svc
1305                               ],
1306                             primary_cust_svc =>
1307                               $primary_cust_svc
1308                                 ? { $primary_cust_svc->hash,
1309                                     label => [ $primary_cust_svc->label ],
1310                                     finger => $primary_cust_svc->svc_x->finger, #uuh
1311                                     $primary_cust_svc->part_svc->hash,
1312                                   }
1313                                 : {}, #'' ?
1314                           };
1315                         } $cust_main->ncancelled_pkgs
1316                   ],
1317     'small_custview' =>
1318       small_custview( $cust_main, $conf->config('countrydefault') ),
1319   };
1320
1321 }
1322
1323 sub list_svcs {
1324   my $p = shift;
1325
1326   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1327   return { 'error' => $session } if $context eq 'error';
1328
1329   my $search = { 'custnum' => $custnum };
1330   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1331   my $cust_main = qsearchs('cust_main', $search )
1332     or return { 'error' => "unknown custnum $custnum" };
1333
1334   my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1335   if ( ! $pkgnum && $p->{'svcnum'} ) {
1336     my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1337     $pkgnum = $cust_svc->pkgnum if $cust_svc;
1338   }
1339
1340   my @cust_svc = ();
1341   #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1342   foreach my $cust_pkg ( $p->{'ncancelled'} 
1343                          ? $cust_main->ncancelled_pkgs
1344                          : $cust_main->unsuspended_pkgs ) {
1345     next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1346     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1347   }
1348   if ( $p->{'svcdb'} ) {
1349     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1350                   ? $p->{'svcdb'}
1351                   : ref($p->{'svcdb'}) eq 'ARRAY'
1352                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1353                     : { $p->{'svcdb'} => 1 };
1354     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1355   }
1356
1357   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1358   #              @svc_x;
1359
1360     my $conf = new FS::Conf;
1361
1362   { 
1363     'svcnum'   => $session->{'svcnum'},
1364     'custnum'  => $custnum,
1365     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1366     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1367     'svcs'     => [
1368       map { 
1369             my $svc_x = $_->svc_x;
1370             my($label, $value) = $_->label;
1371             my $svcdb = $_->part_svc->svcdb;
1372             my $part_pkg = $_->cust_pkg->part_pkg;
1373
1374             my %hash = (
1375               'svcnum' => $_->svcnum,
1376               'svcdb'  => $svcdb,
1377               'label'  => $label,
1378               'value'  => $value,
1379             );
1380
1381             if ( $svcdb eq 'svc_acct' ) {
1382               %hash = (
1383                 %hash,
1384                 'username'   => $svc_x->username,
1385                 'email'      => $svc_x->email,
1386                 'finger'     => $svc_x->finger,
1387                 'seconds'    => $svc_x->seconds,
1388                 'upbytes'    => display_bytecount($svc_x->upbytes),
1389                 'downbytes'  => display_bytecount($svc_x->downbytes),
1390                 'totalbytes' => display_bytecount($svc_x->totalbytes),
1391
1392                 'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1393                 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1394                 'recharge_upbytes'    =>
1395                   display_bytecount($part_pkg->option('recharge_upbytes',1)),
1396                 'recharge_downbytes'  =>
1397                   display_bytecount($part_pkg->option('recharge_downbytes',1)),
1398                 'recharge_totalbytes' =>
1399                   display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1400                 # more...
1401               );
1402
1403             } elsif ( $svcdb eq 'svc_dsl' ) {
1404               $hash{'phonenum'} = $svc_x->phonenum;
1405               if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1406                 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1407                 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1408                   if $svc_x->company;
1409               } else {
1410                 $hash{'name'} = $cust_main->name;
1411               }
1412             }
1413             # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1414             #  %hash = (
1415             #    %hash,
1416             #  );
1417             #}
1418
1419             \%hash;
1420           }
1421           @cust_svc
1422     ],
1423   };
1424
1425 }
1426
1427 sub _customer_svc_x {
1428   my($custnum, $svcnum, $table) = @_;
1429
1430   $custnum =~ /^(\d+)$/ or die "illegal custnum";
1431   my $search = " AND custnum = $1";
1432   #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1433
1434   qsearchs( {
1435     'table'     => ($table || 'svc_acct'),
1436     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
1437                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) ',#.
1438                    #'LEFT JOIN cust_main USING ( custnum ) ',
1439     'hashref'   => { 'svcnum' => $svcnum, },
1440     'extra_sql' => $search, #important
1441   } );
1442
1443 }
1444
1445 sub list_dsl_devices {
1446   my $p = shift;
1447
1448   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1449   return { 'error' => $session } if $context eq 'error';
1450
1451   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1452     or return { 'error' => "Service not found" };
1453
1454   return {
1455     'devices' => [ map {
1456                          +{ 'mac_addr' => $_->mac_addr };
1457                        } $svc_dsl->dsl_device
1458                  ],
1459   };
1460
1461 }
1462
1463 sub add_dsl_device {
1464   my $p = shift;
1465
1466   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1467   return { 'error' => $session } if $context eq 'error';
1468
1469   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1470     or return { 'error' => "Service not found" };
1471
1472   return { 'error' => 'No MAC address supplied' }
1473     unless length($p->{'mac_addr'});
1474
1475   my $dsl_device = new FS::dsl_device { 'svcnum'   => $svc_dsl->svcnum,
1476                                         'mac_addr' => scalar($p->{'mac_addr'}),
1477                                       };
1478   my $error = $dsl_device->insert;
1479   return { 'error' => $error };
1480
1481 }
1482
1483 sub delete_dsl_device {
1484   my $p = shift;
1485
1486   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1487   return { 'error' => $session } if $context eq 'error';
1488
1489   my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1490     or return { 'error' => "Service not found" };
1491
1492   my $dsl_device = qsearchs('dsl_device', { 'svcnum'   => $svc_dsl->svcnum,
1493                                             'mac_addr' => scalar($p->{'mac_addr'}),
1494                                           }
1495                            )
1496     or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
1497
1498   my $error = $dsl_device->delete;
1499   return { 'error' => $error };
1500
1501 }
1502
1503 sub port_graph {
1504   my $p = shift;
1505   _usage_details( \&_port_graph, $p,
1506                   'svcdb' => 'svc_port',
1507                 );
1508 }
1509
1510 sub _port_graph {
1511   my($svc_port, $begin, $end) = @_;
1512   my @usage = ();
1513   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1514   push @usage, { 'png' => $pngOrError };
1515   (@usage);
1516 }
1517
1518 sub _list_svc_usage {
1519   my($svc_acct, $begin, $end) = @_;
1520   my @usage = ();
1521   foreach my $part_export ( 
1522     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1523     qw( sqlradius sqlradius_withdomain )
1524   ) {
1525     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1526   }
1527   (@usage);
1528 }
1529
1530 sub list_svc_usage {
1531   _usage_details(\&_list_svc_usage, @_);
1532 }
1533
1534 sub _list_support_usage {
1535   my($svc_acct, $begin, $end) = @_;
1536   my @usage = ();
1537   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1538             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1539           ) {
1540     push @usage, { 'seconds'  => $_->seconds,
1541                    'support'  => $_->support,
1542                    '_date'    => $_->_date,
1543                    'id'       => $_->transaction_id,
1544                    'creator'  => $_->creator,
1545                    'subject'  => $_->subject,
1546                    'status'   => $_->status,
1547                    'ticketid' => $_->ticketid,
1548                  };
1549   }
1550   (@usage);
1551 }
1552
1553 sub list_support_usage {
1554   _usage_details(\&_list_support_usage, @_);
1555 }
1556
1557 sub _list_cdr_usage {
1558   my($svc_phone, $begin, $end) = @_;
1559   map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1560                        $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1561 }
1562
1563 sub list_cdr_usage {
1564   my $p = shift;
1565   _usage_details( \&_list_cdr_usage, $p,
1566                   'svcdb' => 'svc_phone',
1567                 );
1568 }
1569
1570 sub _usage_details {
1571   my($callback, $p, %opt) = @_;
1572
1573   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1574   return { 'error' => $session } if $context eq 'error';
1575
1576   my $search = { 'svcnum' => $p->{'svcnum'} };
1577   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1578
1579   my $svcdb = $opt{'svcdb'} || 'svc_acct';
1580
1581   my $svc_x = qsearchs( $svcdb, $search );
1582   return { 'error' => 'No service selected in list_svc_usage' } 
1583     unless $svc_x;
1584
1585   my $header = $svcdb eq 'svc_phone'
1586                  ? [ split(',', FS::cdr::invoice_header('default') ) ]  #XXX
1587                  : [];
1588
1589   my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1590   my $freq     = $cust_pkg->part_pkg->freq;
1591   my $start    = $cust_pkg->setup;
1592   #my $end      = $cust_pkg->bill; # or time?
1593   my $end      = time;
1594
1595   unless ( $p->{beginning} ) {
1596     $p->{beginning} = $cust_pkg->last_bill;
1597     $p->{ending}    = $end;
1598   }
1599
1600   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1601
1602   #kinda false laziness with FS::cust_main::bill, but perhaps
1603   #we should really change this bit to DateTime and DateTime::Duration
1604   #
1605   #change this bit to use Date::Manip? CAREFUL with timezones (see
1606   # mailing list archive)
1607   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1608     (localtime($p->{ending}) )[0,1,2,3,4,5];
1609   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1610     (localtime($p->{beginning}) )[0,1,2,3,4,5];
1611
1612   if ( $freq =~ /^\d+$/ ) {
1613     $nmon += $freq;
1614     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1615     $pmon -= $freq;
1616     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1617   } elsif ( $freq =~ /^(\d+)w$/ ) {
1618     my $weeks = $1;
1619     $nmday += $weeks * 7;
1620     $pmday -= $weeks * 7;
1621   } elsif ( $freq =~ /^(\d+)d$/ ) {
1622     my $days = $1;
1623     $nmday += $days;
1624     $pmday -= $days;
1625   } elsif ( $freq =~ /^(\d+)h$/ ) {
1626     my $hours = $1;
1627     $nhour += $hours;
1628     $phour -= $hours;
1629   } else {
1630     return { 'error' => "unparsable frequency: ". $freq };
1631   }
1632   
1633   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1634   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1635
1636   { 
1637     'error'     => '',
1638     'svcnum'    => $p->{svcnum},
1639     'beginning' => $p->{beginning},
1640     'ending'    => $p->{ending},
1641     'previous'  => ($previous > $start) ? $previous : $start,
1642     'next'      => ($next < $end) ? $next : $end,
1643     'header'    => $header,
1644     'usage'     => \@usage,
1645   };
1646 }
1647
1648 sub order_pkg {
1649   my $p = shift;
1650
1651   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1652   return { 'error' => $session } if $context eq 'error';
1653
1654   my $search = { 'custnum' => $custnum };
1655   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1656   my $cust_main = qsearchs('cust_main', $search )
1657     or return { 'error' => "unknown custnum $custnum" };
1658
1659   my $status = $cust_main->status;
1660   #false laziness w/ClientAPI/Signup.pm
1661
1662   my $cust_pkg = new FS::cust_pkg ( {
1663     'custnum' => $custnum,
1664     'pkgpart' => $p->{'pkgpart'},
1665   } );
1666   my $error = $cust_pkg->check;
1667   return { 'error' => $error } if $error;
1668
1669   my @svc = ();
1670   unless ( $p->{'svcpart'} eq 'none' ) {
1671
1672     my $svcdb;
1673     my $svcpart = '';
1674     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1675       $svcpart = $1;
1676       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1677       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1678       $svcdb = $part_svc->svcdb;
1679     } else {
1680       $svcdb = 'svc_acct';
1681     }
1682     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1683
1684     my %fields = (
1685       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
1686       'svc_domain'   => [ qw( domain ) ],
1687       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
1688       'svc_external' => [ qw( id title ) ],
1689       'svc_pbx'      => [ qw( id title ) ],
1690     );
1691   
1692     my $svc_x = "FS::$svcdb"->new( {
1693       'svcpart'   => $svcpart,
1694       map { $_ => $p->{$_} } @{$fields{$svcdb}}
1695     } );
1696     
1697     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1698       my @acct_snarf;
1699       my $snarfnum = 1;
1700       while ( length($p->{"snarf_machine$snarfnum"}) ) {
1701         my $acct_snarf = new FS::acct_snarf ( {
1702           'machine'   => $p->{"snarf_machine$snarfnum"},
1703           'protocol'  => $p->{"snarf_protocol$snarfnum"},
1704           'username'  => $p->{"snarf_username$snarfnum"},
1705           '_password' => $p->{"snarf_password$snarfnum"},
1706         } );
1707         $snarfnum++;
1708         push @acct_snarf, $acct_snarf;
1709       }
1710       $svc_x->child_objects( \@acct_snarf );
1711     }
1712     
1713     my $y = $svc_x->setdefault; # arguably should be in new method
1714     return { 'error' => $y } if $y && !ref($y);
1715   
1716     $error = $svc_x->check;
1717     return { 'error' => $error } if $error;
1718
1719     push @svc, $svc_x;
1720
1721   }
1722
1723   use Tie::RefHash;
1724   tie my %hash, 'Tie::RefHash';
1725   %hash = ( $cust_pkg => \@svc );
1726   #msgcat
1727   $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1728   return { 'error' => $error } if $error;
1729
1730   my $conf = new FS::Conf;
1731   if ( $conf->exists('signup_server-realtime') ) {
1732
1733     my $bill_error = _do_bop_realtime( $cust_main, $status );
1734
1735     if ($bill_error) {
1736       $cust_pkg->cancel('quiet'=>1);
1737       return $bill_error;
1738     } else {
1739       $cust_pkg->reexport;
1740     }
1741
1742   } else {
1743     $cust_pkg->reexport;
1744   }
1745
1746   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1747
1748   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1749
1750 }
1751
1752 sub change_pkg {
1753   my $p = shift;
1754
1755   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1756   return { 'error' => $session } if $context eq 'error';
1757
1758   my $search = { 'custnum' => $custnum };
1759   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1760   my $cust_main = qsearchs('cust_main', $search )
1761     or return { 'error' => "unknown custnum $custnum" };
1762
1763   my $status = $cust_main->status;
1764   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1765     or return { 'error' => "unknown package $p->{pkgnum}" };
1766
1767   my @newpkg;
1768   my $error = FS::cust_pkg::order( $custnum,
1769                                    [$p->{pkgpart}],
1770                                    [$p->{pkgnum}],
1771                                    \@newpkg,
1772                                  );
1773
1774   my $conf = new FS::Conf;
1775   if ( $conf->exists('signup_server-realtime') ) {
1776
1777     my $bill_error = _do_bop_realtime( $cust_main, $status );
1778
1779     if ($bill_error) {
1780       $newpkg[0]->suspend;
1781       return $bill_error;
1782     } else {
1783       $newpkg[0]->reexport;
1784     }
1785
1786   } else {  
1787     $newpkg[0]->reexport;
1788   }
1789
1790   return { error => '', pkgnum => $cust_pkg->pkgnum };
1791
1792 }
1793
1794 sub order_recharge {
1795   my $p = shift;
1796
1797   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1798   return { 'error' => $session } if $context eq 'error';
1799
1800   my $search = { 'custnum' => $custnum };
1801   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1802   my $cust_main = qsearchs('cust_main', $search )
1803     or return { 'error' => "unknown custnum $custnum" };
1804
1805   my $status = $cust_main->status;
1806   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1807     or return { 'error' => "unknown service " . $p->{'svcnum'} };
1808
1809   my $svc_x = $cust_svc->svc_x;
1810   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1811
1812   my %vhash =
1813     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
1814     qw ( recharge_seconds recharge_upbytes recharge_downbytes
1815          recharge_totalbytes );
1816   my $amount = $part_pkg->option('recharge_amount', 1); 
1817   
1818   my ($l, $v, $d) = $cust_svc->label;  # blah
1819   my $pkg = "Recharge $v"; 
1820
1821   my $bill_error = $cust_main->charge($amount, $pkg,
1822      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
1823      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1824      $part_pkg->taxclass); #meh
1825
1826   my $conf = new FS::Conf;
1827   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1828
1829     $bill_error = _do_bop_realtime( $cust_main, $status );
1830
1831     if ($bill_error) {
1832       return $bill_error;
1833     } else {
1834       my $error = $svc_x->recharge (\%vhash);
1835       return { 'error' => $error } if $error;
1836     }
1837
1838   } else {  
1839     my $error = $bill_error;
1840     $error ||= $svc_x->recharge (\%vhash);
1841     return { 'error' => $error } if $error;
1842   }
1843
1844   return { error => '', svc => $cust_svc->part_svc->svc };
1845
1846 }
1847
1848 sub _do_bop_realtime {
1849   my ($cust_main, $status) = (shift, shift);
1850
1851     my $old_balance = $cust_main->balance;
1852
1853     my $bill_error =    $cust_main->bill
1854                      || $cust_main->apply_payments_and_credits
1855                      || $cust_main->realtime_collect('selfservice' => 1);
1856
1857     if (    $cust_main->balance > $old_balance
1858          && $cust_main->balance > 0
1859          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1860               1 : $status eq 'suspended' ) ) {
1861       #this makes sense.  credit is "un-doing" the invoice
1862       my $conf = new FS::Conf;
1863       $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1864                           'self-service decline',
1865                           'reason_type' => $conf->config('signup_credit_type'),
1866                         );
1867       $cust_main->apply_credits( 'order' => 'newest' );
1868
1869       return { 'error' => '_decline', 'bill_error' => $bill_error };
1870     }
1871
1872     '';
1873 }
1874
1875 sub renew_info {
1876   my $p = shift;
1877
1878   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1879   return { 'error' => $session } if $context eq 'error';
1880
1881   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1882     or return { 'error' => "unknown custnum $custnum" };
1883
1884   my @cust_pkg = sort { $a->bill <=> $b->bill }
1885                  grep { $_->part_pkg->freq ne '0' }
1886                  $cust_main->ncancelled_pkgs;
1887
1888   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1889
1890   my $total = $cust_main->balance;
1891
1892   my @array = map {
1893                     my $bill = $_->bill;
1894                     $total += $_->part_pkg->base_recur($_, \$bill);
1895                     my $renew_date = $_->part_pkg->add_freq($_->bill);
1896                     {
1897                       'pkgnum'             => $_->pkgnum,
1898                       'amount'             => sprintf('%.2f', $total),
1899                       'bill_date'          => $_->bill,
1900                       'bill_date_pretty'   => time2str('%x', $_->bill),
1901                       'renew_date'         => $renew_date,
1902                       'renew_date_pretty'  => time2str('%x', $renew_date),
1903                       'expire_date'        => $_->expire,
1904                       'expire_date_pretty' => time2str('%x', $_->expire),
1905                     };
1906                   }
1907                   @cust_pkg;
1908
1909   return { 'dates' => \@array };
1910
1911 }
1912
1913 sub payment_info_renew_info {
1914   my $p = shift;
1915   my $renew_info   = renew_info($p);
1916   my $payment_info = payment_info($p);
1917   return { %$renew_info,
1918            %$payment_info,
1919          };
1920 }
1921
1922 sub order_renew {
1923   my $p = shift;
1924
1925   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1926   return { 'error' => $session } if $context eq 'error';
1927
1928   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1929     or return { 'error' => "unknown custnum $custnum" };
1930
1931   my $date = $p->{'date'};
1932
1933   my $now = time;
1934
1935   #freeside-daily -n -d $date fs_daily $custnum
1936   $cust_main->bill_and_collect( 'time'         => $date,
1937                                 'invoice_time' => $now,
1938                                 'actual_time'  => $now,
1939                                 'check_freq'   => '1d',
1940                               );
1941
1942   return { 'error' => '' };
1943
1944 }
1945
1946 sub suspend_pkg {
1947   my $p = shift;
1948   my $session = _cache->get($p->{'session_id'})
1949     or return { 'error' => "Can't resume session" }; #better error message
1950
1951   my $custnum = $session->{'custnum'};
1952
1953   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1954     or return { 'error' => "unknown custnum $custnum" };
1955
1956   my $conf = new FS::Conf;
1957   my $reasonnum = 
1958     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
1959       or return { 'error' => 'Permission denied' };
1960
1961   my $pkgnum = $p->{'pkgnum'};
1962
1963   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1964                                         'pkgnum'  => $pkgnum,   } )
1965     or return { 'error' => "unknown pkgnum $pkgnum" };
1966
1967   my $error = $cust_pkg->suspend(reason => $reasonnum);
1968   return { 'error' => $error };
1969
1970 }
1971
1972 sub cancel_pkg {
1973   my $p = shift;
1974   my $session = _cache->get($p->{'session_id'})
1975     or return { 'error' => "Can't resume session" }; #better error message
1976
1977   my $custnum = $session->{'custnum'};
1978
1979   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1980     or return { 'error' => "unknown custnum $custnum" };
1981
1982   my $pkgnum = $p->{'pkgnum'};
1983
1984   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1985                                         'pkgnum'  => $pkgnum,   } )
1986     or return { 'error' => "unknown pkgnum $pkgnum" };
1987
1988   my $error = $cust_pkg->cancel('quiet' => 1);
1989   return { 'error' => $error };
1990
1991 }
1992
1993 sub provision_phone {
1994  my $p = shift;
1995  my @bulkdid;
1996  @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
1997
1998  if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
1999       my($context, $session, $custnum) = _custoragent_session_custnum($p);
2000       return { 'error' => $session } if $context eq 'error';
2001     
2002       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2003       return { 'error' => 'service not found' } unless $svc_phone;
2004       return { 'error' => 'invalid svcnum' } 
2005         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2006
2007       $svc_phone->email($p->{'email'}) 
2008         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2009       $svc_phone->forwarddst($p->{'forwarddst'}) 
2010         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
2011             && $p->{'forwarddst'} =~ /^(\d+|)$/;
2012       return { 'error' => $svc_phone->replace };
2013  }
2014
2015 # single DID LNP
2016  unless($p->{'lnp'}) {
2017     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2018     $p->{'lnp_status'} = "portingin";
2019     return _provision( 'FS::svc_phone',
2020                   [qw(lnp_desired_due_date lnp_other_provider 
2021                     lnp_other_provider_account phonenum countrycode lnp_status)],
2022                   [qw(phonenum countrycode)],
2023                   $p,
2024                   @_
2025                 );
2026  }
2027
2028 # single DID order
2029  unless (scalar(@bulkdid)) {
2030     return _provision( 'FS::svc_phone',
2031                   [qw(phonenum countrycode)],
2032                   [qw(phonenum countrycode)],
2033                   $p,
2034                   @_
2035                 );
2036  }
2037
2038 # bulk DID order case
2039   my $error;
2040   foreach my $did ( @bulkdid ) {
2041     $did =~ s/[^0-9]//g;
2042     $error = _provision( 'FS::svc_phone',
2043               [qw(phonenum countrycode)],
2044               [qw(phonenum countrycode)],
2045               {
2046                 'pkgnum' => $p->{'pkgnum'},
2047                 'svcpart' => $p->{'svcpart'},
2048                 'phonenum' => $did,
2049                 'countrycode' => $p->{'countrycode'},
2050                 'session_id' => $p->{'session_id'},
2051               }
2052             );
2053     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2054   }
2055   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2056 }
2057
2058 sub provision_acct {
2059   my $p = shift;
2060   warn "provision_acct called\n"
2061     if $DEBUG;
2062
2063   return { 'error' => gettext('passwords_dont_match') }
2064     if $p->{'_password'} ne $p->{'_password2'};
2065   return { 'error' => gettext('empty_password') }
2066     unless length($p->{'_password'});
2067  
2068   if ($p->{'domsvc'}) {
2069     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2070                                                   qw ( svcpart pkgnum ) );
2071     return { 'error' => gettext('invalid_domain') }
2072       unless ($domains{$p->{'domsvc'}});
2073   }
2074
2075   warn "provision_acct calling _provision\n"
2076     if $DEBUG;
2077   _provision( 'FS::svc_acct',
2078               [qw(username _password domsvc)],
2079               [qw(username _password domsvc)],
2080               $p,
2081               @_
2082             );
2083 }
2084
2085 sub provision_external {
2086   my $p = shift;
2087   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2088   _provision( 'FS::svc_external',
2089               [],
2090               [qw(id title)],
2091               $p,
2092               @_
2093             );
2094 }
2095
2096 sub _provision {
2097   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2098   warn "_provision called for $class\n"
2099     if $DEBUG;
2100
2101   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2102   return { 'error' => $session } if $context eq 'error';
2103
2104   my $search = { 'custnum' => $custnum };
2105   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2106   my $cust_main = qsearchs('cust_main', $search )
2107     or return { 'error' => "unknown custnum $custnum" };
2108
2109   my $pkgnum = $p->{'pkgnum'};
2110
2111   warn "searching for custnum $custnum pkgnum $pkgnum\n"
2112     if $DEBUG;
2113   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2114                                         'pkgnum'  => $pkgnum,
2115                                                                } )
2116     or return { 'error' => "unknown pkgnum $pkgnum" };
2117
2118   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2119     if $DEBUG;
2120   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2121     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2122
2123   warn "creating $class record\n"
2124     if $DEBUG;
2125   my $svc_x = $class->new( {
2126     'pkgnum'  => $p->{'pkgnum'},
2127     'svcpart' => $p->{'svcpart'},
2128     map { $_ => $p->{$_} } @$fields
2129   } );
2130   warn "inserting $class record\n"
2131     if $DEBUG;
2132   my $error = $svc_x->insert;
2133
2134   unless ( $error ) {
2135     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2136       if $DEBUG;
2137     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2138   }
2139
2140   my $return = { 'svc'   => $part_svc->svc,
2141                  'error' => $error,
2142                  map { $_ => $svc_x->get($_) } @$return_fields
2143                };
2144   warn "_provision returning ". Dumper($return). "\n"
2145     if $DEBUG;
2146   return $return;
2147
2148 }
2149
2150 sub part_svc_info {
2151   my $p = shift;
2152
2153   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2154   return { 'error' => $session } if $context eq 'error';
2155
2156   my $search = { 'custnum' => $custnum };
2157   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2158   my $cust_main = qsearchs('cust_main', $search )
2159     or return { 'error' => "unknown custnum $custnum" };
2160
2161   my $pkgnum = $p->{'pkgnum'};
2162
2163   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2164                                         'pkgnum'  => $pkgnum,
2165                                                                } )
2166     or return { 'error' => "unknown pkgnum $pkgnum" };
2167
2168   my $svcpart = $p->{'svcpart'};
2169
2170   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2171                                       'svcpart' => $svcpart,           } )
2172     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2173   my $part_svc = $pkg_svc->part_svc;
2174
2175   my $conf = new FS::Conf;
2176
2177   my $ret = {
2178     'svc'     => $part_svc->svc,
2179     'svcdb'   => $part_svc->svcdb,
2180     'pkgnum'  => $pkgnum,
2181     'svcpart' => $svcpart,
2182     'custnum' => $custnum,
2183
2184     'security_phrase' => 0, #XXX !
2185     'svc_acct_pop'    => [], #XXX !
2186     'popnum'          => '',
2187     'init_popstate'   => '',
2188     'popac'           => '',
2189     'acstate'         => '',
2190
2191     'small_custview' =>
2192       small_custview( $cust_main, $conf->config('countrydefault') ),
2193
2194   };
2195
2196   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2197                      && $ret->{'svcdb'} eq 'svc_phone') {
2198         $ret->{'svcnum'} = $p->{'svcnum'};
2199         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2200         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2201             $ret->{'email'} = $svc_phone->email;
2202             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2203         }
2204   }
2205
2206   $ret;
2207 }
2208
2209 sub unprovision_svc {
2210   my $p = shift;
2211
2212   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2213   return { 'error' => $session } if $context eq 'error';
2214
2215   my $search = { 'custnum' => $custnum };
2216   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2217   my $cust_main = qsearchs('cust_main', $search )
2218     or return { 'error' => "unknown custnum $custnum" };
2219
2220   my $svcnum = $p->{'svcnum'};
2221
2222   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2223     or return { 'error' => "unknown svcnum $svcnum" };
2224
2225   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2226     unless $cust_svc->cust_pkg->custnum == $custnum;
2227
2228   my $conf = new FS::Conf;
2229
2230   return { 'svc'   => $cust_svc->part_svc->svc,
2231            'error' => $cust_svc->cancel,
2232            'small_custview' =>
2233              small_custview( $cust_main, $conf->config('countrydefault') ),
2234          };
2235
2236 }
2237
2238 sub myaccount_passwd {
2239   my $p = shift;
2240   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2241   return { 'error' => $session } if $context eq 'error';
2242
2243   return { 'error' => "New passwords don't match." }
2244     if $p->{'new_password'} ne $p->{'new_password2'};
2245
2246   return { 'error' => 'Enter new password' }
2247     unless length($p->{'new_password'});
2248
2249   #my $search = { 'custnum' => $custnum };
2250   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2251   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2252   my $search = " AND custnum = $1";
2253   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2254
2255   my $svc_acct = qsearchs( {
2256     'table'     => 'svc_acct',
2257     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2258                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2259                    'LEFT JOIN cust_main USING ( custnum ) ',
2260     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2261     'extra_sql' => $search, #important
2262   } )
2263     or return { 'error' => "Service not found" };
2264
2265   if ( exists($p->{'old_password'}) ) {
2266     return { 'error' => "Incorrect password." }
2267       unless $svc_acct->check_password($p->{'old_password'});
2268   }
2269
2270   $svc_acct->_password($p->{'new_password'});
2271   my $error = $svc_acct->replace();
2272
2273   my($label, $value) = $svc_acct->cust_svc->label;
2274
2275   return { 'error' => $error,
2276            'label' => $label,
2277            'value' => $value,
2278          };
2279
2280 }
2281
2282 sub reset_passwd {
2283   my $p = shift;
2284
2285   my $conf = new FS::Conf;
2286   my $verification = $conf->config('selfservice-password_reset_verification')
2287     or return { 'error' => 'Password resets disabled' };
2288
2289   my $username = $p->{'username'};
2290
2291   my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2292     or return { 'error' => 'Account not found' };
2293
2294   my $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2295                                         'domsvc'   => $svc_domain->svcnum  }
2296                          )
2297     or return { 'error' => 'Account not found' };
2298
2299   my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2300     or return { 'error' => 'Account not found' };
2301
2302   my $cust_main = $cust_pkg->cust_main;
2303
2304   my %verify = (
2305     'paymask' => sub { 
2306       my( $p, $cust_main ) = @_;
2307       $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2308         && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2309     },
2310     'amount'  => sub {
2311       my( $p, $cust_main ) = @_;
2312       my $cust_pay = qsearchs({
2313         'table' => 'cust_pay',
2314         'hashref' => { 'custnum' => $cust_main->custnum },
2315         'order_by' => 'ORDER BY _date DESC LIMIT 1',
2316       })
2317         or return 0;
2318
2319       $p->{'amount'} == $cust_pay->paid;
2320     },
2321     'zip'     => sub {
2322       my( $p, $cust_main ) = @_;
2323       $p->{'zip'} eq $cust_main->zip
2324         || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2325     },
2326   );
2327
2328   foreach my $verify ( split(',', $verification) ) {
2329
2330     &{ $verify{$verify} }( $p, $cust_main )
2331       or return { 'error' => 'Account not found' };
2332
2333   }
2334
2335   #we're verified.  now what?
2336  
2337
2338   return { 'error' => '' };
2339 }
2340
2341
2342 sub create_ticket {
2343   my $p = shift;
2344   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2345   return { 'error' => $session } if $context eq 'error';
2346
2347   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2348   FS::TicketSystem->init();
2349
2350   my $conf = new FS::Conf;
2351   my $queue = $p->{'queue'}
2352               || $conf->config('ticket_system-selfservice_queueid')
2353               || $conf->config('ticket_system-default_queueid');
2354
2355   warn "$me create_ticket: creating ticket\n" if $DEBUG;
2356   my $err_or_ticket = FS::TicketSystem->create_ticket(
2357     '', #create RT session based on FS CurrentUser (fs_selfservice)
2358     'queue'   => $queue,
2359     'custnum' => $custnum,
2360     'svcnum'  => $session->{'svcnum'},
2361     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2362   );
2363
2364   if ( ref($err_or_ticket) ) {
2365     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2366       if $DEBUG;
2367     return { 'error'     => '',
2368              'ticket_id' => $err_or_ticket->id,
2369            };
2370   } else {
2371     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2372       if $DEBUG;
2373     return { 'error' => $err_or_ticket };
2374   }
2375
2376
2377 }
2378
2379 sub did_report {
2380   my $p = shift;
2381   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2382   return { 'error' => $session } if $context eq 'error';
2383  
2384   return { error => 'requested format not implemented' } 
2385     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2386
2387   my $conf = new FS::Conf;
2388   my $age_threshold = 0;
2389   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2390     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2391
2392   my $search = { 'custnum' => $custnum };
2393   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2394   my $cust_main = qsearchs('cust_main', $search )
2395     or return { 'error' => "unknown custnum $custnum" };
2396
2397 # does it make more sense to just run one sql query for this instead of all the
2398 # insanity below? would increase performance greately for large data sets?
2399   my @svc_phone = ();
2400   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2401         my @part_svc = $cust_pkg->part_svc;
2402         foreach my $part_svc ( @part_svc ) {
2403             if($part_svc->svcdb eq 'svc_phone'){
2404                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2405                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2406                     push @svc_phone, $cust_pkg_svc->svc_x
2407                         if $cust_pkg_svc->date_inserted >= $age_threshold;
2408                 }
2409             }
2410         }
2411   }
2412
2413   my $csv;
2414   my $xls;
2415   my($xls_r,$xls_c) = (0,0);
2416   my $xls_workbook;
2417   my $content = '';
2418   my @fields = qw( countrycode phonenum pin sip_password phone_name );
2419   if($p->{'format'} eq 'csv') {
2420     $csv = new Text::CSV_XS { 'always_quote' => 1,
2421                                  'eol'          => "\n",
2422                                 };
2423     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2424     $content .= $csv->string;
2425   }
2426   elsif($p->{'format'} eq 'xls') {
2427     my $XLS1 = new IO::Scalar \$content;
2428     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
2429         or return { 'error' => "Error opening .xls file: $!" };
2430     $xls = $xls_workbook->add_worksheet('DIDs');
2431     foreach ( @fields ) {
2432         $xls->write(0,$xls_c++,$_);
2433     }
2434     $xls_r++;
2435   }
2436
2437   foreach my $svc_phone ( @svc_phone ) {
2438     my @cols = map { $svc_phone->$_ } @fields;
2439     if($p->{'format'} eq 'csv') {
2440         return { 'error' => 'Unable to create CSV' } 
2441             unless $csv->combine(@cols);
2442         $content .= $csv->string;
2443     }
2444     elsif($p->{'format'} eq 'xls') {
2445         $xls_c = 0;
2446         foreach ( @cols ) {
2447             $xls->write($xls_r,$xls_c++,$_);
2448         }
2449         $xls_r++;
2450     }
2451   }
2452
2453   $xls_workbook->close() if $p->{'format'} eq 'xls';
2454   
2455   { content => $content, format => $p->{'format'}, };
2456 }
2457
2458 sub get_ticket {
2459   my $p = shift;
2460   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2461   return { 'error' => $session } if $context eq 'error';
2462
2463   warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2464   FS::TicketSystem->init();
2465   return { 'error' => 'get_ticket configuration error' }
2466     if $FS::TicketSystem::system ne 'RT_Internal';
2467
2468   # check existence and ownership as part of this
2469   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2470   my $rt_session = FS::TicketSystem->session('');
2471   my $Ticket = FS::TicketSystem->get_ticket_object(
2472     $rt_session, 
2473     ticket_id => $p->{'ticket_id'},
2474     custnum => $custnum
2475   );
2476   return { 'error' => 'ticket not found' } if !$Ticket;
2477
2478   if ( length( $p->{'subject'} || '' ) ) {
2479     # subject change
2480     if ( $p->{'subject'} ne $Ticket->Subject ) {
2481       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2482       return { 'error' => "unable to set subject: $msg" } if !$val;
2483     }
2484   }
2485
2486   if(length($p->{'reply'})) {
2487     my @err_or_res = FS::TicketSystem->correspond_ticket(
2488       $rt_session,
2489       'ticket_id' => $p->{'ticket_id'},
2490       'content' => $p->{'reply'},
2491     );
2492
2493     return { 'error' => 'unable to reply to ticket' } 
2494     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2495   }
2496
2497   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2498   my $err_or_ticket = FS::TicketSystem->get_ticket(
2499     $rt_session,
2500     'ticket_id' => $p->{'ticket_id'},
2501   );
2502
2503   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2504     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2505       if $DEBUG;
2506     return { 'error' => $err_or_ticket };
2507   }
2508
2509   my @custs = @{$err_or_ticket->{'custs'}};
2510   my @txns = @{$err_or_ticket->{'txns'}};
2511   my @filtered_txns;
2512
2513   # superseded by check in get_ticket_object
2514   #return { 'error' => 'invalid ticket requested' } 
2515   #unless grep($_ eq $custnum, @custs);
2516
2517   foreach my $txn ( @txns ) {
2518     push @filtered_txns, $txn 
2519     if ($txn->{'type'} eq 'EmailRecord' 
2520       || $txn->{'type'} eq 'Correspond'
2521       || $txn->{'type'} eq 'Create');
2522   }
2523
2524   warn "$me get_ticket: successful: \n"
2525   if $DEBUG;
2526   return { 'error'     => '',
2527     'transactions' => \@filtered_txns,
2528     'ticket_fields' => $err_or_ticket->{'fields'},
2529     'ticket_id' => $p->{'ticket_id'},
2530   };
2531 }
2532
2533 sub adjust_ticket_priority {
2534   my $p = shift;
2535   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2536   return { 'error' => $session } if $context eq 'error';
2537
2538   warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2539   FS::TicketSystem->init;
2540   my $ss_priority = FS::TicketSystem->selfservice_priority;
2541
2542   return { 'error' => 'adjust_ticket_priority configuration error' }
2543     if $FS::TicketSystem::system ne 'RT_Internal'
2544       or !$ss_priority;
2545
2546   my $values = $p->{'values'}; #hashref, id => priority value
2547   my %ticket_error;
2548
2549   foreach my $id (keys %$values) {
2550     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
2551     my $Ticket = FS::TicketSystem->get_ticket_object('',
2552       'ticket_id' => $id,
2553       'custnum'   => $custnum,
2554     );
2555     if ( !$Ticket ) {
2556       $ticket_error{$id} = 'ticket not found';
2557       next;
2558     }
2559     
2560   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
2561   # We're not going to implement it for RT_External.
2562     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
2563     my $new_value = $values->{$id};
2564     next if $old_value eq $new_value;
2565
2566     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
2567
2568     # AddCustomFieldValue works fine (replacing any existing value) if it's 
2569     # a single-valued custom field, which it should be.  If it's not, you're 
2570     # doing something wrong.
2571     my ($val, $msg);
2572     if ( length($new_value) ) {
2573       ($val, $msg) = $Ticket->AddCustomFieldValue( 
2574         Field => $ss_priority,
2575         Value => $new_value,
2576       );
2577     }
2578     else {
2579       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
2580         Field => $ss_priority,
2581         Value => $old_value,
2582       );
2583     }
2584
2585     $ticket_error{$id} = $msg if !$val;
2586     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
2587   }
2588   return { 'error' => '',
2589            'ticket_error' => \%ticket_error,
2590            %{ customer_info($p) } # send updated customer info back
2591          }
2592 }
2593
2594 #--
2595
2596 sub _custoragent_session_custnum {
2597   my $p = shift;
2598
2599   my($context, $session, $custnum);
2600   if ( $p->{'session_id'} ) {
2601
2602     $context = 'customer';
2603     $session = _cache->get($p->{'session_id'})
2604       or return ( 'error' => "Can't resume session" ); #better error message
2605     $custnum = $session->{'custnum'};
2606
2607   } elsif ( $p->{'agent_session_id'} ) {
2608
2609     $context = 'agent';
2610     my $agent_cache = new FS::ClientAPI_SessionCache( {
2611       'namespace' => 'FS::ClientAPI::Agent',
2612     } );
2613     $session = $agent_cache->get($p->{'agent_session_id'})
2614       or return ( 'error' => "Can't resume session" ); #better error message
2615     $custnum = $p->{'custnum'};
2616
2617   } else {
2618     $context = 'error';
2619     return ( 'error' => "Can't resume session" ); #better error message
2620   }
2621
2622   ($context, $session, $custnum);
2623
2624 }
2625
2626 1;
2627