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