Skip to content

Instantly share code, notes, and snippets.

@briandfoy
Last active June 2, 2021 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briandfoy/f0f9405dda27aafd90ee79efb1ffa139 to your computer and use it in GitHub Desktop.
Save briandfoy/f0f9405dda27aafd90ee79efb1ffa139 to your computer and use it in GitHub Desktop.
Process the LeanPub royalties CSV
#!/usr/bin/perl
# https://gist.github.com/briandfoy/f0f9405dda27aafd90ee79efb1ffa139
=head1 NAME
=head1 SYNOPSIS
# first, get your royalty report from
# https://leanpub.com/u/USER/generate_all_royalties_csv
# download that somewhere
% leanpub_sales leanpubhashblahblah.csv
=head1 DESCRIPTION
This digests the LeanPub royalty report by title, year, and month to
produce a report:
==================================================
Quantum Mechanics for New Puppies
Copies: 22,957 Sales: 229,570.00 Royalties: 160,825.00
--------------------------------------------------
2020/06 743 7430.00 5201.00
...
=head1 AUTHOR
Copyright 2020-2021, brian d foy, <brian.d.foy@gmail.com>
See my LeanPub books at https://leanpub.com/u/briandfoy
=head1 LICENSE
You can use this program under the terms of the Artistic License 2.0.
=cut
use v5.30;
use warnings;
use Text::CSV_XS;
my $file = $ARGV[0];
die "No such file <$file>\n" unless -e $file;
open my $fh, '<:utf8', $file or die "Could not open file <$file>\n\t$!\n";
my $csv = Text::CSV_XS->new;
my @headers = $csv->header( $fh, { munge_column_names => sub { $_ } } );
use constant {
REVENUE => 'Book Revenue',
ROYALTY => 'Book Royalty',
DATE => 'Date Purchased (UTC)',
TITLE => 'Book Title',
};
my %Grand;
my %Totals;
while( my $row = $csv->getline_hr( $fh ) ) {
say dumper( $row );
my( $year, $month ) = $row->{+DATE} =~ m/\A(\d{4})-(\d{2})/;
my $title = $row->{+TITLE};
$Grand{$title}{$year}{$month}{_count}++;
no warnings 'numeric';
$Grand{$title}{$year}{$month}{_sales} += $row->{+REVENUE};
$Grand{$title}{$year}{$month}{_royalties} += $row->{+ROYALTY};
$Totals{$title}{_count}++;
$Totals{$title}{_sales} += $row->{+REVENUE};
$Totals{$title}{_royalties} += $row->{+ROYALTY};
}
foreach my $title ( sort keys %Grand ) {
state @keys = qw(_count _sales _royalties);
printf "%s\n%s\n Copies: %d Sales: %.2f Royalties: %.2f\n%s\n",
'=' x 50,
$title,
$Totals{$title}->@{@keys},
'-' x 50;
foreach my $year ( sort { $a <=> $b } keys $Grand{$title}->%* ) {
foreach my $month ( sort { $a <=> $b } keys $Grand{$title}{$year}->%* ) {
my $g = $Grand{$title}{$year}{$month};
printf " %4d/%02d %3d %6.2f %6.2f\n",
$year, $month, $g->@{@keys};
}
}
print "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment