service refactor!
[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   #   #OR
85   #  'svc'      => $svc_x, #or $cust_svc, it just needs a svcnum
86   #
87   # ##
88   # #optional
89   # ##
90   #  'ahref'    => 1, # if set true, returns <A HREF="$url">
91
92 use FS::CGI qw(popurl);
93 sub svc_url {
94   my %opt = @_;
95
96   #? return '' unless ref($opt{part_svc});
97
98   my $svcdb = $opt{svcdb} || $opt{part_svc}->svcdb;
99   my $query = exists($opt{query}) ? $opt{query} : $opt{svc}->svcnum;
100   my $url;
101   warn "$me [svc_url] checking for /$opt{action}/$svcdb.cgi component"
102     if $DEBUG;
103   if ( $opt{m}->interp->comp_exists("/$opt{action}/$svcdb.cgi") ) {
104     $url = "$svcdb.cgi?";
105   } else {
106
107     my $generic = $opt{action} eq 'search' ? 'cust_svc' : 'svc_Common';
108
109     $url = "$generic.html?svcdb=$svcdb;";
110     $url .= 'svcnum=' if $query =~ /^\d+(;|$)/;
111   }
112
113   my $p = popurl(2); #?
114   my $return = "$p$opt{action}/$url$query";
115
116   $return = qq!<A HREF="$return">! if $opt{ahref};
117
118   $return;
119 }
120
121 sub svc_link {
122   my($m, $part_svc, $cust_svc) = @_ or return '';
123   svc_X_link( $part_svc->svc, @_ );
124 }
125
126 sub svc_label_link {
127   my($m, $part_svc, $cust_svc) = @_ or return '';
128   svc_X_link( ($cust_svc->label)[1], @_ );
129 }
130
131 sub svc_X_link {
132   my ($x, $m, $part_svc, $cust_svc) = @_ or return '';
133   my $ahref = svc_url(
134     'ahref'    => 1,
135     'm'        => $m,
136     'action'   => 'view',
137     'part_svc' => $part_svc,
138     'svc'      => $cust_svc,
139   );
140
141   "$ahref$x</A>";
142 }
143
144 sub parse_lt_gt {
145   my($cgi, $field) = @_;
146
147   my @search = ();
148
149   my %op = ( 
150     'lt' => '<',
151     'gt' => '>',
152   );
153
154   foreach my $op (keys %op) {
155
156     warn "checking for ${field}_$op field\n"
157       if $DEBUG;
158
159     if ( $cgi->param($field."_$op") =~ /^\s*\$?\s*([\d\,\s]+(\.\d\d)?)\s*$/ ) {
160
161       my $num = $1;
162       $num =~ s/[\,\s]+//g;
163       my $search = "$field $op{$op} $num";
164       push @search, $search;
165
166       warn "found ${field}_$op field; adding search element $search\n"
167         if $DEBUG;
168     }
169
170   }
171
172   @search;
173
174 }
175
176 sub bytecount_unexact {
177   my $bc = shift;
178   return("$bc bytes")
179     if ($bc < 1000);
180   return(sprintf("%.2f Kbytes", $bc/1000))
181     if ($bc < 1000000);
182   return(sprintf("%.2f Mbytes", $bc/1000000))
183     if ($bc < 1000000000);
184   return(sprintf("%.2f Gbytes", $bc/1000000000));
185 }
186
187 ###
188 # cust_main report subroutines
189 ###
190
191
192 =item cust_header [ CUST_FIELDS_VALUE ]
193
194 Returns an array of customer information headers according to the supplied
195 customer fields value, or if no value is supplied, the B<cust-fields>
196 configuration value.
197
198 =cut
199
200 use vars qw( @cust_fields );
201
202 sub cust_header {
203
204   warn "FS::svc_Common::cust_header called"
205     if $DEBUG;
206
207   my %header2method = (
208     'Customer'                 => 'name',
209     'Cust#'                    => 'custnum',
210     'Name'                     => 'contact',
211     'Company'                  => 'company',
212     '(bill) Customer'          => 'name',
213     '(service) Customer'       => 'ship_name',
214     '(bill) Name'              => 'contact',
215     '(service) Name'           => 'ship_contact',
216     '(bill) Company'           => 'company',
217     '(service) Company'        => 'ship_company',
218     'Address 1'                => 'address1',
219     'Address 2'                => 'address2',
220     'City'                     => 'city',
221     'State'                    => 'state',
222     'Zip'                      => 'zip',
223     'Country'                  => 'country_full',
224     'Day phone'                => 'daytime', # XXX should use msgcat, but how?
225     'Night phone'              => 'night',   # XXX should use msgcat, but how?
226     'Invoicing email(s)'       => 'invoicing_list_emailonly',
227   );
228
229   my $cust_fields;
230   my @cust_header;
231   if ( @_ && $_[0] ) {
232
233     warn "  using supplied cust-fields override".
234           " (ignoring cust-fields config file)"
235       if $DEBUG;
236     $cust_fields = shift;
237
238   } else {
239
240     my $conf = new FS::Conf;
241     if (    $conf->exists('cust-fields')
242          && $conf->config('cust-fields') =~ /^([\w \|\#\(\)]+):?/
243        )
244     {
245       warn "  found cust-fields configuration value"
246         if $DEBUG;
247       $cust_fields = $1;
248     } else { 
249       warn "  no cust-fields configuration value found; using default 'Customer'"
250         if $DEBUG;
251       $cust_fields = 'Customer';
252     }
253   
254   }
255
256   @cust_header = split(/ \| /, $cust_fields);
257   @cust_fields = map { $header2method{$_} } @cust_header;
258
259   #my $svc_x = shift;
260   @cust_header;
261 }
262
263 =item cust_sql_fields [ CUST_FIELDS_VALUE ]
264
265 Returns a list of fields for the SELECT portion of an SQL query.
266
267 As with L<the cust_header subroutine|/cust_header>, the fields returned are
268 defined by the supplied customer fields setting, or if no customer fields
269 setting is supplied, the <B>cust-fields</B> configuration value. 
270
271 =cut
272
273 sub cust_sql_fields {
274
275   my @fields = qw( last first company );
276   push @fields, map "ship_$_", @fields;
277   push @fields, 'country';
278
279   cust_header(@_);
280   #inefficientish, but tiny lists and only run once per page
281   push @fields,
282     grep { my $field = $_; grep { $_ eq $field } @cust_fields }
283          qw( address1 address2 city state zip daytime night );
284
285   map "cust_main.$_", @fields;
286 }
287
288 =item cust_fields SVC_OBJECT [ CUST_FIELDS_VALUE ]
289
290 Given a svc_ object that contains fields from cust_main (say, from a
291 JOINed search.  See httemplate/search/svc_* for examples), returns an array
292 of customer information, or "(unlinked)" if this service is not linked to a
293 customer.
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_fields {
302   my $svc_x = shift;
303   warn "FS::svc_Common::cust_fields called for $svc_x ".
304        "(cust_fields: @cust_fields)"
305     if $DEBUG > 1;
306
307   #cust_header(@_) unless @cust_fields; #now need to cache to keep cust_fields
308   #                                     #override incase we were passed as a sub
309
310   my $seen_unlinked = 0;
311   map { 
312     if ( $svc_x->custnum ) {
313       warn "  $svc_x -> $_"
314         if $DEBUG > 1;
315       $svc_x->$_(@_);
316     } else {
317       warn "  ($svc_x unlinked)"
318         if $DEBUG > 1;
319       $seen_unlinked++ ? '' : '(unlinked)';
320     }
321   } @cust_fields;
322 }
323
324 ###
325 # begin JSRPC code...
326 ###
327
328 package FS::UI::Web::JSRPC;
329
330 use strict;
331 use vars qw($DEBUG);
332 use Carp;
333 use Storable qw(nfreeze);
334 use MIME::Base64;
335 use JSON;
336 use FS::UID;
337 use FS::Record qw(qsearchs);
338 use FS::queue;
339
340 $DEBUG = 0;
341
342 sub new {
343         my $class = shift;
344         my $self  = {
345                 env => {},
346                 job => shift,
347                 cgi => shift,
348         };
349
350         bless $self, $class;
351
352         croak "CGI object required as second argument" unless $self->{'cgi'};
353
354         return $self;
355 }
356
357 sub process {
358
359   my $self = shift;
360
361   my $cgi = $self->{'cgi'};
362
363   # XXX this should parse JSON foo and build a proper data structure
364   my @args = $cgi->param('arg');
365
366   #work around konqueror bug!
367   @args = map { s/\x00$//; $_; } @args;
368
369   my $sub = $cgi->param('sub'); #????
370
371   warn "FS::UI::Web::JSRPC::process:\n".
372        "  cgi=$cgi\n".
373        "  sub=$sub\n".
374        "  args=".join(', ',@args)."\n"
375     if $DEBUG;
376
377   if ( $sub eq 'start_job' ) {
378
379     $self->start_job(@args);
380
381   } elsif ( $sub eq 'job_status' ) {
382
383     $self->job_status(@args);
384
385   } else {
386
387     die "unknown sub $sub";
388
389   }
390
391 }
392
393 sub start_job {
394   my $self = shift;
395
396   warn "FS::UI::Web::start_job: ". join(', ', @_) if $DEBUG;
397 #  my %param = @_;
398   my %param = ();
399   while ( @_ ) {
400     my( $field, $value ) = splice(@_, 0, 2);
401     unless ( exists( $param{$field} ) ) {
402       $param{$field} = $value;
403     } elsif ( ! ref($param{$field}) ) {
404       $param{$field} = [ $param{$field}, $value ];
405     } else {
406       push @{$param{$field}}, $value;
407     }
408   }
409   warn "FS::UI::Web::start_job\n".
410        join('', map {
411                       if ( ref($param{$_}) ) {
412                         "  $_ => [ ". join(', ', @{$param{$_}}). " ]\n";
413                       } else {
414                         "  $_ => $param{$_}\n";
415                       }
416                     } keys %param )
417     if $DEBUG;
418
419   #first get the CGI params shipped off to a job ASAP so an id can be returned
420   #to the caller
421   
422   my $job = new FS::queue { 'job' => $self->{'job'} };
423   
424   #too slow to insert all the cgi params as individual args..,?
425   #my $error = $queue->insert('_JOB', $cgi->Vars);
426   
427   #warn 'froze string of size '. length(nfreeze(\%param)). " for job args\n"
428   #  if $DEBUG;
429
430   my $error = $job->insert( '_JOB', encode_base64(nfreeze(\%param)) );
431
432   if ( $error ) {
433
434     warn "job not inserted: $error\n"
435       if $DEBUG;
436
437     $error;  #this doesn't seem to be handled well,
438              # will trigger "illegal jobnum" below?
439              # (should never be an error inserting the job, though, only thing
440              #  would be Pg f%*kage)
441   } else {
442
443     warn "job inserted successfully with jobnum ". $job->jobnum. "\n"
444       if $DEBUG;
445
446     $job->jobnum;
447   }
448   
449 }
450
451 sub job_status {
452   my( $self, $jobnum ) = @_; #$url ???
453
454   sleep 1; # XXX could use something better...
455
456   my $job;
457   if ( $jobnum =~ /^(\d+)$/ ) {
458     $job = qsearchs('queue', { 'jobnum' => $jobnum } );
459   } else {
460     die "FS::UI::Web::job_status: illegal jobnum $jobnum\n";
461   }
462
463   my @return;
464   if ( $job && $job->status ne 'failed' ) {
465     @return = ( 'progress', $job->statustext );
466   } elsif ( !$job ) { #handle job gone case : job successful
467                       # so close popup, redirect parent window...
468     @return = ( 'complete' );
469   } else {
470     @return = ( 'error', $job ? $job->statustext : $jobnum );
471   }
472
473   objToJson(\@return);
474
475 }
476
477 1;
478