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