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