@shipengine/elements 0.26.4 → 0.26.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -26,7 +26,6 @@ var jsBase64 = require('js-base64');
26
26
  var cardValidator = require('card-validator');
27
27
  var reactQuery = require('react-query');
28
28
  var brands = require('@packlink/brands');
29
- var reactApi = require('@shipengine/react-api');
30
29
 
31
30
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
32
31
 
@@ -2628,6 +2627,27 @@ const overrideCarrierCodes$1 = (carrier, overrides) => {
2628
2627
  return overrides[carrier] || carrier;
2629
2628
  };
2630
2629
 
2630
+ var $$f = _export;
2631
+ var $includes = arrayIncludes.includes;
2632
+ var fails$7 = fails$q;
2633
+ var addToUnscopables$1 = addToUnscopables$3;
2634
+
2635
+ // FF99+ bug
2636
+ var BROKEN_ON_SPARSE = fails$7(function () {
2637
+ return !Array(1).includes();
2638
+ });
2639
+
2640
+ // `Array.prototype.includes` method
2641
+ // https://tc39.es/ecma262/#sec-array.prototype.includes
2642
+ $$f({ target: 'Array', proto: true, forced: BROKEN_ON_SPARSE }, {
2643
+ includes: function includes(el /* , fromIndex = 0 */) {
2644
+ return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
2645
+ }
2646
+ });
2647
+
2648
+ // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
2649
+ addToUnscopables$1('includes');
2650
+
2631
2651
  // Declaring these flags to allow shorthand object syntax, i.e. { flagName } instead of { flagName: true }
2632
2652
  const hasEuCustomsRules = true,
2633
2653
  hasProvinces = true,
@@ -2867,27 +2887,9 @@ const isPoBox = addressLine => PO_BOX_REGEX.test(addressLine);
2867
2887
  * @category Utilities
2868
2888
  */
2869
2889
  const isPoBoxAddress = address => !!(isPoBox(address.addressLine1) || address.addressLine2 && isPoBox(address.addressLine2));
2870
-
2871
- var $$f = _export;
2872
- var $includes = arrayIncludes.includes;
2873
- var fails$7 = fails$q;
2874
- var addToUnscopables$1 = addToUnscopables$3;
2875
-
2876
- // FF99+ bug
2877
- var BROKEN_ON_SPARSE = fails$7(function () {
2878
- return !Array(1).includes();
2879
- });
2880
-
2881
- // `Array.prototype.includes` method
2882
- // https://tc39.es/ecma262/#sec-array.prototype.includes
2883
- $$f({ target: 'Array', proto: true, forced: BROKEN_ON_SPARSE }, {
2884
- includes: function includes(el /* , fromIndex = 0 */) {
2885
- return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
2886
- }
2887
- });
2888
-
2889
- // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
2890
- addToUnscopables$1('includes');
2890
+ const isEmptyAddress = address => {
2891
+ return !address || Object.entries(address).every(([key, value]) => key === "countryCode" || [null, "", "unknown"].includes(value));
2892
+ };
2891
2893
 
2892
2894
  const USPS_CARRIER_CODES = ["usps", "stamps_com"];
2893
2895
  const isUspsCarrier = carrierCode => USPS_CARRIER_CODES.includes(carrierCode);
@@ -4801,11 +4803,15 @@ const CostBreakdown = ({
4801
4803
  children: [jsxRuntime.jsx("td", Object.assign({
4802
4804
  css: getTableCellLabelStyles
4803
4805
  }, {
4804
- children: priceItem.label
4806
+ children: jsxRuntime.jsx(giger.Typography, {
4807
+ children: priceItem.label
4808
+ })
4805
4809
  })), jsxRuntime.jsx("td", Object.assign({
4806
4810
  "data-testid": priceItem.label.toLowerCase()
4807
4811
  }, {
4808
- children: formatMoney(priceItem.value)
4812
+ children: jsxRuntime.jsx(giger.Typography, {
4813
+ children: formatMoney(priceItem.value)
4814
+ })
4809
4815
  }))]
4810
4816
  }, index + priceItem.value.amount))
4811
4817
  })
@@ -6560,6 +6566,10 @@ const styles$n = createStyles({
6560
6566
  display: "flex",
6561
6567
  flexDirection: "column"
6562
6568
  },
6569
+ icon: theme => ({
6570
+ padding: `${theme.spacing(0.4)}px 0 0 ${theme.spacing(0.5)}px`,
6571
+ position: "absolute"
6572
+ }),
6563
6573
  link: {
6564
6574
  border: "none"
6565
6575
  },
@@ -7255,6 +7265,11 @@ const CarrierTermsForm = ({
7255
7265
  children: jsxRuntime.jsx(CheckboxInput, {
7256
7266
  checkboxLabel: jsxRuntime.jsx(reactI18next.Trans, {
7257
7267
  components: {
7268
+ icon: jsxRuntime.jsx(giger.Icon, {
7269
+ css: styles$n.icon,
7270
+ name: showTerms ? gigerTheme.IconNames.CHEVRON_TOP : gigerTheme.IconNames.CHEVRON_BOTTOM,
7271
+ size: giger.IconSize.SIZE_SMALL
7272
+ }),
7258
7273
  terms: jsxRuntime.jsx(giger.Link, {
7259
7274
  css: theme => ({
7260
7275
  fontWeight: theme.typography.fontWeight.normal
@@ -12266,7 +12281,7 @@ const ShipmentForm = ({
12266
12281
  warehouseId,
12267
12282
  warehouses
12268
12283
  }) => {
12269
- var _a, _b, _c, _d, _e, _f, _g, _h;
12284
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
12270
12285
  features = Object.assign({
12271
12286
  browseRates: true,
12272
12287
  includeShipsuranceInsurance: true,
@@ -12444,16 +12459,16 @@ const ShipmentForm = ({
12444
12459
  }, [form]);
12445
12460
  const handleSubmit = form.handleSubmit(values => __awaiter(void 0, void 0, void 0, function* () {
12446
12461
  try {
12447
- const _j = values,
12462
+ const _k = values,
12448
12463
  {
12449
12464
  __mode: discard
12450
- } = _j,
12451
- payload = __rest(_j, ["__mode"]);
12465
+ } = _k,
12466
+ payload = __rest(_k, ["__mode"]);
12452
12467
  const updatedShipment = yield onSubmit(Object.assign(Object.assign({}, shipment || {}), payload));
12453
12468
  // Defer shipment hydration to the task queue so that the submission promise resolves first, otherwise the
12454
12469
  // submission count will increment after hydration resets the form, keeping it in revalidate mode
12455
12470
  if (updatedShipment) setTimeout(() => hydrateShipment(updatedShipment), 0);
12456
- } catch (_k) {
12471
+ } catch (_l) {
12457
12472
  // Reset the form to its current state, but as a side effect this sets isDirty to false
12458
12473
  // That way, form lifecycle contract is upheld
12459
12474
  form.reset(form.getValues());
@@ -12536,7 +12551,7 @@ const ShipmentForm = ({
12536
12551
  }
12537
12552
  }), [form, onChangeAddress, shipment]);
12538
12553
  const [editShipToForm, isEditShipFormToOpen, toggleIsEditShipFormToOpen] = useNestedForm(AddressForm, {
12539
- address: (_a = shipment === null || shipment === void 0 ? void 0 : shipment.shipTo) !== null && _a !== void 0 ? _a : salesOrder === null || salesOrder === void 0 ? void 0 : salesOrder.shipTo,
12554
+ address: (_b = (_a = addressPreference === null || addressPreference === void 0 ? void 0 : addressPreference.selection) !== null && _a !== void 0 ? _a : shipment === null || shipment === void 0 ? void 0 : shipment.shipTo) !== null && _b !== void 0 ? _b : salesOrder === null || salesOrder === void 0 ? void 0 : salesOrder.shipTo,
12540
12555
  formId: "edit-ship-to-form",
12541
12556
  onSubmit: handleSubmitEditShipTo,
12542
12557
  onSubmitParse: onSubmitParseShipTo
@@ -12586,7 +12601,7 @@ const ShipmentForm = ({
12586
12601
  });
12587
12602
  if (errors) throw new Error(errors.map(e => e.message).join(", "));
12588
12603
  if (!shipment) throw new Error("errorMessages.unableToLoad.shipment");
12589
- const isEmptyShipTo = Object.entries(shipment.shipTo).every(([key, value]) => key === "countryCode" || [null, "", "unknown"].includes(value));
12604
+ const addressPreferenceIsEmpty = isEmptyAddress(addressPreference === null || addressPreference === void 0 ? void 0 : addressPreference.selection);
12590
12605
  return jsxRuntime.jsxs("form", Object.assign({
12591
12606
  id: "shipment-form",
12592
12607
  onSubmit: formLogger.capture(handleSubmit)
@@ -12610,7 +12625,7 @@ const ShipmentForm = ({
12610
12625
  }), jsxRuntime.jsx(FieldLabel, Object.assign({
12611
12626
  label: !isEditShipFormToOpen ? "purchase-label:fields.shipTo" : ""
12612
12627
  }, {
12613
- children: !isEditShipFormToOpen && (isEmptyShipTo ? jsxRuntime.jsx(giger.Button, Object.assign({
12628
+ children: !isEditShipFormToOpen && (addressPreferenceIsEmpty ? jsxRuntime.jsx(giger.Button, Object.assign({
12614
12629
  onClick: toggleIsEditShipFormToOpen,
12615
12630
  variant: giger.ButtonVariant.OUTLINED
12616
12631
  }, {
@@ -12654,7 +12669,7 @@ const ShipmentForm = ({
12654
12669
  }, {
12655
12670
  children: formatDate(salesOrder.orderDate)
12656
12671
  })), jsxRuntime.jsx(Spacer, {})]
12657
- })), ((_b = salesOrder === null || salesOrder === void 0 ? void 0 : salesOrder.paymentDetails) === null || _b === void 0 ? void 0 : _b.grandTotal) && jsxRuntime.jsxs(FieldLabel, Object.assign({
12672
+ })), ((_c = salesOrder === null || salesOrder === void 0 ? void 0 : salesOrder.paymentDetails) === null || _c === void 0 ? void 0 : _c.grandTotal) && jsxRuntime.jsxs(FieldLabel, Object.assign({
12658
12673
  label: t("purchase-label:fields.orderValue")
12659
12674
  }, {
12660
12675
  children: [jsxRuntime.jsx(giger.Typography, Object.assign({
@@ -12732,7 +12747,7 @@ const ShipmentForm = ({
12732
12747
  }), jsxRuntime.jsx(CustomsItemsDisplay, {
12733
12748
  onUpdate: handleUpdateCustomsItems,
12734
12749
  shipment: shipment
12735
- }), ((_c = customsErrors === null || customsErrors === void 0 ? void 0 : customsErrors.customsItems) === null || _c === void 0 ? void 0 : _c.type) === "too_small" && jsxRuntime.jsxs(jsxRuntime.Fragment, {
12750
+ }), ((_d = customsErrors === null || customsErrors === void 0 ? void 0 : customsErrors.customsItems) === null || _d === void 0 ? void 0 : _d.type) === "too_small" && jsxRuntime.jsxs(jsxRuntime.Fragment, {
12736
12751
  children: [jsxRuntime.jsx(Spacer, {}), jsxRuntime.jsx(giger.InlineNotification, {
12737
12752
  title: t("purchase-label:errorMessages.customsItemsRequired"),
12738
12753
  type: giger.NotificationType.ERROR
@@ -12896,14 +12911,14 @@ const ShipmentForm = ({
12896
12911
  label: "purchase-label:fields.addOns"
12897
12912
  }, {
12898
12913
  children: [jsxRuntime.jsx(Switch, Object.assign({
12899
- defaultChecked: ((_d = shipment === null || shipment === void 0 ? void 0 : shipment.confirmation) !== null && _d !== void 0 ? _d : "none") !== "none",
12914
+ defaultChecked: ((_e = shipment === null || shipment === void 0 ? void 0 : shipment.confirmation) !== null && _e !== void 0 ? _e : "none") !== "none",
12900
12915
  label: t("purchase-label:fields.confirmation"),
12901
12916
  name: "confirmationEnabled",
12902
12917
  onChange: e => form.setValue("confirmation", e.target.checked ? alchemy.SE.ConfirmationType.DELIVERY : undefined, {
12903
12918
  shouldDirty: true
12904
12919
  }),
12905
12920
  shouldUnmount: true,
12906
- value: ((_e = shipment === null || shipment === void 0 ? void 0 : shipment.confirmation) !== null && _e !== void 0 ? _e : "none") !== "none"
12921
+ value: ((_f = shipment === null || shipment === void 0 ? void 0 : shipment.confirmation) !== null && _f !== void 0 ? _f : "none") !== "none"
12907
12922
  }, {
12908
12923
  children: jsxRuntime.jsx(Select, {
12909
12924
  control: form.control,
@@ -12915,7 +12930,7 @@ const ShipmentForm = ({
12915
12930
  shouldUnregister: true
12916
12931
  })
12917
12932
  })), jsxRuntime.jsxs(Switch, Object.assign({
12918
- defaultChecked: ((_f = shipment === null || shipment === void 0 ? void 0 : shipment.insuranceProvider) !== null && _f !== void 0 ? _f : "none") !== "none",
12933
+ defaultChecked: ((_g = shipment === null || shipment === void 0 ? void 0 : shipment.insuranceProvider) !== null && _g !== void 0 ? _g : "none") !== "none",
12919
12934
  label: t("purchase-label:fields.insurance"),
12920
12935
  name: "insuranceEnabled",
12921
12936
  onChange: e => {
@@ -12925,7 +12940,7 @@ const ShipmentForm = ({
12925
12940
  });
12926
12941
  },
12927
12942
  shouldUnmount: true,
12928
- value: ((_g = shipment === null || shipment === void 0 ? void 0 : shipment.insuranceProvider) !== null && _g !== void 0 ? _g : "none") !== "none"
12943
+ value: ((_h = shipment === null || shipment === void 0 ? void 0 : shipment.insuranceProvider) !== null && _h !== void 0 ? _h : "none") !== "none"
12929
12944
  }, {
12930
12945
  children: [insuranceProviderOptions.length === 1 && insuranceProviderOptions[0].value === "carrier" ? null : jsxRuntime.jsx(Select, {
12931
12946
  control: form.control,
@@ -12949,7 +12964,7 @@ const ShipmentForm = ({
12949
12964
  showCurrencySymbol: true
12950
12965
  })]
12951
12966
  })), hasUps && jsxRuntime.jsx(Switch, {
12952
- defaultChecked: ((_h = shipment === null || shipment === void 0 ? void 0 : shipment.advancedOptions) === null || _h === void 0 ? void 0 : _h.additionalHandling) || false,
12967
+ defaultChecked: ((_j = shipment === null || shipment === void 0 ? void 0 : shipment.advancedOptions) === null || _j === void 0 ? void 0 : _j.additionalHandling) || false,
12953
12968
  label: jsxRuntime.jsx(reactI18next.Trans, {
12954
12969
  components: {
12955
12970
  Link: jsxRuntime.jsx(giger.Link, {
@@ -13783,7 +13798,7 @@ var common = {
13783
13798
  agreement: "Agreement"
13784
13799
  },
13785
13800
  terms: {
13786
- agreeToTerms: "I agree to the <terms>Terms of Service</terms>",
13801
+ agreeToTerms: "I agree to the <terms>Terms of Service<icon/></terms>",
13787
13802
  title: "Terms of Service"
13788
13803
  }
13789
13804
  },
@@ -14687,7 +14702,9 @@ const useAddress = ({
14687
14702
  return updatedShipment;
14688
14703
  }), [handleValidateAddress, onChange, shipment, updateShipment]);
14689
14704
  React.useEffect(() => {
14690
- if (!addressPreference && (shipment === null || shipment === void 0 ? void 0 : shipment.shipTo)) {
14705
+ if (!addressPreference && (shipment === null || shipment === void 0 ? void 0 : shipment.shipTo) &&
14706
+ // without this check it will keep reverting a one-off label's address preference back to empty for some reason
14707
+ !isEmptyAddress(shipment === null || shipment === void 0 ? void 0 : shipment.shipTo)) {
14691
14708
  void handleValidateAddress(shipment === null || shipment === void 0 ? void 0 : shipment.shipTo, salesOrder === null || salesOrder === void 0 ? void 0 : salesOrder.shipTo);
14692
14709
  }
14693
14710
  }, [addressPreference, handleValidateAddress, salesOrder === null || salesOrder === void 0 ? void 0 : salesOrder.shipTo, shipment === null || shipment === void 0 ? void 0 : shipment.shipTo]);
@@ -15473,67 +15490,42 @@ const PurchaseLabelBySalesOrder = _a => {
15473
15490
  }));
15474
15491
  };
15475
15492
 
15476
- let shipmentsCreated = 0;
15477
- const useGetOrCreateShipment = shipmentId => {
15478
- const {
15479
- client
15480
- } = alchemy.useShipEngine();
15481
- const shipmentCreation = React.useMemo(() => {
15482
- return ++shipmentsCreated;
15483
- },
15484
- // eslint-disable-next-line react-hooks/exhaustive-deps
15485
- []);
15486
- return reactQuery.useQuery({
15487
- onError: reactApi.onError,
15488
- queryFn: () => __awaiter(void 0, void 0, void 0, function* () {
15489
- var _a;
15490
- if (shipmentId) {
15491
- return (yield client.salesOrderShipments.get(shipmentId)).data;
15492
- } else {
15493
- const warehouses = (yield client.warehouses.list()).data.warehouses;
15494
- const defaultOrFirstWarehouse = (_a = warehouses.find(warehouse => warehouse.isDefault)) !== null && _a !== void 0 ? _a : warehouses[0];
15495
- if (defaultOrFirstWarehouse === undefined) {
15496
- throw [alchemy.CodedError.fromObject({
15497
- errorCode: "unknown",
15498
- errorSource: "client",
15499
- errorType: "unknown",
15500
- message: "errorMessages.noWarehouses"
15501
- })];
15502
- }
15503
- const shipTo = {
15504
- addressLine1: "",
15505
- cityLocality: "",
15506
- countryCode: "",
15507
- name: "",
15508
- phone: "",
15509
- postalCode: "",
15510
- stateProvince: ""
15511
- };
15512
- const newShipment = yield client.shipments.create({
15513
- shipTo: shipTo,
15514
- warehouseId: defaultOrFirstWarehouse.warehouseId
15515
- });
15516
- return newShipment.data.shipments[0];
15517
- }
15518
- }),
15519
- queryKey: ["useGetOrCreateShipment", shipmentId || `--${shipmentCreation}`],
15520
- retry: shipmentId !== undefined
15521
- });
15493
+ const getDefaultWarehouse = warehouses => {
15494
+ var _a;
15495
+ return (_a = warehouses === null || warehouses === void 0 ? void 0 : warehouses.find(w => w.isDefault)) !== null && _a !== void 0 ? _a : warehouses === null || warehouses === void 0 ? void 0 : warehouses[0];
15522
15496
  };
15523
15497
 
15524
- const useLoadOrCreateShipment = shipmentId => {
15498
+ const useGetOrCreateShipment = shipmentId => {
15499
+ var _a, _b;
15525
15500
  const {
15526
- data: shipment,
15527
- error: loadShipmentErrors,
15528
- refetch: refetchShipment,
15529
- isLoading
15530
- } = useGetOrCreateShipment(shipmentId);
15531
- const errors = [...(loadShipmentErrors !== null && loadShipmentErrors !== void 0 ? loadShipmentErrors : [])];
15501
+ data: warehouses
15502
+ } = alchemy.useListWarehouses({
15503
+ enabled: shipmentId === undefined
15504
+ });
15505
+ const createShipment = alchemy.useCreateShipment();
15506
+ // useCreateShipment as called by this hook will only ever create one shipment at a time,
15507
+ // lens it for convenience
15508
+ const createdShipment = React.useMemo(() => {
15509
+ var _a, _b;
15510
+ return (_b = (_a = createShipment.data) === null || _a === void 0 ? void 0 : _a.shipments) === null || _b === void 0 ? void 0 : _b[0];
15511
+ }, [createShipment.data]);
15512
+ // If no shipmentId passed, trigger create shipment mutation
15513
+ React.useEffect(() => {
15514
+ if (warehouses && shipmentId === undefined && !createShipment.isLoading && !createdShipment) {
15515
+ createShipment.mutate({
15516
+ warehouseId: getDefaultWarehouse(warehouses).warehouseId
15517
+ });
15518
+ }
15519
+ }, [warehouses, shipmentId, createShipment, createdShipment]);
15520
+ const getShipment = alchemy.useGetShipment(shipmentId !== null && shipmentId !== void 0 ? shipmentId : createdShipment === null || createdShipment === void 0 ? void 0 : createdShipment.shipmentId);
15521
+ const errors = [...((_a = getShipment.error) !== null && _a !== void 0 ? _a : []), ...((_b = createShipment.error) !== null && _b !== void 0 ? _b : [])];
15532
15522
  return {
15533
15523
  errors: errors.length > 0 ? errors : undefined,
15534
- isLoading: isLoading,
15535
- refetchShipment,
15536
- shipment
15524
+ isLoading:
15525
+ //bootstrap isLoading to true if one off and create shipment mutation hasn't been triggered yet
15526
+ !createShipment.isError && createShipment.isIdle && shipmentId === undefined || getShipment.isLoading || createShipment.isLoading,
15527
+ refetchShipment: getShipment.refetch,
15528
+ shipment: getShipment.data
15537
15529
  };
15538
15530
  };
15539
15531
 
@@ -15541,36 +15533,26 @@ const PurchaseLabelByShipment = _a => {
15541
15533
  var {
15542
15534
  onLoad,
15543
15535
  onShipmentUpdated,
15544
- features
15536
+ shipmentId
15545
15537
  } = _a,
15546
- props = __rest(_a, ["onLoad", "onShipmentUpdated", "features"]);
15547
- const _b = useLoadOrCreateShipment("shipmentId" in props ? props.shipmentId : undefined),
15538
+ props = __rest(_a, ["onLoad", "onShipmentUpdated", "shipmentId"]);
15539
+ const _b = useGetOrCreateShipment(shipmentId),
15548
15540
  {
15549
15541
  shipment
15550
15542
  } = _b,
15551
15543
  shipmentProps = __rest(_b, ["shipment"]);
15544
+ const handleShipmentUpdated = shipment => {
15545
+ void shipmentProps.refetchShipment();
15546
+ onShipmentUpdated === null || onShipmentUpdated === void 0 ? void 0 : onShipmentUpdated(shipment);
15547
+ };
15552
15548
  return jsxRuntime.jsx(SuspendShipment, Object.assign({
15553
15549
  shipment: shipment
15554
15550
  }, shipmentProps, {
15555
15551
  children: shipment && jsxRuntime.jsx(ConfigureShipment, Object.assign({
15556
15552
  errors: shipmentProps.errors,
15557
- features: features,
15558
15553
  isLoading: shipmentProps.isLoading,
15559
- onAddressValidation: props.onAddressValidation,
15560
- onApplyPreset: props.onApplyPreset,
15561
- onBeforeLabelCreate: props.onBeforeLabelCreate,
15562
- onChangeAddress: props.onChangeAddress,
15563
- onChangeShipmentFormMode: props.onChangeShipmentFormMode,
15564
- onLabelCreateFailure: props.onLabelCreateFailure,
15565
- onLabelCreateSuccess: props.onLabelCreateSuccess,
15566
- onRateSaved: props.onRateSaved,
15567
- onRatesCalculated: props.onRatesCalculated,
15568
- onShipmentUpdated: onShipmentUpdated,
15569
- onToggleAddressPreferenceDisclosure: props.onToggleAddressPreferenceDisclosure,
15570
- printLabelLayout: props.printLabelLayout,
15571
- shipment: shipment,
15572
- shippingPresets: props.shippingPresets,
15573
- warehouseId: props.warehouseId
15554
+ onShipmentUpdated: handleShipmentUpdated,
15555
+ shipment: shipment
15574
15556
  }, props))
15575
15557
  }));
15576
15558
  };
@@ -15899,6 +15881,7 @@ exports.getRequestedServices = getRequestedServices;
15899
15881
  exports.getSalesOrderItemsFromSalesOrderOrShipment = getSalesOrderItemsFromSalesOrderOrShipment;
15900
15882
  exports.getTotalRateAmount = getTotalRateAmount;
15901
15883
  exports.isDomesticAddress = isDomesticAddress;
15884
+ exports.isEmptyAddress = isEmptyAddress;
15902
15885
  exports.isFlatRatePackageCode = isFlatRatePackageCode;
15903
15886
  exports.isMilitaryAddress = isMilitaryAddress;
15904
15887
  exports.isNowOrInTheFuture = isNowOrInTheFuture;
package/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { jsx, jsxs, Fragment } from '@emotion/react/jsx-runtime';
2
2
  import { useController, get as get$1, set as set$2, useWatch, useFormState, useForm } from 'react-hook-form';
3
3
  import { useTranslation, Trans } from 'react-i18next';
4
- import { Typography, FormField, FieldMessageType, Checkbox, Input, Icon, Divider, Link, SelectAutocomplete, Select as Select$1, OptionGroup, Option, Button, Switch as Switch$1, Textarea, ButtonVariant, InlineNotification, NotificationType, ButtonColor, Grid, GridChild, Tag, TagColor, ButtonSize, Spinner, IconSize, Skeleton, SkeletonAnimation, SkeletonVariant, SkeletonBackgroundColor, RadioGroup, Radio, Stepper, Step, SpinnerSize, ChipList, Chip, Table, TableBody, TableBaseRow, TableBodyCell, TableHeader, TableHeaderCell, Popover, DropdownOptionList, DatePicker as DatePicker$1, BottomSheet } from '@packlink/giger';
4
+ import { Typography, FormField, FieldMessageType, Checkbox, Input, Icon, Divider, Link, SelectAutocomplete, Select as Select$1, OptionGroup, Option, Button, Switch as Switch$1, Textarea, ButtonVariant, InlineNotification, NotificationType, ButtonColor, Grid, GridChild, Tag, TagColor, IconSize, ButtonSize, Spinner, Skeleton, SkeletonAnimation, SkeletonVariant, SkeletonBackgroundColor, RadioGroup, Radio, Stepper, Step, SpinnerSize, ChipList, Chip, Table, TableBody, TableBaseRow, TableBodyCell, TableHeader, TableHeaderCell, Popover, DropdownOptionList, DatePicker as DatePicker$1, BottomSheet } from '@packlink/giger';
5
5
  import axios from 'axios';
6
- import alchemy, { logger, SE, useValidateAddresses, useAddFunds, useGetCarrierById, useGetAccountSettings, useUpdateAccountSettings, useUpdateAutoFunding, useGetAutoFundingConfiguration, Currency, useListCarriers, useConnectCarrier, useListWarehouses, useUpdateWarehouse, useCreateWarehouse, useDeleteWarehouse, useUpdateSalesOrderShipment, useParseAddress, useListCustomPackageTypes, useCalculateRates, useGetShipmentRates, useListLabels, useCreateLabel, useListSalesOrderShipments, useCreateSalesOrderShipment, useListSalesOrders, useGetSalesOrder, useListOrderSources, useRefreshOrderSource, useShipEngine, CodedError, useGetSalesOrderShipment, useGetLabel, useVoidLabel } from '@shipengine/alchemy';
6
+ import alchemy, { logger, SE, useValidateAddresses, useAddFunds, useGetCarrierById, useGetAccountSettings, useUpdateAccountSettings, useUpdateAutoFunding, useGetAutoFundingConfiguration, Currency, useListCarriers, useConnectCarrier, useListWarehouses, useUpdateWarehouse, useCreateWarehouse, useDeleteWarehouse, useUpdateSalesOrderShipment, useParseAddress, useListCustomPackageTypes, useCalculateRates, useGetShipmentRates, useListLabels, useCreateLabel, useListSalesOrderShipments, useCreateSalesOrderShipment, useListSalesOrders, useGetSalesOrder, useListOrderSources, useRefreshOrderSource, useCreateShipment, useGetShipment, useGetSalesOrderShipment, useGetLabel, useVoidLabel } from '@shipengine/alchemy';
7
7
  import { zodResolver } from '@hookform/resolvers/zod';
8
8
  import { z } from 'zod';
9
9
  import * as React from 'react';
@@ -21,9 +21,8 @@ import { isValidPhoneNumber } from 'libphonenumber-js/min';
21
21
  import copy from 'copy-to-clipboard';
22
22
  import { encode } from 'js-base64';
23
23
  import cardValidator from 'card-validator';
24
- import { useQueryClient, useQuery } from 'react-query';
24
+ import { useQueryClient } from 'react-query';
25
25
  import { IconNames as IconNames$1 } from '@packlink/brands';
26
- import { onError } from '@shipengine/react-api';
27
26
 
28
27
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
29
28
 
@@ -2596,6 +2595,27 @@ const overrideCarrierCodes$1 = (carrier, overrides) => {
2596
2595
  return overrides[carrier] || carrier;
2597
2596
  };
2598
2597
 
2598
+ var $$f = _export;
2599
+ var $includes = arrayIncludes.includes;
2600
+ var fails$7 = fails$q;
2601
+ var addToUnscopables$1 = addToUnscopables$3;
2602
+
2603
+ // FF99+ bug
2604
+ var BROKEN_ON_SPARSE = fails$7(function () {
2605
+ return !Array(1).includes();
2606
+ });
2607
+
2608
+ // `Array.prototype.includes` method
2609
+ // https://tc39.es/ecma262/#sec-array.prototype.includes
2610
+ $$f({ target: 'Array', proto: true, forced: BROKEN_ON_SPARSE }, {
2611
+ includes: function includes(el /* , fromIndex = 0 */) {
2612
+ return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
2613
+ }
2614
+ });
2615
+
2616
+ // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
2617
+ addToUnscopables$1('includes');
2618
+
2599
2619
  // Declaring these flags to allow shorthand object syntax, i.e. { flagName } instead of { flagName: true }
2600
2620
  const hasEuCustomsRules = true,
2601
2621
  hasProvinces = true,
@@ -2835,27 +2855,9 @@ const isPoBox = addressLine => PO_BOX_REGEX.test(addressLine);
2835
2855
  * @category Utilities
2836
2856
  */
2837
2857
  const isPoBoxAddress = address => !!(isPoBox(address.addressLine1) || address.addressLine2 && isPoBox(address.addressLine2));
2838
-
2839
- var $$f = _export;
2840
- var $includes = arrayIncludes.includes;
2841
- var fails$7 = fails$q;
2842
- var addToUnscopables$1 = addToUnscopables$3;
2843
-
2844
- // FF99+ bug
2845
- var BROKEN_ON_SPARSE = fails$7(function () {
2846
- return !Array(1).includes();
2847
- });
2848
-
2849
- // `Array.prototype.includes` method
2850
- // https://tc39.es/ecma262/#sec-array.prototype.includes
2851
- $$f({ target: 'Array', proto: true, forced: BROKEN_ON_SPARSE }, {
2852
- includes: function includes(el /* , fromIndex = 0 */) {
2853
- return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
2854
- }
2855
- });
2856
-
2857
- // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
2858
- addToUnscopables$1('includes');
2858
+ const isEmptyAddress = address => {
2859
+ return !address || Object.entries(address).every(([key, value]) => key === "countryCode" || [null, "", "unknown"].includes(value));
2860
+ };
2859
2861
 
2860
2862
  const USPS_CARRIER_CODES = ["usps", "stamps_com"];
2861
2863
  const isUspsCarrier = carrierCode => USPS_CARRIER_CODES.includes(carrierCode);
@@ -4769,11 +4771,15 @@ const CostBreakdown = ({
4769
4771
  children: [jsx("td", Object.assign({
4770
4772
  css: getTableCellLabelStyles
4771
4773
  }, {
4772
- children: priceItem.label
4774
+ children: jsx(Typography, {
4775
+ children: priceItem.label
4776
+ })
4773
4777
  })), jsx("td", Object.assign({
4774
4778
  "data-testid": priceItem.label.toLowerCase()
4775
4779
  }, {
4776
- children: formatMoney(priceItem.value)
4780
+ children: jsx(Typography, {
4781
+ children: formatMoney(priceItem.value)
4782
+ })
4777
4783
  }))]
4778
4784
  }, index + priceItem.value.amount))
4779
4785
  })
@@ -6528,6 +6534,10 @@ const styles$n = createStyles({
6528
6534
  display: "flex",
6529
6535
  flexDirection: "column"
6530
6536
  },
6537
+ icon: theme => ({
6538
+ padding: `${theme.spacing(0.4)}px 0 0 ${theme.spacing(0.5)}px`,
6539
+ position: "absolute"
6540
+ }),
6531
6541
  link: {
6532
6542
  border: "none"
6533
6543
  },
@@ -7223,6 +7233,11 @@ const CarrierTermsForm = ({
7223
7233
  children: jsx(CheckboxInput, {
7224
7234
  checkboxLabel: jsx(Trans, {
7225
7235
  components: {
7236
+ icon: jsx(Icon, {
7237
+ css: styles$n.icon,
7238
+ name: showTerms ? IconNames.CHEVRON_TOP : IconNames.CHEVRON_BOTTOM,
7239
+ size: IconSize.SIZE_SMALL
7240
+ }),
7226
7241
  terms: jsx(Link, {
7227
7242
  css: theme => ({
7228
7243
  fontWeight: theme.typography.fontWeight.normal
@@ -12234,7 +12249,7 @@ const ShipmentForm = ({
12234
12249
  warehouseId,
12235
12250
  warehouses
12236
12251
  }) => {
12237
- var _a, _b, _c, _d, _e, _f, _g, _h;
12252
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
12238
12253
  features = Object.assign({
12239
12254
  browseRates: true,
12240
12255
  includeShipsuranceInsurance: true,
@@ -12412,16 +12427,16 @@ const ShipmentForm = ({
12412
12427
  }, [form]);
12413
12428
  const handleSubmit = form.handleSubmit(values => __awaiter(void 0, void 0, void 0, function* () {
12414
12429
  try {
12415
- const _j = values,
12430
+ const _k = values,
12416
12431
  {
12417
12432
  __mode: discard
12418
- } = _j,
12419
- payload = __rest(_j, ["__mode"]);
12433
+ } = _k,
12434
+ payload = __rest(_k, ["__mode"]);
12420
12435
  const updatedShipment = yield onSubmit(Object.assign(Object.assign({}, shipment || {}), payload));
12421
12436
  // Defer shipment hydration to the task queue so that the submission promise resolves first, otherwise the
12422
12437
  // submission count will increment after hydration resets the form, keeping it in revalidate mode
12423
12438
  if (updatedShipment) setTimeout(() => hydrateShipment(updatedShipment), 0);
12424
- } catch (_k) {
12439
+ } catch (_l) {
12425
12440
  // Reset the form to its current state, but as a side effect this sets isDirty to false
12426
12441
  // That way, form lifecycle contract is upheld
12427
12442
  form.reset(form.getValues());
@@ -12504,7 +12519,7 @@ const ShipmentForm = ({
12504
12519
  }
12505
12520
  }), [form, onChangeAddress, shipment]);
12506
12521
  const [editShipToForm, isEditShipFormToOpen, toggleIsEditShipFormToOpen] = useNestedForm(AddressForm, {
12507
- address: (_a = shipment === null || shipment === void 0 ? void 0 : shipment.shipTo) !== null && _a !== void 0 ? _a : salesOrder === null || salesOrder === void 0 ? void 0 : salesOrder.shipTo,
12522
+ address: (_b = (_a = addressPreference === null || addressPreference === void 0 ? void 0 : addressPreference.selection) !== null && _a !== void 0 ? _a : shipment === null || shipment === void 0 ? void 0 : shipment.shipTo) !== null && _b !== void 0 ? _b : salesOrder === null || salesOrder === void 0 ? void 0 : salesOrder.shipTo,
12508
12523
  formId: "edit-ship-to-form",
12509
12524
  onSubmit: handleSubmitEditShipTo,
12510
12525
  onSubmitParse: onSubmitParseShipTo
@@ -12554,7 +12569,7 @@ const ShipmentForm = ({
12554
12569
  });
12555
12570
  if (errors) throw new Error(errors.map(e => e.message).join(", "));
12556
12571
  if (!shipment) throw new Error("errorMessages.unableToLoad.shipment");
12557
- const isEmptyShipTo = Object.entries(shipment.shipTo).every(([key, value]) => key === "countryCode" || [null, "", "unknown"].includes(value));
12572
+ const addressPreferenceIsEmpty = isEmptyAddress(addressPreference === null || addressPreference === void 0 ? void 0 : addressPreference.selection);
12558
12573
  return jsxs("form", Object.assign({
12559
12574
  id: "shipment-form",
12560
12575
  onSubmit: formLogger.capture(handleSubmit)
@@ -12578,7 +12593,7 @@ const ShipmentForm = ({
12578
12593
  }), jsx(FieldLabel, Object.assign({
12579
12594
  label: !isEditShipFormToOpen ? "purchase-label:fields.shipTo" : ""
12580
12595
  }, {
12581
- children: !isEditShipFormToOpen && (isEmptyShipTo ? jsx(Button, Object.assign({
12596
+ children: !isEditShipFormToOpen && (addressPreferenceIsEmpty ? jsx(Button, Object.assign({
12582
12597
  onClick: toggleIsEditShipFormToOpen,
12583
12598
  variant: ButtonVariant.OUTLINED
12584
12599
  }, {
@@ -12622,7 +12637,7 @@ const ShipmentForm = ({
12622
12637
  }, {
12623
12638
  children: formatDate(salesOrder.orderDate)
12624
12639
  })), jsx(Spacer, {})]
12625
- })), ((_b = salesOrder === null || salesOrder === void 0 ? void 0 : salesOrder.paymentDetails) === null || _b === void 0 ? void 0 : _b.grandTotal) && jsxs(FieldLabel, Object.assign({
12640
+ })), ((_c = salesOrder === null || salesOrder === void 0 ? void 0 : salesOrder.paymentDetails) === null || _c === void 0 ? void 0 : _c.grandTotal) && jsxs(FieldLabel, Object.assign({
12626
12641
  label: t("purchase-label:fields.orderValue")
12627
12642
  }, {
12628
12643
  children: [jsx(Typography, Object.assign({
@@ -12700,7 +12715,7 @@ const ShipmentForm = ({
12700
12715
  }), jsx(CustomsItemsDisplay, {
12701
12716
  onUpdate: handleUpdateCustomsItems,
12702
12717
  shipment: shipment
12703
- }), ((_c = customsErrors === null || customsErrors === void 0 ? void 0 : customsErrors.customsItems) === null || _c === void 0 ? void 0 : _c.type) === "too_small" && jsxs(Fragment, {
12718
+ }), ((_d = customsErrors === null || customsErrors === void 0 ? void 0 : customsErrors.customsItems) === null || _d === void 0 ? void 0 : _d.type) === "too_small" && jsxs(Fragment, {
12704
12719
  children: [jsx(Spacer, {}), jsx(InlineNotification, {
12705
12720
  title: t("purchase-label:errorMessages.customsItemsRequired"),
12706
12721
  type: NotificationType.ERROR
@@ -12864,14 +12879,14 @@ const ShipmentForm = ({
12864
12879
  label: "purchase-label:fields.addOns"
12865
12880
  }, {
12866
12881
  children: [jsx(Switch, Object.assign({
12867
- defaultChecked: ((_d = shipment === null || shipment === void 0 ? void 0 : shipment.confirmation) !== null && _d !== void 0 ? _d : "none") !== "none",
12882
+ defaultChecked: ((_e = shipment === null || shipment === void 0 ? void 0 : shipment.confirmation) !== null && _e !== void 0 ? _e : "none") !== "none",
12868
12883
  label: t("purchase-label:fields.confirmation"),
12869
12884
  name: "confirmationEnabled",
12870
12885
  onChange: e => form.setValue("confirmation", e.target.checked ? SE.ConfirmationType.DELIVERY : undefined, {
12871
12886
  shouldDirty: true
12872
12887
  }),
12873
12888
  shouldUnmount: true,
12874
- value: ((_e = shipment === null || shipment === void 0 ? void 0 : shipment.confirmation) !== null && _e !== void 0 ? _e : "none") !== "none"
12889
+ value: ((_f = shipment === null || shipment === void 0 ? void 0 : shipment.confirmation) !== null && _f !== void 0 ? _f : "none") !== "none"
12875
12890
  }, {
12876
12891
  children: jsx(Select, {
12877
12892
  control: form.control,
@@ -12883,7 +12898,7 @@ const ShipmentForm = ({
12883
12898
  shouldUnregister: true
12884
12899
  })
12885
12900
  })), jsxs(Switch, Object.assign({
12886
- defaultChecked: ((_f = shipment === null || shipment === void 0 ? void 0 : shipment.insuranceProvider) !== null && _f !== void 0 ? _f : "none") !== "none",
12901
+ defaultChecked: ((_g = shipment === null || shipment === void 0 ? void 0 : shipment.insuranceProvider) !== null && _g !== void 0 ? _g : "none") !== "none",
12887
12902
  label: t("purchase-label:fields.insurance"),
12888
12903
  name: "insuranceEnabled",
12889
12904
  onChange: e => {
@@ -12893,7 +12908,7 @@ const ShipmentForm = ({
12893
12908
  });
12894
12909
  },
12895
12910
  shouldUnmount: true,
12896
- value: ((_g = shipment === null || shipment === void 0 ? void 0 : shipment.insuranceProvider) !== null && _g !== void 0 ? _g : "none") !== "none"
12911
+ value: ((_h = shipment === null || shipment === void 0 ? void 0 : shipment.insuranceProvider) !== null && _h !== void 0 ? _h : "none") !== "none"
12897
12912
  }, {
12898
12913
  children: [insuranceProviderOptions.length === 1 && insuranceProviderOptions[0].value === "carrier" ? null : jsx(Select, {
12899
12914
  control: form.control,
@@ -12917,7 +12932,7 @@ const ShipmentForm = ({
12917
12932
  showCurrencySymbol: true
12918
12933
  })]
12919
12934
  })), hasUps && jsx(Switch, {
12920
- defaultChecked: ((_h = shipment === null || shipment === void 0 ? void 0 : shipment.advancedOptions) === null || _h === void 0 ? void 0 : _h.additionalHandling) || false,
12935
+ defaultChecked: ((_j = shipment === null || shipment === void 0 ? void 0 : shipment.advancedOptions) === null || _j === void 0 ? void 0 : _j.additionalHandling) || false,
12921
12936
  label: jsx(Trans, {
12922
12937
  components: {
12923
12938
  Link: jsx(Link, {
@@ -13751,7 +13766,7 @@ var common = {
13751
13766
  agreement: "Agreement"
13752
13767
  },
13753
13768
  terms: {
13754
- agreeToTerms: "I agree to the <terms>Terms of Service</terms>",
13769
+ agreeToTerms: "I agree to the <terms>Terms of Service<icon/></terms>",
13755
13770
  title: "Terms of Service"
13756
13771
  }
13757
13772
  },
@@ -14655,7 +14670,9 @@ const useAddress = ({
14655
14670
  return updatedShipment;
14656
14671
  }), [handleValidateAddress, onChange, shipment, updateShipment]);
14657
14672
  useEffect(() => {
14658
- if (!addressPreference && (shipment === null || shipment === void 0 ? void 0 : shipment.shipTo)) {
14673
+ if (!addressPreference && (shipment === null || shipment === void 0 ? void 0 : shipment.shipTo) &&
14674
+ // without this check it will keep reverting a one-off label's address preference back to empty for some reason
14675
+ !isEmptyAddress(shipment === null || shipment === void 0 ? void 0 : shipment.shipTo)) {
14659
14676
  void handleValidateAddress(shipment === null || shipment === void 0 ? void 0 : shipment.shipTo, salesOrder === null || salesOrder === void 0 ? void 0 : salesOrder.shipTo);
14660
14677
  }
14661
14678
  }, [addressPreference, handleValidateAddress, salesOrder === null || salesOrder === void 0 ? void 0 : salesOrder.shipTo, shipment === null || shipment === void 0 ? void 0 : shipment.shipTo]);
@@ -15441,67 +15458,42 @@ const PurchaseLabelBySalesOrder = _a => {
15441
15458
  }));
15442
15459
  };
15443
15460
 
15444
- let shipmentsCreated = 0;
15445
- const useGetOrCreateShipment = shipmentId => {
15446
- const {
15447
- client
15448
- } = useShipEngine();
15449
- const shipmentCreation = useMemo(() => {
15450
- return ++shipmentsCreated;
15451
- },
15452
- // eslint-disable-next-line react-hooks/exhaustive-deps
15453
- []);
15454
- return useQuery({
15455
- onError,
15456
- queryFn: () => __awaiter(void 0, void 0, void 0, function* () {
15457
- var _a;
15458
- if (shipmentId) {
15459
- return (yield client.salesOrderShipments.get(shipmentId)).data;
15460
- } else {
15461
- const warehouses = (yield client.warehouses.list()).data.warehouses;
15462
- const defaultOrFirstWarehouse = (_a = warehouses.find(warehouse => warehouse.isDefault)) !== null && _a !== void 0 ? _a : warehouses[0];
15463
- if (defaultOrFirstWarehouse === undefined) {
15464
- throw [CodedError.fromObject({
15465
- errorCode: "unknown",
15466
- errorSource: "client",
15467
- errorType: "unknown",
15468
- message: "errorMessages.noWarehouses"
15469
- })];
15470
- }
15471
- const shipTo = {
15472
- addressLine1: "",
15473
- cityLocality: "",
15474
- countryCode: "",
15475
- name: "",
15476
- phone: "",
15477
- postalCode: "",
15478
- stateProvince: ""
15479
- };
15480
- const newShipment = yield client.shipments.create({
15481
- shipTo: shipTo,
15482
- warehouseId: defaultOrFirstWarehouse.warehouseId
15483
- });
15484
- return newShipment.data.shipments[0];
15485
- }
15486
- }),
15487
- queryKey: ["useGetOrCreateShipment", shipmentId || `--${shipmentCreation}`],
15488
- retry: shipmentId !== undefined
15489
- });
15461
+ const getDefaultWarehouse = warehouses => {
15462
+ var _a;
15463
+ return (_a = warehouses === null || warehouses === void 0 ? void 0 : warehouses.find(w => w.isDefault)) !== null && _a !== void 0 ? _a : warehouses === null || warehouses === void 0 ? void 0 : warehouses[0];
15490
15464
  };
15491
15465
 
15492
- const useLoadOrCreateShipment = shipmentId => {
15466
+ const useGetOrCreateShipment = shipmentId => {
15467
+ var _a, _b;
15493
15468
  const {
15494
- data: shipment,
15495
- error: loadShipmentErrors,
15496
- refetch: refetchShipment,
15497
- isLoading
15498
- } = useGetOrCreateShipment(shipmentId);
15499
- const errors = [...(loadShipmentErrors !== null && loadShipmentErrors !== void 0 ? loadShipmentErrors : [])];
15469
+ data: warehouses
15470
+ } = useListWarehouses({
15471
+ enabled: shipmentId === undefined
15472
+ });
15473
+ const createShipment = useCreateShipment();
15474
+ // useCreateShipment as called by this hook will only ever create one shipment at a time,
15475
+ // lens it for convenience
15476
+ const createdShipment = useMemo(() => {
15477
+ var _a, _b;
15478
+ return (_b = (_a = createShipment.data) === null || _a === void 0 ? void 0 : _a.shipments) === null || _b === void 0 ? void 0 : _b[0];
15479
+ }, [createShipment.data]);
15480
+ // If no shipmentId passed, trigger create shipment mutation
15481
+ useEffect(() => {
15482
+ if (warehouses && shipmentId === undefined && !createShipment.isLoading && !createdShipment) {
15483
+ createShipment.mutate({
15484
+ warehouseId: getDefaultWarehouse(warehouses).warehouseId
15485
+ });
15486
+ }
15487
+ }, [warehouses, shipmentId, createShipment, createdShipment]);
15488
+ const getShipment = useGetShipment(shipmentId !== null && shipmentId !== void 0 ? shipmentId : createdShipment === null || createdShipment === void 0 ? void 0 : createdShipment.shipmentId);
15489
+ const errors = [...((_a = getShipment.error) !== null && _a !== void 0 ? _a : []), ...((_b = createShipment.error) !== null && _b !== void 0 ? _b : [])];
15500
15490
  return {
15501
15491
  errors: errors.length > 0 ? errors : undefined,
15502
- isLoading: isLoading,
15503
- refetchShipment,
15504
- shipment
15492
+ isLoading:
15493
+ //bootstrap isLoading to true if one off and create shipment mutation hasn't been triggered yet
15494
+ !createShipment.isError && createShipment.isIdle && shipmentId === undefined || getShipment.isLoading || createShipment.isLoading,
15495
+ refetchShipment: getShipment.refetch,
15496
+ shipment: getShipment.data
15505
15497
  };
15506
15498
  };
15507
15499
 
@@ -15509,36 +15501,26 @@ const PurchaseLabelByShipment = _a => {
15509
15501
  var {
15510
15502
  onLoad,
15511
15503
  onShipmentUpdated,
15512
- features
15504
+ shipmentId
15513
15505
  } = _a,
15514
- props = __rest(_a, ["onLoad", "onShipmentUpdated", "features"]);
15515
- const _b = useLoadOrCreateShipment("shipmentId" in props ? props.shipmentId : undefined),
15506
+ props = __rest(_a, ["onLoad", "onShipmentUpdated", "shipmentId"]);
15507
+ const _b = useGetOrCreateShipment(shipmentId),
15516
15508
  {
15517
15509
  shipment
15518
15510
  } = _b,
15519
15511
  shipmentProps = __rest(_b, ["shipment"]);
15512
+ const handleShipmentUpdated = shipment => {
15513
+ void shipmentProps.refetchShipment();
15514
+ onShipmentUpdated === null || onShipmentUpdated === void 0 ? void 0 : onShipmentUpdated(shipment);
15515
+ };
15520
15516
  return jsx(SuspendShipment, Object.assign({
15521
15517
  shipment: shipment
15522
15518
  }, shipmentProps, {
15523
15519
  children: shipment && jsx(ConfigureShipment, Object.assign({
15524
15520
  errors: shipmentProps.errors,
15525
- features: features,
15526
15521
  isLoading: shipmentProps.isLoading,
15527
- onAddressValidation: props.onAddressValidation,
15528
- onApplyPreset: props.onApplyPreset,
15529
- onBeforeLabelCreate: props.onBeforeLabelCreate,
15530
- onChangeAddress: props.onChangeAddress,
15531
- onChangeShipmentFormMode: props.onChangeShipmentFormMode,
15532
- onLabelCreateFailure: props.onLabelCreateFailure,
15533
- onLabelCreateSuccess: props.onLabelCreateSuccess,
15534
- onRateSaved: props.onRateSaved,
15535
- onRatesCalculated: props.onRatesCalculated,
15536
- onShipmentUpdated: onShipmentUpdated,
15537
- onToggleAddressPreferenceDisclosure: props.onToggleAddressPreferenceDisclosure,
15538
- printLabelLayout: props.printLabelLayout,
15539
- shipment: shipment,
15540
- shippingPresets: props.shippingPresets,
15541
- warehouseId: props.warehouseId
15522
+ onShipmentUpdated: handleShipmentUpdated,
15523
+ shipment: shipment
15542
15524
  }, props))
15543
15525
  }));
15544
15526
  };
@@ -15796,4 +15778,4 @@ var voidLabel = /*#__PURE__*/Object.freeze({
15796
15778
  Element: Element
15797
15779
  });
15798
15780
 
15799
- export { AddFundsForm, AutoFundingForm, ButtonGroup, CarrierBalance, CopyButton, Country, Cube, DateRangeCombo, DateRangeSelect, ErrorFallback, fields as Field, FieldLabel, FormPortal, FundAndPurchase, InlineLabel, ItemsBreakdown, LinkAction, listCarriers as ListCarriers, Loader, ManageFunding, manageWarehouses as ManageWarehouses, onboarding as Onboarding, PageLayoutProvider, Portal, PoweredByShipEngine, purchaseLabel as PurchaseLabel, RootPortalProvider, Section, Spacer, Spread, StoryNotes, index as Templates, UsState, UsaCity, viewShipment as ViewShipment, voidLabel as VoidLabel, autoFundingSchema, calculateTotal, capitalizeFirstLetter, convertDimensions, convertWeight, countries, countryCodes, createCodedErrors, createDictionary, createStyles, currencySymbol, daysAfter, errorMap, euCountryCodes, extendZod, formLogger, formatCreditCardNumber, formatDate, formatDateDDMMYY, formatExpiration, formatFractionalWeight, formatMoney, getAddFundsSchema, getCustomsFromSalesOrder, getExpirationYears, getIsCustomsRequiredForSalesOrder, getIsCustomsRequiredForShipment, getIsInternationalShipment, getPendingShipment, getRateRequiresAcknowledgement, getRelativeDates, getRequestedServices, getSalesOrderItemsFromSalesOrderOrShipment, getTotalRateAmount, isDomesticAddress, isFlatRatePackageCode, isMilitaryAddress, isNowOrInTheFuture, isPoBox, isPoBoxAddress, isString, isUnitedStatesTerritory, isUnsupportedByUps, isUpsCarrier, isUspsCarrier, moneySchema, mostRecent, nextDayCutoff, omitTime, overrideCarrierCodes$1 as overrideCarrierCodes, phoneSchema, phoneSchemaUnvalidated, postalCodeRegex$3 as postalCodeRegex, sortByCreationDate, throwAny, throwJoinedMessages, usCities, usStateCodes, usStates, useAddressValidation, useCarrierMetadata, useConfirmationOptions, useCountryCodeOptions, useCustomsContentsOptions, useCustomsNonDeliveryOptions, useDateRangeOptions, useExpirationMonthOptions, useInsuranceProviderOptions, useNestedForm, usePackageOptions, usePageLayout, useRateOptions, useRootPortal, useRunOnceOnTrue, useServiceCodeOptions, useShipmentMetadata, useShippingPresetsOptions, useStateCodeOptions, useToggle, useWarehouseOptions, validationResolver };
15781
+ export { AddFundsForm, AutoFundingForm, ButtonGroup, CarrierBalance, CopyButton, Country, Cube, DateRangeCombo, DateRangeSelect, ErrorFallback, fields as Field, FieldLabel, FormPortal, FundAndPurchase, InlineLabel, ItemsBreakdown, LinkAction, listCarriers as ListCarriers, Loader, ManageFunding, manageWarehouses as ManageWarehouses, onboarding as Onboarding, PageLayoutProvider, Portal, PoweredByShipEngine, purchaseLabel as PurchaseLabel, RootPortalProvider, Section, Spacer, Spread, StoryNotes, index as Templates, UsState, UsaCity, viewShipment as ViewShipment, voidLabel as VoidLabel, autoFundingSchema, calculateTotal, capitalizeFirstLetter, convertDimensions, convertWeight, countries, countryCodes, createCodedErrors, createDictionary, createStyles, currencySymbol, daysAfter, errorMap, euCountryCodes, extendZod, formLogger, formatCreditCardNumber, formatDate, formatDateDDMMYY, formatExpiration, formatFractionalWeight, formatMoney, getAddFundsSchema, getCustomsFromSalesOrder, getExpirationYears, getIsCustomsRequiredForSalesOrder, getIsCustomsRequiredForShipment, getIsInternationalShipment, getPendingShipment, getRateRequiresAcknowledgement, getRelativeDates, getRequestedServices, getSalesOrderItemsFromSalesOrderOrShipment, getTotalRateAmount, isDomesticAddress, isEmptyAddress, isFlatRatePackageCode, isMilitaryAddress, isNowOrInTheFuture, isPoBox, isPoBoxAddress, isString, isUnitedStatesTerritory, isUnsupportedByUps, isUpsCarrier, isUspsCarrier, moneySchema, mostRecent, nextDayCutoff, omitTime, overrideCarrierCodes$1 as overrideCarrierCodes, phoneSchema, phoneSchemaUnvalidated, postalCodeRegex$3 as postalCodeRegex, sortByCreationDate, throwAny, throwJoinedMessages, usCities, usStateCodes, usStates, useAddressValidation, useCarrierMetadata, useConfirmationOptions, useCountryCodeOptions, useCustomsContentsOptions, useCustomsNonDeliveryOptions, useDateRangeOptions, useExpirationMonthOptions, useInsuranceProviderOptions, useNestedForm, usePackageOptions, usePageLayout, useRateOptions, useRootPortal, useRunOnceOnTrue, useServiceCodeOptions, useShipmentMetadata, useShippingPresetsOptions, useStateCodeOptions, useToggle, useWarehouseOptions, validationResolver };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shipengine/elements",
3
- "version": "0.26.4",
3
+ "version": "0.26.6",
4
4
  "typedoc": {
5
5
  "entryPoint": "./src/index.ts",
6
6
  "readmeFile": "../../README.md",
@@ -30,9 +30,8 @@
30
30
  "@jest/globals": "28.1.3",
31
31
  "@packlink/brands": "3.24.0",
32
32
  "@packlink/giger-theme": "1.3.1",
33
- "@shipengine/alchemy": "0.4.18",
34
- "@shipengine/js-api": "0.10.0",
35
- "@shipengine/react-api": "0.5.6",
33
+ "@shipengine/alchemy": "0.4.24",
34
+ "@shipengine/js-api": "0.13.1",
36
35
  "@storybook/addons": "6.5.16",
37
36
  "@storybook/components": "7.0.0-rc.1",
38
37
  "@storybook/core-events": "7.0.0-rc.1",
@@ -18,6 +18,10 @@ export declare const styles: {
18
18
  display: "flex";
19
19
  flexDirection: "column";
20
20
  };
21
+ icon: (theme: import("@packlink/giger-theme/dist/lib/Theme").Theme) => {
22
+ padding: string;
23
+ position: "absolute";
24
+ };
21
25
  link: {
22
26
  border: string;
23
27
  };
@@ -1,26 +1,9 @@
1
- import { UseShippingPresetsOptionsProps } from "../../hooks";
2
- import { ConfigureShipmentProps } from "../configure-shipment";
3
- import { UseConfigureShipmentProps, UseImportSalesOrderProps } from "./hooks";
4
- export type SalesOrderProps = {
1
+ import { UseImportSalesOrderProps } from "./hooks";
2
+ import { PurchaseLabelCommonProps } from "./purchase-label";
3
+ export type PurchaseLabelSalesOrderProps = PurchaseLabelCommonProps & {
5
4
  externalOrderId?: UseImportSalesOrderProps["externalOrderId"];
6
5
  externalOrderNumber?: UseImportSalesOrderProps["externalOrderNumber"];
7
- features?: ConfigureShipmentProps["features"];
8
- onAddressValidation?: ConfigureShipmentProps["onAddressValidation"];
9
- onApplyPreset?: ConfigureShipmentProps["onApplyPreset"];
10
- onBeforeLabelCreate?: ConfigureShipmentProps["onBeforeLabelCreate"];
11
- onChangeAddress?: ConfigureShipmentProps["onChangeAddress"];
12
- onChangeShipmentFormMode?: ConfigureShipmentProps["onChangeShipmentFormMode"];
13
- onLabelCreateFailure?: ConfigureShipmentProps["onLabelCreateFailure"];
14
- onLabelCreateSuccess?: ConfigureShipmentProps["onLabelCreateSuccess"];
15
- onLoad?: UseConfigureShipmentProps["onLoad"];
16
- onRateSaved?: ConfigureShipmentProps["onRateSaved"];
17
- onRatesCalculated?: ConfigureShipmentProps["onRatesCalculated"];
18
- onShipmentUpdated?: ConfigureShipmentProps["onShipmentUpdated"];
19
- onToggleAddressPreferenceDisclosure?: ConfigureShipmentProps["onToggleAddressPreferenceDisclosure"];
20
6
  orderSourceCode?: UseImportSalesOrderProps["orderSourceCode"];
21
- printLabelLayout?: ConfigureShipmentProps["printLabelLayout"];
22
7
  salesOrderId?: UseImportSalesOrderProps["salesOrderId"];
23
- shippingPresets?: UseShippingPresetsOptionsProps;
24
- warehouseId?: UseConfigureShipmentProps["warehouseId"];
25
8
  };
26
- export declare const PurchaseLabelBySalesOrder: ({ features, externalOrderId, externalOrderNumber, onLoad, onShipmentUpdated, orderSourceCode, salesOrderId, warehouseId, printLabelLayout, ...props }: SalesOrderProps) => import("@emotion/react/jsx-runtime").JSX.Element;
9
+ export declare const PurchaseLabelBySalesOrder: ({ features, externalOrderId, externalOrderNumber, onLoad, onShipmentUpdated, orderSourceCode, salesOrderId, warehouseId, printLabelLayout, ...props }: PurchaseLabelSalesOrderProps) => import("@emotion/react/jsx-runtime").JSX.Element;
@@ -1,12 +1,5 @@
1
- import { ReactNode } from "react";
2
- import { SalesOrderProps } from "./purchase-label-by-sales-order";
3
- type ShipmentOrderProps = {
4
- children?: ReactNode;
5
- } & ({
6
- shipmentId: string;
7
- } | {
8
- oneOff: true;
9
- });
10
- type PurchaseLabelByShipmentProps = Partial<SalesOrderProps> & ShipmentOrderProps;
11
- export declare const PurchaseLabelByShipment: ({ onLoad, onShipmentUpdated, features, ...props }: PurchaseLabelByShipmentProps) => import("@emotion/react/jsx-runtime").JSX.Element;
12
- export {};
1
+ import { PurchaseLabelCommonProps } from "./purchase-label";
2
+ export type PurchaseLabelByShipmentProps = PurchaseLabelCommonProps & {
3
+ shipmentId?: string;
4
+ };
5
+ export declare const PurchaseLabelByShipment: ({ onLoad, onShipmentUpdated, shipmentId, ...props }: PurchaseLabelByShipmentProps) => import("@emotion/react/jsx-runtime").JSX.Element;
@@ -1,17 +1,30 @@
1
- /// <reference types="react" />
2
- import { SalesOrderProps } from "./purchase-label-by-sales-order";
3
- type ComponentShipmentProps = SalesOrderProps & {
4
- shipmentId: string;
1
+ import React from "react";
2
+ import { UseShippingPresetsOptionsProps } from "../../hooks";
3
+ import { ConfigureShipmentProps } from "../configure-shipment";
4
+ import { UseConfigureShipmentProps } from "./hooks";
5
+ import { PurchaseLabelSalesOrderProps } from "./purchase-label-by-sales-order";
6
+ import { PurchaseLabelByShipmentProps } from "./purchase-label-by-shipment";
7
+ export type PurchaseLabelCommonProps = {
8
+ features?: ConfigureShipmentProps["features"];
9
+ onAddressValidation?: ConfigureShipmentProps["onAddressValidation"];
10
+ onApplyPreset?: ConfigureShipmentProps["onApplyPreset"];
11
+ onBeforeLabelCreate?: ConfigureShipmentProps["onBeforeLabelCreate"];
12
+ onChangeAddress?: ConfigureShipmentProps["onChangeAddress"];
13
+ onChangeShipmentFormMode?: ConfigureShipmentProps["onChangeShipmentFormMode"];
14
+ onLabelCreateFailure?: ConfigureShipmentProps["onLabelCreateFailure"];
15
+ onLabelCreateSuccess?: ConfigureShipmentProps["onLabelCreateSuccess"];
16
+ onLoad?: UseConfigureShipmentProps["onLoad"];
17
+ onRateSaved?: ConfigureShipmentProps["onRateSaved"];
18
+ onRatesCalculated?: ConfigureShipmentProps["onRatesCalculated"];
19
+ onShipmentUpdated?: ConfigureShipmentProps["onShipmentUpdated"];
20
+ onToggleAddressPreferenceDisclosure?: ConfigureShipmentProps["onToggleAddressPreferenceDisclosure"];
21
+ printLabelLayout?: ConfigureShipmentProps["printLabelLayout"];
22
+ shippingPresets?: UseShippingPresetsOptionsProps;
23
+ warehouseId?: UseConfigureShipmentProps["warehouseId"];
5
24
  };
6
- type ComponentOneOffProps = SalesOrderProps & {
7
- oneOff: true;
8
- };
9
- type ComponentSalesOrderProps = SalesOrderProps & {
10
- salesOrderId: string;
11
- };
12
- export type ComponentProps = ComponentShipmentProps | ComponentOneOffProps | ComponentSalesOrderProps;
13
- export declare const Component: ({ ...props }: ComponentProps) => import("@emotion/react/jsx-runtime").JSX.Element;
14
- export declare const Element: ({ resources, ...props }: ComponentProps & {
25
+ type ElementProps = PurchaseLabelByShipmentProps | PurchaseLabelSalesOrderProps;
26
+ export declare const Component: ({ ...props }: ElementProps) => import("@emotion/react/jsx-runtime").JSX.Element;
27
+ export declare const Element: ({ resources, ...props }: ElementProps & {
15
28
  resources?: {
16
29
  en: {
17
30
  "wallet-history": {
@@ -606,5 +619,5 @@ export declare const Element: ({ resources, ...props }: ComponentProps & {
606
619
  };
607
620
  } | undefined;
608
621
  }) => import("@emotion/react/jsx-runtime").JSX.Element;
609
- export type ElementProps = React.ComponentProps<typeof Element>;
622
+ export type ComponentProps = React.ComponentProps<typeof Element>;
610
623
  export {};
@@ -1,2 +1,6 @@
1
- import { CodedError, SalesOrderShipment } from "@shipengine/alchemy";
2
- export declare const useGetOrCreateShipment: (shipmentId?: string) => import("react-query").UseQueryResult<SalesOrderShipment, CodedError[]>;
1
+ export declare const useGetOrCreateShipment: (shipmentId?: string) => {
2
+ errors: import("@shipengine/alchemy").CodedError[] | undefined;
3
+ isLoading: boolean;
4
+ refetchShipment: <TPageData>(options?: (import("react-query").RefetchOptions & import("react-query").RefetchQueryFilters<TPageData>) | undefined) => Promise<import("react-query").QueryObserverResult<import("@shipengine/alchemy").SalesOrderShipment, import("@shipengine/alchemy").CodedError[]>>;
5
+ shipment: import("@shipengine/alchemy").SalesOrderShipment | undefined;
6
+ };
@@ -23,3 +23,4 @@ export declare const isPoBox: (addressLine: string) => boolean;
23
23
  * @category Utilities
24
24
  */
25
25
  export declare const isPoBoxAddress: (address: SE.Address) => boolean;
26
+ export declare const isEmptyAddress: (address?: SE.Address) => boolean;
@@ -0,0 +1,2 @@
1
+ import { SE } from "@shipengine/alchemy";
2
+ export declare const getDefaultWarehouse: (warehouses: SE.Warehouse[]) => SE.Warehouse;
@@ -1,6 +0,0 @@
1
- export declare const useLoadOrCreateShipment: (shipmentId?: string) => {
2
- errors: import("@shipengine/js-api").CodedError[] | undefined;
3
- isLoading: boolean;
4
- refetchShipment: <TPageData>(options?: (import("react-query").RefetchOptions & import("react-query").RefetchQueryFilters<TPageData>) | undefined) => Promise<import("react-query").QueryObserverResult<import("@shipengine/js-api").SalesOrderShipment, import("@shipengine/js-api").CodedError[]>>;
5
- shipment: import("@shipengine/js-api").SalesOrderShipment | undefined;
6
- };