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);
12 use File::Copy qw(copy);
16 getopts('va:P:C:e:', \%opt);
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' );
22 # Map TAXNONVOICE/TAXVOICE to Freeside taxclass names
24 'TAXNONVOICE' => 'Other',
29 #$Net::SFTP::Foreign::debug = -1;
32 freeside-ipifony-download
38 freesideuser sftpuser@hostname[:path]
50 my $user = shift or die &HELP_MESSAGE;
51 my $dbh = adminsuidsetup $user;
52 $FS::UID::AutoCommit = 0;
62 die "no such directory: $opt{a}\n"
64 die "archive directory $opt{a} is not writable by the freeside user\n"
70 $e911_part_pkg = FS::part_pkg->by_key($opt{e})
71 or die "E911 pkgpart $opt{e} not found.\n";
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";
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";
85 $categorynum = $category->categorynum;
88 #my $tmpdir = File::Temp->newdir();
89 my $tmpdir = tempdir( CLEANUP => 1 ); #DIR=>somewhere?
93 my ($sftpuser, $path);
95 $sftpuser = $1 || $ENV{USER};
100 if ( $opt{P} =~ /^(\d+)$/ ) {
104 # for now assume SFTP download as the only method
105 print STDERR "Connecting to $sftpuser\@$host...\n" if $opt{v};
107 my $sftp = Net::SFTP::Foreign->new(
111 # for now we don't support passwords. use authorized_keys.
113 #more => ($opt{v} ? '-v' : ''),
115 die "failed to connect to '$sftpuser\@$host'\n(".$sftp->error.")\n"
118 $sftp->setcwd($path) if $path;
120 my $files = $sftp->ls('ready', wanted => qr/\.csv$/, names_only => 1);
122 print STDERR "No charge files found.\n" if $opt{v};
126 my %cust_main; # cache
127 my %e911_qty; # custnum => sum of E911-subject quantity
129 my %is_e911 = map {$_ => 1} @E911_CODES;
131 FILE: foreach my $filename (@$files) {
132 print STDERR "Retrieving $filename\n" if $opt{v};
133 $sftp->get("ready/$filename", "$tmpdir/$filename");
135 warn "failed to download $filename\n";
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');
144 # something is seriously wrong
145 die "failed to create archive directory on server:\n".$sftp->error."\n";
148 #move to server archive dir
149 $sftp->rename("ready/$filename", "done/$filename");
151 warn "failed to archive $filename on server:\n".$sftp->error."\n";
152 } # process it anyway, I guess/
154 #copy to local archive dir
156 print STDERR "Copying $tmpdir/$filename to archive dir $opt{a}\n"
158 copy("$tmpdir/$filename", $opt{a});
159 warn "failed to copy $tmpdir/$filename to $opt{a}: $!" if $!;
162 open my $fh, "<$tmpdir/$filename";
163 my $csv = Text::CSV->new; # orthodox CSV
165 while (my $line = <$fh>) {
166 $csv->parse($line) or do {
167 warn "can't parse $filename: ".$csv->error_input."\n";
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};
177 $cust_main{$hash{custnum}} ||= FS::cust_main->by_key($hash{custnum});
179 warn "customer #$hash{custnum} not found\n";
182 print STDERR "Found customer #$hash{custnum}: ".$cust_main->name."\n"
185 my $amount = sprintf('%.2f',$hash{quantity} * $hash{unit_price});
187 # bill the charge on the customer's next bill date, if that's within
188 # the current calendar month; otherwise bill it immediately
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);
199 # construct arguments for $cust_main->charge
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} },
208 if (my $classname = $hash{classname}) {
209 if (!exists($classnum_of{$classname}) ) {
211 my $pkg_class = qsearchs('pkg_class', {
212 classname => $classname,
213 categorynum => $categorynum,
215 if (!defined($pkg_class)) {
217 $pkg_class = FS::pkg_class->new({
218 classname => $classname,
219 categorynum => $categorynum,
221 my $error = $pkg_class->insert;
222 die "Error creating package class for product code '$classname':\n".
227 $classnum_of{$classname} = $pkg_class->classnum;
229 $charge_opt{classnum} = $classnum_of{$classname};
231 print STDERR " Charging $hash{unit_price} * $hash{quantity}\n"
233 my $error = $cust_main->charge(\%charge_opt);
235 warn "Error creating charge: $error" if $error;
239 $sum_charges += $amount;
242 if ( $opt{e} and $is_e911{$hash{classname}} ) {
243 $e911_qty{$hash{custnum}} ||= 0;
244 $e911_qty{$hash{custnum}} += $hash{quantity};
250 # Order E911 packages
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({
260 start_date => $cust_main->get('charge_date'),
261 quantity => $quantity,
263 my $error = $cust_main->order_pkg({ cust_pkg => $cust_pkg });
265 warn "Error creating e911 charge for customer $custnum: $error\n";
269 $num_lines += $quantity;
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
289 freeside-ipifony-download - Download and import invoice items from IPifony.
293 freeside-ipifony-download
300 freesideuser sftpuser@hostname[:path]
302 =head1 REQUIRED PARAMETERS
304 I<freesideuser>: the Freeside user to run as.
306 I<sftpuser>: the SFTP user to connect as. The 'freeside' system user should
307 have an authorization key to connect as that user.
309 I<hostname>: the SFTP server.
311 =head1 OPTIONAL PARAMETERS
315 -a I<archivedir>: Save a copy of the downloaded file to I<archivedir>.
317 -P I<port>: Connect to that TCP port.
319 -C I<category>: The name of a package category to use when creating package
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.
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.