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