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