BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
1542 lines · 125.3 KB · download this file
package BlowfishCMS::Addon::Store;
# Store: products in the catalogue, an items-for-sale block, and payment
# through Stripe Checkout (the buyer pays on Stripe's page; card details never
# reach this server).
#
# Where each part runs:
# admin service Products screen (/admin/?kind=x-store): products, their
# pictures and the shop settings, in the catalogue.
# public service the items-for-sale block on pages.
# store service (its own account, _bfxstore) /x/store/checkout, /x/store/
# webhook, /x/store/thanks, /x/store/stock.json and the
# Orders screen (/admin/x/store/). Only it can read the
# Stripe keys and the orders, which hold buyers' details.
# the browser the cart (store.js keeps it in the visitor's browser:
# no cookies); checkout sends its lines as item=ID:QTY.
#
# New orders are emailed (1.2.0) through BlowfishCMS's mail queue: to the
# owner, and a confirmation to the buyer, once Stripe says the order is paid.
#
# Print on demand (1.5.0): a product can be made and sent by Printful or
# Gelato (store_products.pod, pod_ref, pod_files). Checkout copies that onto
# the order's lines (order_items.pod), and once Stripe says the order is paid
# the store service sends those lines to the printer (pod_orders: one row per
# order and printer). The printers' webhooks (/x/store/pod/PRINTER/TOKEN, the
# token in the secrets folder) only say "look at order X": the service then
# asks the printer itself, so nothing in a webhook is trusted. Their keys and
# the Print on demand tab (/admin/x/store/pod) are the store service's; the
# Products screen lists Printful's items from /admin/x/store/pod/printful.json.
use v5.36;
use utf8;
use JSON::PP ();
use Digest::SHA qw(sha256_hex);
use Encode qw(encode decode);
use List::Util ();
BEGIN {
no strict 'refs';
*{$_}=\&{"BlowfishCMS::$_"} for qw(h param setting site_url own_origin window window_html admin_page end_page start_page fields hidden
redirect json_response header attempt failed_action clean_error now random_id render_markdown json_ld save_image remove_image upload_or_picture choose_picture_button
addon_setting addon_setting_save addon_data_dir addon_secret_dir fetch_request mail_queue mail_address_ok switch_button switch_field list_order order_list_attrs order_row_attrs drag_handle move_buttons row_menu sort_order_save admin_row admin_list);
}
sub db () { $BlowfishCMS::db }
our @picture_problems; # pictures a Printful sync couldn't fetch (from_service says so)
# ---- Money (the core's Payments.pm since 1.3.0), in the shop's currency ----------------
sub currencies { return BlowfishCMS::currencies() }
sub currency { my $c=addon_setting('store','currency','usd');return $c =~ /\A[a-z]{3}\z/ ? $c : 'usd' }
sub money ($amount,$cur=currency()) { return BlowfishCMS::money($amount,$cur) }
# "12.50" -> 1250 (or 12 for zero-decimal currencies); dies on anything else.
sub parse_money ($text,$what,$cur=currency()) { return BlowfishCMS::parse_money($text,$what,$cur) }
sub money_input ($amount,$cur=currency()) { return BlowfishCMS::money_input($amount,$cur) }
# ---- Catalogue tables (admin service) ------------------------------------------------
sub migrate ($dbh) {
$dbh->do("CREATE TABLE IF NOT EXISTS store_products (id TEXT PRIMARY KEY, title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', price INTEGER NOT NULL, image TEXT NOT NULL DEFAULT '', stock INTEGER, active INTEGER NOT NULL DEFAULT 1, shipping INTEGER NOT NULL DEFAULT 0, sort_order INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)");
# 1.5.0: who makes it. pod is '' (the owner sends it), 'printful' or
# 'gelato'; pod_ref the printer's item (Printful's sync variant ID, Gelato's
# product UID); pod_files Gelato's print files ({"default": URL, "back": URL}).
# 1.6.0: options (sizes and the like, each with its price and printer's
# item: [{id, label, price, ref}], or '' for one kind), and for a product
# that comes from Printful by itself: pod_sync (its sync product ID),
# pod_image (the mockup its picture was made from; '' once the owner
# chooses their own) and pod_note (why it's off sale, in words).
my %have=map {$_->[1]=>1} @{$dbh->selectall_arrayref('PRAGMA table_info(store_products)')};
$dbh->do("ALTER TABLE store_products ADD COLUMN $_ TEXT NOT NULL DEFAULT ''") for grep {!$have{$_}} qw(pod pod_ref pod_files options pod_sync pod_image pod_note pictures);
# 1.5.0's copy of Printful's item names was written in one encoding and
# read in another, so a name taken from it (3″×3″) was saved garbled
# (3″×3″). Such a title is mended: one whose characters are all
# bytes, that reads as UTF-8 and has the C1 control characters real text
# never has.
for my $r (@{$dbh->selectall_arrayref('SELECT id,title FROM store_products',{Slice=>{}})}) {
my $fixed=mended($r->{title});
$dbh->do('UPDATE store_products SET title=? WHERE id=?',undef,$fixed,$r->{id}) if defined $fixed;
}
}
sub mended ($text) {
return undef unless ($text//'') =~ /[\x80-\x9f]/ && $text !~ /[^\x00-\xff]/;
my $chars=attempt {Encode::decode('UTF-8',Encode::encode('latin1',$text),Encode::FB_CROAK())};
return defined $chars && $chars ne $text ? $chars : undef;
}
sub products ($active_only=0) {
return (attempt {db()->selectall_arrayref('SELECT * FROM store_products'.($active_only?' WHERE active=1':'').' ORDER BY sort_order, created_at',{Slice=>{}})}) // [];
}
sub product ($id) { return ($id//'') =~ /\A[a-f0-9]{16}\z/ ? (attempt {db()->selectrow_hashref('SELECT * FROM store_products WHERE id=?',undef,$id)}) : undef }
# A product's main picture: the one chosen (or Printful's main mockup); when
# there's none, or its file is gone, its first picture that isn't hidden
# (1.7.3: a product Printful gave no main mockup showed none on its card).
sub main_picture ($p) {
my $have=sub ($f) {length($f//'') && $f =~ /\A[A-Za-z0-9._-]{1,120}\z/ && -e "$BlowfishCMS::store/store/$f"};
return $p->{image} if $have->($p->{image});
my ($first)=grep {$have->($_)} map {$_->{file}} grep {!$_->{hidden}} @{pictures_of($p)};
return $first // '';
}
sub image_url ($p) { my $f=main_picture($p);return length $f ? "/media/store/$f" : '' }
# A product's options ([{id, label, price, ref}]; none for one kind of it).
sub options_of ($p) {
my $o=length($p->{options}//'') ? ((attempt {JSON::PP->new->decode($p->{options})}) // []) : [];
return [] unless ref $o eq 'ARRAY';
my @ok=grep {ref $_ eq 'HASH' && ($_->{id}//'') =~ /\A[A-Za-z0-9_-]{1,40}\z/ && ($_->{price}//'') =~ /\A\d+\z/} @$o;
# In stock unless Printful said it isn't (1.7.1): options saved by 1.6.0
# have no word on it, and print on demand is nearly always in stock, so a
# missing word mustn't stop a sale.
$_->{available}=(defined $_->{available} && !$_->{available}) ? 0 : 1 for @ok;
return \@ok;
}
sub option_of ($p,$id) { return (grep {$_->{id} eq ($id//'')} @{options_of($p)})[0] }
# Its price in words: one price, or "from" the cheapest option's.
sub price_text ($p,$cur) {
my @prices=sort {$a<=>$b} map {$_->{price}} @{options_of($p)};
return money($p->{price},$cur) unless @prices;
return $prices[0]==$prices[-1] ? money($prices[0],$cur) : 'from '.money($prices[0],$cur);
}
# ---- Print on demand: who makes a product ---------------------------------------------
sub pod_providers { return qw(printful gelato) }
sub pod_label ($p) { return +{printful=>'Printful',gelato=>'Gelato'}->{$p//''} // '' }
# What a product's printer needs ({provider, ref, files}), from a product or
# from an order line (which keeps a copy, as JSON, made at checkout); undef
# for what the owner sends.
sub pod_of ($row,$opt=undef) {
my $p=$row->{pod}//'';
if ($p =~ /\A\{/) {my $d=(attempt {JSON::PP->new->decode($p)}) // {};return ref $d eq 'HASH' && pod_label($d->{provider}) ? $d : undef}
return undef unless pod_label($p);
# An option made by the printer has its own item.
return {provider=>$p,ref=>$opt->{ref},files=>{}} if $opt && length($opt->{ref}//'');
my $files=length($row->{pod_files}//'') ? ((attempt {JSON::PP->new->decode($row->{pod_files})}) // {}) : {};
return {provider=>$p,ref=>$row->{pod_ref}//'',files=>ref $files eq 'HASH' ? $files : {}};
}
# ---- The block ----------------------------------------------------------------------
sub blocks {
my @choices=(['','All products'],map {[$_->{id},$_->{title}]} @{products()});
return {store_products=>{label=>'Items for sale',order=>20,fields=>[
[title=>'Panel title','text',120],
[subtitle=>'Panel subtitle','text',160,'optional'],
[product=>'Show','select',\@choices],
[columns=>'Layout','select',[[grid=>'Grid of cards'],[list=>'One per row, picture beside the text']]],
],defaults=>{title=>'shop',columns=>'grid'},manage=>['x-store','manage products'],
note=>'Products are added under Products. Buyers pay on Stripe’s checkout page; orders appear under Orders.',
render=>\&render_block}};
}
sub render_block ($b,%o) {
my $d=$b->{data};my $list=products(1);
$list=[grep {$_->{id} eq $d->{product}} @$list] if length($d->{product}//'');
my $cur=currency();my $site=site_url();my $back=($BlowfishCMS::route//'/') =~ m{\A/[a-z0-9/-]*\z} ? $BlowfishCMS::route : '/';
my $button=addon_setting('store','button','Buy');
my $html='<div class="store-items store-items--'.(($d->{columns}//'') eq 'list' ? 'list' : 'grid').'">';
# Each product a card (1.7.0): its picture and name lead to its own page;
# "View" opens it, and one with nothing to choose can go into the cart
# from here too.
for my $p (@$list) {
my $img=image_url($p);my $url=product_url($p);my $opts=options_of($p);
my $choose=@$opts>1;
$html.='<article class="store-item" data-product="'.h($p->{id}).'">';
$html.='<a class="store-item__picture" href="'.h($url).'" tabindex="-1" aria-hidden="true"><img class="store-item__image" src="'.h($img).'" alt="" loading="lazy"></a>' if length $img;
$html.='<div class="store-item__text"><h3 class="store-item__name"><a href="'.h($url).'">'.h($p->{title}).'</a></h3><p class="store-item__price">'.h(price_text($p,$cur)).'</p>';
my $about=excerpt($p->{description},140);
$html.='<p class="store-item__description">'.h($about).'</p>' if length $about;
$html.='<div class="store-item__actions">'
.($choose ? '' : '<form class="store-buy" method="post" action="/x/store/checkout" data-currency="'.h($cur).'" data-minor="'.(money_input(100,$cur) eq '100' ? 1 : 100).'"'
.(addon_setting('store','cart',1) ? ' data-cart="'.h(addon_setting('store','cart_button','Add to cart')).'" data-title="'.h($p->{title}).'" data-price="'.(0+(@$opts ? $opts->[0]{price} : $p->{price})).'"'.(length $img ? ' data-image="'.h($img).'"' : '') : '')
.'>'.hidden(product=>$p->{id},back=>$back,quantity=>1).(@$opts ? hidden(option=>$opts->[0]{id}) : '')
.'<button type="submit" class="buttonlike store-buy__button">'.h($button).'</button><p class="store-buy__status" role="status"></p></form>')
.'<a class="buttonlike store-item__view'.($choose ? ' store-item__view--main' : '').'" href="'.h($url).'">View<span class="sr-only"> '.h($p->{title}).'</span></a>'
.'</div></div></article>';
$html.=json_ld(product_ld($p,$cur,$site));
}
$html.='</div>';
$html='<p class="empty-media">Nothing for sale yet.</p>' unless @$list;
return window_html($d->{title},$d->{subtitle},$html,%o);
}
# ---- A product's own page (store service, /x/store/item/ID/its-name; 1.7.0) -----------------
sub product_url ($p) {
my $s=lc($p->{title}//'');$s =~ s/[^a-z0-9]+/-/g;$s =~ s/\A-+|-+\z//g;$s=substr($s,0,60) =~ s/-+\z//r;
return "/x/store/item/$p->{id}".(length $s ? "/$s" : '');
}
# The start of a description, as plain words.
sub excerpt ($text,$max) {
my $t=$text//'';$t =~ s/!?\[([^\]]*)\]\([^)]*\)/$1/g;$t =~ s/[#*_`>|~]+//g;$t =~ s/\s+/ /g;$t =~ s/\A | \z//g;
return length $t>$max ? (substr($t,0,$max-1) =~ s/\s+\S*\z//r).'…' : $t;
}
# What search engines read about a product.
sub product_ld ($p,$cur,$site) {
my $opts=options_of($p);my $url=$site.product_url($p);
my %seen;my @images=map {$site.'/media/store/'.$_} grep {length && !$seen{$_}++} main_picture($p),map {$_->{file}} grep {!$_->{hidden}} @{pictures_of($p)};
my @prices=map {$_->{price}} @$opts;my $stock=!@$opts || grep {$_->{available}} @$opts;
my $avail=$stock ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock';
return {'@type'=>'Product',name=>$p->{title},(@images ? (image=>[@images[0..($#images<9 ? $#images : 9)]]) : ()),
(length $p->{description} ? (description=>excerpt($p->{description},500)) : ()),
offers=>(@prices>1 && List::Util::min(@prices)!=List::Util::max(@prices)
? {'@type'=>'AggregateOffer',lowPrice=>money_input(List::Util::min(@prices),$cur),highPrice=>money_input(List::Util::max(@prices),$cur),offerCount=>scalar @prices,priceCurrency=>uc $cur,url=>$url,availability=>$avail}
: {'@type'=>'Offer',price=>money_input(@prices ? $prices[0] : $p->{price},$cur),priceCurrency=>uc $cur,url=>$url,availability=>$avail})};
}
sub sitemap { return [map {[product_url($_),substr($_->{updated_at}//'',0,10)]} @{products(1)}] }
# The page: its pictures to click through, its colours and sizes to choose,
# how many, and the same cart as the shop. Without JavaScript the colours
# and sizes are radio buttons, and checkout finds the option they name.
sub product_page ($id) {
my $p=product($id);
return 0 unless $p && $p->{active};
my $cur=currency();my $site=site_url();my $url=product_url($p);
my $opts=options_of($p);my $pics=pictures_of($p);
my %colors;my @colors=grep {length && !$colors{$_}++} map {$_->{color}//''} @$opts;
my %sizes;my @sizes=grep {length && !$sizes{$_}++} map {$_->{size}//''} @$opts;
# Options told apart by colour and size; any others are chosen by name.
my $by_attr=@$opts>1 && (@colors>1 || @sizes>1) && !grep {!length($_->{color}//'') && !length($_->{size}//'')} @$opts;
my ($first)=(grep({$_->{available}} @$opts),@$opts);
# The pictures: its colours' (each marked with its colour), with its main
# one first unless it's one of them (Printful's thumbnail is a colour's mockup).
my $main_src=$p->{pod_image}//'';
my $is_main=sub ($pic) {length $main_src && grep {$_ eq $main_src} $pic->{src}//'',@{ref $pic->{also} eq 'ARRAY' ? $pic->{also} : []}};
# The main picture first (once: it may be one of the others), then the
# rest in the owner's order, without those they hid (1.7.3).
my @vis=grep {!$_->{hidden}} @$pics;my $main=main_picture($p);
my ($as)=grep {$_->{file} eq $main || $is_main->($_)} @vis;
my @gallery=$as ? ($as,grep {$_ != $as} @vis) : ((length $main ? ({file=>$main,color=>''}) : ()),@vis);
# The first shown: the chosen option's own picture, else its colour's, else the first.
my $first_pic=$first ? (grep {my $pic=$_;grep {$_ eq $first->{id}} @{$pic->{variants}//[]}} @gallery)[0] : undef;
$first_pic //= (grep {($_->{color}//'') eq $first->{color}} @gallery)[0] if $first && length($first->{color}//'');
$first_pic //= $gallery[0];
my $src=sub ($g) {'/media/store/'.$g->{file}};
# Like a big shop's product page: the thumbnails in a column beside the
# main picture (a row under it on phones); hovering or clicking one shows
# it, the arrows and arrow keys step through, the main picture opens full size.
my $g='<div class="store-gallery'.(@gallery>1 ? ' store-gallery--many' : '').'" data-store-gallery>';
if (@gallery) {
my $n=0;
$g.='<ul class="store-gallery__thumbs" aria-label="Pictures">'.join('',map {$n++;'<li><button type="button" class="store-gallery__thumb" data-src="'.h($src->($_)).'" data-color="'.h($_->{color}//'').'" data-variants="'.h(join(' ',@{$_->{variants}//[]})).'" aria-label="Picture '.$n.(length($_->{color}//'') ? ", $_->{color}" : '').'" aria-pressed="'.($_ == $first_pic ? 'true' : 'false').'"><img src="'.h($src->($_)).'" alt="" loading="lazy"></button></li>'} @gallery).'</ul>' if @gallery>1;
$g.='<div class="store-gallery__stage"><button type="button" class="store-gallery__zoom" data-store-zoom aria-label="Show this picture full size"><img class="store-gallery__main" src="'.h($src->($first_pic)).'" alt="'.h($p->{title}).'" data-store-main></button>'
.(@gallery>1 ? '<button type="button" class="store-gallery__nav store-gallery__nav--prev" data-store-step="-1" aria-label="Previous picture">‹</button><button type="button" class="store-gallery__nav store-gallery__nav--next" data-store-step="1" aria-label="Next picture">›</button>'
.'<p class="store-gallery__count" aria-live="polite" data-store-count></p>' : '').'</div>';
} else {$g.='<div class="store-gallery__stage store-gallery__stage--none"></div>'}
$g.='</div>';
my $cart=addon_setting('store','cart',1);my $button=addon_setting('store','button','Buy');
my $minor=money_input(100,$cur) eq '100' ? 1 : 100;
my $price=$first ? $first->{price} : $p->{price};
my $f='<form class="store-buy store-buy--page" method="post" action="/x/store/checkout" data-currency="'.h($cur).'" data-minor="'.$minor.'" data-title="'.h($p->{title}).'" data-price="'.(0+$price).'"'
.($first_pic ? ' data-image="'.h($src->($first_pic)).'"' : '')
.($cart ? ' data-cart="'.h(addon_setting('store','cart_button','Add to cart')).'"' : '')
.(@$opts>1 ? ' data-options="'.h(JSON::PP->new->canonical->encode([map {+{id=>$_->{id},label=>$_->{label},price=>0+$_->{price},color=>$_->{color}//'',size=>$_->{size}//'',available=>$_->{available} ? JSON::PP::true : JSON::PP::false}} @$opts])).'"' : '')
.'>'.hidden(product=>$p->{id},back=>$url);
if ($by_attr) {
$f.='<input type="hidden" name="option" value="'.h($first->{id}).'" data-label="'.h($first->{label}).'" data-price="'.(0+$first->{price}).'">';
if (@colors>1) {
my %hex;$hex{$_->{color}} //= $_->{hex} for grep {length($_->{hex}//'')} @$opts;
$f.='<fieldset class="store-choice store-choice--color"><legend>Colour: <span data-store-chosen="color">'.h($first->{color}).'</span></legend><div class="store-choice__list">'
.join('',map {'<label class="store-swatch"><input type="radio" name="color" value="'.h($_).'"'.($_ eq $first->{color} ? ' checked' : '').'><span class="store-swatch__chip"'.(length($hex{$_}//'') ? ' data-hex="'.h($hex{$_}).'"' : '').'></span><span class="store-swatch__name">'.h($_).'</span></label>'} @colors).'</div></fieldset>';
} elsif (@colors) {$f.=hidden(color=>$colors[0])}
if (@sizes>1) {
my %made=map {$_->{size}=>1} grep {($_->{color}//'') eq ($first->{color}//'') && $_->{available}} @$opts;
$f.='<fieldset class="store-choice store-choice--size"><legend>Size: <span data-store-chosen="size">'.h($first->{size}).'</span></legend><div class="store-choice__list">'
.join('',map {'<label class="store-pill"><input type="radio" name="size" value="'.h($_).'"'.($_ eq $first->{size} ? ' checked' : '').($made{$_} ? '' : ' disabled').'><span>'.h($_).'</span></label>'} @sizes).'</div></fieldset>';
} elsif (@sizes) {$f.=hidden(size=>$sizes[0])}
} elsif (@$opts>1) {
$f.='<fieldset class="store-choice store-choice--size"><legend>Choose</legend><div class="store-choice__list">'
.join('',map {'<label class="store-pill"><input type="radio" name="option" value="'.h($_->{id}).'" data-label="'.h($_->{label}).'" data-price="'.(0+$_->{price}).'"'.($_ == $first ? ' checked' : '').($_->{available} ? '' : ' disabled').'><span>'.h($_->{label}).'</span></label>'} @$opts).'</div></fieldset>';
} elsif (@$opts) {$f.=hidden(option=>$opts->[0]{id})}
$f.='<div class="store-qty"><label for="store-qty-'.h($p->{id}).'">Quantity</label><div class="store-stepper"><button type="button" class="store-stepper__step" data-store-qty="-1" aria-label="One fewer">−</button>'
.'<input id="store-qty-'.h($p->{id}).'" type="number" name="quantity" value="1" min="1" max="10" inputmode="numeric"><button type="button" class="store-stepper__step" data-store-qty="1" aria-label="One more">+</button></div></div>'
.'<button type="submit" class="buttonlike store-buy__button"'.($first && !$first->{available} ? ' disabled' : '').'>'.h($first && !$first->{available} ? 'Out of stock' : $button).'</button><p class="store-buy__status" role="status"></p></form>';
my $shop=attempt {my $pg=BlowfishCMS::addon_page('store');$pg ? $pg->{path} : undef};
my $info='<div class="store-product__info"><h1 class="store-product__title">'.h($p->{title}).'</h1>'
.'<p class="store-product__price" data-store-price>'.h($first ? money($first->{price},$cur) : money($p->{price},$cur)).'</p>'.$f
.(length $p->{description} ? '<div class="store-product__description">'.render_markdown($p->{description}).'</div>' : '')
.'<p class="store-product__back"><a href="'.h($shop // '/').'">← Back to the shop</a></p></div>';
start_page($p->{title},$url,200,{description=>excerpt($p->{description},160) || "$p->{title}, ".price_text($p,$cur),
(length image_url($p) ? (image=>$site.image_url($p)) : ()),jsonld=>[product_ld($p,$cur,$site)]});
window('shop','<div class="store-product">'.$g.$info.'</div>');
end_page();
return 1;
}
# ---- Products screen (admin service, /admin/?kind=x-store) ------------------------------
sub admin {
my $message=param('notice',2000);my $edit=product(param('edit',16));
if ($BlowfishCMS::method eq 'POST') {
attempt {
my $action=param('action',30);
list_order(ids=>[map {$_->{id}} @{products()}],back=>'/admin/?kind=x-store',
save=>sub (@ids) {sort_order_save(db(),'store_products','id',@ids)});
if ($action eq 'product_save') {
my $p=product(param('id',16));
my %v=(title=>param('title',120),description=>param('description',5000),active=>param('active',1) eq '1'?1:0,shipping=>param('shipping',1) eq '1'?1:0);
$v{description} =~ s/\r\n?/\n/g;
die "Give the product a name.\n" unless length $v{title};
# One from Printful by itself: its options and prices are Printful's.
my $synced=$p && length $p->{pod_sync};
$v{price}=$synced ? $p->{price} : parse_money(param('price',20),'Price');
die "Price: Stripe needs at least 0.50 (or about that in your currency).\n" if $v{price}<50 && !$synced;
my $stock=param('stock',9);
die "Number available: a whole number, or leave it empty for no limit.\n" if length $stock && $stock !~ /\A\d{1,7}\z/;
$v{stock}=length $stock ? 0+$stock : undef;
# Who makes it: the owner, or a printer (which needs its item, and Gelato the print files).
$v{pod}=$synced ? 'printful' : param('pod',10);$v{pod}='' unless pod_label($v{pod});$v{pod_ref}='';$v{pod_files}='';
if ($v{pod} eq 'printful' && !$synced) {
$v{pod_ref}=param('pod_printful',20);
die "Printful item: its sync variant ID, a number (Print on demand lists your Printful items).\n" unless $v{pod_ref} =~ /\A\d{1,15}\z/;
}
if ($v{pod} eq 'gelato') {
$v{pod_ref}=param('pod_gelato',300);
die "Gelato product UID: copy it from Gelato’s product catalogue, such as apparel_product_gca_t-shirt_….\n" unless $v{pod_ref} =~ /\A[A-Za-z0-9][A-Za-z0-9_.-]{5,299}\z/;
my %files;
for (['default','pod_file','Print file'],['back','pod_file_back','Back print file']) {
my ($type,$field,$what)=@$_;my $url=param($field,1000);next unless length $url;
$url=site_url().$url if $url =~ m{\A/[^/]};
die "$what: the full address of the file, starting with https://.\n" unless $url =~ m{\Ahttps?://[^\s<>"]+\z};
$files{$type}=$url;
}
die "Print file: the address of the design Gelato prints (PNG, JPEG or PDF), such as one under Files.\n" unless $files{default};
$v{pod_files}=JSON::PP->new->canonical->encode(\%files);
}
# A printer sends it, so it always needs an address.
$v{shipping}=1 if length $v{pod};
my $upload=upload_or_picture('image');my $image;
if ($upload) {mkdir "$BlowfishCMS::store/store",0755 unless -d "$BlowfishCMS::store/store";$image=save_image($upload,'store')->{filename}}
attempt {
if ($p) {
# A picture of the owner's own replaces Printful's mockup for good.
db()->do('UPDATE store_products SET title=?,description=?,price=?,stock=?,active=?,shipping=?,pod=?,pod_ref=?,pod_files=?,image=?,pod_image=?,updated_at=? WHERE id=?',undef,
@v{qw(title description price stock active shipping pod pod_ref pod_files)},$image//$p->{image},$image ? '' : $p->{pod_image},now(),$p->{id});
} else {
my $order=1+(db()->selectrow_array('SELECT max(sort_order) FROM store_products')//0);
db()->do('INSERT INTO store_products (id,title,description,price,stock,active,shipping,pod,pod_ref,pod_files,image,sort_order,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)',undef,
substr(random_id(),0,16),@v{qw(title description price stock active shipping pod pod_ref pod_files)},$image//'',$order,now(),now());
}
1;
} or do {my $e=$@;remove_image('store',$image) if $image;die $e};
# The main picture it replaces goes, unless it's one of the product's pictures too.
remove_image('store',$p->{image}) if $p && $image && length $p->{image} && !grep {$_->{file} eq $p->{image}} @{pictures_of($p)};
redirect('/admin/?kind=x-store¬ice='.CGI::escape(encode('UTF-8',($p?'Saved ':'Added ').$v{title}.'.')));
}
if ($action eq 'product_active') {
my $p=product(param('id',16)) or die "That product no longer exists.\n";my $on=param('on',1) eq '1' ? 1 : 0;
db()->do('UPDATE store_products SET active=?,updated_at=? WHERE id=?',undef,$on,now(),$p->{id});
redirect('/admin/?kind=x-store¬ice='.CGI::escape(encode('UTF-8',$on ? "$p->{title} is for sale." : "$p->{title} is off sale; it stays here.")));
}
if ($action eq 'product_delete') {
my $p=product(param('id',16)) or die "That product no longer exists.\n";
db()->do('DELETE FROM store_products WHERE id=?',undef,$p->{id});
remove_image('store',$p->{image}) if length $p->{image};remove_image('store',$_->{file}) for @{pictures_of($p)};
# One from Printful isn't made again by the next sync.
if (length $p->{pod_sync}) {
my %d=map {$_=>1} split(' ',addon_setting('store','printful_deleted','')),$p->{pod_sync};
addon_setting_save('store',printful_deleted=>join(' ',sort keys %d));
}
redirect('/admin/?kind=x-store¬ice='.CGI::escape(encode('UTF-8',"Deleted $p->{title}. Past orders keep its name.".(length $p->{pod_sync} ? ' It won’t come back from Printful.' : ''))));
}
# A product's pictures (1.7.3): the owner's own added, any made the
# main one, hidden or shown, put in order; their own deleted.
if ($action =~ /\Apicture_(add|main|hide|delete|move|color)\z/) {
my $what=$1;
my $p=product(param('id',16)) or die "That product no longer exists.\n";
my $pics=pictures_of($p);my %set;my $done;
my $file=param('file',130);my ($pic)=grep {$_->{file} eq $file} @$pics;
my $back=sub ($text) {redirect('/admin/?kind=x-store&edit='.$p->{id}.'¬ice='.CGI::escape(encode('UTF-8',$text)).'#pictures')};
die "That picture is no longer there.\n" if $what ne 'add' && $what ne 'main' && !$pic;
if ($what eq 'add') {
my @fh=grep {$_} $BlowfishCMS::q->upload('pictures');
@fh=(upload_or_picture('pictures')) unless @fh;
@fh=grep {$_} @fh;
die "Choose one or more pictures (JPEG, PNG or WebP), or one from Pictures.\n" unless @fh;
die "Up to 20 pictures at a time.\n" if @fh>20;
die "A product can have up to 80 pictures.\n" if @$pics+@fh>80;
my $color=param('color',60);$color='' unless grep {($_->{color}//'') eq $color} @{options_of($p)};
mkdir "$BlowfishCMS::store/store",0755 unless -d "$BlowfishCMS::store/store";
my @made;
attempt {push @made,save_image($_,'store')->{filename} for @fh;1} or do {my $e=$@;remove_image('store',$_) for @made;die $e};
push @$pics,map {+{file=>$_,own=>1,color=>$color,src=>''}} @made;
$done=scalar(@made).' picture'.(@made==1 ? '' : 's').' added.';
}
if ($what eq 'main') {
my $f=$file eq ($p->{image}//'') ? $file : $pic ? $pic->{file} : die "That picture is no longer there.\n";
# The main picture it replaces: the owner's own is kept among the
# pictures; Printful's mockup goes (it's among them anyway).
my $old=$p->{image}//'';
if (length $old && $old ne $f && !grep {$_->{file} eq $old} @$pics) {
if (length $p->{pod_image}) {remove_image('store',$old)} else {push @$pics,{file=>$old,own=>1,color=>'',src=>''}}
}
$set{image}=$f;$set{pod_image}='';
$done='That picture is the main one now: the shop’s card shows it, and Printful leaves it be.';
}
if ($what eq 'hide') {
my $on=param('on',1) eq '1';
if ($on) {delete $pic->{hidden}} else {$pic->{hidden}=1}
$done=$on ? 'Shown in the shop again.' : 'Hidden from the shop. It stays here, and Printful won’t bring it back.';
}
if ($what eq 'delete') {
die "A picture from Printful can be hidden, not deleted: it would come back with the next sync.\n" unless $pic->{own};
@$pics=grep {$_ != $pic} @$pics;
remove_image('store',$pic->{file});
# Was it the main one? Then the first picture left is (or Printful's main mockup, at the next sync).
$set{image}='' if $pic->{file} eq ($p->{image}//'');
$done='Picture deleted.';
}
if ($what eq 'move') {
my ($at)=grep {$pics->[$_] == $pic} 0..$#$pics;my $to=$at+(param('direction',4) eq 'up' ? -1 : 1);
@$pics[$at,$to]=@$pics[$to,$at] if $to>=0 && $to<=$#$pics;
$done='Moved.';
}
if ($what eq 'color') {
my $color=param('color',60);$color='' unless grep {($_->{color}//'') eq $color} @{options_of($p)};
$pic->{color}=$color;$done=length $color ? "Shown with $color." : 'Shown with every colour.';
}
$set{pictures}=pictures_json($pics);
my @k=sort keys %set;
db()->do('UPDATE store_products SET '.join(',',map {"$_=?"} @k).',updated_at=? WHERE id=?',undef,@set{@k},now(),$p->{id});
$back->($done);
}
if ($action eq 'printful_undelete') {
addon_setting_save('store',printful_deleted=>'');
redirect('/admin/?kind=x-store¬ice='.CGI::escape(encode('UTF-8','The Printful products you deleted come back at the next sync (Print on demand → sync with Printful).')));
}
if ($action eq 'store_settings') {
my $cur=param('currency',3);die "Choose a currency.\n" unless grep {$_ eq $cur} currencies();
my $countries=uc param('ship_countries',300);$countries =~ s/[\s,]+/ /g;$countries =~ s/^ | $//g;
die "Shipping countries: two-letter codes such as US CA GB, separated by spaces.\n" unless $countries =~ /\A(?:[A-Z]{2}(?: [A-Z]{2})*)?\z/;
my $button=param('button',30);die "Give the button some text.\n" unless length $button;
my $free=param('free_over',20);
# A setting the form didn't send keeps what it was.
my $sent=sub ($k) {defined $BlowfishCMS::q->param($k)};
my $flag=sub ($k) {$sent->($k) ? (param($k,1) eq '1' ? 1 : 0) : addon_setting('store',$k,1)};
my $cart_button=$sent->('cart_button') ? param('cart_button',30) : addon_setting('store','cart_button','Add to cart');
die "Give the cart button some text.\n" unless length $cart_button;
my $note=$sent->('confirmation_note') ? param('confirmation_note',1000) : addon_setting('store','confirmation_note','');$note =~ s/\r\n?/\n/g;
addon_setting_save('store',currency=>$cur,ship_countries=>$countries,button=>$button,
shipping_amount=>parse_money(param('shipping_amount',20)||'0','Shipping cost',$cur),shipping_label=>param('shipping_label',60)||'Shipping',
free_over=>($sent->('free_over') ? (length $free ? parse_money($free,'Free shipping over',$cur) : '') : addon_setting('store','free_over','')),
cart=>$flag->('cart'),cart_button=>$cart_button,
email_owner=>$flag->('email_owner'),email_buyer=>$flag->('email_buyer'),confirmation_note=>$note);
redirect('/admin/?kind=x-store¬ice=Shop%20settings%20saved.');
}
die "Choose an action.\n";
} or $message=failed_action($@);
}
admin_page('Products',section=>'x-store',notice=>$message,
intro=>'What you sell. Put an <strong>Items for sale</strong> block on any page to show them. Payments and orders are under Orders.');
my $cur=currency();my $list=products();
my $i=0;
my $rows=admin_list([map {my $p=$_;$i++;
admin_row(title=>$p->{title},order=>$p->{id},off=>!$p->{active},
lead=>length $p->{image} ? '<img class="store-admin__thumb" src="'.h(image_url($p)).'" alt="">' : '',
meta=>[h(price_text($p,$cur)),(@{options_of($p)}>1 ? scalar(@{options_of($p)}).' options' : ()),
(defined $p->{stock} ? '<span data-store-stock="'.h($p->{id}).'" data-total="'.h($p->{stock}).'">'.h($p->{stock}).' available in total</span>' : 'no limit'),
(length $p->{pod_sync} ? 'from Printful' : pod_label($p->{pod}) ? 'made by '.pod_label($p->{pod}) : $p->{shipping} ? 'shipped' : ()),($p->{active} ? () : 'hidden'),
(length $p->{pod_note} ? '<span class="is-warn">'.h($p->{pod_note}).'</span>' : ())],
actions=>switch_button('x-store','product_active',$p->{id},$p->{active},'for sale',what=>'For sale',name=>$p->{title})
.'<a class="buttonlike" href="/admin/?kind=x-store&edit='.h($p->{id}).'#product-form">edit</a>',
menu=>move_buttons('x-store',$p->{id},$i,scalar @$list,label=>$p->{title})
.'<form method="post" action="/admin/" class="delete-form" data-confirm="Delete '.h($p->{title}).'? Past orders keep its name.'.(length $p->{pod_sync} ? ' It won’t come back from Printful; to hide it for now, switch it off instead.' : '').'">'.fields('product_delete','x-store',$p->{id}).'<button class="text-button danger">delete</button></form>')} @$list],
order=>'x-store',empty=>'No products yet. Add the first one below, or connect Printful under Print on demand: what you publish there appears here by itself.');
my $synced=addon_setting('store','printful_synced','');my @deleted=split ' ',addon_setting('store','printful_deleted','');
$rows.='<p class="media-label">Products from Printful appear and change by themselves'.(length $synced ? ' (last: '.h($synced =~ s/T/ /r =~ s/:\d\dZ\z/ UTC/r).')' : '').'. Their options and prices are Printful’s; their name, description, picture and whether they’re for sale are yours.</p>'
.(length(addon_setting('store','printful_pictures_problem','')) ? '<p class="media-label"><strong>At the last sync, '.h(addon_setting('store','printful_pictures_problem','')).'.</strong> The rest are shown; sync with Printful (Print on demand) tries again.</p>' : '')
.(@deleted ? '<form method="post" action="/admin/" class="admin-form">'.fields('printful_undelete','x-store').'<p class="media-label">'.scalar(@deleted).' Printful product'.(@deleted==1 ? '' : 's').' you deleted '.(@deleted==1 ? 'is' : 'are').' left out. <button class="text-button">bring them back</button></p></form>' : '')
if length $synced || grep {length $_->{pod_sync}} @$list;
window('products',$rows);
# How many are left (the shop's service counts orders; this screen can't
# read them), and the printers' fields (Printful's items come from the
# service too, which holds its key).
print '<script defer src="/addons/store/store-admin.js?v=2"></script>';
my $e=$edit // {title=>'',description=>'',price=>0,stock=>undef,active=>1,shipping=>0,pod=>'',pod_ref=>'',pod_files=>''};
my $pod=pod_of($e) // {provider=>'',ref=>'',files=>{}};my $pp=$pod->{provider};
my $maker='<fieldset class="store-maker"><legend>Who makes and sends it</legend>'
.'<label>Made by<select name="pod" data-store-pod>'.join('',map {'<option value="'.$_->[0].'"'.($_->[0] eq $pp ? ' selected' : '').'>'.h($_->[1]).'</option>'}
['','Me: I send it myself'],[printful=>'Printful prints it and sends it to the buyer'],[gelato=>'Gelato prints it and sends it to the buyer']).'</select>'
.'<span class="optional">A printer is sent each paid order by itself, once it’s connected under Print on demand.</span></label>'
.'<div class="theme-editor__grid" data-pod-for="printful"><label>Printful item<input name="pod_printful" value="'.h($pp eq 'printful' ? $pod->{ref} : '').'" maxlength="20" inputmode="numeric" list="store-printful-items" autocomplete="off" placeholder="sync variant ID">'
.'<span class="optional" data-printful-note>Printful only. The item’s sync variant ID: Print on demand lists your Printful items, or pick one here.</span></label><datalist id="store-printful-items"></datalist></div>'
.'<div class="theme-editor__grid" data-pod-for="gelato"><label>Gelato product UID<input name="pod_gelato" value="'.h($pp eq 'gelato' ? $pod->{ref} : '').'" maxlength="300" spellcheck="false" autocomplete="off" placeholder="apparel_product_gca_t-shirt_…">'
.'<span class="optional">Gelato only. From Gelato’s product catalogue: the product, size and colour in one.</span></label>'
.'<label>Print file<input name="pod_file" value="'.h($pp eq 'gelato' ? $pod->{files}{default}//'' : '').'" maxlength="1000" spellcheck="false" inputmode="url" placeholder="https://…/design.png">'
.'<span class="optional">Gelato only. The address of the design: PNG, JPEG or PDF, such as one under Files.</span></label>'
.'<label>Back print file<input name="pod_file_back" value="'.h($pp eq 'gelato' ? $pod->{files}{back}//'' : '').'" maxlength="1000" spellcheck="false" inputmode="url" placeholder="optional">'
.'<span class="optional">Gelato only, optional: a design for the back.</span></label></div></fieldset>';
# One from Printful by itself: its options and prices are shown, not edited.
my $synced_edit=$edit && length $edit->{pod_sync};
if ($synced_edit) {
my $opts=options_of($edit);
$maker='<fieldset class="store-maker"><legend>From Printful</legend><p class="media-label">Printful makes and sends it. Its options and prices come from Printful, and change there.'
.(length $edit->{pod_note} ? ' <strong>'.h($edit->{pod_note}).'</strong>' : '').'</p>'
.(@$opts ? '<ul class="store-options">'.join('',map {'<li>'.h($_->{label}).' · '.h(money($_->{price},$cur)).'</li>'} @$opts).'</ul>' : '').'</fieldset>';
}
my $f='<form id="product-form" method="post" action="/admin/" enctype="multipart/form-data" class="admin-form" data-choose-submit="no">'.fields('product_save','x-store',$edit ? $edit->{id} : '')
.'<div class="theme-editor__grid"><label>Name<input name="title" value="'.h($e->{title}).'" maxlength="120" required></label>'
.($synced_edit ? '' : '<label>Price ('.uc($cur).')<input name="price" data-currency="'.h($cur).'" value="'.($edit ? h(money_input($e->{price},$cur)) : '').'" maxlength="20" required inputmode="decimal" placeholder="12.50"></label>')
.'<label>Number available<input name="stock" value="'.h($e->{stock}//'').'" maxlength="9" inputmode="numeric" placeholder="no limit"><span class="optional">In total, across all orders. Leave empty for no limit.</span></label></div>'
.'<label>Description<textarea name="description" rows="5" maxlength="5000" data-markdown>'.h($e->{description}).'</textarea><span class="optional">Markdown: the toolbar’s ? lists what it can do.</span></label>'
.'<label>Main picture<input name="image" type="file" accept="image/jpeg,image/png,image/webp"><span class="optional">'.($edit && length $e->{image} ? 'Choose a file to replace the main picture. More pictures, and which is main, under Pictures below.' : 'JPEG, PNG or WebP. More pictures can be added once it’s saved.').'</span></label>'.choose_picture_button('Choose the product picture')
.$maker
.($synced_edit ? hidden(shipping=>1) : switch_field('shipping','Needs shipping',$e->{shipping},hint=>'Asks for an address at checkout. Always on for what a printer makes.'))
.switch_field('active','For sale',$e->{active},hint=>'Shown on pages.')
.'<button class="buttonlike is-primary" type="submit">'.($edit ? 'save product' : 'add product').'</button>'.($edit ? ' <a href="/admin/?kind=x-store">cancel</a>' : '').'</form>'
.BlowfishCMS::markdown_help_html();
window($edit ? 'edit '.$edit->{title} : 'add a product',$f);
window('pictures of '.$edit->{title},pictures_panel($edit)) if $edit;
my $s='<form method="post" action="/admin/" class="admin-form">'.fields('store_settings','x-store').'<div class="theme-editor__grid">'
.'<label>Currency<select name="currency">'.join('',map {'<option value="'.$_.'"'.($_ eq $cur?' selected':'').'>'.uc($_).'</option>'} currencies()).'</select><span class="optional">Prices are in this currency.</span></label>'
.'<label>Button text<input name="button" value="'.h(addon_setting('store','button','Buy')).'" maxlength="30" required></label></div>'
.'<div class="theme-editor__grid"><label>Shipping cost per order<input name="shipping_amount" value="'.h(money_input(addon_setting('store','shipping_amount',0),$cur)).'" maxlength="20" inputmode="decimal"><span class="optional">Added when an order needs shipping. 0 for free shipping.</span></label>'
.'<label>Shipping name<input name="shipping_label" value="'.h(addon_setting('store','shipping_label','Shipping')).'" maxlength="60"></label>'
.'<label>Ships to<input name="ship_countries" value="'.h(addon_setting('store','ship_countries','US')).'" maxlength="300" placeholder="US CA"><span class="optional">Two-letter country codes.</span></label>'
.'<label>Free shipping over<input name="free_over" value="'.h(length(addon_setting('store','free_over','')) ? money_input(addon_setting('store','free_over',''),$cur) : '').'" maxlength="20" inputmode="decimal" placeholder="never"><span class="optional">Optional: orders of this much or more ship free.</span></label></div>'
.'<h3>Cart</h3>'.switch_field('cart','Buyers collect items in a cart and pay for them together',addon_setting('store','cart',1))
.'<div class="theme-editor__grid"><label>Cart button<input name="cart_button" value="'.h(addon_setting('store','cart_button','Add to cart')).'" maxlength="30" required></label></div>'
.'<p class="media-label">The cart is kept in the buyer’s own browser (no cookies). Without the cart, each item’s button goes straight to payment.</p>'
.'<h3>Emails</h3>'.switch_field('email_owner','Email me each new order',addon_setting('store','email_owner',1))
.switch_field('email_buyer','Email buyers a confirmation of their order',addon_setting('store','email_buyer',1))
.'<label>A note for the confirmation<textarea name="confirmation_note" rows="2" maxlength="1000">'.h(addon_setting('store','confirmation_note','')).'</textarea><span class="optional">Optional, such as when orders are sent.</span></label>'
.'<p class="media-label">Emails go through the site’s Postmark connection (Settings → Mail): yours to the <em>update alerts</em> address, or else where contact messages go. Buyers’ replies reach you there too.</p>'
.'<button class="buttonlike" type="submit">save</button></form>';
window('shop settings',$s);
end_page();
return 1;
}
# ---- A product's pictures, on Products (admin service, 1.7.3) -------------------------------
# Every picture the product's page shows, in its order: the main one marked
# (the shop's card shows it), each from Printful or the owner's own, its
# colour, whether it's hidden; and adding the owner's own, for a colour or all.
sub pictures_panel ($p) {
my $pics=pictures_of($p);my $main=main_picture($p);my $id=$p->{id};
my %colors;my @colors=grep {length && !$colors{$_}++} map {$_->{color}//''} @{options_of($p)};
my $form=sub ($action,$inner,%o) {'<form method="post" action="/admin/" class="'.($o{class}//'inline-form').'"'.($o{confirm} ? ' data-confirm="'.h($o{confirm}).'"' : '').($o{auto} ? ' data-auto-submit' : '').'>'.fields($action,'x-store',$id).$inner.'</form>'};
my $color_select=sub ($name,$now) {'<select name="'.$name.'">'.join('',map {'<option value="'.h($_->[0]).'"'.($_->[0] eq $now ? ' selected' : '').'>'.h($_->[1]).'</option>'} ['','every colour'],map {[$_,$_]} @colors).'</select>'};
# Which of them is the main one: its file, or Printful's main mockup by its address.
my $mock=$p->{pod_image}//'';
my ($main_pic)=grep {$_->{file} eq $main} @$pics;
($main_pic)=grep {length $mock && $main eq ($p->{image}//'') && grep {$_ eq $mock} $_->{src}//'',@{ref $_->{also} eq 'ARRAY' ? $_->{also} : []}} @$pics unless $main_pic;
# The main picture first when it's of its own (Printful's main mockup, or one uploaded with the product).
my @rows;
unless ($main_pic) {
push @rows,admin_row(title=>'Main picture',lead=>(length $main ? '<img class="store-admin__thumb" src="/media/store/'.h($main).'" alt="">' : ''),
badges=>[['main',1]],meta=>[length $main ? (length $p->{pod_image} ? 'Printful’s main mockup' : 'yours') : 'none yet: add one below, or choose one of these']) if length $main || !@$pics;
}
my $n=0;
for my $pic (@$pics) {
$n++;my $f=$pic->{file};my $is_main=$main_pic && $pic == $main_pic;
my @variants=@{$pic->{variants}//[]};
# Its variants by size (its colour is said already), or by their whole label.
my %label=map {$_->{id}=>(length($_->{size}//'') ? $_->{size} : $_->{label})} @{options_of($p)};
push @rows,admin_row(title=>"Picture $n",off=>$pic->{hidden},lead=>'<img class="store-admin__thumb" src="/media/store/'.h($f).'" alt="">',
badges=>[($is_main ? (['main',1]) : ()),($pic->{hidden} ? ('hidden') : ())],
meta=>[($pic->{own} ? 'yours' : 'from Printful'),(length($pic->{color}//'') ? h($pic->{color}) : 'every colour'),
(@variants && @variants<@{options_of($p)} ? h(join(', ',map {$label{$_}//$_} @variants[0..($#variants<3 ? $#variants : 3)]).(@variants>4 ? ' …' : '')) : ())],
actions=>($is_main ? '' : $form->('picture_main',hidden(file=>$f).'<button class="buttonlike">make main</button>'))
.$form->('picture_hide',hidden(file=>$f,on=>$pic->{hidden} ? 1 : 0).'<button class="buttonlike">'.($pic->{hidden} ? 'show' : 'hide').'</button>'),
menu=>($n>1 ? $form->('picture_move',hidden(file=>$f,direction=>'up').'<button class="text-button">move up</button>') : '')
.($n<@$pics ? $form->('picture_move',hidden(file=>$f,direction=>'down').'<button class="text-button">move down</button>') : '')
.($pic->{own} && @colors>1 ? $form->('picture_color',hidden(file=>$f).'<label>Colour '.$color_select->('color',$pic->{color}//'').'</label><button class="text-button no-js-only">save</button>',auto=>1) : '')
.($pic->{own} ? $form->('picture_delete',hidden(file=>$f).'<button class="text-button danger">delete</button>',confirm=>'Delete this picture?') : ''),
menu_for=>"picture $n");
}
return '<div id="pictures">'
.'<p class="media-label">What the product’s page shows, in this order; the <em>main</em> one is on the shop’s card too. '
.(length $p->{pod_sync} ? 'Printful’s pictures change with Printful; one that’s wrong can be hidden (it stays hidden), and your own added. ' : '')
.'A picture of a colour shows when that colour is chosen.</p>'
.admin_list(\@rows,empty=>'No pictures yet.')
.'<form method="post" action="/admin/" enctype="multipart/form-data" class="admin-form" data-choose-submit="no">'.fields('picture_add','x-store',$id)
.'<div class="theme-editor__grid"><label>Add pictures<input name="pictures" type="file" accept="image/jpeg,image/png,image/webp" multiple><span class="optional">JPEG, PNG or WebP; up to 20 at a time.</span></label>'
.(@colors>1 ? '<label>Shown with'.$color_select->('color','').'<span class="optional">A colour’s pictures show when it’s chosen.</span></label>' : '').'</div>'
.choose_picture_button('Choose a picture for '.$p->{title})
.'<button class="buttonlike is-primary" type="submit">add pictures</button></form></div>';
}
# ---- Printful's products, handed over by the store service (admin service, 1.6.0) ------
# The store service reads Printful (it holds the key) and hands what it found
# over through the core (addon_hand_over), since only the admin service can
# write the catalogue: {kind: "printful", complete: 1 when it's every product,
# products: [{id, name, image, variants: [{id, name, price, currency}]}],
# gone: [ids]}. Printful decides a product's options and prices; the owner its
# name, description, picture and whether it's for sale. A new one is for sale
# at once; one gone from Printful goes off sale; one the owner deleted isn't
# made again (printful_deleted).
sub from_service ($d) {
die "Not a hand-over the Store knows.\n" unless ref $d eq 'HASH' && ($d->{kind}//'') eq 'printful';
my $cur=currency();my %seen;my %n=(added=>0,changed=>0,same=>0,off=>0);
@picture_problems=();
my %deleted=map {$_=>1} split ' ',addon_setting('store','printful_deleted','');
for my $sp (@{ref $d->{products} eq 'ARRAY' ? $d->{products} : []}) {
next unless ref $sp eq 'HASH' && ($sp->{id}//'') =~ /\A\d{1,15}\z/;
$seen{$sp->{id}}=1;
$n{printful_product_save($sp,$cur)}++ unless $deleted{$sp->{id}};
}
my @gone=grep {/\A\d{1,15}\z/} @{ref $d->{gone} eq 'ARRAY' ? $d->{gone} : []};
push @gone,map {$_->{pod_sync}} grep {length $_->{pod_sync} && !$seen{$_->{pod_sync}}} @{products()} if $d->{complete};
my $note='It’s no longer in Printful.';
$n{off}+=db()->do("UPDATE store_products SET active=0,pod_note=?,updated_at=? WHERE pod='printful' AND pod_sync=? AND (active=1 OR pod_note<>?)",undef,$note,now(),$_,$note)>0 ? 1 : 0 for @gone;
# Pictures that couldn't be fetched are said, here (the log) and on Products.
my $pics=@picture_problems ? scalar(@picture_problems).' picture'.(@picture_problems==1 ? '' : 's')." couldn’t be fetched ($picture_problems[0])" : '';
addon_setting_save('store',printful_synced=>now(),printful_pictures_problem=>$pics);
return "Printful: $n{added} added, $n{changed} changed, $n{off} off sale".(length $pics ? "; $pics" : '');
}
# One of Printful's products into the catalogue: 'added', 'changed' or 'same'.
sub printful_product_save ($sp,$cur) {
my $clean=sub ($v,$max) {$v//='';$v =~ s/[\x00-\x1f\x7f]+/ /g;$v =~ s/\A\s+|\s+\z//g;return substr($v,0,$max)};
my $name=$clean->($sp->{name},120);$name='Printful product' unless length $name;
my (@opts,$problem,%label);
my $url_ok=sub ($u) {($u//'') =~ m{\Ahttps?://[^\s<>"]{1,1000}\z}};
for my $v (@{ref $sp->{variants} eq 'ARRAY' ? $sp->{variants} : []}) {
next unless ref $v eq 'HASH' && ($v->{id}//'') =~ /\A\d{1,15}\z/;
if (lc($v->{currency}||$cur) ne $cur) {$problem//="Its prices in Printful are in ".uc($v->{currency}).", and the shop’s in ".uc($cur).'.';next}
my $price=attempt {parse_money($v->{price}//'','Price',$cur)};
if (!defined $price || $price<50) {$problem//='Printful gives it no price of at least 0.50.';next}
# Its colour and size (1.7.0), and a label for the cart: "Navy / M",
# or from its name ("Sticker / 3″×3″" is offered as "3″×3″").
my ($color,$size)=($clean->($v->{color},60),$clean->($v->{size},60));
my $label=join(' / ',grep {length} $color,$size);
unless (length $label) {$label=$clean->($v->{name},120);$label=$1 if $label =~ /\A\Q$name\E\s*[\/—–-]\s*(.+)\z/}
$label="$label ($v->{id})" if $label{$label}++;
my $hex=($v->{hex}//'') =~ /\A#[0-9a-fA-F]{6}\z/ ? lc $v->{hex} : '';
push @opts,{id=>"$v->{id}",label=>$label,price=>$price,ref=>"$v->{id}",color=>$color,size=>$size,hex=>$hex,
available=>(defined $v->{available} && !$v->{available}) ? JSON::PP::false : JSON::PP::true,
images=>[grep {$url_ok->($_)} @{ref $v->{images} eq 'ARRAY' ? $v->{images} : []}]};
}
my $note=!@opts ? $problem // 'Printful has nothing of it to sell.' : !(grep {$_->{available}} @opts) ? 'Printful has none of it in stock.' : '';
# Its pictures (1.7.2): every variant's mockups, each once, marked with its
# colour and the variants it shows, so the page can show a colour's
# pictures and jump to a size's (1.7.0 kept only each colour's first
# variant's, so a sticker's sizes, all one colour, had one picture). Up to 60.
my (%at,@want);
for my $o (@opts) {
for my $src (@{$o->{images}}) {
if (defined $at{$src}) {push @{$want[$at{$src}]{variants}},$o->{id};next}
$at{$src}=@want;push @want,{src=>$src,color=>$o->{color},variants=>[$o->{id}]};
}
}
splice @want,60 if @want>60;
delete $_->{images} for @opts;
my $json=@opts ? JSON::PP->new->canonical->encode(\@opts) : '';
my $low=@opts ? (sort {$a<=>$b} map {$_->{price}} @opts)[0] : 0;
my $mockup=$url_ok->($sp->{image}) ? $sp->{image} : '';
my $p=db()->selectrow_hashref("SELECT * FROM store_products WHERE pod='printful' AND pod_sync=?",undef,$sp->{id});
# The main mockup goes through the same check, last: when it's one of the
# variants' pictures it joins that one, so the page doesn't show it twice.
push @want,{src=>$mockup,color=>'',variants=>[]} if length $mockup && !grep {$_->{src} eq $mockup} @want;
my $pictures=printful_pictures($p ? pictures_of($p) : [],\@want,$p ? $p->{image} : '');
unless ($p) {
my $image=length $mockup ? attempt {printful_picture($mockup)} : undef;
# The blank product's description to start with (the owner's from then on).
my $about=$sp->{about}//'';$about =~ s/\r\n?/\n/g;$about =~ s/[\x00-\x09\x0b-\x1f\x7f]+/ /g;$about=substr($about,0,5000);
my $order=1+(db()->selectrow_array('SELECT max(sort_order) FROM store_products')//0);
db()->do('INSERT INTO store_products (id,title,description,price,stock,active,shipping,pod,pod_ref,pod_files,options,pod_sync,pod_image,pod_note,image,pictures,sort_order,created_at,updated_at) VALUES (?,?,?,?,NULL,?,1,?,?,?,?,?,?,?,?,?,?,?,?)',undef,
substr(random_id(),0,16),$name,$about,$low,length $note ? 0 : 1,'printful','','',$json,$sp->{id},$image ? $mockup : '',$note,$image//'',$pictures,$order,now(),now());
return 'added';
}
my %set=(options=>$json,price=>$low||$p->{price},pod_note=>$note,pictures=>$pictures);
# Off sale while something's wrong; back on sale once it's put right.
$set{active}=0 if length $note;
$set{active}=1 if !length $note && length $p->{pod_note} && !$p->{active};
# A picture that came from Printful follows its mockup (one of the owner's own stays).
if (length $mockup && (length $p->{pod_image} ? $p->{pod_image} ne $mockup : !length $p->{image})) {
if (my $image=attempt {printful_picture($mockup)}) {
remove_image('store',$p->{image}) if length $p->{image} && !grep {$_->{file} eq $p->{image}} @{pictures_of({pictures=>$pictures})};
$set{image}=$image;$set{pod_image}=$mockup;
}
}
my @k=grep {($p->{$_}//'') ne ($set{$_}//'')} sort keys %set;
return 'same' unless @k;
db()->do('UPDATE store_products SET '.join(',',map {"$_=?"} @k).',updated_at=? WHERE id=?',undef,@set{@k},now(),$p->{id});
return 'changed';
}
# A product's pictures besides its main one, in the order shown:
# [{file, src, color, variants, hash, also, own, hidden}]. Printful's mockups
# (1.7.0) carry where they came from (src), their colour and the variants
# they show; the owner's own (1.7.3) are marked own, with a colour or none;
# any can be hidden from the shop (a Printful one that's wrong comes back
# with every sync otherwise).
sub pictures_of ($p) {
my $l=length($p->{pictures}//'') ? ((attempt {JSON::PP->new->decode($p->{pictures})}) // []) : [];
return ref $l eq 'ARRAY' ? [grep {ref $_ eq 'HASH' && ($_->{file}//'') =~ /\A[A-Za-z0-9._-]{1,120}\z/} @$l] : [];
}
sub pictures_json ($list) { return @$list ? JSON::PP->new->canonical->encode($list) : '' }
# Printful's mockups as the product's pictures: those it had are kept, new
# ones fetched, gone ones removed; the owner's own, which they hid, and the
# order they chose are kept (1.7.3). Returns them as JSON. A picture is kept
# once however many addresses and variants show it: Printful often makes each
# size's mockup a file of its own that looks just like the others of that
# colour, so the same picture (by its bytes) is one picture, for all of them.
# $main, the product's main picture's file, is never removed.
sub printful_pictures ($had,$want,$main='') {
# Each kept picture by its address, and by the others that turned out to be the same picture.
my %have;for my $e (grep {!$_->{own} && length($_->{src}//'')} @$had) {$have{$_}//=$e for $e->{src},@{ref $e->{also} eq 'ARRAY' ? $e->{also} : []}}
my (@now,%by_hash,%kept);
for my $w (@$want) {
my ($file,$hash);
# One kept before is kept (1.7.0 kept no fingerprint, so those are fetched once more).
my $h=$have{$w->{src}};
($file,$hash)=($h->{file},$h->{hash}) if $h && length($h->{hash}//'');
unless (defined $file) {
my $bytes=attempt {printful_fetch($w->{src})};
unless (defined $bytes) {push @picture_problems,clean_error($@);next}
$hash=sha256_hex($bytes);
unless ($by_hash{$hash}) {
$file=attempt {mkdir "$BlowfishCMS::store/store",0755 unless -d "$BlowfishCMS::store/store";open my $fh,'<',\$bytes or die "unreadable\n";save_image($fh,'store')->{filename}};
unless ($file) {push @picture_problems,clean_error($@);next}
}
}
# The same picture again: its variants (and its address) join the one already kept.
if (length($hash//'') && (my $same=$by_hash{$hash})) {
my %v=map {$_=>1} @{$same->{variants}};push @{$same->{variants}},grep {!$v{$_}++} @{$w->{variants}//[]};
push @{$same->{also}},$w->{src} unless $w->{src} eq $same->{src} || grep {$_ eq $w->{src}} @{$same->{also}//[]};
next;
}
my $kept_before=ref $h eq 'HASH' && length($h->{hash}//'');
my $entry={file=>$file,src=>$w->{src},color=>$w->{color}//'',variants=>[@{$w->{variants}//[]}],hash=>$hash//'',
($kept_before && ref $h->{also} eq 'ARRAY' ? (also=>[@{$h->{also}}]) : ()),($kept_before && $h->{hidden} ? (hidden=>1) : ())};
$by_hash{$hash}=$entry if length($hash//'');
push @now,$entry;
}
# In the order the owner left them: those it had (its own, and Printful's still there), then new ones.
my %fresh=map {$_->{file}=>$_} @now;my (@out,%placed);
for my $e (@$had) {
if ($e->{own}) {push @out,$e;next}
my $f=$fresh{$e->{file}} or next;
push @out,$f unless $placed{$f->{file}}++;
}
push @out,grep {!$placed{$_->{file}}} @now;
$kept{$_->{file}}=1 for @out;
remove_image('store',$_->{file}) for grep {!$kept{$_->{file}} && $_->{file} ne ($main//'')} @$had;
return pictures_json(\@out);
}
# A Printful mockup's bytes: from a secure web address (not this server's own
# network), or the tests' stand-in.
sub printful_fetch ($url) {
my $files=$BlowfishCMS::startup_env{BLOWFISH_PRINTFUL_FILES}//'';
unless (length $files && index($url,$files)==0) {
my ($host)=$url =~ m{\Ahttps://([a-z0-9.-]+)(?::\d+)?/}i;
die "A picture’s address isn’t one to fetch: ".substr($url,0,80)."\n"
if !$host || $host =~ /\A[\d.]+\z/ || $host =~ /(?:\A|\.)localhost\z/i || $host !~ /\./;
}
require HTTP::Tiny;
my $r=HTTP::Tiny->new(timeout=>30,verify_SSL=>1,max_size=>30*1048576)->get($url);
die "Printful’s picture couldn’t be fetched (".($r->{status}//'?').' '.($r->{reason}//'')."): ".substr($url,0,80)."\n" unless $r->{success};
return $r->{content};
}
# A Printful mockup as the product's main picture.
sub printful_picture ($url) {
my $bytes=printful_fetch($url);
mkdir "$BlowfishCMS::store/store",0755 unless -d "$BlowfishCMS::store/store";
open my $fh,'<',\$bytes or die "Printful’s picture couldn’t be read.\n";
return save_image($fh,'store')->{filename};
}
# ---- The store service: orders, Stripe -------------------------------------------------
# Stripe itself (its API, the key files, the webhook's signature, the keys'
# panel) is the core's Payments.pm since 1.3.0, with the store's own keys.
sub orders_db {
state %open;my $file=addon_data_dir('store').'/orders.sqlite';
return $open{$file} if $open{$file} && $open{$file}->ping;
my $o=DBI->connect("dbi:SQLite:dbname=$file",'','',{RaiseError=>1,PrintError=>0,AutoCommit=>1,sqlite_unicode=>1});
$o->do('PRAGMA busy_timeout=5000');
$o->do("CREATE TABLE IF NOT EXISTS orders (id TEXT PRIMARY KEY, status TEXT NOT NULL, product TEXT NOT NULL, title TEXT NOT NULL, quantity INTEGER NOT NULL, unit_amount INTEGER NOT NULL, shipping_amount INTEGER NOT NULL DEFAULT 0, currency TEXT NOT NULL, total INTEGER, session TEXT NOT NULL DEFAULT '', email TEXT NOT NULL DEFAULT '', name TEXT NOT NULL DEFAULT '', address TEXT NOT NULL DEFAULT '', visitor TEXT NOT NULL DEFAULT '', live INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, paid_at TEXT, fulfilled_at TEXT)");
$o->do('CREATE INDEX IF NOT EXISTS orders_product ON orders(product,status)');
$o->do('CREATE TABLE IF NOT EXISTS events (id TEXT PRIMARY KEY, type TEXT NOT NULL, received_at TEXT NOT NULL)');
# 1.2.0: an order holds several items (the cart); orders from before
# become one line each. Its emails are sent once (emailed_at).
if (($o->selectrow_array('PRAGMA user_version')//0)<2) {
$o->do('CREATE TABLE IF NOT EXISTS order_items (order_id TEXT NOT NULL, line INTEGER NOT NULL, product TEXT NOT NULL, title TEXT NOT NULL, quantity INTEGER NOT NULL, unit_amount INTEGER NOT NULL, shipping INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (order_id,line))');
$o->do('INSERT OR IGNORE INTO order_items (order_id,line,product,title,quantity,unit_amount) SELECT id,0,product,title,quantity,unit_amount FROM orders');
attempt {$o->do('ALTER TABLE orders ADD COLUMN emailed_at TEXT')};
$o->do('PRAGMA user_version=2');
}
# 1.5.0: each line keeps what its printer needs (JSON, or '' for what the
# owner sends), and each order what was sent to which printer.
if (($o->selectrow_array('PRAGMA user_version')//0)<3) {
attempt {$o->do("ALTER TABLE order_items ADD COLUMN pod TEXT NOT NULL DEFAULT ''")};
$o->do('PRAGMA user_version=3');
}
# status: sending, failed, draft, made, hold, shipped, delivered, canceled, returned (pod_phase).
$o->do("CREATE TABLE IF NOT EXISTS pod_orders (order_id TEXT NOT NULL, provider TEXT NOT NULL, status TEXT NOT NULL, remote_id TEXT NOT NULL DEFAULT '', remote_status TEXT NOT NULL DEFAULT '', problem TEXT NOT NULL DEFAULT '', tracking TEXT NOT NULL DEFAULT '', live INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, shipped_at TEXT, emailed_at TEXT, PRIMARY KEY (order_id,provider))");
return $open{$file}=$o;
}
sub read_secret ($key) { return BlowfishCMS::stripe_secret('store',$key) }
sub stripe ($verb,$path,$pairs=[],%o) { return BlowfishCMS::stripe_request('store',$verb,$path,$pairs,%o) }
sub stripe_problem ($status,$reply) { return BlowfishCMS::stripe_problem($status,$reply) }
sub live_key ($key) { return BlowfishCMS::stripe_live($key) }
# How many of each limited product are left: stock minus paid orders and
# checkouts started in the last hour (which may still be paid).
sub remaining {
my %left;my $since=BlowfishCMS::strftime('%Y-%m-%dT%H:%M:%SZ',gmtime(time-3600));
my $taken={map {$_->[0]=>$_->[1]} @{orders_db()->selectall_arrayref("SELECT i.product,sum(i.quantity) FROM order_items i JOIN orders o ON o.id=i.order_id WHERE o.status='paid' OR (o.status='pending' AND o.created_at>?) GROUP BY i.product",undef,$since)}};
for my $p (@{products(1)}) {next unless defined $p->{stock};my $l=$p->{stock}-($taken->{$p->{id}}//0);$left{$p->{id}}=$l<0?0:$l}
return \%left;
}
sub message_page ($title,$text,$status=200) {
start_page($title,'/x/store/',$status,{noindex=>1});
window(lc $title,'<h1>'.h($title).'</h1>'.$text);
end_page();
}
sub route ($rest) {
my $method=$BlowfishCMS::method;
if ($rest eq 'stock.json') {
header(200,'application/json; charset=UTF-8',"Cache-Control: no-store\r\n");
print JSON::PP->new->canonical->encode(remaining());return 1;
}
if ($rest eq 'checkout') {checkout();return 1}
# A product's own page (1.7.0): /x/store/item/ID/its-name.
if ($rest =~ m{\Aitem/([a-f0-9]{16})(?:/[a-z0-9-]{0,80})?\z}) {return product_page($1)}
if ($rest eq 'webhook') {webhook();return 1}
if ($rest =~ m{\Apod/(printful|gelato)/([a-f0-9]{32})\z}) {pod_webhook($1,$2);return 1}
if ($rest eq 'thanks') {
my $o=orders_db()->selectrow_hashref('SELECT * FROM orders WHERE id=?',undef,param('order',32));
return 0 unless $o && $o->{id} =~ /\A[a-f0-9]{32}\z/;
my $state=$o->{status} eq 'paid' ? 'Your payment went through.' : 'Your payment is being confirmed. This page will say so once Stripe tells us.';
my $items=order_items($o->{id});
message_page('Thank you','<p>'.h($state).'</p><ul class="store-thanks">'.join('',map {'<li>'.h($_->{quantity}.' × '.$_->{title}).'</li>'} @$items).'</ul><p>Stripe emails your receipt'.(addon_setting('store','email_buyer',1) ? ', and we’ll email you a confirmation' : '').'. <a href="/">Back to the site</a></p>');
return 1;
}
return 0;
}
sub checkout {
if ($BlowfishCMS::method ne 'POST') {header(405,'text/plain; charset=UTF-8');print 'Method Not Allowed';return}
my $origin=$ENV{HTTP_ORIGIN}//'';
if (length $origin && !own_origin($origin)) {header(403,'text/plain; charset=UTF-8');print 'Forbidden';return}
my $fetch=fetch_request();
my $fail=sub ($text,$status=400) {
BlowfishCMS::json_response({ok=>JSON::PP::false,message=>$text},$status) if $fetch;
message_page('Checkout unavailable','<p>'.h($text).'</p><p><a href="javascript:history.back()">Go back</a></p>',$status);
BlowfishCMS::finish();
};
# What's bought: the cart's lines (item=PRODUCT:QUANTITY, or
# PRODUCT.OPTION:QUANTITY for one of its options), or one item, its
# option and quantity (the item's own form, without JavaScript).
my @want;
my @asked=$BlowfishCMS::q->can('multi_param') ? $BlowfishCMS::q->multi_param('item') : $BlowfishCMS::q->param('item');
for my $it (@asked[0..($#asked<29 ? $#asked : 29)]) {push @want,[$1,$2//'',0+$3] if ($it//'') =~ /\A([a-f0-9]{16})(?:\.([A-Za-z0-9_-]{1,40}))?:(\d{1,3})\z/}
my %form;
unless (@want) {
my $qty=param('quantity',3);$qty=1 unless $qty =~ /\A[1-9]\d?\z/;push @want,[param('product',16),param('option',40),0+$qty];
%form=(color=>param('color',60),size=>param('size',60));
}
# Each line: {p (the product), opt (its option, if it has them), qty,
# price, title, pod (what its printer needs)}.
my (%at,@lines);
my $gone=@want>1 ? 'Something in your cart isn’t for sale any more. Remove it and try again.' : 'That item isn’t for sale any more.';
for my $w (@want) {
my ($pid,$oid,$qty)=@$w;next unless $qty>0;
my $p=product($pid);
$fail->($gone,404) unless $p && $p->{active};
my $opts=options_of($p);my $opt;
if (@$opts) {
# The product page's colour and size (without JavaScript) name the option.
if (@want==1 && (length $form{color} || length $form{size})) {
my ($m)=grep {(!length($_->{color}//'') || $_->{color} eq $form{color}) && (!length($_->{size}//'') || $_->{size} eq $form{size})} @$opts;
$oid=$m ? $m->{id} : '';
$fail->("That colour doesn’t come in that size. Choose another.",400) unless $m;
}
$oid=$opts->[0]{id} if @$opts==1 && !length $oid;
$opt=option_of($p,$oid) or $fail->(length $oid ? $gone : "Choose which $p->{title} you’d like.",length $oid ? 404 : 400);
$fail->("$p->{title} ($opt->{label}) is out of stock at the moment.",409) if defined $opt->{available} && !$opt->{available};
}
my $key=$pid.($opt ? ".$opt->{id}" : '');
if (defined $at{$key}) {$lines[$at{$key}]{qty}+=$qty;next}
$at{$key}=@lines;
push @lines,{p=>$p,opt=>$opt,qty=>$qty,price=>$opt ? 0+$opt->{price} : 0+$p->{price},title=>$p->{title}.($opt && @$opts>1 ? " ($opt->{label})" : ''),pod=>pod_of($p,$opt)};
}
$fail->('Your cart is empty.') unless @lines;
$fail->('Choose a quantity from 1 to 10 of each item.') if grep {$_->{qty}>10} @lines;
my $back=param('back',200);$back='/' unless $back =~ m{\A/[a-z0-9/-]*\z};
$fail->('The shop isn’t taking orders yet.',503) unless length read_secret('stripe.key');
# What a printer makes is sold only while that printer is connected.
for (@lines) {next unless $_->{pod};$fail->("$_->{p}{title} can’t be ordered right now. Please try again later.",503) unless length pod_key($_->{pod}{provider})}
my $cur=currency();
# One flat shipping cost per order, when anything in it needs shipping
# (free over an amount, when one is set).
my $subtotal=0;$subtotal+=$_->{price}*$_->{qty} for @lines;
my $ships=grep {$_->{p}{shipping} || $_->{pod}} @lines;
my $free=addon_setting('store','free_over','');
my $ship_amount=!$ships ? 0 : length($free) && $free =~ /\A\d+\z/ && $subtotal>=$free ? 0 : 0+addon_setting('store','shipping_amount',0);
my $odb=orders_db();
# One checkout at a time, so two buyers can't take the last one.
$odb->begin_work;
my ($id,$visitor);
attempt {
# A limited product's number is shared by its options.
my $left=remaining();my %want;$want{$_->{p}{id}}+=$_->{qty} for @lines;
for (grep {defined $_->{p}{stock}} map {$_->{p}} @lines) {my $l=$left->{$_->{id}}//0;die($l ? "Only $l of $_->{title} left.\n" : "$_->{title} is sold out.\n") if $want{$_->{id}}>$l}
$visitor=sha256_hex(($ENV{REMOTE_ADDR}//'').'|'.int(time/3600));
my $since=BlowfishCMS::strftime('%Y-%m-%dT%H:%M:%SZ',gmtime(time-3600));
die "Too many checkouts started from here in the last hour. Try again later.\n"
if $odb->selectrow_array("SELECT count(*) FROM orders WHERE visitor=? AND created_at>?",undef,$visitor,$since)>=20;
$id=random_id();
my $units=0;$units+=$_->{qty} for @lines;
my $first=$lines[0];
$odb->do('INSERT INTO orders (id,status,product,title,quantity,unit_amount,shipping_amount,currency,visitor,live,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)',undef,
$id,'pending',$first->{p}{id},$first->{title}.(@lines>1 ? ' and '.(@lines-1).' more' : ''),$units,$first->{price},$ship_amount,$cur,$visitor,live_key(read_secret('stripe.key')),now());
my $n=0;
for (@lines) {
$odb->do('INSERT INTO order_items (order_id,line,product,title,quantity,unit_amount,shipping,pod) VALUES (?,?,?,?,?,?,?,?)',undef,$id,$n++,$_->{p}{id},$_->{title},$_->{qty},$_->{price},($_->{p}{shipping} || $_->{pod})?1:0,
$_->{pod} ? JSON::PP->new->canonical->encode($_->{pod}) : '');
}
$odb->commit;1;
} or do {my $e=clean_error($@);$odb->rollback;$fail->($e,409)};
my $site=site_url();
my @pairs=(mode=>'payment',client_reference_id=>$id,'metadata[order]'=>$id,
success_url=>"$site/x/store/thanks?order=$id",cancel_url=>$site.$back);
for my $i (0..$#lines) {
my $l=$lines[$i];my $img=image_url($l->{p});
push @pairs,"line_items[$i][quantity]"=>$l->{qty},"line_items[$i][price_data][currency]"=>$cur,"line_items[$i][price_data][unit_amount]"=>$l->{price},
"line_items[$i][price_data][product_data][name]"=>$l->{title},
(length $img ? ("line_items[$i][price_data][product_data][images][0]"=>$site.$img) : ());
}
if ($ships) {
my @countries=split ' ',addon_setting('store','ship_countries','US');
push @pairs,map {("shipping_address_collection[allowed_countries][$_]"=>$countries[$_])} 0..$#countries;
push @pairs,'shipping_options[0][shipping_rate_data][type]'=>'fixed_amount',
'shipping_options[0][shipping_rate_data][fixed_amount][amount]'=>$ship_amount,
'shipping_options[0][shipping_rate_data][fixed_amount][currency]'=>$cur,
'shipping_options[0][shipping_rate_data][display_name]'=>$ship_amount==0 && length $free ? 'Free shipping' : addon_setting('store','shipping_label','Shipping');
}
my ($status,$session)=stripe('POST','/v1/checkout/sessions',\@pairs,idempotency=>$id);
unless ($status==200 && ($session->{url}//'') =~ m{\Ahttps://}) {
$odb->do("UPDATE orders SET status='failed' WHERE id=?",undef,$id);
warn 'Store checkout failed: '.stripe_problem($status,$session)."\n";
$fail->('Payment couldn’t be started. Please try again in a minute.',502);
}
$odb->do('UPDATE orders SET session=? WHERE id=?',undef,$session->{id}//'',$id);
BlowfishCMS::json_response({ok=>JSON::PP::true,url=>$session->{url}}) if $fetch;
# Without JavaScript: a page that moves on to Stripe (a form can't be
# redirected to another site under this site's form-action policy).
header(200,'text/html; charset=UTF-8',"Cache-Control: no-store\r\n");
print '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="refresh" content="0;url='.h($session->{url}).'"><title>Secure payment</title></head><body><p><a href="'.h($session->{url}).'">Continue to secure payment</a></p></body></html>';
}
# Stripe calls this when a checkout finishes. The signature proves it's Stripe.
sub webhook {
if ($BlowfishCMS::method ne 'POST') {header(405,'text/plain; charset=UTF-8');print 'Method Not Allowed';return}
# The signature is checked by the core (Payments.pm); why one is refused
# is noted, in words Stripe shows beside the delivery (no secrets).
my ($event,$problem)=BlowfishCMS::stripe_webhook_event('store');
unless ($event) {
webhook_note(0,$problem);
header(400,'text/plain; charset=UTF-8');print "Bad signature: $problem";return;
}
my $odb=orders_db();
my $new=$odb->do('INSERT OR IGNORE INTO events (id,type,received_at) VALUES (?,?,?)',undef,$event->{id}//'',$event->{type}//'',now());
if ($new>0) {
my $s=$event->{data}{object}//{};my $id=$s->{client_reference_id}//$s->{metadata}{order}//'';
my %status=('checkout.session.completed'=>(($s->{payment_status}//'') eq 'unpaid' ? 'pending' : 'paid'),
'checkout.session.async_payment_succeeded'=>'paid','checkout.session.async_payment_failed'=>'failed','checkout.session.expired'=>'expired');
if (my $st=$status{$event->{type}//''} and $id =~ /\A[a-f0-9]{32}\z/) {
my $ship=$s->{collected_information}{shipping_details} // $s->{shipping_details};
my $addr=ref $ship eq 'HASH' ? $ship : {};
my $cust=$s->{customer_details}//{};
my $n=$odb->do("UPDATE orders SET status=?,total=coalesce(?,total),email=coalesce(nullif(?,''),email),name=coalesce(nullif(?,''),name),address=coalesce(nullif(?,''),address),paid_at=CASE WHEN ?='paid' THEN coalesce(paid_at,?) ELSE paid_at END WHERE id=? AND status<>'paid'",undef,
$st,$s->{amount_total},$cust->{email}//'',$addr->{name}//$cust->{name}//'',(%$addr ? JSON::PP->new->canonical->encode($addr) : ''),$st,now(),$id);
# Paid: the printers' lines go to them, then the emails (which say how that went).
if ($n>0 && $st eq 'paid') {attempt {pod_submit($id)};attempt {order_emails($id)}}
}
}
webhook_note(1,$event->{type}//'');
BlowfishCMS::json_response({received=>JSON::PP::true});
}
# A paid order's emails, queued once: the order to the owner, and a
# confirmation to the buyer (each can be turned off on the Products screen).
sub order_items ($id) { return orders_db()->selectall_arrayref('SELECT * FROM order_items WHERE order_id=? ORDER BY line',{Slice=>{}},$id) }
sub order_summary ($o,$items) {
my $cur=$o->{currency};
my $text=join('',map {" $_->{quantity} × $_->{title} ".money($_->{unit_amount}*$_->{quantity},$cur)."\n"} @$items);
$text.=' '.addon_setting('store','shipping_label','Shipping').' '.money($o->{shipping_amount},$cur)."\n" if $o->{shipping_amount};
my $total=$o->{total}//do {my $t=$o->{shipping_amount}//0;$t+=$_->{unit_amount}*$_->{quantity} for @$items;$t};
return $text.' Total '.money($total,$cur)."\n";
}
sub order_emails ($id) {
my $o=orders_db()->selectrow_hashref('SELECT * FROM orders WHERE id=?',undef,$id) or return;
return if $o->{emailed_at} || $o->{status} ne 'paid';
my $items=order_items($id);
my $site=site_url();my $name=setting('site_title');my $ref=uc substr($id,0,8);
my $addr=length($o->{address}//'') ? address_text($o->{address}) : '';
my $what=@$items==1 ? "$items->[0]{quantity} × $items->[0]{title}" : scalar(@$items).' items';
my $total=money($o->{total}//0,$o->{currency});
if (addon_setting('store','email_owner',1)) {
mail_queue('store',to=>'owner',tag=>'store-order',(mail_address_ok($o->{email}) ? (reply_to=>$o->{email}) : ()),
subject=>'New order'.($o->{live} ? '' : ' (test)').": $what, $total",
text=>"A new order on $name:\n\n".order_summary($o,$items)
."\nBuyer: ".join(' ',grep {length} $o->{name}//'',length($o->{email}//'') ? "<$o->{email}>" : '')."\n"
.(length $addr ? "Ship to: $addr\n" : '')
.pod_email_note($id)
."\nOrder $ref. See it, and mark it sent, on the Orders screen: $site/admin/x/store/\n"
.($o->{live} ? '' : "\nThis was a test-mode payment: no real money moved.\n"));
}
if (addon_setting('store','email_buyer',1) && mail_address_ok($o->{email})) {
my $note=addon_setting('store','confirmation_note','');
mail_queue('store',to=>$o->{email},reply_to=>'owner',from_name=>$name,tag=>'store-confirmation',
subject=>"Your order from $name",
text=>'Thank you'.(length($o->{name}//'') ? ', '.(split ' ',$o->{name})[0] : '')."! Your order from $name is paid:\n\n".order_summary($o,$items)
.(length $addr ? "\nIt will be sent to: $addr\n" : '')
.(length $note ? "\n$note\n" : '')
."\nOrder $ref. Stripe emails your payment receipt separately. Reply to this email with any questions.\n\n$name\n$site\n");
}
orders_db()->do('UPDATE orders SET emailed_at=? WHERE id=?',undef,now(),$id);
}
# The last webhook delivery and its outcome, for the Orders screen.
sub webhook_note ($ok,$text) {
attempt {
my $odb=orders_db();
$odb->do('CREATE TABLE IF NOT EXISTS webhook_log (id INTEGER PRIMARY KEY CHECK(id=1), ok INTEGER NOT NULL, text TEXT NOT NULL, at TEXT NOT NULL)');
$odb->do('INSERT INTO webhook_log (id,ok,text,at) VALUES (1,?,?,?) ON CONFLICT(id) DO UPDATE SET ok=excluded.ok,text=excluded.text,at=excluded.at',undef,$ok?1:0,substr($text,0,300),now());
};
}
sub webhook_last { return attempt {orders_db()->selectrow_hashref('SELECT * FROM webhook_log WHERE id=1')} }
# ---- Print on demand: the printers' APIs (store service) ------------------------------------
# Each printer's key is a file in the secrets folder (printful.key, with
# printful.store for an account-wide token's store; gelato.key), read and
# written the way the Stripe keys are. Their addresses are read when the code
# loads; the tests point them at stand-ins.
sub pod_api ($p) {
state %api;
return $api{$p} //= $p eq 'printful' ? ($BlowfishCMS::startup_env{BLOWFISH_PRINTFUL_API} // 'https://api.printful.com')
: ($BlowfishCMS::startup_env{BLOWFISH_GELATO_API} // 'https://order.gelatoapis.com');
}
sub pod_key ($p) { return pod_label($p) ? read_secret("$p.key") : '' }
# Calls a printer's API: (status, reply). %o: key and store, to try ones not saved yet.
sub pod_request ($p,$verb,$path,$body=undef,%o) {
my $key=$o{key} // pod_key($p);
die pod_label($p)." isn’t connected yet.\n" unless length $key;
my %h=(Accept=>'application/json','User-Agent'=>'BlowfishCMS-Store');
if ($p eq 'printful') {
$h{Authorization}="Bearer $key";
my $store=$o{store} // read_secret('printful.store');
$h{'X-PF-Store-Id'}=$store if length $store;
} else {$h{'X-API-KEY'}=$key}
require HTTP::Tiny;
my $http=HTTP::Tiny->new(timeout=>20,verify_SSL=>1);
my $r=$http->request($verb,pod_api($p).$path,{headers=>{%h,(defined $body ? ('Content-Type'=>'application/json') : ())},
(defined $body ? (content=>JSON::PP->new->canonical->utf8->encode($body)) : ())});
my $reply=(attempt {JSON::PP->new->utf8->decode($r->{content}//'')}) // {};
return ($r->{status},ref $reply eq 'HASH' ? $reply : {});
}
# What went wrong, in words for the owner.
sub pod_problem ($p,$status,$reply) {
my $n=pod_label($p);
return "$n couldn’t be reached. Try again in a minute." if !$status || $status==599;
my $e=$reply->{error};
my $m=ref $e eq 'HASH' ? $e->{message} : $e;
$m //= $reply->{message} // (ref $reply->{result} ? undef : $reply->{result}) // '';
$m=substr("$m",0,300);
return "$n refused the key".(length $m ? ": $m" : '.') if $status==401;
return "$n: the key isn’t allowed to do this".(length $m ? " ($m)" : '').'. Check its permissions.' if $status==403;
return "$n: ".(length $m ? $m : "error $status");
}
# The address in a printers' webhook, made once: /x/store/pod/PRINTER/TOKEN.
sub pod_hook_token {
my $t=read_secret('pod-hook.key');
return $t if $t =~ /\A[a-f0-9]{32}\z/;
$t=random_id();BlowfishCMS::stripe_secret_save('store','pod-hook.key',$t);
return $t;
}
sub pod_hook_url ($p) { return site_url()."/x/store/pod/$p/".pod_hook_token() }
# The Print on demand settings, kept by the store service in its data folder
# (the catalogue's settings can only be written by the admin service).
sub pod_settings {
my $file=addon_data_dir('store').'/pod-settings.json';
my $s=(attempt {open my $fh,'<',$file or die "none\n";local $/;JSON::PP->new->decode(<$fh>)}) // {};
return {confirm=>1,ship_email=>1,gelato_shipping=>'',(ref $s eq 'HASH' ? %$s : ())};
}
sub pod_settings_save (%v) {
my $file=addon_data_dir('store').'/pod-settings.json';
open my $fh,'>',"$file.tmp" or die "Can’t save the settings: the store’s data folder isn’t set up.\n";
print {$fh} JSON::PP->new->canonical->encode({%{pod_settings()},%v});close $fh;
rename "$file.tmp",$file or die "Can’t save the settings.\n";
}
# The last update from each printer, for the Print on demand tab.
sub pod_note ($p,$ok,$text) {
attempt {
orders_db()->do('CREATE TABLE IF NOT EXISTS pod_log (provider TEXT PRIMARY KEY, ok INTEGER NOT NULL, text TEXT NOT NULL, at TEXT NOT NULL)');
orders_db()->do('INSERT INTO pod_log (provider,ok,text,at) VALUES (?,?,?,?) ON CONFLICT(provider) DO UPDATE SET ok=excluded.ok,text=excluded.text,at=excluded.at',undef,$p,$ok?1:0,substr($text,0,300),now());
};
}
sub pod_note_last ($p) { return attempt {orders_db()->selectrow_hashref('SELECT * FROM pod_log WHERE provider=?',undef,$p)} }
# Printful's items (its sync variants), for the Products screen to choose
# from: kept for ten minutes, as Printful asks for each product's variants
# one product at a time.
sub printful_items ($fresh=0) {
my $file=addon_data_dir('store').'/printful-items.json';
# Written and read as UTF-8 bytes (1.5.0 wrote characters and read bytes,
# which garbled names such as 3″×3″).
if (!$fresh && -f $file && time-(stat $file)[9]<600) {
my $c=attempt {open my $fh,'<:raw',$file or die "none\n";local $/;JSON::PP->new->utf8->decode(<$fh>)};
return $c if ref $c eq 'ARRAY' && (!@$c || exists $c->[0]{product_id});
}
my @items=map {my $sp=$_;map {+{id=>0+$_->{id},name=>$_->{name},product=>$sp->{name},product_id=>0+$sp->{id},price=>$_->{price},currency=>$_->{currency}}} @{$sp->{variants}}} @{printful_catalog()};
if (open my $fh,'>:raw',"$file.tmp") {print {$fh} JSON::PP->new->canonical->utf8->encode(\@items);close $fh;rename "$file.tmp",$file}
return \@items;
}
# Printful's products (its sync products) with their variants, or only the
# one given: [{id, name, image, variants: [{id, name, price, currency}]}].
# Printful lists products, then gives each one's variants on its own.
# A store made in Printful for the API (Manual order platform / API) has its
# products under /store/products; one linked to Shopify and the like under
# /sync/products (1.7.0 asks the first, then the second). Each product's
# variants carry their colour, size, stock and mockups (files of type
# "preview"); Printful's catalogue adds each colour's code and the blank
# product's description.
sub printful_get ($what) {
my ($st,$r)=pod_request('printful','GET',"/store/$what");
return ($st,$r) if $st==200 || $st==401 || $st==403;
my ($st2,$r2)=pod_request('printful','GET',"/sync/$what");
return $st2==200 ? ($st2,$r2) : ($st,$r);
}
sub printful_catalog ($only=undef) {
my @ids;
if (defined $only) {@ids=({id=>$only})}
else {
my $offset=0;
for (1..20) {
my ($st,$r)=printful_get("products?limit=100&offset=$offset");
die pod_problem('printful',$st,$r)."\n" unless $st==200;
my $list=ref $r->{result} eq 'ARRAY' ? $r->{result} : [];
push @ids,grep {ref $_ eq 'HASH' && ($_->{id}//'') =~ /\A\d{1,15}\z/ && !$_->{is_ignored}} @$list;
$offset+=@$list;
last if !@$list || $offset>=($r->{paging}{total}//0);
}
}
my (@products,%blank);
for my $sp (@ids) {
my ($st,$d)=printful_get("products/$sp->{id}");
return [] if defined $only && $st==404;
die pod_problem('printful',$st,$d)."\n" unless $st==200 && ref $d->{result} eq 'HASH';
my $info=ref $d->{result}{sync_product} eq 'HASH' ? $d->{result}{sync_product} : $sp;
next if $info->{is_ignored};
my @vars=grep {ref $_ eq 'HASH' && ($_->{id}//'') =~ /\A\d{1,15}\z/ && !$_->{is_ignored}} @{$d->{result}{sync_variants}//[]};
# The blank products' colour codes and descriptions, once each (a missing one only costs the swatch).
my (%catalog,%mine,$about);
for my $pid (grep {/\A\d{1,15}\z/ && !$mine{$_}++} map {ref $_->{product} eq 'HASH' ? $_->{product}{product_id}//'' : ''} @vars) {
$blank{$pid} //= (attempt {my ($s,$c)=pod_request('printful','GET',"/products/$pid");$s==200 && ref $c->{result} eq 'HASH' ? $c->{result} : {}}) // {};
$catalog{$_->{id}}=$_ for grep {ref $_ eq 'HASH' && defined $_->{id}} @{$blank{$pid}{variants}//[]};
$about //= $blank{$pid}{product}{description} if ref $blank{$pid}{product} eq 'HASH' && length($blank{$pid}{product}{description}//'');
}
push @products,{id=>0+$sp->{id},name=>''.($info->{name}//$sp->{name}//''),image=>''.($info->{thumbnail_url}//$sp->{thumbnail_url}//''),about=>''.($about//''),
variants=>[map {my $v=$_;my $cat=$catalog{$v->{variant_id}//(ref $v->{product} eq 'HASH' ? $v->{product}{variant_id} : '')//''}//{};
# Its mockups: files of type "preview" (and any named as mockups); not the print files themselves.
my %seen;my @pics=grep {length && m{\Ahttps?://} && !$seen{$_}++} map {''.($_->{preview_url}//'')} grep {ref $_ eq 'HASH' && ($_->{type}//'') =~ /\A(?:preview|mockup)|mockup/i} @{$v->{files}//[]};
push @pics,''.$v->{product}{image} if !@pics && ref $v->{product} eq 'HASH' && length($v->{product}{image}//'');
+{id=>0+$v->{id},name=>''.($v->{name}//''),price=>''.($v->{retail_price}//''),currency=>lc($v->{currency}//''),
color=>''.($v->{color}//$cat->{color}//''),size=>''.($v->{size}//$cat->{size}//''),hex=>''.($cat->{color_code}//''),
# Out of stock only when Printful says so in words; any other answer (none, "active", a list per region) is in stock.
available=>!ref $v->{availability_status} && lc($v->{availability_status}//'') =~ /\A(?:out_of_stock|temporary_out_of_stock|discontinued)\z/ ? 0 : 1,images=>\@pics}} @vars]};
}
return \@products;
}
# Hands Printful's products to the Products screen's side (the catalogue):
# all of them (complete, so those gone go off sale), or one that changed.
# The core moves it there within a minute.
sub printful_sync ($only=undef) {
my $list=printful_catalog($only);
BlowfishCMS::addon_hand_over('store',{kind=>'printful',(defined $only ? (gone=>@$list ? [] : [0+$only]) : (complete=>1)),products=>$list});
pod_note('printful',1,defined $only ? 'product '.(@$list ? "$only changed" : "$only removed") : scalar(@$list).' product'.(@$list==1 ? '' : 's').' handed to the shop');
unlink addon_data_dir('store').'/printful-items.json';
return scalar @$list;
}
# What Printful is asked to tell the shop about.
sub printful_hook_types { return [qw(package_shipped order_updated order_failed order_canceled order_put_hold order_remove_hold product_synced product_updated product_deleted)] }
# ---- Print on demand: sending paid orders, and hearing back --------------------------------
# The order's delivery address, from Stripe ({name, line1, line2, city,
# state, postal_code, country}), or undef.
sub order_address ($o) {
my $a=length($o->{address}//'') ? ((attempt {JSON::PP->new->decode($o->{address})}) // {}) : {};
my $d=ref $a->{address} eq 'HASH' ? $a->{address} : {};
return undef unless length($d->{line1}//'') && ($d->{country}//'') =~ /\A[A-Z]{2}\z/;
return {name=>$a->{name}//$o->{name}//'',map {($_=>$d->{$_}//'')} qw(line1 line2 city state postal_code country)};
}
# What each printer's status means here.
sub pod_phase ($p,$status) {
my $s=lc($status//'');
return +{draft=>'draft',failed=>'failed',canceled=>'canceled',archived=>'canceled',onhold=>'hold',partial=>'shipped',fulfilled=>'shipped'}->{$s} // 'made' if $p eq 'printful';
return +{draft=>'draft',failed=>'failed',canceled=>'canceled',cancelled=>'canceled',on_hold=>'hold',pending_approval=>'hold',not_connected=>'hold',pending_personalization=>'hold',
shipped=>'shipped',in_transit=>'shipped',delivered=>'delivered',returned=>'returned'}->{$s} // 'made';
}
# Sends a paid order's printers' lines to them, each printer once (again=>1
# sends one that failed again; provider=>NAME only that printer). Test-mode
# orders, and every order while "send straight to production" is off, go as
# drafts, which aren't made or charged until confirmed at the printer.
sub pod_submit ($id,%o) {
my $odb=orders_db();
my $order=$odb->selectrow_hashref('SELECT * FROM orders WHERE id=?',undef,$id) or return;
return unless $order->{status} eq 'paid';
my %by;for my $it (@{order_items($id)}) {my $pod=pod_of($it) or next;push @{$by{$pod->{provider}}},[$it,$pod]}
for my $p (sort keys %by) {
next if $o{provider} && $o{provider} ne $p;
# Claimed first, so a delivery Stripe repeats can't send it twice. Sent
# again only when asked: one that failed, or one stuck sending (each
# send first asks the printer whether it has the order already).
my $row=$odb->selectrow_hashref('SELECT * FROM pod_orders WHERE order_id=? AND provider=?',undef,$id,$p);
my $stale=BlowfishCMS::strftime('%Y-%m-%dT%H:%M:%SZ',gmtime(time-300));
my $n=!$row ? $odb->do("INSERT OR IGNORE INTO pod_orders (order_id,provider,status,live,created_at,updated_at) VALUES (?,?,'sending',?,?,?)",undef,$id,$p,$order->{live}?1:0,now(),now())
: $o{again} && !length $row->{remote_id} && ($row->{status} eq 'failed' || ($row->{status} eq 'sending' && $row->{updated_at} lt $stale))
? $odb->do("UPDATE pod_orders SET status='sending',problem='',updated_at=? WHERE order_id=? AND provider=? AND status=? AND updated_at=?",undef,now(),$id,$p,$row->{status},$row->{updated_at})
: 0;
next unless $n>0;
my ($remote,$rstatus,$problem)=('','','');
attempt {($remote,$rstatus)=($p eq 'printful' ? \&printful_send : \&gelato_send)->($order,$by{$p});1} or $problem=clean_error($@);
my $phase=length $problem ? 'failed' : pod_phase($p,$rstatus);
$odb->do('UPDATE pod_orders SET status=?,remote_id=?,remote_status=?,problem=?,updated_at=? WHERE order_id=? AND provider=?',undef,$phase,$remote//'',$rstatus//'',$problem,now(),$id,$p);
warn "Store: order ".uc(substr($id,0,8))." wasn’t sent to ".pod_label($p).": $problem\n" if length $problem;
}
}
sub pod_draft ($order) { return !$order->{live} || !pod_settings()->{confirm} }
sub printful_send ($order,$lines) {
my $a=order_address($order) or die "The order has no delivery address.\n";
# Sent already, by a try whose answer never came back? Then that's it.
my ($st,$r)=pod_request('printful','GET',"/orders/\@$order->{id}");
return ($r->{result}{id}//'',$r->{result}{status}//'') if $st==200 && ref $r->{result} eq 'HASH';
my $body={external_id=>$order->{id},shipping=>'STANDARD',
recipient=>{name=>$a->{name},address1=>$a->{line1},(length $a->{line2} ? (address2=>$a->{line2}) : ()),city=>$a->{city},
(length $a->{state} ? (state_code=>$a->{state}) : ()),country_code=>$a->{country},zip=>''.$a->{postal_code},(length($order->{email}//'') ? (email=>$order->{email}) : ())},
items=>[map {{sync_variant_id=>0+$_->[1]{ref},quantity=>0+$_->[0]{quantity}}} @$lines]};
($st,$r)=pod_request('printful','POST','/orders'.(pod_draft($order) ? '' : '?confirm=true'),$body);
die pod_problem('printful',$st,$r)."\n" unless $st==200 && ref $r->{result} eq 'HASH';
return ($r->{result}{id}//'',$r->{result}{status}//'');
}
sub gelato_send ($order,$lines) {
my $a=order_address($order) or die "The order has no delivery address.\n";
die "The order has no email address, which Gelato needs.\n" unless length($order->{email}//'');
my ($st,$r)=pod_request('gelato','POST','/v4/orders:search',{orderReferenceIds=>[$order->{id}],limit=>1});
return ($r->{orders}[0]{id}//'',$r->{orders}[0]{fulfillmentStatus}//'') if $st==200 && ref $r->{orders} eq 'ARRAY' && ref $r->{orders}[0] eq 'HASH' && length($r->{orders}[0]{id}//'');
# Gelato wants a first and a last name (up to 25 characters each) and
# address lines of up to 35: a long first line goes on to the second.
my @name=split ' ',$a->{name};my $last=@name>1 ? pop @name : $name[0]//'';my $first=@name ? join(' ',@name) : $last;
my ($l1,$l2)=($a->{line1},$a->{line2});
if (length $l1>35 && !length $l2 && $l1 =~ /\A(.{1,35})\s+(.+)\z/) {($l1,$l2)=($1,$2)}
my $s=pod_settings();
my $body={orderType=>pod_draft($order) ? 'draft' : 'order',orderReferenceId=>$order->{id},customerReferenceId=>substr(sha256_hex(encode('UTF-8',lc $order->{email})),0,32),currency=>uc $order->{currency},
items=>[map {my ($it,$pod)=@$_;{itemReferenceId=>"$order->{id}-$it->{line}",productUid=>$pod->{ref},quantity=>0+$it->{quantity},
files=>[map {{type=>$_,url=>$pod->{files}{$_}}} sort grep {length $pod->{files}{$_}} keys %{$pod->{files}}]}} @$lines],
shippingAddress=>{firstName=>substr($first,0,25),lastName=>substr($last,0,25),addressLine1=>$l1,(length $l2 ? (addressLine2=>$l2) : ()),city=>$a->{city},
postCode=>''.$a->{postal_code},(length $a->{state} ? (state=>$a->{state}) : ()),country=>$a->{country},email=>$order->{email}},
($s->{gelato_shipping} =~ /\A(?:normal|standard|express)\z/ ? (shipmentMethodUid=>$s->{gelato_shipping}) : ())};
($st,$r)=pod_request('gelato','POST','/v4/orders',$body);
die pod_problem('gelato',$st,$r)."\n" unless $st>=200 && $st<300 && length($r->{id}//'');
return ($r->{id},$r->{fulfillmentStatus}//'');
}
# Asks the printer how an order sent to it stands, and acts on news: the
# buyer is emailed when it ships, the owner when it fails or is held.
sub pod_refresh ($id,$p) {
my $odb=orders_db();
my $row=$odb->selectrow_hashref('SELECT * FROM pod_orders WHERE order_id=? AND provider=?',undef,$id,$p) or return;
return unless length $row->{remote_id};
my ($status,@tracking);
if ($p eq 'printful') {
my ($st,$r)=pod_request('printful','GET',"/orders/\@$id");
die pod_problem('printful',$st,$r)."\n" unless $st==200 && ref $r->{result} eq 'HASH';
$status=$r->{result}{status}//'';
for my $s (@{$r->{result}{shipments}//[]}) {
my $number=$s->{tracking_number}//'';$number='' if $number eq '0';
push @tracking,{carrier=>join(' ',grep {length} $s->{carrier}//'',$s->{service}//''),number=>"$number",url=>$s->{tracking_url}//''} if length $number || length($s->{tracking_url}//'');
}
} else {
die "That Gelato order’s ID isn’t one Gelato gives.\n" unless $row->{remote_id} =~ /\A[A-Za-z0-9-]{1,64}\z/;
my ($st,$r)=pod_request('gelato','GET',"/v4/orders/$row->{remote_id}");
die pod_problem('gelato',$st,$r)."\n" unless $st==200;
$status=($r->{orderType}//'') eq 'draft' && ($r->{fulfillmentStatus}//'') !~ /\A(?:canceled|failed)\z/ ? 'draft' : $r->{fulfillmentStatus}//'';
my $ship=ref $r->{shipment} eq 'HASH' ? $r->{shipment} : {};
push @tracking,map {{carrier=>$ship->{shipmentMethodName}//'',number=>$_->{trackingCode}//'',url=>$_->{trackingUrl}//''}} grep {length($_->{trackingCode}//'') || length($_->{trackingUrl}//'')} @{$ship->{packages}//[]};
}
@tracking=grep {$_->{url} eq '' || $_->{url} =~ m{\Ahttps?://}} @tracking;
my $phase=pod_phase($p,$status);
$odb->do('UPDATE pod_orders SET status=?,remote_status=?,problem=?,tracking=?,updated_at=?,shipped_at=CASE WHEN ? IN (\'shipped\',\'delivered\') THEN coalesce(shipped_at,?) ELSE shipped_at END WHERE order_id=? AND provider=?',undef,
$phase,$status,'',(@tracking ? JSON::PP->new->canonical->encode(\@tracking) : $row->{tracking}),now(),$phase,now(),$id,$p);
pod_news($id,$p,$row->{status},$phase);
}
sub pod_tracking ($row) { my $t=length($row->{tracking}//'') ? ((attempt {JSON::PP->new->decode($row->{tracking})}) // []) : [];return ref $t eq 'ARRAY' ? $t : [] }
sub pod_news ($id,$p,$was,$now) {
my $odb=orders_db();
my $order=$odb->selectrow_hashref('SELECT * FROM orders WHERE id=?',undef,$id) or return;
my $row=$odb->selectrow_hashref('SELECT * FROM pod_orders WHERE order_id=? AND provider=?',undef,$id,$p);
my $site=site_url();my $name=setting('site_title');my $ref=uc substr($id,0,8);my $n=pod_label($p);
# Shipped: the buyer hears once, with the tracking.
if ($now =~ /\A(?:shipped|delivered)\z/ && !$row->{emailed_at}) {
if (pod_settings()->{ship_email} && mail_address_ok($order->{email})) {
my @items=grep {my $pod=pod_of($_);$pod && $pod->{provider} eq $p} @{order_items($id)};
my $track=join('',map {' '.join(' ',grep {length} $_->{carrier},$_->{number})."\n".(length $_->{url} ? " $_->{url}\n" : '')} @{pod_tracking($row)});
mail_queue('store',to=>$order->{email},reply_to=>'owner',from_name=>$name,tag=>'store-shipped',
subject=>"Your order from $name is on its way",
text=>'Good news'.(length($order->{name}//'') ? ', '.(split ' ',$order->{name})[0] : '')."! This is on its way to you:\n\n"
.join('',map {" $_->{quantity} × $_->{title}\n"} @items)
.(length $track ? "\nTracking:\n$track" : '')
."\nOrder $ref. Reply to this email with any questions.\n\n$name\n$site\n");
}
$odb->do('UPDATE pod_orders SET emailed_at=? WHERE order_id=? AND provider=?',undef,now(),$id,$p);
}
# Trouble: the owner hears once each time it happens.
if ($now ne $was && $now =~ /\A(?:failed|hold|canceled|returned)\z/ && $order->{live}) {
my $what={failed=>'failed',hold=>'is on hold',canceled=>'was canceled',returned=>'came back undelivered'}->{$now};
mail_queue('store',to=>'owner',tag=>'store-printer',subject=>"$n: order $ref $what",
text=>"$n says order $ref on $name $what (its status there: ".($row->{remote_status}||$now).").\n\nSee it in $n, and on Print on demand: $site/admin/x/store/pod\n");
}
# Everything in it is on its way: the order is sent.
my @lines=@{order_items($id)};
my %sent=map {$_->{provider}=>1} @{$odb->selectall_arrayref("SELECT provider FROM pod_orders WHERE order_id=? AND status IN ('shipped','delivered')",{Slice=>{}},$id)};
$odb->do('UPDATE orders SET fulfilled_at=coalesce(fulfilled_at,?) WHERE id=?',undef,now(),$id)
if @lines && !grep {my $pod=pod_of($_);!$pod || !$sent{$pod->{provider}}} @lines;
}
# How an order stands at its printers, in words.
sub pod_state_text ($row) {
my $n=pod_label($row->{provider});my $s=$row->{status};
return "sending to $n" if $s eq 'sending';
return length $row->{remote_id} ? "$n: failed" : "not sent to $n" if $s eq 'failed';
return "$n: draft, confirm it there".($row->{live} ? '' : ' (test order: delete it there)') if $s eq 'draft';
return +{made=>"$n: being made",hold=>"$n: on hold, see $n",shipped=>"$n: shipped",delivered=>"$n: delivered",canceled=>"$n: canceled",returned=>"$n: returned to sender"}->{$s} // "$n: $s";
}
sub pod_rows ($id) { return orders_db()->selectall_arrayref('SELECT * FROM pod_orders WHERE order_id=? ORDER BY provider',{Slice=>{}},$id) }
# For the owner's email of a new order.
sub pod_email_note ($id) {
my $rows=pod_rows($id);return '' unless @$rows;
return "\n".join('',map {($_->{status} eq 'failed' ? 'Not sent to '.pod_label($_->{provider}).": $_->{problem} Send it again on Print on demand: ".site_url()."/admin/x/store/pod" : 'Sent to '.pod_label($_->{provider}).($_->{status} eq 'draft' ? ' as a draft: confirm it there to have it made' : '')).".\n"} @$rows);
}
# A printer's webhook: only says "look at order X", which is then asked about.
sub pod_webhook ($p,$token) {
if ($BlowfishCMS::method ne 'POST') {header(405,'text/plain; charset=UTF-8');print 'Method Not Allowed';return}
my $saved=read_secret('pod-hook.key');
unless (length $saved && BlowfishCMS::eq_safe($token,$saved) && length pod_key($p)) {header(404,'text/plain; charset=UTF-8');print 'Not Found';return}
my $event=(attempt {JSON::PP->new->utf8->decode($BlowfishCMS::q->param('POSTDATA') // '')}) // {};
$event={} unless ref $event eq 'HASH';
my $type=$p eq 'printful' ? $event->{type}//'' : $event->{event}//'';
my $id=$p eq 'printful' ? (ref $event->{data} eq 'HASH' && ref $event->{data}{order} eq 'HASH' ? $event->{data}{order}{external_id} : '') : $event->{orderReferenceId};
$id //= '';$type=substr($type,0,60) =~ s/[^a-z_]//gr;
# A product published, changed or deleted in Printful: the shop asks
# Printful for it and hands it to its products (1.6.0).
if ($p eq 'printful' && $type =~ /\Aproduct_(?:synced|updated|deleted)\z/) {
my $sid=ref $event->{data} eq 'HASH' && ref $event->{data}{sync_product} eq 'HASH' ? $event->{data}{sync_product}{id}//'' : '';
if ($sid =~ /\A\d{1,15}\z/) {attempt {printful_sync($sid);1} or pod_note($p,0,"$type: ".clean_error($@))}
else {attempt {printful_sync();1} or pod_note($p,0,"$type: ".clean_error($@))}
BlowfishCMS::json_response({received=>JSON::PP::true});
}
if ($id =~ /\A[a-f0-9]{32}\z/ && orders_db()->selectrow_array('SELECT 1 FROM pod_orders WHERE order_id=? AND provider=?',undef,$id,$p)) {
if (attempt {pod_refresh($id,$p);1}) {pod_note($p,1,"$type for order ".uc substr($id,0,8))}
else {pod_note($p,0,"$type for order ".uc(substr($id,0,8)).': '.clean_error($@))}
} else {pod_note($p,1,"$type (not an order from this shop)")}
BlowfishCMS::json_response({received=>JSON::PP::true});
}
# ---- Orders screen (store service, /admin/x/store/) -----------------------------------------
sub address_text ($json) {
my $a=(attempt {JSON::PP->new->decode($json)}) // {};my $d=$a->{address}//{};
return join ', ',grep {length} map {$_//''} $a->{name},$d->{line1},$d->{line2},$d->{city},$d->{state},$d->{postal_code},$d->{country};
}
sub service_admin ($rest) {
return pod_admin() if $rest eq 'pod';
return printful_items_json() if $rest eq 'pod/printful.json';
return 0 unless $rest eq '';
my $message=param('notice',2000);
if ($BlowfishCMS::method eq 'POST') {
attempt {
my $action=param('action',30);
# The Stripe panel's own actions (keys), done by the core.
if (defined(my $done=BlowfishCMS::stripe_panel_action('store',$action))) {redirect('/admin/x/store/?notice='.CGI::escape(encode('UTF-8',$done)))}
if ($action eq 'fulfil' || $action eq 'unfulfil') {
my $n=orders_db()->do('UPDATE orders SET fulfilled_at=? WHERE id=? AND status=?',undef,($action eq 'fulfil' ? now() : undef),param('id',32),'paid');
die "That order isn’t a paid order.\n" unless $n>0;
redirect('/admin/x/store/?show='.CGI::escape(param('show',10)).'#orders');
}
die "Choose an action.\n";
} or $message=failed_action($@);
}
admin_page('Orders',section=>'x-store-service',notice=>$message,
intro=>'Payments go through <a href="https://dashboard.stripe.com/" target="_blank" rel="noopener">Stripe</a>; refunds and payouts are done there.');
# Orders
my $show=param('show',10);$show='paid' unless $show =~ /\A(?:paid|open|all)\z/;
my $where={paid=>"status='paid'",open=>"status='paid' AND fulfilled_at IS NULL",all=>"status<>'failed'"}->{$show};
my $orders=orders_db()->selectall_arrayref("SELECT * FROM orders WHERE $where ORDER BY created_at DESC LIMIT 200",{Slice=>{}});
my %items;push @{$items{$_->{order_id}}},$_ for @{orders_db()->selectall_arrayref("SELECT * FROM order_items WHERE order_id IN (SELECT id FROM orders WHERE $where ORDER BY created_at DESC LIMIT 200) ORDER BY line",{Slice=>{}})};
my %pod;push @{$pod{$_->{order_id}}},$_ for @{orders_db()->selectall_arrayref("SELECT * FROM pod_orders WHERE order_id IN (SELECT id FROM orders WHERE $where ORDER BY created_at DESC LIMIT 200) ORDER BY provider",{Slice=>{}})};
my $o='<p class="store-filter">'.join(' · ',map {$_->[0] eq $show ? '<strong>'.$_->[1].'</strong>' : '<a href="/admin/x/store/?show='.$_->[0].'#orders">'.$_->[1].'</a>'} [open=>'to send'],[paid=>'paid'],[all=>'everything']).'</p>';
$o.=@$orders ? '<table class="seo-table store-orders"><thead><tr><th>When</th><th>Items</th><th>Total</th><th>Buyer</th><th>Status</th><th></th></tr></thead><tbody>'.join('',map {my $r=$_;
'<tr><td>'.h(substr($r->{paid_at}//$r->{created_at},0,16) =~ s/T/ /r).($r->{live}?'':' <span class="media-label">test</span>').'</td><td>'.join('<br>',map {h($_->{quantity}.' × '.$_->{title})} @{$items{$r->{id}} // [{quantity=>$r->{quantity},title=>$r->{title}}]}).'</td><td>'.h(money($r->{total}//($r->{quantity}*$r->{unit_amount}+$r->{shipping_amount}),$r->{currency})).'</td>'
.'<td>'.h($r->{email}).(length $r->{address} ? '<br><span class="media-label">'.h(address_text($r->{address})).'</span>' : '').'</td>'
.'<td>'.h($r->{status} eq 'paid' ? ($r->{fulfilled_at} ? 'sent' : 'paid') : $r->{status})
.join('',map {'<br><span class="media-label">'.pod_state_html($_).'</span>'} @{$pod{$r->{id}}//[]}).'</td>'
.'<td>'.($r->{status} eq 'paid' ? '<form method="post" action="/admin/x/store/">'.fields($r->{fulfilled_at}?'unfulfil':'fulfil','x-store',$r->{id}).hidden(show=>$show).'<button class="text-button">'.($r->{fulfilled_at}?'not sent':'mark sent').'</button></form>' : '').'</td></tr>'} @$orders).'</tbody></table>'
: '<p class="empty-media">No orders here yet.</p>';
window('orders',"<div id=\"orders\">$o</div>");
# Stripe: how the connection stands and its keys (the core's panel), and what to switch on in Stripe.
window('stripe',BlowfishCMS::stripe_panel_html('store','/admin/x/store/',webhook=>'/x/store/webhook',last=>scalar(webhook_last()),unset=>'the shop can’t take payments').'<details class="box-part mail-setup"><summary>Good to know</summary>'.('<ul class="mail-steps"><li>Turn on <em>Email customers about successful payments</em> in Stripe → Settings → Customer emails, so buyers get a receipt.</li><li>Turn on <em>Successful payments</em> under your Stripe notification settings to get an email for every order.</li><li>Refunds are made in the Stripe Dashboard.</li><li>Orders are kept on this server, in the store’s private folder, and are included in backups.</li></ul>').'</details>');
end_page();
return 1;
}
# ---- Print on demand tab (store service, /admin/x/store/pod) ----------------------------------
sub pod_state_html ($row) {
my $t=h(pod_state_text($row));
$t.=': '.h($row->{problem}) if $row->{status} eq 'failed' && length $row->{problem};
$t.=join('',map {' · '.(length $_->{url} ? '<a href="'.h($_->{url}).'" target="_blank" rel="noopener">'.h(length $_->{number} ? $_->{number} : 'tracking').'</a>' : h($_->{number}))} @{pod_tracking($row)});
return $t;
}
# Printful's items for the Products screen's "Printful item" field.
sub printful_items_json {
my $r=attempt {
die "Connect Printful under Print on demand first.\n" unless length pod_key('printful');
+{ok=>JSON::PP::true,items=>printful_items(param('fresh',1) eq '1')};
};
BlowfishCMS::json_response($r // {ok=>JSON::PP::false,message=>clean_error($@)});
return 1;
}
sub pod_admin {
my $message=param('notice',2000);my $here='/admin/x/store/pod';
my $done=sub ($text,$anchor='') {redirect("$here?notice=".CGI::escape(encode('UTF-8',$text)).$anchor)};
if ($BlowfishCMS::method eq 'POST') {
attempt {
my $action=param('action',30);
if ($action eq 'printful_key') {
my $key=param('key',400);$key =~ s/\s+//g;my $store=param('store',20);
die "Paste a Printful private token (developers.printful.com → Your tokens).\n" unless $key =~ m{\A[A-Za-z0-9._~+/=-]{20,400}\z};
die "Store ID: a number, or leave it empty.\n" if length $store && $store !~ /\A\d{1,15}\z/;
my ($st,$r)=pod_request('printful','GET','/sync/products?limit=1',undef,key=>$key,store=>$store);
die pod_problem('printful',$st,$r)."\n" unless $st==200;
BlowfishCMS::stripe_secret_save('store','printful.key',$key);
if (length $store) {BlowfishCMS::stripe_secret_save('store','printful.store',$store)} else {unlink addon_secret_dir('store').'/printful.store'}
unlink addon_data_dir('store').'/printful-items.json';
# Printful's updates: one address per store, set through its API.
my ($hs,$hr)=pod_request('printful','POST','/webhooks',{url=>pod_hook_url('printful'),types=>printful_hook_types()});
my $hook=$hs==200 ? '' : pod_problem('printful',$hs,$hr);
pod_note('printful',!length $hook,length $hook ? "updates not set up: $hook" : 'updates set up');
# Its products, into the shop.
my $n=attempt {printful_sync()};my $why=clean_error($@);
$done->('Printful connected. '.(defined $n ? "Its $n product".($n==1?'':'s').' will be on Products within a minute. ' : "Its products couldn’t be read ($why). ")
.(length $hook ? "Its updates couldn’t be set up ($hook): give the token the webhooks permission and save it again; until then, use sync with Printful and check below."
: 'It will tell the shop when products change and orders ship.'));
}
if ($action eq 'printful_sync') {
die "Connect Printful first.\n" unless length pod_key('printful');
# Its updates again too, in case they were set up for orders only (1.5.0).
my ($hs,$hr)=pod_request('printful','POST','/webhooks',{url=>pod_hook_url('printful'),types=>printful_hook_types()});
my $n=printful_sync();
$done->("Printful’s $n product".($n==1?'':'s').' will be on Products within a minute.'.($hs==200 ? '' : ' Its updates couldn’t be set up ('.pod_problem('printful',$hs,$hr).').'),'#printful');
}
if ($action eq 'gelato_key') {
my $key=param('key',400);$key =~ s/\s+//g;
die "Paste a Gelato API key (Gelato → Developer → API keys).\n" unless $key =~ /\A[A-Za-z0-9:._-]{20,400}\z/;
my ($st,$r)=pod_request('gelato','POST','/v4/orders:search',{limit=>1},key=>$key);
die pod_problem('gelato',$st,$r)."\n" unless $st==200;
BlowfishCMS::stripe_secret_save('store','gelato.key',$key);
$done->('Gelato connected. Add its webhook (the address under Gelato), so the shop hears when orders ship.');
}
if ($action =~ /\A(printful|gelato)_remove\z/) {
my $p=$1;
attempt {pod_request('printful','DELETE','/webhooks')} if $p eq 'printful';
unlink map {addon_secret_dir('store')."/$_"} $p eq 'printful' ? qw(printful.key printful.store) : ('gelato.key');
unlink addon_data_dir('store').'/printful-items.json' if $p eq 'printful';
$done->(pod_label($p).' disconnected. What it makes can’t be bought until it’s connected again.');
}
if ($action eq 'pod_settings') {
my $ship=param('gelato_shipping',10);$ship='' unless $ship =~ /\A(?:normal|standard|express)\z/;
pod_settings_save(confirm=>param('confirm',1) eq '1' ? 1 : 0,ship_email=>param('ship_email',1) eq '1' ? 1 : 0,gelato_shipping=>$ship);
$done->('Print on demand settings saved.');
}
if ($action eq 'pod_send' || $action eq 'pod_check') {
my $id=param('id',32);my $p=param('provider',10);
die "Choose an order.\n" unless $id =~ /\A[a-f0-9]{32}\z/ && pod_label($p);
if ($action eq 'pod_send') {pod_submit($id,again=>1,provider=>$p)} else {pod_refresh($id,$p)}
my $row=orders_db()->selectrow_hashref('SELECT * FROM pod_orders WHERE order_id=? AND provider=?',undef,$id,$p) or die 'That order has nothing for '.pod_label($p).".\n";
$done->('Order '.uc(substr($id,0,8)).': '.pod_state_text($row).($row->{status} eq 'failed' && length $row->{problem} ? " ($row->{problem})" : '').'.','#printers');
}
if ($action eq 'pod_check_all') {
my $rows=orders_db()->selectall_arrayref("SELECT order_id,provider FROM pod_orders WHERE status IN ('draft','made','hold') AND remote_id<>'' ORDER BY updated_at LIMIT 25",{Slice=>{}});
my ($ok,$bad)=(0,0);for (@$rows) {(attempt {pod_refresh($_->{order_id},$_->{provider});1}) ? $ok++ : $bad++}
$done->(@$rows ? "Checked $ok order".($ok==1?'':'s').($bad ? "; $bad couldn’t be checked" : '').'.' : 'Nothing is waiting at the printers.','#printers');
}
if ($action eq 'printful_items') {my $n=scalar @{printful_items(1)};$done->("Printful has $n item".($n==1?'':'s').' to sell.','#printful')}
die "Choose an action.\n";
} or $message=failed_action($@);
}
admin_page('Print on demand',section=>'x-store-service-pod',notice=>$message,
intro=>'Printful and Gelato print an item when it’s bought and send it straight to the buyer. Connect one or both here, then choose who makes each product on <a href="/admin/?kind=x-store">Products</a>.');
my $form=sub ($action,$inner,%o) {'<form method="post" action="'.$here.'" class="'.($o{class}//'admin-form').'"'.($o{confirm} ? ' data-confirm="'.h($o{confirm}).'"' : '').'>'.fields($action,'x-store',$o{id}//'').$inner.'</form>'};
my $table=sub (@rows) {'<table class="seo-table mail-status"><tbody>'.join('',map {'<tr><th>'.h($_->[0]).'</th><td class="is-'.$_->[1].'">'.h($_->[2]).'</td></tr>'} @rows).'</tbody></table>'};
my $last=sub ($p) {my $l=pod_note_last($p);return $l ? ['Last update',$l->{ok}?'ok':'warn',$l->{text}.' ('.($l->{at} =~ s/T/ /r =~ s/Z$/ UTC/r).')'] : ['Last update','warn','none yet']};
window('how it works','<ol class="mail-steps">'
.'<li>Make your products at the printer. In Printful, add them to a store of the kind <em>Manual order platform / API</em>. In Gelato, find the product in its catalogue, and put your design’s file where it has a web address (such as under Files).</li>'
.'<li>Connect the printer below.</li>'
.'<li>On <a href="/admin/?kind=x-store">Products</a>, add each one with its price and picture, and under <em>Made by</em> choose the printer and its item.</li>'
.'<li>When an order is paid, what the printer makes is sent to it by itself, and the buyer gets the tracking when it ships. Test-mode payments arrive as drafts, which aren’t made or charged.</li></ol>'
.'<p class="media-label">The printer charges you for each order through your account with them. Buyers pay you through Stripe: your price, plus the shop’s shipping cost (Products → shop settings).</p>');
# Printful
my $pf=length pod_key('printful');my $pstore=read_secret('printful.store');
my $html=$table->(['Printful',$pf ? ('ok','connected'.(length $pstore ? " (store $pstore)" : '')) : ('warn','not connected: what it makes can’t be bought')],$last->('printful'))
.'<div class="box-part"><h3>Token</h3>'.$form->('printful_key',
'<label>Printful private token<input name="key" type="password" autocomplete="off" spellcheck="false" maxlength="400" required placeholder="'.($pf ? 'saved; paste a new one to replace it' : 'paste the token').'"><span class="optional">developers.printful.com → Your tokens → Create token: for your API store only, with the <em>orders</em>, <em>sync_products</em> and <em>webhooks</em> permissions. It’s checked with Printful before saving and never shown again. Printful tokens expire: make a new one before the date it gives.</span></label>'
.'<label>Store ID<input name="store" value="'.h($pstore).'" maxlength="20" inputmode="numeric" placeholder="only for an account-wide token"><span class="optional">Optional: only for a token that reaches your whole account, the number of the store to use (Printful → Stores).</span></label>'
.'<button class="buttonlike" type="submit">save</button>')
.($pf ? $form->('printful_remove','<button class="text-button danger">disconnect Printful</button>',class=>'delete-form',confirm=>'Disconnect Printful? What it makes can’t be bought until it’s connected again.') : '').'</div>';
if ($pf) {
my $items=attempt {printful_items()};my $why=clean_error($@);
# Which product on Products sells each (one from Printful by itself, or one with a single item picked).
my (%by_product,%by_item);
for (grep {($_->{pod}//'') eq 'printful'} @{products()}) {
if (length $_->{pod_sync}) {push @{$by_product{$_->{pod_sync}}},$_->{title}.($_->{active} ? '' : ' (off sale)')} else {push @{$by_item{$_->{pod_ref}}},$_->{title}}
}
my %group;push @{$group{$_->{product_id}}},$_ for @{ref $items eq 'ARRAY' ? $items : []};
$html.='<div class="box-part" id="printful"><h3>Your Printful products</h3>'
.'<p class="media-label">What you publish in Printful appears on Products by itself, as one product with its options (sizes, colours), within a minute. Its options and prices follow Printful.</p>'
.(ref $items ne 'ARRAY' ? '<p class="empty-media">'.h($why).'</p>'
: !@$items ? '<p class="empty-media">This Printful store has nothing in it yet.</p>'
: '<table class="seo-table"><thead><tr><th>Product</th><th>Options (sync variant ID)</th><th>On Products</th></tr></thead><tbody>'
.join('',map {my $g=$group{$_};my $name=$g->[0]{product};
'<tr><td>'.h($name).'</td><td>'.join('<br>',map {h(($_->{name} =~ s/\A\Q$name\E\s*[\/—–-]\s*//r).(length $_->{price} ? " · $_->{price} ".uc($_->{currency}) : '')).' <code>'.h($_->{id}).'</code>'} @$g).'</td>'
.'<td>'.h(join(', ',@{$by_product{$_}//[]},map {@{$by_item{$_->{id}}//[]}} @$g)).'</td></tr>'} sort {lc $group{$a}[0]{product} cmp lc $group{$b}[0]{product}} keys %group).'</tbody></table>')
.$form->('printful_sync','<button class="buttonlike" type="submit">sync with Printful</button><span class="optional"> Hands every product to Products again. Printful’s webhook does this as they change.</span>').'</div>';
}
window('printful',$html);
# Gelato
my $gl=length pod_key('gelato');
$html=$table->(['Gelato',$gl ? ('ok','connected') : ('warn','not connected: what it makes can’t be bought')],($gl ? ['Webhook address','ok',pod_hook_url('gelato')] : ()),$last->('gelato'))
.'<div class="box-part"><h3>Key</h3>'.$form->('gelato_key',
'<label>Gelato API key<input name="key" type="password" autocomplete="off" spellcheck="false" maxlength="400" required placeholder="'.($gl ? 'saved; paste a new one to replace it' : 'paste the key').'"><span class="optional">Gelato → Developer → API keys → Create. It’s checked with Gelato before saving and never shown again.</span></label>'
.'<button class="buttonlike" type="submit">save</button>')
.($gl ? '<p class="media-label">Then, in Gelato → Developer → Webhooks, add the <em>webhook address</em> above, for the events <em>Order status updated</em> and <em>Order item tracking code updated</em>. Only Gelato should know it.</p>'
.$form->('gelato_remove','<button class="text-button danger">disconnect Gelato</button>',class=>'delete-form',confirm=>'Disconnect Gelato? What it makes can’t be bought until it’s connected again.') : '').'</div>';
window('gelato',$html);
# Settings
my $s=pod_settings();
window('settings',$form->('pod_settings',
switch_field('confirm','Send paid orders straight into production',$s->{confirm},hint=>'Off: they arrive at the printer as drafts, made once you confirm them there. Test-mode payments are always drafts.')
.switch_field('ship_email','Email buyers when their order ships, with its tracking',$s->{ship_email})
.'<div class="theme-editor__grid"><label>Gelato’s shipping<select name="gelato_shipping">'.join('',map {'<option value="'.$_->[0].'"'.($_->[0] eq $s->{gelato_shipping} ? ' selected' : '').'>'.h($_->[1]).'</option>'} ['','the cheapest it has'],[normal=>'normal'],[standard=>'standard'],[express=>'express']).'</select>'
.'<span class="optional">How Gelato sends orders. Printful sends them its standard way.</span></label></div>'
.'<button class="buttonlike" type="submit">save</button>'));
# What's been sent to them
my $rows=orders_db()->selectall_arrayref('SELECT * FROM pod_orders ORDER BY created_at DESC LIMIT 100',{Slice=>{}});
my %items;
if (@$rows) {
my %want=map {$_->{order_id}=>1} @$rows;
for my $it (@{orders_db()->selectall_arrayref("SELECT * FROM order_items WHERE order_id IN (SELECT order_id FROM pod_orders ORDER BY created_at DESC LIMIT 100) AND pod<>'' ORDER BY line",{Slice=>{}})}) {
my $pod=pod_of($it) or next;push @{$items{"$it->{order_id} $pod->{provider}"}},$it if $want{$it->{order_id}};
}
}
my $t=@$rows ? '<table class="seo-table store-orders"><thead><tr><th>When</th><th>Order</th><th>Items</th><th>Status</th><th></th></tr></thead><tbody>'.join('',map {my $r=$_;
'<tr><td>'.h(substr($r->{created_at},0,16) =~ s/T/ /r).($r->{live} ? '' : ' <span class="media-label">test</span>').'</td><td><code>'.h(uc substr($r->{order_id},0,8)).'</code></td>'
.'<td>'.join('<br>',map {h("$_->{quantity} × $_->{title}")} @{$items{"$r->{order_id} $r->{provider}"}//[]}).'</td><td>'.pod_state_html($r).'</td><td>'
.($r->{status} =~ /\A(?:failed|sending)\z/ && !length $r->{remote_id} ? $form->('pod_send',hidden(provider=>$r->{provider}).'<button class="text-button">send again</button>',id=>$r->{order_id},class=>'')
: length $r->{remote_id} && $r->{status} !~ /\A(?:delivered|canceled)\z/ ? $form->('pod_check',hidden(provider=>$r->{provider}).'<button class="text-button">check</button>',id=>$r->{order_id},class=>'') : '')
.'</td></tr>'} @$rows).'</tbody></table>'
.$form->('pod_check_all','<button class="buttonlike" type="submit">check them all</button><span class="optional"> Asks the printers about every order they haven’t sent yet. Their webhooks do this as things change.</span>')
: '<p class="empty-media">Nothing has been sent to a printer yet.</p>';
window('sent to printers',"<div id=\"printers\">$t</div>");
end_page();
return 1;
}
1;