import React, { useState } from 'react';
import { OText, OIcon } from '../shared';
import { StyleSheet, View, Platform, Alert, TouchableOpacity } from 'react-native';
import {
Content,
OrderCustomer,
OrderHeader,
OrderContent,
OrderBusiness,
OrderProducts,
Table,
OrderBill,
Total,
Action,
ContentInfo,
} from './styles';
import { useUtils, useLanguage, useConfig } from 'ordering-components/native';
import { verifyDecimals, getProductPrice, getCurrenySymbol } from '../../utils';
import { FloatingButton } from '../FloatingButton';
import RNHTMLtoPDF from 'react-native-html-to-pdf';
import RNPrint from 'react-native-print';
import { useTheme } from 'styled-components/native';
import { ProductItemAccordion } from '../ProductItemAccordion';
export const OrderSummary = ({ order, navigation, orderStatus, askBluetoothPermission, getPermissions, isGrantedPermissions, checkBluetoothPermission }: any) => {
const handleArrowBack: any = () => {
navigation?.canGoBack() && navigation.goBack();
};
const [{ parsePrice, parseNumber, parseDate }] = useUtils();
const [, t] = useLanguage();
const [{ configs }] = useConfig();
const [state, setState] = useState({
selectedPrinter: { url: undefined },
});
const paymethodsLength = order?.payment_events?.filter((item: any) => item.event === 'payment')?.length
const getFormattedSubOptionName = ({ quantity, name, position, price }: any) => {
if (name !== 'No') {
const pos = position && position !== 'whole' ? `(${t(position.toUpperCase(), position)})` : '';
return pos
? `${quantity} x ${name} ${pos} +${parsePrice(price)}\n`
: `${quantity} x ${name} +${parsePrice(price)}\n`;
} else {
return 'No\n';
}
};
const getSuboptions = (suboptions: any) => {
const array: any = []
suboptions?.length > 0 &&
suboptions?.map((suboption: any) => {
const string = ` ${getFormattedSubOptionName(suboption)}
`
array.push(string)
})
return array.join('')
}
const getOptions = (options: any, productComment: string = '') => {
const array: any = [];
options?.length &&
options?.map((option: any) => {
const string =
` ${option.name}
${getSuboptions(option.suboptions)}`;
array.push(string)
})
if (productComment) {
array.push(`${t('COMMENT', 'Comment')}
${productComment}`)
}
return array.join('')
}
const getIngredients = (ingredients: any) => {
const _ingredients: any = (ingredients.length > 0 && ingredients.filter((i: any) => !i.selected)) || []
const texts: any = []
_ingredients.map((ingredient: any) => {
texts.push(` ${t('NO', 'No')} ${ingredient.name}
`)
})
if (_ingredients.length) {
return `
${t('ORDER_NO', 'Order No.')} ${order.id}
${orderStatus}
${t('ORDER_TYPE', 'Order Type')}: ${deliveryStatus[order?.delivery_type]}
${!!order?.delivery_option
? `${t('DELIVERY_PREFERENCE', 'Delivery Preference')}: ${t(order?.delivery_option?.name?.toUpperCase()?.replace(/ /g, '_'), order?.delivery_option?.name)
} `
: ''
}
${t('DELIVERY_DATE', 'Delivery Date')}: ${deliveryDate(order)}
${t(paymethodsLength > 1 ? 'PAYMENT_METHODS' : 'PAYMENT_METHOD', paymethodsLength > 1 ? 'Payment methods' : 'Payment method')}: ${order?.payment_events?.length > 0 ? handlePaymethodsListString() : t(order?.paymethod?.gateway?.toUpperCase(), order?.paymethod?.name)}
${t('CUSTOMER_DETAILS', 'Customer details')}
${t('FULL_NAME', 'Full Name')}: ${customerName}
${t('EMAIL', 'Email')}: ${order?.customer?.email}
${!!order?.customer?.cellphone
? `${t('MOBILE_PHONE', 'Mobile Phone')}: ${order?.customer?.cellphone
} `
: ''}
${!!order?.customer?.phone
? `${t('MOBILE_PHONE', 'Mobile Phone')}: ${order?.customer?.phone
} `
: ''
}
${t('FULL_ADDRESS', 'Full Addres')}: ${order?.customer?.address}
${!!order?.customer?.internal_number
? `${t('INTERNAL_NUMBER', 'Internal Number')}: ${order?.customer?.internal_number
} `
: ''
}
${order?.customer.zipcode ?
`${t('ZIPCODE', 'Zipcode')}: ${order?.customer.zipcode}`
: ''}
${t('BUSINESS_DETAILS', 'Business details')}
${order?.business?.name}
${order?.business?.email}
${!!order?.business?.cellphone
? `${t('BUSINESS_PHONE', 'Business Phone')}: ${order?.business?.cellphone
} `
: ''
}
${!!order?.business?.phone
? `${t('BUSINESS_PHONE', 'Business Phone')}: ${order?.business?.phone
} `
: ''
}
${t('ADDRESS', 'Address')}: ${order?.business?.address}
${!!order?.business?.address_notes
? `${t('SPECIAL_ADDRESS', 'Special Address')}: ${order?.business?.address_notes
} `
: ''
}
${t('ORDER_DETAILS', 'Order Details')}
${order?.comment ? ('' + t('ORDER_COMMENT', 'Order Comment') + ':' + order?.comment) : ''}
${order?.products.length &&
order?.products.map(
(product: any, i: number) =>
`
${product?.quantity} ${product?.name}
${parsePrice(product.total ?? getProductPrice(product))}
${getIngredients(product?.ingredients)}
${getOptions(product.options, product.comment)}
`
)
}
${t('SUBTOTAL', 'Subtotal')}
${parsePrice(((order?.summary?.subtotal ?? order?.subtotal) + getIncludedTaxes()), { currency: getCurrenySymbol(order?.currency) })}
${order?.summary?.discount > 0
? order?.offer_type === 1
? `
${t('DISCOUNT', 'Discount')} (${verifyDecimals(order?.offer_rate, parsePrice)}%)
`
: `
${t('DISCOUNT', 'Discount')}
`
: ''
}
${order?.summary?.discount > 0
? `
- ${parsePrice(order?.summary?.discount ?? order?.discount, { currency: getCurrenySymbol(order?.currency) })}
`
: ''
}
${order?.offers?.length > 0 ? order?.offers?.filter((offer: any) => offer?.target === 1)?.map((offer: any) => (
`
${order?.rate_type === 1
? `
${t(offer.name?.toUpperCase?.()?.replace(/ /g, '_'), offer.name)} (${verifyDecimals(offer?.rate, parsePrice)}%)
`
: `
${t(offer.name?.toUpperCase?.()?.replace(/ /g, '_'), offer.name)}
`}
- ${parsePrice(offer?.summary?.discount, { currency: getCurrenySymbol(order?.currency) })}
`
)) : ''}
${order?.taxes?.length === 0 && order?.tax_type === 2
? `
${t('TAX', 'Tax')} (${verifyDecimals(order?.tax, parseNumber)}%)}
${parsePrice(order?.summary?.tax ?? 0, { currency: getCurrenySymbol(order?.currency) })}
`
: ''}
${order?.fees?.length === 0 && order?.summary?.service_fee > 0 ? (
`
${t('SERVICE_FEE', 'Service fee')} (${verifyDecimals(order?.service_fee, parseNumber)}%)}
${parsePrice(order?.summary?.service_fee ?? 0, { currency: getCurrenySymbol(order?.currency) })}
`
) : ''}
${order?.taxes?.length > 0 ? order?.taxes?.filter((tax: any) => tax?.type === 2 && tax?.rate !== 0 && tax?.target === 'product').map((tax: any) => (
`
${t(tax?.name?.toUpperCase?.()?.replace(/ /g, '_'), tax?.name) || t('INHERIT_FROM_BUSINESS', 'Inherit from business')} (${verifyDecimals(tax?.rate, parseNumber)}%)
${parsePrice(tax?.summary?.tax_after_discount ?? tax?.summary?.tax ?? 0, { currency: getCurrenySymbol(order?.currency) })}
`
)) : ''}
${order?.offers?.length > 0 ? order?.offers?.filter((offer: any) => offer?.target === 3)?.map((offer: any) => (
`
${t(offer.name?.toUpperCase?.()?.replace(/ /g, '_'), offer.name)} ${offer.rate_type === 1 ? `(${verifyDecimals(offer?.rate, parsePrice)}%)` : ''}
- ${parsePrice(offer?.summary?.discount, { currency: getCurrenySymbol(order?.currency) })}
`
)) : ''}
${order?.summary?.delivery_price > 0 && order.delivery_type !== 2 ?
`
${t('DELIVERY_FEE', 'Delivery Fee')}
${parsePrice(order?.summary?.delivery_price + getIncludedTaxes(true), { currency: getCurrenySymbol(order?.currency) })}
` :
''
}
${t('DRIVER_TIP', 'Driver tip')}
${percentTip ? `(${percentTip}%)` : ''}
${parsePrice(order?.summary?.driver_tip ?? order?.totalDriverTip, { currency: getCurrenySymbol(order?.currency) })}
${order?.taxes?.length > 0 ? order?.taxes?.filter((tax: any) => tax?.type === 2 && tax?.rate !== 0 && tax?.target === 'delivery_fee').map((tax: any, i: number) => (
`
${tax.name || t('INHERIT_FROM_BUSINESS', 'Inherit from business')} (${verifyDecimals(tax?.rate, parsePrice)}%)
${parsePrice(tax?.summary?.tax_after_discount ?? tax?.summary?.tax ?? 0, { currency: getCurrenySymbol(order?.currency) })}
`
)) : ''}
${order?.offers?.length > 0 ? order?.offers?.filter((offer: any) => offer?.target === 2)?.map((offer: any) => (
`
${t(offer.name?.toUpperCase?.()?.replace(/ /g, '_'), offer.name)} ${offer.rate_type === 1 ? `(${verifyDecimals(offer?.rate, parsePrice, { currency: getCurrenySymbol(order?.currency) })}%)` : ''}
- ${parsePrice(offer?.summary?.discount, { currency: getCurrenySymbol(order?.currency) })}
`
)) : ''}
${t('TOTAL', 'Total')}
${parsePrice(order?.summary?.total ?? 0)}
${order?.payment_events.length && `
${t('PAYMENTS', 'Payments')}
`}
${order?.payment_events.length &&
order?.payment_events.map(
(event: any, i: number) =>
`
${event?.wallet_event
? walletName[event?.wallet_event?.wallet?.type]?.name
: event?.paymethod?.gateway && event?.paymethod?.gateway === 'cash' && order?.cash > 0
? `${t(event?.paymethod?.gateway?.toUpperCase(), event?.paymethod?.name)} (${t('CASH_CHANGE_OF', 'Change of :amount:').replace(':amount:', parsePrice(order?.cash))})`
: event?.paymethod?.gateway
? t(event?.paymethod?.gateway?.toUpperCase(), event?.paymethod?.name)
: t(order?.paymethod?.gateway?.toUpperCase(), order?.paymethod?.name)}
${(event?.paymethod?.gateway === 'cash' && order?.cash)
? parsePrice(order?.cash, { currency: order?.currency })
: `-${parsePrice(event?.amount, { currency: order?.currency })}`}
`
)}
`;
};
const deliveryStatus: any = {
1: t('DELIVERY', 'Delivery'),
2: t('PICK_UP', 'Pick up'),
3: t('EAT_IN', 'Eat In'),
4: t('CURBSIDE', 'Curbside'),
5: t('DRIVER_THRU', 'Driver thru'),
};
// @NOTE iOS Only
const selectPrinter = async () => {
const selectedPrinter = await RNPrint.selectPrinter({ x: '100', y: '100' });
setState({ selectedPrinter });
};
// @NOTE iOS Only
const silentPrint = async () => {
if (!state?.selectedPrinter) {
Alert.alert('Must Select Printer First');
}
const jobName = await RNPrint.print({
printerURL: state?.selectedPrinter?.url,
html: orderSummary(),
});
};
const printPDF = async () => {
const results = await RNHTMLtoPDF.convert({
html: orderSummary(),
fileName: 'test',
base64: true,
});
await RNPrint.print({
filePath: results.filePath || '',
jobName: `${t('ORDER_NO', `Order no. ${order.id}`)}`,
});
};
const styles = StyleSheet.create({
btnBackArrow: {
borderWidth: 0,
width: 32,
height: 32,
tintColor: theme.colors.textGray,
backgroundColor: theme.colors.clear,
borderColor: theme.colors.clear,
shadowColor: theme.colors.clear,
paddingLeft: 0,
paddingRight: 0,
marginTop: 10
},
textBold: {
fontWeight: '600',
},
});
const handlePrint = async () => {
if (Platform.OS === 'ios') {
silentPrint()
return
}
const _permissions = await getPermissions()
if (!isGrantedPermissions) {
checkBluetoothPermission()
}
if (isGrantedPermissions) {
const response = await askBluetoothPermission();
const isGranted = _permissions.reduce((allPermissions: boolean, _permission: string) => allPermissions && response?.[_permission] === 'granted', true)
if (isGranted) {
printPDF()
}
}
};
const getIncludedTaxes = (isDeliveryFee?: boolean) => {
if (!order?.taxes) return 0
if (order?.taxes?.length === 0) {
return order.tax_type === 1 ? order?.summary?.tax ?? 0 : 0
} else {
return order?.taxes.reduce((taxIncluded: number, tax: any) => {
return taxIncluded +
(((!isDeliveryFee && tax.type === 1 && tax.target === 'product') ||
(isDeliveryFee && tax.type === 1 && tax.target === 'delivery_fee')) ? tax.summary?.tax : 0)
}, 0)
}
}
return (
<>