import React, {useState} from 'react'
import router from 'next/router'
import {DateTime} from 'luxon'
import {Icon} from '@rmwc/icon'
import {Button} from '@rmwc/button'
import ActionBar from '~/components/admin/actionBar'
import Table from '~/components/table'
Coupons.getInitialProps = async ({ctx}) => {
const {data: coupons} = await ctx.axios.get('/api/coupons')
return {coupons}
}
export default function Coupons({coupons}) {
return (
<>
coupon.code},
{name: 'Valid Until', extractor: coupon => DateTime.fromISO(coupon.valid_until).setZone('local').toFormat('LLL dd, yyyy')},
{name: 'Free Shipping', extractor: coupon => coupon.free_shipping ? : null},
{name: 'Number of Allowed Uses', extractor: coupon => coupon.number_allowed_uses},
{name: 'Discount Type', extractor: coupon => getDiscount(coupon).type},
{name: 'Discount Value', extractor: coupon => getDiscount(coupon).value}
]}
// Map in an id property so the table can use array.map
rows={coupons.map(coupon => ({id: coupon.uuid, ...coupon}))}
/>
>
)
}
function getDiscount(coupon) {
if(coupon.flat_discount_cents)
return {type: 'Flat discount', value: formatMoney(parseInt(coupon.flat_discount_cents, 10))}
if(coupon.percent_discount)
return {type: 'Percent discount', value: coupon.percent_discount + '%'}
if(coupon.per_sock_discount_cents)
return {type: 'Per sock discount', value: formatMoney(parseInt(coupon.per_sock_discount_cents, 10))}
if(coupon.number_of_socks_free)
return {type: 'Free socks', value: coupon.number_of_socks_free + ` pair${coupon.number_of_socks_free !== 1 ? 's' : ''}`}
return {type: 'No Discount', value: null}
}
const formatMoney = money => {
if (money === undefined || money === null) return null;
return '$' + (money / 100).toFixed(2)
}