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