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