some random cleanups
[freeside.git] / FS / FS / UI / Web.pm
1 package FS::UI::Web;
2
3 use strict;
4 use vars qw($DEBUG @ISA @EXPORT_OK $me);
5 use Exporter;
6 use FS::Conf;
7 use FS::Record qw(dbdef);
8 use FS::cust_main;  # are sql_balance and sql_date_balance in the right module?
9
10 #use vars qw(@ISA);
11 #use FS::UI
12 #@ISA = qw( FS::UI );
13 @ISA = qw( Exporter );
14
15 @EXPORT_OK = qw( svc_url );
16
17 $DEBUG = 0;
18 $me = '[FS::UID::Web]';
19
20 ###
21 # date parsing
22 ###
23
24 use Date::Parse;
25 sub parse_beginning_ending {
26   my($cgi, $prefix) = @_;
27   $prefix .= '_' if $prefix;
28
29   my $beginning = 0;
30   if ( $cgi->param($prefix.'begin') =~ /^(\d+)$/ ) {
31     $beginning = $1;
32   } elsif ( $cgi->param($prefix.'beginning') =~ /^([ 0-9\-\/]{1,64})$/ ) {
33     $beginning = str2time($1) || 0;
34   }
35
36   my $ending = 4294967295; #2^32-1
37   if ( $cgi->param($prefix.'end') =~ /^(\d+)$/ ) {
38     $ending = $1 - 1;
39   } elsif ( $cgi->param($prefix.'ending') =~ /^([ 0-9\-\/]{1,64})$/ ) {
40     #probably need an option to turn off the + 86399
41     $ending = str2time($1) + 86399;
42   }
43
44   ( $beginning, $ending );
45 }
46
47 =item svc_url
48
49 Returns a service URL, first checking to see if there is a service-specific
50 page to link to, otherwise to a generic service handling page.  Options are
51 passed as a list of name-value pairs, and include:
52
53 =over 4
54
55 =item * m - Mason request object ($m)
56
57 =item * action - The action for which to construct "edit", "view", or "search"
58
59 =item ** part_svc - Service definition (see L<FS::part_svc>)
60
61 =item ** svcdb - Service table
62
63 =item *** query - Query string
64
65 =item *** svc   - FS::cust_svc or FS::svc_* object
66
67 =item ahref - Optional flag, if set true returns <A HREF="$url"> instead of just the URL.
68
69 =back 
70
71 * Required fields
72
73 ** part_svc OR svcdb is required
74
75 *** query OR svc is required
76
77 =cut
78
79   # ##
80   # #required
81   # ##
82   #  'm'        => $m, #mason request object
83   #  'action'   => 'edit', #or 'view'
84   #
85   #  'part_svc' => $part_svc, #usual
86   #   #OR
87   #  'svcdb'    => 'svc_table',
88   #
89   #  'query'    => #optional query string
90   #                # (pass a blank string if you want a "raw" URL to add your
91   #                #  own svcnum to)
92   #   #OR
93   #  'svc'      => $svc_x, #or $cust_svc, it just needs a svcnum
94   #
95   # ##
96   # #optional
97   # ##
98   #  'ahref'    => 1, # if set true, returns <A HREF="$url">
99
100 use FS::CGI qw(rooturl);
101 sub svc_url {
102   my %opt = @_;
103
104   #? return '' unless ref($opt{part_svc});
105
106   my $svcdb = $opt{svcdb} || $opt{part_svc}->svcdb;
107   my $query = exists($opt{query}) ? $opt{query} : $opt{svc}->svcnum;
108   my $url;
109   warn "$me [svc_url] checking for /$opt{action}/$svcdb.cgi component"
110     if $DEBUG;
111   if ( $opt{m}->interp->comp_exists("/$opt{action}/$svcdb.cgi") ) {
112     $url = "$svcdb.cgi?";
113   } else {
114
115     my $generic = $opt{action} eq 'search' ? 'cust_svc' : 'svc_Common';
116
117     $url = "$generic.html?svcdb=$svcdb;";
118     $url .= 'svcnum=' if $query =~ /^\d+(;|$)/ or $query eq '';
119   }
120
121   import FS::CGI 'rooturl'; #WTF!  why is this necessary
122   my $return = rooturl(). "$opt{action}/$url$query";
123
124   $return = qq!<A HREF="$return">! if $opt{ahref};
125
126   $return;
127 }
128
129 sub svc_link {
130   my($m, $part_svc, $cust_svc) = @_ or return '';
131   svc_X_link( $part_svc->svc, @_ );
132 }
133
134 sub svc_label_link {
135   my($m, $part_svc, $cust_svc) = @_ or return '';
136   svc_X_link( ($cust_svc->label)[1], @_ );
137 }
138
139 sub svc_X_link {
140   my ($x, $m, $part_svc, $cust_svc) = @_ or return '';
141   my $ahref = svc_url(
142     'ahref'    => 1,
143     'm'        => $m,
144     'action'   => 'view',
145     'part_svc' => $part_svc,
146     'svc'      => $cust_svc,
147   );
148
149   "$ahref$x</A>";
150 }
151
152 sub svc_export_links {
153   my ($m, $part_svc, $cust_svc) = @_ or return '';
154
155   my $ahref = $cust_svc->export_links;
156
157   join('', @$ahref);
158 }
159
160 sub parse_lt_gt {
161   my($cgi, $field) = @_;
162
163   my @search = ();
164
165   my %op = ( 
166     'lt' => '<',
167     'gt' => '>',
168   );
169
170   foreach my $op (keys %op) {
171
172     warn "checking for ${field}_$op field\n"
173       if $DEBUG;
174
175     if ( $cgi->param($field."_$op") =~ /^\s*\$?\s*(-?[\d\,\s]+(\.\d\d)?)\s*$/ ) {
176
177       my $num = $1;
178       $num =~ s/[\,\s]+//g;
179       my $search = "$field $op{$op} $num";
180       push @search, $search;
181
182       warn "found ${field}_$op field; adding search element $search\n"
183         if $DEBUG;
184     }
185
186   }
187
188   @search;
189
190 }
191
192 ###
193 # cust_main report subroutines
194 ###
195
196
197 =item cust_header [ CUST_FIELDS_VALUE ]
198
199 Returns an array of customer information headers according to the supplied
200 customer fields value, or if no value is supplied, the B<cust-fields>
201 configuration value.
202
203 =cut
204
205 use vars qw( @cust_fields @cust_colors @cust_styles @cust_aligns );
206
207 sub cust_header {
208
209   warn "FS::UI:Web::cust_header called"
210     if $DEBUG;
211
212   my %header2method = (
213     'Customer'                 => 'name',
214     'Cust. Status'             => 'ucfirst_cust_status',
215     'Cust#'                    => 'custnum',
216     'Name'                     => 'contact',
217     'Company'                  => 'company',
218     '(bill) Customer'          => 'name',
219     '(service) Customer'       => 'ship_name',
220     '(bill) Name'              => 'contact',
221     '(service) Name'           => 'ship_contact',
222     '(bill) Company'           => 'company',
223     '(service) Company'        => 'ship_company',
224     'Address 1'                => 'address1',
225     'Address 2'                => 'address2',
226     'City'                     => 'city',
227     'State'                    => 'state',
228     'Zip'                      => 'zip',
229     'Country'                  => 'country_full',
230     'Day phone'                => 'daytime', # XXX should use msgcat, but how?
231     'Night phone'              => 'night',   # XXX should use msgcat, but how?
232     'Fax number'               => 'fax',
233     'Invoicing email(s)'       => 'invoicing_list_emailonly_scalar',
234     'Payment Type'             => 'payby',
235     'Current Balance'          => 'current_balance',
236   );
237
238   my %header2colormethod = (
239     'Cust. Status' => 'cust_statuscolor',
240   );
241   my %header2style = (
242     'Cust. Status' => 'b',
243   );
244   my %header2align = (
245     'Cust. Status' => 'c',
246   );
247
248   my $cust_fields;
249   my @cust_header;
250   if ( @_ && $_[0] ) {
251
252     warn "  using supplied cust-fields override".
253           " (ignoring cust-fields config file)"
254       if $DEBUG;
255     $cust_fields = shift;
256
257   } else {
258
259     my $conf = new FS::Conf;
260     if (    $conf->exists('cust-fields')
261          && $conf->config('cust-fields') =~ /^([\w\. \|\#\(\)]+):?/
262        )
263     {
264       warn "  found cust-fields configuration value"
265         if $DEBUG;
266       $cust_fields = $1;
267     } else { 
268       warn "  no cust-fields configuration value found; using default 'Cust. Status | Customer'"
269         if $DEBUG;
270       $cust_fields = 'Cust. Status | Customer';
271     }
272   
273   }
274
275   @cust_header = split(/ \| /, $cust_fields);
276   @cust_fields = map { $header2method{$_} } @cust_header;
277   @cust_colors = map { exists $header2colormethod{$_}
278                          ? $header2colormethod{$_}
279                          : ''
280                      }
281                      @cust_header;
282   @cust_styles = map { exists $header2style{$_} ? $header2style{$_} : '' }
283                      @cust_header;
284   @cust_aligns = map { exists $header2align{$_} ? $header2align{$_} : 'l' }
285                      @cust_header;
286
287   #my $svc_x = shift;
288   @cust_header;
289 }
290
291 =item cust_sql_fields [ CUST_FIELDS_VALUE ]
292
293 Returns a list of fields for the SELECT portion of an SQL query.
294
295 As with L<the cust_header subroutine|/cust_header>, the fields returned are
296 defined by the supplied customer fields setting, or if no customer fields
297 setting is supplied, the <B>cust-fields</B> configuration value. 
298
299 =cut
300
301 sub cust_sql_fields {
302
303   my @fields = qw( last first company );
304   push @fields, map "ship_$_", @fields;
305   push @fields, 'country';
306
307   cust_header(@_);
308   #inefficientish, but tiny lists and only run once per page
309   push @fields,
310     grep { my $field = $_; grep { $_ eq $field } @cust_fields }
311          qw( address1 address2 city state zip daytime night fax payby );
312
313   my @extra_fields = ();
314   if (grep { $_ eq 'current_balance' } @cust_fields) {
315     push @extra_fields, FS::cust_main->balance_sql . " AS current_balance";
316   }
317
318   map("cust_main.$_", @fields), @extra_fields;
319 }
320
321 =item cust_fields OBJECT [ CUST_FIELDS_VALUE ]
322
323 Given an object that contains fields from cust_main (say, from a
324 JOINed search.  See httemplate/search/svc_* for examples), returns an array
325 of customer information, or "(unlinked)" if this service is not linked to a
326 customer.
327
328 As with L<the cust_header subroutine|/cust_header>, the fields returned are
329 defined by the supplied customer fields setting, or if no customer fields
330 setting is supplied, the <B>cust-fields</B> configuration value. 
331
332 =cut
333
334 sub cust_fields {
335   my $record = shift;
336   warn "FS::UI::Web::cust_fields called for $record ".
337        "(cust_fields: @cust_fields)"
338     if $DEBUG > 1;
339
340   #cust_header(@_) unless @cust_fields; #now need to cache to keep cust_fields
341   #                                     #override incase we were passed as a sub
342
343   my $seen_unlinked = 0;
344   map { 
345     if ( $record->custnum ) {
346       warn "  $record -> $_"
347         if $DEBUG > 1;
348       $record->$_(@_);
349     } else {
350       warn "  ($record unlinked)"
351         if $DEBUG > 1;
352       $seen_unlinked++ ? '' : '(unlinked)';
353     }
354   } @cust_fields;
355 }
356
357 =item cust_colors
358
359 Returns an array of subroutine references (or empty strings) for returning
360 customer information colors.
361
362 As with L<the cust_header subroutine|/cust_header>, the fields returned are
363 defined by the supplied customer fields setting, or if no customer fields
364 setting is supplied, the <B>cust-fields</B> configuration value. 
365
366 =cut
367
368 sub cust_colors {
369   map { 
370     my $method = $_;
371     if ( $method ) {
372       sub { shift->$method(@_) };
373     } else {
374       '';
375     }
376   } @cust_colors;
377 }
378
379 =item cust_styles
380
381 Returns an array of customer information styles.
382
383 As with L<the cust_header subroutine|/cust_header>, the fields returned are
384 defined by the supplied customer fields setting, or if no customer fields
385 setting is supplied, the <B>cust-fields</B> configuration value. 
386
387 =cut
388
389 sub cust_styles {
390   map { 
391     if ( $_ ) {
392       $_;
393     } else {
394       '';
395     }
396   } @cust_styles;
397 }
398
399 =item cust_aligns
400
401 Returns an array or scalar (depending on context) of customer information
402 alignments.
403
404 As with L<the cust_header subroutine|/cust_header>, the fields returned are
405 defined by the supplied customer fields setting, or if no customer fields
406 setting is supplied, the <B>cust-fields</B> configuration value. 
407
408 =cut
409
410 sub cust_aligns {
411   if ( wantarray ) {
412     @cust_aligns;
413   } else {
414     join('', @cust_aligns);
415   }
416 }
417
418 ###
419 # begin JSRPC code...
420 ###
421
422 package FS::UI::Web::JSRPC;
423
424 use strict;
425 use vars qw($DEBUG);
426 use Carp;
427 use Storable qw(nfreeze);
428 use MIME::Base64;
429 use JSON;
430 use FS::UID qw(getotaker);
431 use FS::Record qw(qsearchs);
432 use FS::queue;
433
434 $DEBUG = 0;
435
436 sub new {
437         my $class = shift;
438         my $self  = {
439                 env => {},
440                 job => shift,
441                 cgi => shift,
442         };
443
444         bless $self, $class;
445
446         croak "CGI object required as second argument" unless $self->{'cgi'};
447
448         return $self;
449 }
450
451 sub process {
452
453   my $self = shift;
454
455   my $cgi = $self->{'cgi'};
456
457   # XXX this should parse JSON foo and build a proper data structure
458   my @args = $cgi->param('arg');
459
460   #work around konqueror bug!
461   @args = map { s/\x00$//; $_; } @args;
462
463   my $sub = $cgi->param('sub'); #????
464
465   warn "FS::UI::Web::JSRPC::process:\n".
466        "  cgi=$cgi\n".
467        "  sub=$sub\n".
468        "  args=".join(', ',@args)."\n"
469     if $DEBUG;
470
471   if ( $sub eq 'start_job' ) {
472
473     $self->start_job(@args);
474
475   } elsif ( $sub eq 'job_status' ) {
476
477     $self->job_status(@args);
478
479   } else {
480
481     die "unknown sub $sub";
482
483   }
484
485 }
486
487 sub start_job {
488   my $self = shift;
489
490   warn "FS::UI::Web::start_job: ". join(', ', @_) if $DEBUG;
491 #  my %param = @_;
492   my %param = ();
493   while ( @_ ) {
494     my( $field, $value ) = splice(@_, 0, 2);
495     unless ( exists( $param{$field} ) ) {
496       $param{$field} = $value;
497     } elsif ( ! ref($param{$field}) ) {
498       $param{$field} = [ $param{$field}, $value ];
499     } else {
500       push @{$param{$field}}, $value;
501     }
502   }
503   $param{CurrentUser} = getotaker();
504   warn "FS::UI::Web::start_job\n".
505        join('', map {
506                       if ( ref($param{$_}) ) {
507                         "  $_ => [ ". join(', ', @{$param{$_}}). " ]\n";
508                       } else {
509                         "  $_ => $param{$_}\n";
510                       }
511                     } keys %param )
512     if $DEBUG;
513
514   #first get the CGI params shipped off to a job ASAP so an id can be returned
515   #to the caller
516   
517   my $job = new FS::queue { 'job' => $self->{'job'} };
518   
519   #too slow to insert all the cgi params as individual args..,?
520   #my $error = $queue->insert('_JOB', $cgi->Vars);
521   
522   #warn 'froze string of size '. length(nfreeze(\%param)). " for job args\n"
523   #  if $DEBUG;
524
525   my $error = $job->insert( '_JOB', encode_base64(nfreeze(\%param)) );
526
527   if ( $error ) {
528
529     warn "job not inserted: $error\n"
530       if $DEBUG;
531
532     $error;  #this doesn't seem to be handled well,
533              # will trigger "illegal jobnum" below?
534              # (should never be an error inserting the job, though, only thing
535              #  would be Pg f%*kage)
536   } else {
537
538     warn "job inserted successfully with jobnum ". $job->jobnum. "\n"
539       if $DEBUG;
540
541     $job->jobnum;
542   }
543   
544 }
545
546 sub job_status {
547   my( $self, $jobnum ) = @_; #$url ???
548
549   sleep 1; # XXX could use something better...
550
551   my $job;
552   if ( $jobnum =~ /^(\d+)$/ ) {
553     $job = qsearchs('queue', { 'jobnum' => $jobnum } );
554   } else {
555     die "FS::UI::Web::job_status: illegal jobnum $jobnum\n";
556   }
557
558   my @return;
559   if ( $job && $job->status ne 'failed' ) {
560     @return = ( 'progress', $job->statustext );
561   } elsif ( !$job ) { #handle job gone case : job successful
562                       # so close popup, redirect parent window...
563     @return = ( 'complete' );
564   } else {
565     @return = ( 'error', $job ? $job->statustext : $jobnum );
566   }
567
568   objToJson(\@return);
569
570 }
571
572 1;
573