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