RT#37908: Convert existing email-sending code to use common interface [removals and...
[freeside.git] / FS / bin / freeside-ipifony-download
1 #!/usr/bin/perl
2
3 use strict;
4 use Getopt::Std;
5 use Date::Format qw(time2str);
6 use File::Temp qw(tempdir);
7 use Net::SFTP::Foreign;
8 use FS::UID qw(adminsuidsetup);
9 use FS::Record qw(qsearch qsearchs);
10 use FS::cust_main;
11 use FS::Conf;
12 use File::Copy qw(copy);
13 use Text::CSV;
14
15 my %opt;
16 getopts('va:P:C:e:', \%opt);
17
18 # Product codes that are subject to flat rate E911 charges.  For these 
19 # products, the'quantity' field represents the number of lines.
20 my @E911_CODES = ( 'V-HPBX', 'V-TRUNK' );
21
22 # Map TAXNONVOICE/TAXVOICE to Freeside taxclass names
23 my %TAXCLASSES = (
24   'TAXNONVOICE' => 'Other',
25   'TAXVOICE'   => 'VoIP',
26 );
27   
28
29 #$Net::SFTP::Foreign::debug = -1;
30 sub HELP_MESSAGE { '
31   Usage:
32       freeside-ipifony-download 
33         [ -v ]
34         [ -a archivedir ]
35         [ -P port ]
36         [ -C category ]
37         [ -e pkgpart ]
38         freesideuser sftpuser@hostname[:path]
39 ' }
40
41 my @fields = (
42   'custnum',
43   'date_desc',
44   'quantity',
45   'unit_price',
46   'classname',
47   'taxclass',
48 );
49
50 my $user = shift or die &HELP_MESSAGE;
51 my $dbh = adminsuidsetup $user;
52 $FS::UID::AutoCommit = 0;
53
54 # for statistics
55 my $num_charges = 0;
56 my $num_errors = 0;
57 my $sum_charges = 0;
58 # cache classnums
59 my %classnum_of;
60
61 if ( $opt{a} ) {
62   die "no such directory: $opt{a}\n"
63     unless -d $opt{a};
64   die "archive directory $opt{a} is not writable by the freeside user\n"
65     unless -w $opt{a};
66 }
67
68 my $e911_part_pkg;
69 if ( $opt{e} ) {
70   $e911_part_pkg = FS::part_pkg->by_key($opt{e})
71     or die "E911 pkgpart $opt{e} not found.\n";
72
73   if ( $e911_part_pkg->base_recur > 0 or $e911_part_pkg->freq ) {
74     die "E911 pkgpart $opt{e} must be a one-time charge.\n";
75   }
76 }
77
78 my $categorynum = '';
79 if ( $opt{C} ) {
80   # find this category (don't auto-create it, it should exist already)
81   my $category = qsearchs('pkg_category', { categoryname => $opt{C} });
82   if (!defined($category)) {
83     die "Package category '$opt{C}' does not exist.\n";
84   }
85   $categorynum = $category->categorynum;
86 }
87
88 #my $tmpdir = File::Temp->newdir();
89 my $tmpdir = tempdir( CLEANUP => 1 ); #DIR=>somewhere?
90
91 my $host = shift
92   or die &HELP_MESSAGE;
93 my ($sftpuser, $path);
94 $host =~ s/^(.+)\@//;
95 $sftpuser = $1 || $ENV{USER};
96 $host =~ s/:(.*)//;
97 $path = $1;
98
99 my $port = 22;
100 if ( $opt{P} =~ /^(\d+)$/ ) {
101   $port = $1;
102 }
103
104 # for now assume SFTP download as the only method
105 print STDERR "Connecting to $sftpuser\@$host...\n" if $opt{v};
106
107 my $sftp = Net::SFTP::Foreign->new(
108   host      => $host,
109   user      => $sftpuser,
110   port      => $port,
111   # for now we don't support passwords. use authorized_keys.
112   timeout   => 30,
113   #more      => ($opt{v} ? '-v' : ''),
114 );
115 die "failed to connect to '$sftpuser\@$host'\n(".$sftp->error.")\n"
116   if $sftp->error;
117
118 $sftp->setcwd($path) if $path;
119
120 my $files = $sftp->ls('ready', wanted => qr/\.csv$/, names_only => 1);
121 if (!@$files) {
122   print STDERR "No charge files found.\n" if $opt{v};
123   exit(-1);
124 }
125
126 my %cust_main; # cache
127 my %e911_qty; # custnum => sum of E911-subject quantity
128
129 my %is_e911 = map {$_ => 1} @E911_CODES;
130
131 FILE: foreach my $filename (@$files) {
132   print STDERR "Retrieving $filename\n" if $opt{v};
133   $sftp->get("ready/$filename", "$tmpdir/$filename");
134   if($sftp->error) {
135     warn "failed to download $filename\n";
136     next FILE;
137   }
138
139   # make sure server archive dir exists
140   if ( !$sftp->stat('done') ) {
141     print STDERR "Creating $path/done\n" if $opt{v};
142     $sftp->mkdir('done');
143     if($sftp->error) {
144       # something is seriously wrong
145       die "failed to create archive directory on server:\n".$sftp->error."\n";
146     }
147   }
148   #move to server archive dir
149   $sftp->rename("ready/$filename", "done/$filename");
150   if($sftp->error) {
151     warn "failed to archive $filename on server:\n".$sftp->error."\n";
152   } # process it anyway, I guess/
153
154   #copy to local archive dir
155   if ( $opt{a} ) {
156     print STDERR "Copying $tmpdir/$filename to archive dir $opt{a}\n"
157       if $opt{v};
158     copy("$tmpdir/$filename", $opt{a});
159     warn "failed to copy $tmpdir/$filename to $opt{a}: $!" if $!;
160   }
161
162   open my $fh, "<$tmpdir/$filename";
163   my $csv = Text::CSV->new; # orthodox CSV
164   my %hash;
165   while (my $line = <$fh>) {
166     $csv->parse($line) or do {
167       warn "can't parse $filename: ".$csv->error_input."\n";
168       next FILE;
169     };
170     @hash{@fields} = $csv->fields();
171     if ( $hash{custnum} =~ /^cust/ ) {
172       # there appears to be a header row
173       print STDERR "skipping header row\n" if $opt{v};
174       next;
175     }
176     my $cust_main = 
177       $cust_main{$hash{custnum}} ||= FS::cust_main->by_key($hash{custnum});
178     if (!$cust_main) {
179       warn "customer #$hash{custnum} not found\n";
180       next;
181     }
182     print STDERR "Found customer #$hash{custnum}: ".$cust_main->name."\n"
183       if $opt{v};
184
185     my $amount = sprintf('%.2f',$hash{quantity} * $hash{unit_price});
186
187     # bill the charge on the customer's next bill date, if that's within
188     # the current calendar month; otherwise bill it immediately
189     # (see RT#24325)
190     my $next_bill_date = $cust_main->next_bill_date;
191     if ( $next_bill_date ) {
192       my ($bill_month, $bill_year) = (localtime($next_bill_date))[4, 5];
193       my ($this_month, $this_year) = (localtime(time))[4, 5];
194       if ( $this_month == $bill_month and $this_year == $bill_year ) {
195         $cust_main->set('charge_date', $next_bill_date);
196       }
197     }
198
199     # construct arguments for $cust_main->charge
200     my %charge_opt = (
201       amount      => $hash{unit_price},
202       quantity    => $hash{quantity},
203       start_date  => $cust_main->get('charge_date'),
204       pkg         => $hash{date_desc} .
205                    ' (' . $hash{quantity} . ' @ $' . $hash{unit_price} . ' ea)',
206       taxclass    => $TAXCLASSES{ $hash{taxclass} },
207     );
208     if (my $classname = $hash{classname}) {
209       if (!exists($classnum_of{$classname}) ) {
210         # then look it up
211         my $pkg_class = qsearchs('pkg_class', {
212             classname   => $classname,
213             categorynum => $categorynum,
214         });
215         if (!defined($pkg_class)) {
216           # then create it
217           $pkg_class = FS::pkg_class->new({
218               classname   => $classname,
219               categorynum => $categorynum,
220           });
221           my $error = $pkg_class->insert;
222           die "Error creating package class for product code '$classname':\n".
223             "$error\n"
224             if $error;
225         }
226
227         $classnum_of{$classname} = $pkg_class->classnum;
228       }
229       $charge_opt{classnum} = $classnum_of{$classname};
230     }
231     print STDERR "  Charging $hash{unit_price} * $hash{quantity}\n"
232       if $opt{v};
233     my $error = $cust_main->charge(\%charge_opt);
234     if ($error) {
235       warn "Error creating charge: $error" if $error;
236       $num_errors++;
237     } else {
238       $num_charges++;
239       $sum_charges += $amount;
240     }
241
242     if ( $opt{e} and $is_e911{$hash{classname}} ) {
243       $e911_qty{$hash{custnum}} ||= 0;
244       $e911_qty{$hash{custnum}} += $hash{quantity};
245     }
246   } #while $line
247   close $fh;
248 } #FILE
249
250 # Order E911 packages
251 my $num_e911 = 0;
252 my $num_lines = 0;
253 foreach my $custnum ( keys (%e911_qty) ) {
254   my $cust_main = $cust_main{$custnum};
255   my $quantity = $e911_qty{$custnum};
256   next if $quantity == 0;
257   my $cust_pkg = FS::cust_pkg->new({
258       pkgpart     => $opt{e},
259       custnum     => $custnum,
260       start_date  => $cust_main->get('charge_date'),
261       quantity    => $quantity,
262   });
263   my $error = $cust_main->order_pkg({ cust_pkg => $cust_pkg });
264   if ( $error ) {
265     warn "Error creating e911 charge for customer $custnum: $error\n";
266     $num_errors++;
267   } else {
268     $num_e911++;
269     $num_lines += $quantity;
270   }
271 }
272
273 $dbh->commit;
274
275 if ($opt{v}) {
276   print STDERR "
277 Finished!
278   Processed files: @$files
279   Created charges: $num_charges
280   Sum of charges: \$".sprintf('%0.2f', $sum_charges)."
281   E911 charges: $num_e911
282   E911 lines: $num_lines
283   Errors: $num_errors
284 ";
285 }
286
287 =head1 NAME
288
289 freeside-ipifony-download - Download and import invoice items from IPifony.
290
291 =head1 SYNOPSIS
292
293       freeside-ipifony-download 
294         [ -v ]
295         [ -a archivedir ]
296         [ -P port ]
297         [ -C category ]
298         [ -T taxclass ]
299         [ -e pkgpart ]
300         freesideuser sftpuser@hostname[:path]
301
302 =head1 REQUIRED PARAMETERS
303
304 I<freesideuser>: the Freeside user to run as.
305
306 I<sftpuser>: the SFTP user to connect as.  The 'freeside' system user should 
307 have an authorization key to connect as that user.
308
309 I<hostname>: the SFTP server.
310
311 =head1 OPTIONAL PARAMETERS
312
313 -v: Be verbose.
314
315 -a I<archivedir>: Save a copy of the downloaded file to I<archivedir>.
316
317 -P I<port>: Connect to that TCP port.
318
319 -C I<category>: The name of a package category to use when creating package
320 classes.
321
322 -e I<pkgpart>: The pkgpart (L<FS::part_pkg>) to use for E911 charges.  A 
323 package of this type will be ordered for each invoice that has E911-subject
324 line items.  The 'quantity' field on this package will be set to the total 
325 quantity of those line items.
326
327 The E911 package must be a one-time package (flat rate, no frequency, no 
328 recurring fee) with setup fee equal to the fee per line.
329
330 =cut
331
332 1;
333