import React, { FC, useEffect, useRef, useState } from 'react' import { __experimentalHeading as Heading, Button, ButtonGroup, Snackbar, Spinner, } from '@wordpress/components' import bringLogo from '../../assets/img/Bring_logo.svg' import './styles.scss' import { merchantActionableBookingError } from './bookingErrors' import { BookingRequest, MybringCustomerAndServices, Order, Parcel, ServiceDetails, } from './model/models' import apiFetch from '@wordpress/api-fetch' import CustomerSelector from './components/CustomerSelector' import ShippingOptionSelector from './components/ShippingOptionSelector' import PackageDetails from './components/PackageDetails' import { redo, pages, search, undo } from '@wordpress/icons' import { useI18n } from '@wordpress/react-i18n' import Tips from './tips/Tips' import FeedbackForm from './components/FeedbackForm' import { getAdminLink } from '@woocommerce/settings' import CustomsInformationNotice from './components/CustomsInformationNotice' import OrderReturns from './components/OrderReturns' import UpdateAvailableBanner from './components/UpdateAvailableBanner' import { AutoUpdates } from './model/autoUpdates' import { isCustomsValidationError, productsNeedingCustomsInfo, } from './customsRules' import { useReviewedParcels } from './useReviewedParcels' import { useLatestCallback } from './useLatestCallback' import { parcelCountAffectsValidation } from './validationErrors' import { servicesSelectableFor } from './parcelLockerServices' import { Notice, useEnableWpCompatOverlaySlot } from '@wordpress/ui' import { useAnnounce } from './components/useAnnounce' const getServiceCode = (bookingServiceCode: string): string => { switch (bookingServiceCode) { case 'PICKUP_PARCEL': return '0340' case 'PICKUP_PARCEL_BULK': return '0342' case 'HOME_DELIVERY_PARCEL': return '0349' default: return bookingServiceCode } } const OrderDetails: FC = () => { const { __ } = useI18n() useEnableWpCompatOverlaySlot() const [selectedShippingOption, setSelectedShippingOption] = useState() const [order, setOrder] = useState() const [loading, setLoading] = useState(false) const [selectedCustomer, setSelectedCustomer] = useState() const [inProgress, setInProgress] = useState(false) const [parcels, setParcels] = useState>([]) const [labelsInProgress, setLabelsInProgress] = useState(false) const [waybillsInProgress, setWaybillsInProgress] = useState(false) const [returnLabelsInProgress, setReturnLabelsInProgress] = useState(false) const [labelFailure, setLabelFailure] = useState(false) const [waybillFailure, setWaybillFailure] = useState(false) const [bringNotSelected, setBringNotSelected] = useState(false) const [updateAvailable, setUpdateAvailable] = useState(false) const [autoUpdates, setAutoUpdates] = useState() const [availableServices, setAvailableServices] = useState< Array >([]) const [error, setError] = useState(false) const [bookingError, setBookingError] = useState(false) const [bookingErrorMessage, setBookingErrorMessage] = useState< string | undefined >(undefined) const [isValidating, setIsValidating] = useState(false) const [validationRequestFailed, setValidationRequestFailed] = useState(false) const latestOrderFetch = useRef(0) const [customersAndServices, setCustomersAndServices] = useState< Array >([]) const [requiresAge20Validation, setRequiresAge20Validation] = useState(false) const validatedFor = useRef(undefined) const urlParams = new URLSearchParams(window.location.search) const orderId = urlParams.get('post') || urlParams.get('id') const fetchOrder = ( id: string, customerNumber?: string, shippingOption?: string, parcelWeightsInGrams?: Array ) => { const params = new URLSearchParams() if (customerNumber) { params.set('customerNumber', customerNumber) } if (shippingOption) { params.set('selectedShippingOption', shippingOption) } if (parcelWeightsInGrams?.length) { params.set('parcelWeights', parcelWeightsInGrams.join(',')) } // Each fetch validates the order for the selected customer and service. Only the latest one is applied, // and booking stays disabled while it runs, or if it failed const fetchId = ++latestOrderFetch.current setIsValidating(true) return apiFetch({ path: `/posten-bring-checkout/orders/${id}${ params.size > 0 ? `?${params.toString()}` : '' }`, }) .catch(err => { if (fetchId === latestOrderFetch.current) { setIsValidating(false) setValidationRequestFailed(true) setBookingError(true) } throw err }) .then((response: Order) => { if (fetchId !== latestOrderFetch.current) { return undefined } setIsValidating(false) setValidationRequestFailed(false) if (response) { setOrder(response) setBringNotSelected( (!response.order_shipping_option || response.order_shipping_option === '') && response.mybring_bookings?.length === 0 ) setRequiresAge20Validation( response.items.some(i => i.requires_age_20_verification) ) } return response }) } // Saving HS codes or SKUs can finish after the customer or service changed, or after the // editor was hidden, so the revalidation always uses the current selection const refreshOrder = useLatestCallback( async (parcelWeightsInGrams?: Array) => { if (!order) return await fetchOrder( order.order_id, selectedCustomer, selectedShippingOption, parcelWeightsInGrams ).catch(() => undefined) } ) const selectedServiceCode = getServiceCode(selectedShippingOption ?? '') const { splitParcels, reviewParcels, reviewedParcelWeights } = useReviewedParcels(setParcels, parcelWeightsInGrams => { if (parcelCountAffectsValidation(selectedServiceCode)) { refreshOrder(parcelWeightsInGrams) } }) const fetchCustomers = (from: string, to: string) => { return apiFetch>({ path: `/posten-bring-checkout/customers?from=${from}&to=${to}`, }).then(response => { if (response) { setCustomersAndServices(response) if (response.length > 0) { const defaultCustomer = response.find(it => it.defaultCustomer) setSelectedCustomer( defaultCustomer?.customerNumber || response[0].customerNumber ) } } }) } const getAvailableServices = ( from: string, to: string, totalWeight?: number ) => { return apiFetch>({ path: `/posten-bring-checkout/services?from=${from}&to=${to}&weight=${ totalWeight || 0 / 1000 }`, }).then(response => { if (response) { setAvailableServices(response) } }) } useEffect(() => { // @ts-expect-error 2339 if (window.prefetchedOrder && window.prefetchedOrder[orderId]) { // @ts-expect-error 2339 setUpdateAvailable(window.prefetchedOrder?.updateAvailable) // @ts-expect-error 2339 setAutoUpdates(window.prefetchedOrder?.autoUpdates) // @ts-expect-error 2339 const prefetchedData = window.prefetchedOrder[orderId] const prefetchedOrder = prefetchedData.order as Order setOrder(prefetchedOrder) setBringNotSelected( (!prefetchedOrder.order_shipping_option || prefetchedOrder.order_shipping_option === '') && prefetchedOrder.mybring_bookings?.length === 0 ) setCustomersAndServices( prefetchedData.customers as Array ) if (prefetchedData.customers.length > 0) { const defaultCustomer = ( prefetchedData.customers as Array ).find(it => it.defaultCustomer) setSelectedCustomer( defaultCustomer?.customerNumber || prefetchedData.customers[0].customerNumber ) } setAvailableServices( prefetchedData.shippingOptions as Array ) setRequiresAge20Validation( prefetchedOrder.items.some(i => i.requires_age_20_verification) ) } else { const fetchOrderCustomersAndServices = async (id: string) => { await fetchOrder(id) .then(orderResult => { if (!orderResult) { return } return Promise.all([ fetchCustomers(orderResult.from_country, orderResult.to_country), getAvailableServices( orderResult.from_country, orderResult.to_country, orderResult.total_weight ), ]) }) .then(() => setLoading(false)) .catch(() => { setLoading(false) setError(true) }) } if (orderId) { setError(false) setLoading(true) fetchOrderCustomersAndServices(orderId) } } }, [orderId]) useEffect(() => { if ( selectedCustomer && selectedShippingOption === undefined && order?.order_shipping_option ) { validatedFor.current = `${selectedCustomer}/${order.order_shipping_option}` setSelectedShippingOption(order.order_shipping_option) } else if (selectedCustomer && selectedShippingOption) { const selection = `${selectedCustomer}/${selectedShippingOption}` const previouslyValidated = validatedFor.current validatedFor.current = selection // Validation depends on the selection for age verification VAS and for HS codes on 3639, 0330 and 0340 if (previouslyValidated && previouslyValidated !== selection && orderId) { fetchOrder( orderId, selectedCustomer, selectedShippingOption, reviewedParcelWeights() ).catch(() => undefined) } } }, [ orderId, selectedShippingOption, selectedCustomer, order?.order_shipping_option, requiresAge20Validation, reviewedParcelWeights, ]) const validationErrors = order?.order_validation_errors ?? [] const productsMissingCustomsInfo = productsNeedingCustomsInfo( order ? [order] : [] ) const shownValidationErrors = productsMissingCustomsInfo.length > 0 ? validationErrors.filter(it => !isCustomsValidationError(it)) : validationErrors const validationFailed = validationErrors.length > 0 && validationErrors.every(it => it.bookingDisabled) const bookingFormShown = !loading && !bringNotSelected && !error && order?.mybring_bookings?.length === 0 const technicalIssueShown = !loading && !bringNotSelected && error && !(order && (order.mybring_bookings?.length || 0) > 0) // @ts-expect-error 2339 const logSharing = Boolean(window.postenBringCheckoutLogSharing) useAnnounce( technicalIssueShown && logSharing && __( 'We are having some technical issues right now. Our developers have been notified. Please check back soon.', 'posten-bring-checkout' ), 'assertive' ) useAnnounce( technicalIssueShown && !logSharing && __( 'We are having some technical issues right now. Please check back soon. If it continues, turn on "Send us error logs" in the settings so our developers are notified.', 'posten-bring-checkout' ), 'assertive' ) useAnnounce( bookingFormShown && bookingError && (bookingErrorMessage ?? __( 'An error occurred! We have been notified and are investigating. Please try again later, or contact us via ', 'posten-bring-checkout' ) + __('checkout.implementering@posten.no', 'posten-bring-checkout')), 'assertive' ) useAnnounce( bookingFormShown && shownValidationErrors.map(it => it.message).join(' ') ) const placeOrder = async () => { setInProgress(true) setBookingError(false) setBookingErrorMessage(undefined) const data = { orderRef: orderId, testIndicator: false, selectedShippingOption, customerNumber: selectedCustomer, packages: parcels.map(parcel => ({ weightInKg: parcel.weightInGrams / 1000, })), } as BookingRequest apiFetch({ path: `/posten-bring-checkout/bookings?orderId=${order?.order_id}`, method: 'POST', headers: { 'Content-Type': 'application/json', }, data, }) .then(() => { setInProgress(false) setLoading(true) return fetchOrder(order!.order_id) }) .then(() => { setLoading(false) }) .catch(err => { setLoading(false) setInProgress(false) setBookingError(true) setBookingErrorMessage(merchantActionableBookingError(err)) }) } const getLabels = async (labelType: string) => { setLabelFailure(false) const newTab = window.open('', '_blank') const response = await apiFetch({ path: `/posten-bring-checkout/labels?orderIds=${orderId}&labelType=${labelType}`, method: 'GET', headers: { Accept: 'application/pdf', }, parse: false, }).catch(_ => { setLabelFailure(true) }) setLabelsInProgress(false) setReturnLabelsInProgress(false) if (response?.ok) { const blob = await response.blob() const url = window.URL.createObjectURL( new Blob([blob], { type: 'application/pdf' }) ) if (newTab) { newTab.location.href = url } } } const getWaybills = async () => { setWaybillFailure(false) const newTab = window.open('', '_blank') const response = await apiFetch({ path: `/posten-bring-checkout/waybills?orderIds=${orderId}`, method: 'GET', headers: { Accept: 'application/pdf', }, parse: false, }).catch(_ => { setWaybillFailure(true) }) setWaybillsInProgress(false) if (response?.ok) { const blob = await response.blob() const url = window.URL.createObjectURL( new Blob([blob], { type: 'application/pdf' }) ) if (newTab) { newTab.location.href = url } } } return ( <>
{loading ? (
) : ( <> {bringNotSelected ? (
{__( 'Bring has not been selected for this order', 'posten-bring-checkout' )}
) : ( <> {order && (order.mybring_bookings?.length || 0) > 0 && (
{__( 'Shipment has been ordered', 'posten-bring-checkout' )}
{order.mybring_bookings[0].waybillUrl && ( )} {order.mybring_bookings[0].returnLabelUrl && ( )} {labelFailure && ( setLabelFailure(false)} > {__( 'An error occurred while generating label. Please try again', 'posten-bring-checkout' )} )} {waybillFailure && ( setWaybillFailure(false)} > {__( 'An error occurred while generating waybill. Please try again', 'posten-bring-checkout' )} )}
{__('Shipment ', 'posten-bring-checkout') + order.mybring_bookings[0].consignmentNumber}
{ availableServices?.find( service => service.service_id === getServiceCode( order.mybring_bookings[0].serviceId ) )?.name }
{order.mybring_bookings[0].waybillUrl && (
{__( 'Do you want to order ', 'posten-bring-checkout' )}{' '} {__('pickup', 'posten-bring-checkout')} ?
)}
{order.from_country !== order.to_country && !( order.mybring_bookings[0].serviceId === '0340' && order.from_country === 'NO' ) && (
{__('Download ', 'posten-bring-checkout')} {__( 'commercial invoice', 'posten-bring-checkout' )} {__('Download ', 'posten-bring-checkout')} {__( 'Proforma invoice', 'posten-bring-checkout' )}
)}
)} {error && !(order && (order.mybring_bookings?.length || 0) > 0) && (
{__('Book shipping', 'posten-bring-checkout')}
{ // @ts-expect-error 2339 window.postenBringCheckoutLogSharing ? ( __( 'We are having some technical issues right now. Our developers have been notified. Please check back soon.', 'posten-bring-checkout' ) ) : ( <> {__( 'We are having some technical issues right now. Please check back soon. If it continues, turn on "Send us error logs" in the settings so our developers are notified.', 'posten-bring-checkout' )}{' '} {__('Open settings', 'posten-bring-checkout')} ) }
)} {order && !error && order.mybring_bookings?.length === 0 && (
{__('Book shipping', 'posten-bring-checkout')}
{bookingError && ( {bookingErrorMessage ?? ( <> {__( 'An error occurred! We have been notified and are investigating. Please try again later, or contact us via ', 'posten-bring-checkout' )} {__( 'checkout.implementering@posten.no', 'posten-bring-checkout' )} )} )} {productsMissingCustomsInfo.length > 0 && (
refreshOrder(reviewedParcelWeights()) } />
)} {shownValidationErrors.length > 0 && ( }> {shownValidationErrors.map( (validationError, idx) => (
{validationError.message}
) )}
)}

{__( 'By ordering, you accept our ', 'posten-bring-checkout' )} {__( 'terms and conditions.', 'posten-bring-checkout' )}

)} )} )}
{!loading && !bringNotSelected && (
)} {bringNotSelected ? null : (
{updateAvailable && autoUpdates && ( )}
)} ) } export default OrderDetails