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