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