revbank/plugins/products
2022-06-11 16:31:44 +02:00

55 lines
1.3 KiB
Perl

#!perl
HELP1 "<productID>" => "Add a product to pending transaction";
HELP "edit" => "Edit product list";
my $filename = 'revbank.products';
sub _read_products() {
open my $fh, '<', $filename or die "$filename: $!";
my %products;
while (readline $fh) {
/^\s*#/ and next;
/\S/ or next;
chomp;
my ($ids, $p, $d) = split " ", $_, 3;
my @ids = split /,/, $ids;
$products{ $_ } = { id => $ids[0], price => $p, description => $d}
for @ids;
}
return \%products;
}
sub command :Tab(edit,&tab) ($self, $cart, $command, @) {
if ($command eq 'edit') {
system $ENV{EDITOR} || 'vi', $filename;
return ACCEPT;
}
my $product = _read_products->{ $command } or return NEXT;
my $price = parse_amount( $product->{price} ) or return NEXT;
my @existing = grep {
$_->attribute('plugin') eq $self->id and
$_->attribute('product_id') eq $product->{id}
} $cart->entries('plugin');
if (@existing) {
$existing[0]->quantity($existing[0]->quantity + 1);
return ACCEPT;
}
$cart->add(
-$price,
$product->{description},
{ product_id => $product->{id}, plugin => $self->id }
);
return ACCEPT;
}
sub tab {
return grep /\D/, keys %{ _read_products() };
}