
* Add gift bulk create (#1490) * Add gift card bulk create dialog WIP * Update schema, add gift card bulk create mutation and types * Add gift card bulk create modal and mutation * Fix types and update messages * Refactor gift card bulk create * Add closing gift card bulk create dialog after success * Change gift card list closeDialog prop name to onClose * Review fixes * Review fixes * Add error message to invalid expiryDate (#1518) * Add error message to invalid expiryDate * Add default messages * Replace filter with some * Add gift card export (#1499) * wip * Add exporting gift cards * Update messages * Fix types * Review fixes * Review fixes * Refactor passing messages to export settings component * Refactor * Update messages * Gift card customer page (#1520) * Add gift cards card to customer page (#1456) * WIP * WIP * Extract activate/deactivate logic to a hook * add optional side action * Add query for customer's gift cards * Add component for giftcard status chip * Graphql run types * Add gift card card to customer page * Fix status chip header * Revert style change * Unify status chip logic * Fix naming scheme * Add currentOpts to act/deactivate gift cards hook * Add queries to refetch prop * Simplify gift card list component * Fix order status chip * Extract messages to separate file * Remove unused lines of code * Tests and messages * Fix card list rendering * Type fix * Code review fixes * Review changes * Scripts * Change variable name * Fix formatted message * Check if giftcards exist before rendering collection * Add loading button to CardMenu component (#1476) * WIP * WIP * Add gift card card to customer page * Fix status chip header * Fix naming scheme * Add currentOpts to act/deactivate gift cards hook * Remove unused lines of code * Revert style change * Tests and messages * Fix card list rendering * Type fix * Code review fixes * Review changes * Scripts * Add loading animation to card menu buttons * Added default messages * Change conditional prop checking to filtering * Issue gift card in customer page (#1468) * WIP * WIP * Replace typed query with make query * Add customer details context to customer page * Add context to customer gift cards * Disable customer select when initial customer is present * Pass initial customer to create gift card form * Fixes after cherry-pick * Code cleanup * Remove getInitialData function * Remove unused package * Remove new line * Post-rebase fixes * Code cleanup & extract messages * Remove unused code * Create customer details hook * Minor fixes * Update default messages * Update gift card types * Type fixes * Change directory of useCustomerDetails hook * CR Fixes * Update tests * Make PageTitleWithStatusChip use ExtendedPageHeader * Update tests * Update hook name * Post-rebase fixes * Eslint fix * Fix scrollbar appearing in menu issue (#1539) * Change displayCode to last4CodeChars (#1573) * Add filtered redirect to gift card page from customer details (#1556) * Limit number of channel list items (#1607) * Add max height to single select field menu items container * Add storybook case * Update stories tests * Fix gift card product changing to preorder on save issue (#1583) * Variant preorder fix * Global threshold input should be optional * update snapshot * Add displaying logic gift cards list toolbar (#1617) * add displaying logic for gift card toolbar * Logic fix * Handle bulk export after creation (#1544) * Add gift bulk create (#1490) * Add gift card bulk create dialog WIP * Update schema, add gift card bulk create mutation and types * Add gift card bulk create modal and mutation * Fix types and update messages * Refactor gift card bulk create * Add closing gift card bulk create dialog after success * Change gift card list closeDialog prop name to onClose * Review fixes * Review fixes * Add gift card export (#1499) * wip * Add exporting gift cards * Update messages * Fix types * Review fixes * Review fixes * Refactor passing messages to export settings component * Refactor * Update messages * Handle export after bulk gift card creation * Add default messages * Create an util function to get correct input for export * Update component's name * Change modal's title * Update messages Co-authored-by: Magdalena Markusik <magdalena@markusik.com> * Gift Card List item number change doesn't refetch fix (#1643) * Fix number of rows change not refetching list * Add pagination reset * Update descriptions for gift card messages to be more descriptive (#1648) * Gift card history timeline (#1597) * Update queries and mutations * Allow title to be a react node * Show user name if it exists in data object * Update types * Refresh queries on note add * Add gift card history * type fix * Update messages * Fix timeline note * Add event fragment to form update result * Update types * Fix typo * Update messages * Disable input if gift card is expired * Remove unused imports * CR Fixes * Change messages location * Change message to include user in order * Allow adding notes to expired gift cards * Fix disabled input showing dropdown issue (#1636) * On click is disabled when component is disabled * update tests * Order filtering for gift cards in Order List View (#1628) * Add gift card order filter * Add gift card filter card in orders view * Bump macaw version * Update messages * Update tests * Code review changes * update messages * Change info card message to use only one message * Fix order gift card filter * Gift card filter in product list view (#1621) * Add GiftCard or Normal filter in Product List View * Fix tests * Fix type check * Don't filter if query param is not in enum * Update messages * Update tests * Code cleanup * Add default messages * Pass intl rather than initialise it in util * Post-rebase fixes * Change product type details messages (#1642) * Update product type gift card options messages * update tests * Add sorting to gift card list (#1569) * Update queries and types for sorting * Add optional handleError method to makeQuery * Add sorting to gift card list * Sorting hook uses useGiftCardList hook * Convert to boolean * Add default sorting field * format fix * Add expiry error handling for issuing gift cards (#1634) * Add expiry error handling for issuing gift cards * Add expiry error message to gift card bulk issue * Update Gift Card tag queries to utilise multiple tags (#1685) * Change displayCode to last4CodeChars (#1573) * Update types * WIP * Update gift card forms to utilise multiple tags * Code cleanup * Update gift card event types * Fixes * Change column with no click handler behaviour * Remove an ability to sort by tags * Remove unused code * Update tests * Update timeline events * Update messages * change array reduce to join * Add Y scroll to dialog content * Bulk create Y scroll fix * Endless loading fix (#1732) * Order filtering for gift cards in Order List View (#1628) * Add gift card order filter * Add gift card filter card in orders view * Bump macaw version * Update messages * Update tests * Code review changes * update messages * Change info card message to use only one message * Fix order gift card filter * Wip * Extract dialog component outside of gift card create * Update component's name * Extract dialog component outside of export component to provider * Update tests * Various gift card bugs fixes (#1749) * Change currency to options field * Fix hover and font size * Fix gift card list width * Fix bulk delete dialog * Allow balance to be sorted only when currency is filtered * Sorting by balance after removing currency filter defualts to usedBy * Fix trash icon * Add filter dependency * Fix single deletion with bulk * Update tests * Refactor Links used in Gift Cards * Fix export dialog (#1791) Co-authored-by: Magdalena Markusik <magdalena@markusik.com>
482 lines
13 KiB
TypeScript
482 lines
13 KiB
TypeScript
import { ThemeType } from "@saleor/macaw-ui";
|
|
import uniqBy from "lodash/uniqBy";
|
|
import moment from "moment-timezone";
|
|
import { MutationFunction, MutationResult } from "react-apollo";
|
|
import { IntlShape } from "react-intl";
|
|
|
|
import { ConfirmButtonTransitionState } from "./components/ConfirmButton";
|
|
import { MultiAutocompleteChoiceType } from "./components/MultiAutocompleteSelectField";
|
|
import { StatusType } from "./components/StatusChip/types";
|
|
import { StatusLabelProps } from "./components/StatusLabel";
|
|
import { AddressType, AddressTypeInput } from "./customers/types";
|
|
import {
|
|
commonStatusMessages,
|
|
orderStatusMessages,
|
|
paymentStatusMessages
|
|
} from "./intl";
|
|
import { OrderDetails_order_shippingAddress } from "./orders/types/OrderDetails";
|
|
import {
|
|
MutationResultAdditionalProps,
|
|
PartialMutationProviderOutput,
|
|
UserError
|
|
} from "./types";
|
|
import {
|
|
AddressInput,
|
|
CountryCode,
|
|
DateRangeInput,
|
|
OrderStatus,
|
|
PaymentChargeStatusEnum
|
|
} from "./types/globalTypes";
|
|
|
|
export type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
|
|
T,
|
|
Exclude<keyof T, Keys>
|
|
> &
|
|
{ [K in Keys]-?: Required<Pick<T, K>> }[Keys];
|
|
|
|
export type RequireOnlyOne<T, Keys extends keyof T = keyof T> = Pick<
|
|
T,
|
|
Exclude<keyof T, Keys>
|
|
> &
|
|
{
|
|
[K in Keys]-?: Required<Pick<T, K>> &
|
|
Partial<Record<Exclude<Keys, K>, undefined>>;
|
|
}[Keys];
|
|
|
|
export function renderCollection<T>(
|
|
collection: T[],
|
|
renderItem: (
|
|
item: T | undefined,
|
|
index: number | undefined,
|
|
collection: T[]
|
|
) => any,
|
|
renderEmpty?: (collection: T[]) => any
|
|
) {
|
|
if (collection === undefined) {
|
|
return renderItem(undefined, undefined, collection);
|
|
}
|
|
if (collection.length === 0) {
|
|
return !!renderEmpty ? renderEmpty(collection) : null;
|
|
}
|
|
return collection.map(renderItem);
|
|
}
|
|
|
|
export function decimal(value: string | number) {
|
|
if (typeof value === "string") {
|
|
return value === "" ? null : value;
|
|
}
|
|
return value;
|
|
}
|
|
|
|
export function weight(value: string) {
|
|
return value === "" ? null : parseFloat(value);
|
|
}
|
|
|
|
export const removeDoubleSlashes = (url: string) =>
|
|
url.replace(/([^:]\/)\/+/g, "$1");
|
|
|
|
export const transformPaymentStatus = (
|
|
status: string,
|
|
intl: IntlShape
|
|
): { localized: string; status: StatusLabelProps["status"] } => {
|
|
switch (status) {
|
|
case PaymentChargeStatusEnum.PARTIALLY_CHARGED:
|
|
return {
|
|
localized: intl.formatMessage(paymentStatusMessages.partiallyPaid),
|
|
status: StatusType.ERROR
|
|
};
|
|
case PaymentChargeStatusEnum.FULLY_CHARGED:
|
|
return {
|
|
localized: intl.formatMessage(paymentStatusMessages.paid),
|
|
status: StatusType.SUCCESS
|
|
};
|
|
case PaymentChargeStatusEnum.PARTIALLY_REFUNDED:
|
|
return {
|
|
localized: intl.formatMessage(paymentStatusMessages.partiallyRefunded),
|
|
status: StatusType.ERROR
|
|
};
|
|
case PaymentChargeStatusEnum.FULLY_REFUNDED:
|
|
return {
|
|
localized: intl.formatMessage(paymentStatusMessages.refunded),
|
|
status: StatusType.SUCCESS
|
|
};
|
|
case PaymentChargeStatusEnum.PENDING:
|
|
return {
|
|
localized: intl.formatMessage(paymentStatusMessages.pending),
|
|
status: StatusType.NEUTRAL
|
|
};
|
|
case PaymentChargeStatusEnum.REFUSED:
|
|
return {
|
|
localized: intl.formatMessage(paymentStatusMessages.refused),
|
|
status: StatusType.ERROR
|
|
};
|
|
case PaymentChargeStatusEnum.CANCELLED:
|
|
return {
|
|
localized: intl.formatMessage(commonStatusMessages.cancelled),
|
|
status: StatusType.ERROR
|
|
};
|
|
case PaymentChargeStatusEnum.NOT_CHARGED:
|
|
return {
|
|
localized: intl.formatMessage(paymentStatusMessages.unpaid),
|
|
status: StatusType.ERROR
|
|
};
|
|
}
|
|
return {
|
|
localized: status,
|
|
status: StatusType.ERROR
|
|
};
|
|
};
|
|
|
|
export const transformOrderStatus = (
|
|
status: string,
|
|
intl: IntlShape
|
|
): { localized: string; status: StatusType } => {
|
|
switch (status) {
|
|
case OrderStatus.FULFILLED:
|
|
return {
|
|
localized: intl.formatMessage(orderStatusMessages.fulfilled),
|
|
status: StatusType.SUCCESS
|
|
};
|
|
case OrderStatus.PARTIALLY_FULFILLED:
|
|
return {
|
|
localized: intl.formatMessage(orderStatusMessages.partiallyFulfilled),
|
|
status: StatusType.NEUTRAL
|
|
};
|
|
case OrderStatus.UNFULFILLED:
|
|
return {
|
|
localized: intl.formatMessage(orderStatusMessages.unfulfilled),
|
|
status: StatusType.ERROR
|
|
};
|
|
case OrderStatus.CANCELED:
|
|
return {
|
|
localized: intl.formatMessage(commonStatusMessages.cancelled),
|
|
status: StatusType.ERROR
|
|
};
|
|
case OrderStatus.DRAFT:
|
|
return {
|
|
localized: intl.formatMessage(orderStatusMessages.draft),
|
|
status: StatusType.ERROR
|
|
};
|
|
case OrderStatus.UNCONFIRMED:
|
|
return {
|
|
localized: intl.formatMessage(orderStatusMessages.unconfirmed),
|
|
status: StatusType.NEUTRAL
|
|
};
|
|
case OrderStatus.PARTIALLY_RETURNED:
|
|
return {
|
|
localized: intl.formatMessage(orderStatusMessages.partiallyReturned),
|
|
status: StatusType.NEUTRAL
|
|
};
|
|
case OrderStatus.RETURNED:
|
|
return {
|
|
localized: intl.formatMessage(orderStatusMessages.returned),
|
|
status: StatusType.NEUTRAL
|
|
};
|
|
}
|
|
return {
|
|
localized: status,
|
|
status: StatusType.ERROR
|
|
};
|
|
};
|
|
|
|
export const transformAddressToForm = (data?: AddressType) => ({
|
|
city: data?.city || "",
|
|
cityArea: data?.cityArea || "",
|
|
companyName: data?.companyName || "",
|
|
country: data?.country?.code || "",
|
|
countryArea: data?.countryArea || "",
|
|
firstName: data?.firstName || "",
|
|
lastName: data?.lastName || "",
|
|
phone: data?.phone || "",
|
|
postalCode: data?.postalCode || "",
|
|
streetAddress1: data?.streetAddress1 || "",
|
|
streetAddress2: data?.streetAddress2 || ""
|
|
});
|
|
|
|
export function maybe<T>(exp: () => T): T | undefined;
|
|
export function maybe<T>(exp: () => T, d: T): T;
|
|
export function maybe(exp: any, d?: any) {
|
|
try {
|
|
const result = exp();
|
|
return result === undefined ? d : result;
|
|
} catch {
|
|
return d;
|
|
}
|
|
}
|
|
|
|
export function only<T>(obj: T, key: keyof T): boolean {
|
|
return Object.keys(obj).every(objKey =>
|
|
objKey === key ? obj[key] !== undefined : obj[key] === undefined
|
|
);
|
|
}
|
|
|
|
export function empty(obj: {}): boolean {
|
|
return Object.keys(obj).every(key => obj[key] === undefined);
|
|
}
|
|
|
|
export function hasErrors(errorList: UserError[] | null): boolean {
|
|
return !(
|
|
errorList === undefined ||
|
|
errorList === null ||
|
|
errorList.length === 0
|
|
);
|
|
}
|
|
|
|
export function getMutationState(
|
|
called: boolean,
|
|
loading: boolean,
|
|
...errorList: any[][]
|
|
): ConfirmButtonTransitionState {
|
|
if (loading) {
|
|
return "loading";
|
|
}
|
|
if (called) {
|
|
return errorList.map(hasErrors).reduce((acc, curr) => acc || curr, false)
|
|
? "error"
|
|
: "success";
|
|
}
|
|
return "default";
|
|
}
|
|
|
|
interface SaleorMutationResult {
|
|
errors?: UserError[];
|
|
}
|
|
export function getMutationErrors<
|
|
TData extends Record<string, SaleorMutationResult>
|
|
>(data: TData): UserError[] {
|
|
return Object.values(data).reduce(
|
|
(acc: UserError[], mut) => [...acc, ...maybe(() => mut.errors, [])],
|
|
[]
|
|
);
|
|
}
|
|
export function getMutationStatus<
|
|
TData extends Record<string, SaleorMutationResult | any>
|
|
>(opts: MutationResult<TData>): ConfirmButtonTransitionState {
|
|
const errors = opts.data ? getMutationErrors(opts.data) : [];
|
|
|
|
return getMutationState(opts.called, opts.loading, errors);
|
|
}
|
|
|
|
export function getMutationProviderData<TData, TVariables>(
|
|
mutateFn: MutationFunction<TData, TVariables>,
|
|
opts: MutationResult<TData> & MutationResultAdditionalProps
|
|
): PartialMutationProviderOutput<TData, TVariables> {
|
|
return {
|
|
mutate: variables => mutateFn({ variables }),
|
|
opts
|
|
};
|
|
}
|
|
|
|
interface User {
|
|
email: string;
|
|
firstName?: string;
|
|
lastName?: string;
|
|
}
|
|
|
|
export function getUserName(user?: User, returnEmail?: boolean) {
|
|
return user && (user.email || (user.firstName && user.lastName))
|
|
? user.firstName && user.lastName
|
|
? [user.firstName, user.lastName].join(" ")
|
|
: returnEmail
|
|
? user.email
|
|
: user.email.split("@")[0]
|
|
: undefined;
|
|
}
|
|
|
|
export function getUserInitials(user?: User) {
|
|
return user && (user.email || (user.firstName && user.lastName))
|
|
? (user.firstName && user.lastName
|
|
? user.firstName[0] + user.lastName[0]
|
|
: user.email.slice(0, 2)
|
|
).toUpperCase()
|
|
: undefined;
|
|
}
|
|
|
|
interface AnyEvent {
|
|
stopPropagation: () => void;
|
|
}
|
|
export function stopPropagation(cb: (event?: AnyEvent) => void) {
|
|
return (event: AnyEvent) => {
|
|
event.stopPropagation();
|
|
cb(event);
|
|
};
|
|
}
|
|
|
|
export interface DateTime {
|
|
date: string;
|
|
time: string;
|
|
}
|
|
|
|
export function joinDateTime(date: string, time?: string) {
|
|
if (!date) {
|
|
return null;
|
|
}
|
|
const setTime = time || "00:00";
|
|
const dateTime = moment(date + " " + setTime).format();
|
|
return dateTime;
|
|
}
|
|
|
|
export function splitDateTime(dateTime: string) {
|
|
if (!dateTime) {
|
|
return {
|
|
date: "",
|
|
time: ""
|
|
};
|
|
}
|
|
// Default html input format YYYY-MM-DD HH:mm
|
|
const splitDateTime = moment(dateTime)
|
|
.format("YYYY-MM-DD HH:mm")
|
|
.split(" ");
|
|
return {
|
|
date: splitDateTime[0],
|
|
time: splitDateTime[1]
|
|
};
|
|
}
|
|
|
|
export function generateCode(charNum: number) {
|
|
let result = "";
|
|
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
for (let i = 0; i < charNum; i++) {
|
|
result += characters.charAt(Math.floor(Math.random() * characters.length));
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export function isInEnum<TEnum extends {}>(needle: string, haystack: TEnum) {
|
|
return Object.keys(haystack).includes(needle);
|
|
}
|
|
|
|
export function findInEnum<TEnum extends {}>(needle: string, haystack: TEnum) {
|
|
const match = Object.keys(haystack).find(key => key === needle);
|
|
if (!!match) {
|
|
return haystack[needle as keyof TEnum];
|
|
}
|
|
|
|
throw new Error(`Key ${needle} not found in enum`);
|
|
}
|
|
|
|
export function addressToAddressInput<T>(
|
|
address: T & OrderDetails_order_shippingAddress
|
|
): AddressInput {
|
|
const { id, __typename, ...rest } = address;
|
|
return {
|
|
...rest,
|
|
country: findInEnum(address.country.code, CountryCode)
|
|
};
|
|
}
|
|
|
|
export function findValueInEnum<TEnum extends {}>(
|
|
needle: string,
|
|
haystack: TEnum
|
|
): TEnum[keyof TEnum] {
|
|
const match = Object.entries(haystack).find(([_, value]) => value === needle);
|
|
|
|
if (!match) {
|
|
throw new Error(`Value ${needle} not found in enum`);
|
|
}
|
|
|
|
return (needle as unknown) as TEnum[keyof TEnum];
|
|
}
|
|
|
|
export function parseBoolean(a: string, defaultValue: boolean): boolean {
|
|
if (a === undefined) {
|
|
return defaultValue;
|
|
}
|
|
return a === "true";
|
|
}
|
|
|
|
export function capitalize(s: string) {
|
|
return s.charAt(0).toLocaleUpperCase() + s.slice(1);
|
|
}
|
|
|
|
export function transformFormToAddressInput<T>(
|
|
address: T & AddressTypeInput
|
|
): T & AddressInput {
|
|
return {
|
|
...address,
|
|
country: findInEnum(address.country, CountryCode)
|
|
};
|
|
}
|
|
|
|
export function getStringOrPlaceholder(
|
|
s: string | undefined,
|
|
placeholder?: string
|
|
): string {
|
|
return s || placeholder || "...";
|
|
}
|
|
|
|
export const getDatePeriod = (days: number): DateRangeInput => {
|
|
if (days < 1) {
|
|
return {};
|
|
}
|
|
|
|
const end = moment().startOf("day");
|
|
const start = end.subtract(days - 1);
|
|
const format = "YYYY-MM-DD";
|
|
|
|
return {
|
|
gte: start.format(format),
|
|
lte: end.format(format)
|
|
};
|
|
};
|
|
|
|
export const isDarkTheme = (themeType: ThemeType) => themeType === "dark";
|
|
|
|
export const transformAddressToAddressInput = (data?: AddressType) => ({
|
|
city: data?.city || "",
|
|
cityArea: data?.cityArea || "",
|
|
companyName: data?.companyName || "",
|
|
country: findInEnum(data?.country?.code || "", CountryCode),
|
|
countryArea: data?.countryArea || "",
|
|
firstName: data?.firstName || "",
|
|
lastName: data?.lastName || "",
|
|
phone: data?.phone || "",
|
|
postalCode: data?.postalCode || "",
|
|
streetAddress1: data?.streetAddress1 || "",
|
|
streetAddress2: data?.streetAddress2 || ""
|
|
});
|
|
|
|
export function getFullName<T extends { firstName: string; lastName: string }>(
|
|
data: T
|
|
) {
|
|
if (!data || !data.firstName || !data.lastName) {
|
|
return "";
|
|
}
|
|
|
|
return `${data.firstName} ${data.lastName}`;
|
|
}
|
|
export const flatten = (obj: unknown) => {
|
|
// Be cautious that repeated keys are overwritten
|
|
|
|
const result = {};
|
|
|
|
Object.keys(obj).forEach(key => {
|
|
if (typeof obj[key] === "object" && obj[key] !== null) {
|
|
Object.assign(result, flatten(obj[key]));
|
|
} else {
|
|
result[key] = obj[key];
|
|
}
|
|
});
|
|
|
|
return result;
|
|
};
|
|
|
|
export function PromiseQueue() {
|
|
let queue = Promise.resolve();
|
|
|
|
function add<T>(operation: (value: T | void) => PromiseLike<T>) {
|
|
return new Promise((resolve, reject) => {
|
|
queue = queue
|
|
.then(operation)
|
|
.then(resolve)
|
|
.catch(reject);
|
|
});
|
|
}
|
|
|
|
return { queue, add };
|
|
}
|
|
|
|
export const combinedMultiAutocompleteChoices = (
|
|
selected: MultiAutocompleteChoiceType[],
|
|
choices: MultiAutocompleteChoiceType[]
|
|
) => uniqBy([...selected, ...choices], "value");
|