no reason for multi-select to be disabled on these
[freeside.git] / FS / FS / part_export / a2billing.pm
1 package FS::part_export::a2billing;
2
3 use strict;
4 use vars qw(@ISA @EXPORT_OK $DEBUG %info %options);
5 use Exporter;
6 use Tie::IxHash;
7 use FS::Record qw( qsearch qsearchs str2time_sql );
8 use FS::part_export;
9 use FS::svc_acct;
10 use FS::svc_phone;
11 use Locale::Country qw(country_code2code);
12 use Date::Format qw(time2str);
13 use Carp qw( cluck );
14
15 @ISA = qw(FS::part_export);
16
17 $DEBUG = 0;
18
19 tie %options, 'Tie::IxHash',
20   'datasrc'     => { label=>'DBI data source ' },
21   'username'    => { label=>'Database username' },
22   'password'    => { label=>'Database password' },
23   'didgroup'    => { label=>'DID group ID', default=>1 },
24   'credit'      => { label=>'Default credit limit' },
25   'billtype'    => {label=>'Billing type',
26                     type => 'select',
27                     options => ['Dial Out Rate', 'Free']
28                   },
29   'debug'       => { label=>'Enable debugging', type=>'checkbox' }
30 ;
31
32 my $notes = <<'END';
33 <p>Real-time export to the backend database of an <a
34 href="http://www.asterisk2billing.org">Asterisk2Billing</a> billing server.
35 This is both a svc_acct and a svc_phone export, and needs to be attached 
36 to both a svc_acct and svc_phone definition within the same package.</p>
37 <ul>
38 <li>When you set up this export, it will create 'svcnum' fields in the 
39 cc_card and cc_did tables in the A2Billing database to store the 
40 service numbers of svc_acct and svc_phone records.  The database username 
41 must have ALTER TABLE privileges.</li>
42 <li><i>DBI data source</i> should look like<br>
43 <b>dbi:mysql:host=</b><i>hostname</i><b>;database=</b><i>dbname</i>
44 </li>
45 END
46
47 %info = (
48   'svc'      => ['svc_acct', 'svc_phone'],
49   'desc'     => 'Export to Asterisk2Billing database',
50   'options'  => \%options,
51   'nodomain' => 'Y',
52   'no_machine' => 1,
53   'notes'    => $notes
54 );
55
56 sub dbh {
57   my $self = shift;
58   $self->{dbh} ||= DBI->connect(
59                       $self->option('datasrc'),
60                       $self->option('username'),
61                       $self->option('password')
62                       ) or die $DBI::errstr;
63
64   $self->{dbh}->trace(1, '%%%FREESIDE_LOG%%%/a2b_exportlog.'.$self->exportnum)
65     if $DEBUG;
66
67   $self->{dbh};
68 }
69
70 # hook insert/replace, because we need to make some changes to the
71 # database when the export is created
72 sub insert {
73   my $self = shift;
74   my $error = $self->SUPER::insert(@_);
75   return $error if $error;
76   if ( $self->option('datasrc') ) {
77     my $error;
78     foreach (qw(cc_card cc_did)) {
79       $self->dbh->do("ALTER TABLE $_ ADD COLUMN svcnum int")
80         or $error = $self->dbh->errstr;
81       $error = '' if $error =~ /Duplicate column name/; # harmless
82       return "Error preparing a2billing database: $error\n" if $error;
83     }
84   }
85   '';
86 }
87
88 sub replace {
89   my $new = shift;
90   my $old = shift || $new->replace_old;
91   my $old_datasrc = $old->option('datasrc');
92   my $error = $new->SUPER::replace($old, @_);
93   return $error if $error;
94
95   if ($new->option('datasrc') and $new->option('datasrc') ne $old_datasrc) {
96     my $dbh = $new->a2b_connect;
97     my $error;
98     foreach (qw(cc_card cc_did)) {
99       $new->dbh->do("ALTER TABLE $_ ADD COLUMN svcnum int")
100         or $error = $new->dbh->errstr;
101       $error = '' if $error =~ /Duplicate column name/; # harmless
102       return "Error preparing a2billing database: $error\n" if $error;
103     }
104   }
105   '';
106 }
107
108 sub export_insert {
109   my $self = shift;
110   my $svc = shift;
111   my $cust_pkg = $svc->cust_svc->cust_pkg;
112   my $cust_main = $cust_pkg->cust_main;
113   my $location = $cust_pkg->cust_location;
114   my $part_pkg = $cust_pkg->part_pkg;
115
116   my $error;
117   $DEBUG ||= $self->option('debug');
118
119   # 3-letter UN country code
120   my $country3 = uc(country_code2code($location->country, 'alpha2' => 'alpha3'));
121   
122   my $dbh = $self->a2b_connect;
123
124   if ( $svc->isa('FS::svc_acct') ) {
125     # export to cc_card (customer identity) and cc_sip_buddies (SIP extension)
126
127     my $username = $svc->username;
128
129     my %cc_card = (
130       svcnum    => $svc->svcnum,
131       username  => $username,
132       useralias => $username,
133       uipass    => $svc->_password,
134       creditlimit    => $cust_main->credit_limit || $self->option('credit') || 0,
135       tariff    => $part_pkg->option('a2billing_tariff'),
136       status    => 1,
137       lastname  => $cust_main->last, # $svc->finger?
138       firstname => $cust_main->first,
139       address   => $location->address1 .
140                   ($location->address2 ? ', '.$location->address2 : ''),
141       city      => $location->city,
142       state     => $location->state,
143       country   => $country3,
144       zipcode   => $location->zip,
145       simultaccess  => $part_pkg->option('a2billing_simultaccess'),
146       typepaid  => $part_pkg->option('a2billing_type'),
147       sip_buddy => 1,
148       company_name => $cust_main->company,
149       activated => 't',
150     );
151     warn "creating A2B cc_card record for $username\n" if $DEBUG;
152     $error = $self->a2b_insert_or_replace('cc_card', 'svcnum', \%cc_card);
153     return "Error creating A2Billing customer identity: $error" if $error;
154     
155     my $fullcontact = '';
156     if ( $svc->ip_addr ) {
157       $fullcontact = "sip:$username\@".$svc->ip_addr;
158     }
159
160     my $cc_card_id = $self->a2b_find('cc_card', 'svcnum', $svc->svcnum);
161     # these are the fields we know about; some of them might need to be 
162     # export options eventually, and there are a lot more fields in the table
163     my %cc_sip_buddy = (
164       id_cc_card      => $cc_card_id,
165       name            => $username,
166       accountcode     => $username,
167       regexten        => $username,
168       amaflags        => 'billing',
169       context         => 'a2billing',
170       host            => 'dynamic',
171       port            => 5060,
172       secret          => $svc->_password,
173       username        => $username,
174       allow           => 'ulaw,alaw,gsm,g729',
175       ipaddr          => ($svc->slipip || ''),
176       fullcontact     => $fullcontact,
177     );
178     warn "creating A2B cc_sip_buddies record for $username\n" if $DEBUG;
179     $error = $self->a2b_insert_or_replace('cc_sip_buddies', 'id_cc_card',
180                                           \%cc_sip_buddy);
181     return "Error creating A2Billing SIP extension: $error" if $error;
182
183     # then, if there are any DIDs on the package, set them up
184     foreach ( $self->_linked_svcs($svc, 'svc_phone') ) {
185       warn "triggering export of svc_phone #".$_->svcnum."\n" if $DEBUG;
186       $error = $self->export_insert($_->svc_x);
187       return $error if $error;
188     }
189     return '';
190
191   } elsif ( $svc->isa('FS::svc_phone') ) {
192     # find the linked svc_acct
193     my $svc_acct;
194     foreach ($self->_linked_svcs($svc, 'svc_acct')) {
195       $svc_acct = $_->svc_x;
196       last;
197     }
198     if ( !$svc_acct ) {
199       # it hasn't been created yet, so just exit.
200       # this service will be exported later.
201       warn "no linked svc_acct; deferring phone number export\n" if $DEBUG;
202       return '';
203     }
204     # find the card and sip_buddies records
205     my $cc_card_id = $self->a2b_find('cc_card', 'svcnum', $svc_acct->svcnum);
206     my $cc_sip_buddies_id = $self->a2b_find('cc_sip_buddies', 'id_cc_card', $cc_card_id);
207     if (!$cc_card_id or !$cc_sip_buddies_id) {
208       warn "When exporting svc_phone #".$svc->svcnum.", svc_acct #".$svc_acct->svcnum." was not found in A2Billing.\n";
209       if ( $FS::svc_Common::noexport_hack ) {
210         # recursion protection
211         return "During export of linked DID#".$svc->phonenum.", svc_acct #".$svc_acct->svcnum." was not found in A2Billing.";
212       }
213       return $svc_acct->export_insert; # which will call back to here when 
214                                        # it's done
215     }
216
217     # Create the DID.
218     my $cc_country_id = $self->a2b_find('cc_country', 'countrycode', $country3);
219     my %cc_did = (
220       svcnum          => $svc->svcnum,
221       id_cc_didgroup  => $self->option('didgroup'),
222       id_cc_country   => $cc_country_id,
223       iduser          => $cc_card_id,
224       did             => $svc->phonenum,
225       billingtype     => ($self->option('billtype') eq 'Dial Out Rate' ? 2 : 3),
226       activated       => 1,
227     );
228
229     # use 'did' as the key here so that if the DID already exists, we 
230     # link it to this customer.
231     $error = $self->a2b_insert_or_replace('cc_did', 'did', \%cc_did);
232     return "Error creating A2Billing DID record: $error" if $error;
233
234     my $cc_did_id = $self->a2b_find('cc_did', 'svcnum', $svc->svcnum);
235     
236     my $destination = 'SIP/' . $svc->phonenum . '@' . $svc_acct->username;
237     my %cc_did_destination = (
238       destination     => $destination,
239       priority        => 1,
240       id_cc_card      => $cc_card_id,
241       id_cc_did       => $cc_did_id,
242     );
243
244     # and if there's already a destination, change it to point to
245     # this customer's SIP extension
246     $error = $self->a2b_insert_or_replace('cc_did_destination', 'id_cc_did',
247                                           \%cc_did_destination);
248     return "Error linking A2Billing DID record to customer: $error" if $error;
249
250     my %cc_did_use = (
251       id_cc_card      => $cc_card_id,
252       id_did          => $cc_did_id,
253       activated       => 1,
254       month_payed     => 1, # it's the default in the A2Billing code, I think
255     );
256     # and change the in-use record, too
257     my $id_use = $self->a2b_find('cc_did_use',
258       id_did          => $cc_did_id,
259       activated       => 1,
260     );
261     if ( $id_use ) {
262       $error = $self->a2b_insert_or_replace('cc_did_use', 'id',
263         { id          => $id_use,
264           releasedate => time2str('%Y-%m-%d %H:%M:%S', time),
265           activated   => 0
266         }
267       );
268       return "Error closing existing A2Billing DID assignment record: $error"
269         if $error;
270
271       # and do an update instead of an insert
272       $cc_did_use{id} = $id_use;
273     }
274
275     $error = $self->a2b_insert_or_replace('cc_did_use', 'id', \%cc_did_use);
276     return "Error creating A2Billing DID use record: $error" if $error;
277
278   } # if $svc->isa(...)
279   '';
280 }
281
282 sub export_delete {
283   my $self = shift;
284   my $svc = shift;
285
286   my $error;
287   $DEBUG ||= $self->option('debug');
288
289   if ( $svc->isa('FS::svc_acct') ) {
290
291     # first remove the DID links
292     foreach ($self->_linked_svcs($svc, 'svc_phone')) {
293       warn "triggering export of svc_phone #".$_->svcnum."\n" if $DEBUG;
294       $error = $self->export_delete($_->svc_x);
295       return $error if $error;
296     }
297
298     # a2billing never deletes a card, just sets status = 0.
299     # though we also need to remove the svcnum, since that svcnum is no 
300     # longer valid.
301     my $cc_card_id = $self->a2b_find('cc_card', 'svcnum', $svc->svcnum);
302     if (!$cc_card_id) {
303       warn "tried to remove svc_acct #".$svc->svcnum." from A2Billing, but couldn't find it.\n";
304       # which is not really a problem.
305       return '';
306     }
307     warn "deactivating A2B cc_card record #$cc_card_id\n" if $DEBUG;
308     $error = $self->a2b_insert_or_replace('cc_card', 'id', {
309         id        => $cc_card_id,
310         status    => 0,
311         activated => 0,
312         svcnum    => 0,
313     });
314     return $error if $error;
315
316   } elsif ( $svc->isa('FS::svc_phone') ) {
317
318     my $cc_did_id = $self->a2b_find('cc_did', 'svcnum', $svc->svcnum);
319     if ( $cc_did_id ) {
320       warn "deactivating DID ".$svc->phonenum."\n" if $DEBUG;
321       $error = $self->a2b_insert_or_replace('cc_did', 'id',
322         { id        => $cc_did_id,
323           activated => 0,
324           iduser    => 0,
325           svcnum    => 0,
326         }
327       );
328       return $error if $error;
329     } else {
330       warn "tried to remove svc_phone #".$svc->svcnum." from A2Billing, but couldn't find it.\n";
331       return '';
332     }
333
334     my $cc_did_destination_id = $self->a2b_find('cc_did_destination',
335       'id_cc_did', $cc_did_id,
336       'activated', 1
337     );
338     if ( $cc_did_destination_id ) {
339       warn "unlinking DID ".$svc->phonenum." from customer\n" if $DEBUG;
340       $error = $self->a2b_delete('cc_did_destination', $cc_did_destination_id);
341       return $error if $error;
342     } else {
343       warn "no cc_did_destination found for cc_did #$cc_did_id\n";
344     }
345     
346     my $cc_did_use_id = $self->a2b_find('cc_did_use',
347       'id_did', $cc_did_id,
348       'activated', 1
349     );
350     if ( $cc_did_use_id ) {
351       warn "closing DID assignment\n" if $DEBUG;
352       $error = $self->a2b_insert_or_replace('cc_did_use', 'id',
353         { id          => $cc_did_use_id,
354           releasedate => time2str('%Y-%m-%d %H:%M:%S', time),
355           activated   => 0
356         }
357       );
358       return "Error closing existing A2Billing DID assignment record: $error"
359         if $error;
360     } else {
361       warn "no cc_did_use found for cc_did #$cc_did_id\n";
362     }
363
364   }
365   '';
366 }
367
368 sub export_replace {
369   my $self = shift;
370   my $new = shift;
371   my $old = shift || $self->replace_old;
372
373   my $error;
374   $DEBUG ||= $self->option('debug');
375
376   if ( $new->isa('FS::svc_acct') ) {
377
378     my $cc_card_id = $self->a2b_find('cc_card', 'svcnum', $new->svcnum);
379     if ( $cc_card_id and $new->username ne $old->username ) {
380       # If the username is changing and any DIDs are provisioned, we need to 
381       # change their destinations.  To do this, we unlink them.  This will 
382       # close their did_use records, delete their cc_did_destinations, and 
383       # set their cc_dids to inactive.
384       foreach ($self->_linked_svcs($new, 'svc_phone')) {
385         warn "triggering export of svc_phone #".$_->svcnum."\n" if $DEBUG;
386         $error = $self->export_delete($_->svc_x);
387         return $error if $error;
388       }
389     }
390
391     # export_insert will replace the record with the same svcnum, if there 
392     # is one, and then re-export all existing DIDs (which is convenient since
393     # we just unlinked them).
394     $error = $self->export_insert($new);
395     return $error if $error;
396
397   } elsif ( $new->isa('FS::svc_phone') ) {
398
399     # if the phone number has changed, need to create a new DID.
400     if ( $new->phonenum ne $old->phonenum ) {
401       # deactivate/unlink/close the old DID
402       # and create/link the new one
403       $error = $self->export_delete($old)
404             || $self->export_insert($new);
405       return $error if $error;
406     }
407     # otherwise we don't care
408   }
409
410   '';
411 }
412
413 sub export_suspend {
414   my $self = shift;
415   my $svc = shift;
416
417   my $error;
418   $DEBUG ||= $self->option('debug');
419
420   if ( $svc->isa('FS::svc_acct') ) {
421     $error = $self->a2b_insert_or_replace('cc_card', 'svcnum',
422       { svcnum    => $svc->svcnum,
423         status    => 6, # "SUSPENDED FOR UNDERPAYMENT"
424         activated => 0, # still used in some places, grrr
425       }
426     );
427   } elsif ( $svc->isa('FS::svc_phone') ) {
428     # deactivate the DID
429     $error = $self->a2b_insert_or_replace('cc_did', 'svcnum',
430       { svcnum    => $svc->svcnum,
431         activated => 0,
432       }
433     );
434   }
435   $error || '';
436 }
437
438 sub export_unsuspend {
439   my $self = shift;
440   my $svc = shift;
441
442   my $error;
443   $DEBUG ||= $self->option('debug');
444
445   if ( $svc->isa('FS::svc_acct') ) {
446     $error = $self->a2b_insert_or_replace('cc_card', 'svcnum',
447       { svcnum    => $svc->svcnum,
448         status    => 1, #"ACTIVE"
449         activated => 1,
450       }
451     );
452   } elsif ( $svc->isa('FS::svc_phone') ) {
453     $error = $self->a2b_insert_or_replace('cc_did', 'svcnum',
454       { svcnum    => $svc->svcnum,
455         activated => 1,
456       }
457     );
458   }
459   $error || '';
460 }
461
462 =item a2b_insert_or_replace TABLE KEY HASHREF
463
464 Create a record in TABLE with the values in HASHREF.  If there's already one 
465 that matches on the KEY field, update the existing record instead of creating
466 a new one.  Pass an empty KEY to just insert the record without checking.
467
468 =cut
469
470 sub a2b_insert_or_replace {
471   my $self = shift;
472   my $table = shift;
473   my $key = shift;
474   my $hashref = shift;
475
476   if ( $key ) {
477     my $id = $self->a2b_find($table, $key, $hashref->{$key});
478     if ( $id ) {
479       my $sql = "UPDATE $table SET " .
480                 join(', ', map { "$_ = ?" } keys(%$hashref)) .
481                 " WHERE id = ?";
482       $self->dbh->do($sql, {}, values(%$hashref), $id)
483         or return $self->dbh->errstr;
484       return '';
485     }
486   }
487   # no key, or no existing record
488   my $sql = "INSERT INTO $table (".  join(', ', keys(%$hashref)) . ")" .
489             " VALUES (" . join(', ', map { '?' } keys(%$hashref)) . ")";
490   $self->dbh->do($sql, {}, values(%$hashref))
491     or return $self->dbh->errstr;
492   return '';
493 }
494
495 =item a2b_delete TABLE ID
496
497 Remove the record with id ID from TABLE.
498
499 =cut
500
501 sub a2b_delete {
502   my $self = shift;
503   my ($table, $id) = @_;
504   my $sql = "DELETE FROM $table WHERE id = ?";
505   $self->dbh->do($sql, {}, $id)
506     or return $self->dbh->errstr;
507   return '';
508 }
509
510 =item a2b_find TABLE KEY VALUE [ KEY VALUE ... ]
511
512 Search TABLE for a row where KEY equals VALUE, and return its "id" field.
513
514 =cut
515
516 sub a2b_find {
517   my $self = shift;
518   my ($table, %params) = @_;
519   my $sql = "SELECT id FROM $table WHERE " .
520     join(' AND ', map { "$_ = ?" } keys(%params));
521   my ($id) = $self->dbh->selectrow_array($sql, {}, values(%params));
522   die $self->dbh->errstr if $self->dbh->errstr;
523   $id || '';
524 }
525
526 # find services on the same package that are exportable with this export
527 # and are of a specified svcdb
528 #
529 # just to avoid repeating myself
530 sub _linked_svcs {
531   my ($self, $svc, $svcdb) = @_;
532   # index the svcparts that belong to the a2billing export
533   my $export_svcparts = $self->{export_svcparts} ||= 
534     { map { $_->svcpart => $_->part_svc->svcdb }
535       $self->export_svc
536     };
537
538   my $pkgnum = $svc->cust_svc->pkgnum;
539   my @svcs = qsearch('cust_svc', { pkgnum => $pkgnum });
540   grep { $export_svcparts->{$_->svcpart} eq $svcdb } @svcs;
541 }
542
543 1;