saleor-dashboard/src/misc.ts
Paweł Chyła 8adadfb2ab
Static datagrid in order view (#3276)
* Init datagrid

* Product type and channels on datagrid

* Move get cell content to utils

* Add channels to storybook

* Add product description to datagrid

* Thubnail cell with avatar

* Translations

* Allow add new empty  product in datagrid

* Search product types

* useProductForm wth save  bar and exit modal

* Add description to product fixture

* Add loading placeholder

* Remove old column picker

* Sorting

* Remove old ProductList

* Update filter props

* Add header icons

* Add sort icons to datagrid column

* Show available channels

* Add price  and updatedAt columns

* Fix sorting, only sort on selected columns

* Sort by channel

* Allow delete name and product type

* Fix show not product found

* Extract mssages

* Product datagrid custom column picker

* Column picker in data grid in dirty hack for bug

* fix storybook props

* Restore Datagrid defalt column picker with custom render

* Add sort by attributes

* Use datagrid loading cells

* Fix product searching

* Show attributes before last updated

* Readonly all fields in datagrid

* Fix creating new datagrid row

* Remove add new procut button from datagrid

* Show only active sorted column

* Temp fix for column filter

* Fix column mismatch

* Add comments and spred props to ColumnPicker

* Cleanup

* Update avatar size and styles

* On row click with hover on row styles

* Use new theme

* Change placeholder image

* Draw rounded image with border

* Readonly product datagrid

* Use new theme colors in datagrid

* Add vertical borders control to datagrid

* Add empty column to add padding

* Add coursor to datagrid

* Restore vertical borders, fix cursor pointer

* Add custom freezed column

* Initial tooltip for column

* Move tooltip to datagrid

* Adjust datagrid colors style, add possibility to select column

* Change datagrid selected cells colors

* Fix typo and extract messages

* Base order  datagrid

* Cleanup Datagrid component

* Cleanup and code refactor

* Remove cursor pointer props from readonlyCell

* Use money cell for total column

* Add custom cell renderers and fix types

* Simple tags implemenrtion for status and payment col

* Add colors from theme

* Make tagCell more dynamic

* Refactor Datagrid file structure

* Add loading indicators

* Selecting column without cells in readonly

* Add sort icons to orders list

* Refactor after CR. fix typos

* Change color of selected colum cell on hover

* Improve selected header text contrast

* Move useColumnPickerColumns to hooks dir with tests

* Add less padding to column picker button

* Remove double border top

* Fix cursor pointer for tagCell and moneyCell

* useGetCellContent hook

* On loading show only one row

* Add missing darkmod color for warning tag

* Refactor columns in datagrid

* Add new macaw theme provider to storybook

* Fix  passing props in datagrid

* Trigger deployment

* Fix column picker in products

* useDatagridColumns

* Fix one more time

* Add column picker with default columns

* Change color for selected header change to textBrandDefault

* Remove unused code, move attributes colums as last

* Cleanup useDatagridColumns

* Improve DatagridProps

* Static datagrid for products (#3144)

* Migrate top nav of product list page to new MacawUI (#3290)

* feat: migrate top nav of product page

* feat: add proper deprecation links

---------

Co-authored-by: Michał Droń <dron.official@yahoo.com>

* Remove datagrid card paddding (#3310)

* Implement card view for product list (#3292)

* Add temporary view switcher

* Add basic product tile view

* Bump macaw-ui

* Add ellipsis

* Bump macaw-ui

* Add status dot & fix non-rectangular thumbnails

* Bump macaw-ui

* Add variable size placeholder icon

* Improve loader

* Fix top nav menu key error

* Add pagination

* Add unit tests

* Extract messages

* Extract status color to function

* CR Refactor

* Hold product view state in local storage (#3315)

* Remember view state for product list

* Use util status function for status dots

* Fix for empty column and hover in datagrid for product (#3324)

* Remove datagrid card paddding (#3310)

* Fix for empty column and hover in datagrid for product (#3324)

* Use themeValues from macaw (#3326)

* Upgrade macaw

* Use themeValues

* Use themeValues from macaw (#3326)

* Upgrade macaw

* Use themeValues

* Add empty column from datagrid, improve theme types

* Use theme type from typeof

* Filter empty column from default

* New product header (#3346)

* Extraxt messages

* Remve title left padding

* Fix switching view

* Add margin right to nav button

* Improve view switch

* Update switch view icons

* Add spacing to switch

* Add more space

* Add new filterbar to order list

* Code refactor and tests

* Extract messages

* Write unit tests

* Improve switch component

* Overwrite Pill styles

* Common method to get status color for pills

* Local Pill component POC

* Add ThemeProvider to test wrapper

* Extract messages

* Refactor Pill

* Fix Pill path

* Fix tests mocks

* Remove scrollbar and border bottom

* Add custom border to to datagrid

* Fix borders

* Fix border bottom

* Refactor and cleanup

* Remove not needed selectionActions code

* Move logic code t misc

* Fix scrollbar and zindex datagrid borders

* Fix product tiles condition

* Fix empty column when save column change

* Fix bottom line in layout overlap

* Keep first column in datagrid not removable

* Fix for not existing column

* Add loader over datagrid, fix problem with border top when empty text in variants

* Fix error color and change color in datagrid

* Filter presets select

* Fix delete tab name in modal, change order preset key

* Extract messages and apply cr fixes

* Keep active tab when filter and search change

* Apply filter in useColumnDefault

---------

Co-authored-by: Michał Droń <dron.official@yahoo.com>
Co-authored-by: Krzysztof Żuraw <9116238+krzysztofzuraw@users.noreply.github.com>
Co-authored-by: Michał Droń <droniu@droniu.dev>
2023-04-20 09:52:44 +02:00

603 lines
16 KiB
TypeScript

import { FetchResult, MutationFunction, MutationResult } from "@apollo/client";
import {
AddressInput,
CountryCode,
DateRangeInput,
OrderStatus,
PaymentChargeStatusEnum,
} from "@dashboard/graphql";
import { Node, SlugNode } from "@dashboard/types";
import { ConfirmButtonTransitionState, ThemeType } from "@saleor/macaw-ui";
import { DefaultTheme, ThemeTokensValues } from "@saleor/macaw-ui/next";
import uniqBy from "lodash/uniqBy";
import moment from "moment-timezone";
import { IntlShape } from "react-intl";
import { MultiAutocompleteChoiceType } from "./components/MultiAutocompleteSelectField";
import { AddressType, AddressTypeInput } from "./customers/types";
import {
commonStatusMessages,
errorMessages,
orderStatusMessages,
paymentStatusMessages,
} from "./intl";
import {
MutationResultAdditionalProps,
PartialMutationProviderOutput,
StatusType,
UserError,
} from "./types";
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[] | undefined,
renderItem: (
item: T | undefined,
index: number | undefined,
collection: T[] | undefined,
) => 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: StatusType } => {
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.INFO,
};
case PaymentChargeStatusEnum.FULLY_REFUNDED:
return {
localized: intl.formatMessage(paymentStatusMessages.refunded),
status: StatusType.INFO,
};
case PaymentChargeStatusEnum.PENDING:
return {
localized: intl.formatMessage(paymentStatusMessages.pending),
status: StatusType.WARNING,
};
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.WARNING,
};
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.INFO,
};
case OrderStatus.UNCONFIRMED:
return {
localized: intl.formatMessage(orderStatusMessages.unconfirmed),
status: StatusType.INFO,
};
case OrderStatus.PARTIALLY_RETURNED:
return {
localized: intl.formatMessage(orderStatusMessages.partiallyReturned),
status: StatusType.INFO,
};
case OrderStatus.RETURNED:
return {
localized: intl.formatMessage(orderStatusMessages.returned),
status: StatusType.INFO,
};
}
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";
}
export interface SaleorMutationResult {
errors?: any[];
}
type InferPromiseResult<T> = T extends Promise<infer V> ? V : never;
export const extractMutationErrors = async <
TData extends InferPromiseResult<TPromise>,
TPromise extends Promise<FetchResult<TData>>,
TErrors extends ReturnType<typeof getMutationErrors>,
>(
submitPromise: TPromise,
): Promise<TErrors> => {
const result = await submitPromise;
const e = getMutationErrors(result);
return e as TErrors;
};
export const hasMutationErrors = (result: FetchResult): boolean => {
if (!result?.data) {
return false;
}
return Object.values(result.data).some(
({ errors }: SaleorMutationResult) => errors.length > 0,
);
};
export const getMutationErrors = <
T extends FetchResult<any>,
TData extends T["data"],
TErrors extends TData[keyof TData]["errors"],
>(
result: T,
): TErrors[] => {
if (!result?.data) {
return [] as TErrors;
}
return Object.values(result.data).reduce(
(acc: TErrors[], mut: TData) => [
...acc,
...(mut.errors || []),
...(mut?.results?.flatMap(res => res.errors) || []),
],
[] as TErrors[],
) as TErrors;
};
export function getMutationStatus<
TData extends Record<string, SaleorMutationResult | any>,
>(opts: MutationResult<TData>): ConfirmButtonTransitionState {
const errors = getMutationErrors(opts);
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,
};
}
export const parseLogMessage = ({
intl,
code,
field,
}: {
intl: IntlShape;
code: string;
field?: string;
}) =>
intl.formatMessage(errorMessages.baseCodeErrorMessage, {
errorCode: code,
fieldError:
field &&
intl.formatMessage(errorMessages.codeErrorFieldMessage, {
fieldName: field,
}),
});
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) {
const hasName = user?.firstName && user?.lastName;
const hasEmail = !!user?.email;
if (hasName) {
return `${user.firstName[0] + user.lastName[0]}`.toUpperCase();
}
if (hasEmail) {
return user.email.slice(0, 2).toUpperCase();
}
return undefined;
}
interface AnyEventWithPropagation {
stopPropagation: () => void;
}
export function stopPropagation<T extends AnyEventWithPropagation>(
cb: (event?: T) => void,
) {
return (event: T) => {
event.stopPropagation();
cb(event);
};
}
interface AnyEventWithPreventDefault {
preventDefault: () => void;
}
export function preventDefault<T extends AnyEventWithPreventDefault>(
cb: (event?: T) => void,
) {
return (event: T) => {
event.preventDefault();
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 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 | undefined,
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");
export type WithOptional<T, K extends keyof T> = Omit<T, K> &
Partial<Pick<T, K>>;
export const getBySlug = (slugToCompare: string) => (obj: SlugNode) =>
obj.slug === slugToCompare;
export const getById = (idToCompare: string) => (obj: Node) =>
obj.id === idToCompare;
export const getByUnmatchingId =
(idToCompare: string) => (obj: { id: string }) =>
obj.id !== idToCompare;
export const findById = <T extends Node>(id: string, list?: T[]) =>
list?.find(getById(id));
const COLOR_WARNING = "#FBE5AC";
const COLOR_WARNING_DARK = "#3E2F0A";
type CustomWarningColor = typeof COLOR_WARNING | typeof COLOR_WARNING_DARK;
export const getStatusColor = (
status: "error" | "warning" | "info" | "success" | "generic",
currentTheme?: DefaultTheme,
): keyof ThemeTokensValues["colors"]["background"] | CustomWarningColor => {
switch (status) {
case "error":
return "surfaceCriticalDepressed";
case "info":
return "surfaceBrandDepressed";
case "success":
return "decorativeSurfaceSubdued2";
case "warning":
// TODO: use color from new macaw theme when will be ready
return currentTheme === "defaultDark"
? COLOR_WARNING_DARK
: COLOR_WARNING;
case "generic":
return "surfaceBrandSubdued";
default:
return "surfaceBrandSubdued";
}
};
export const isFirstColumn = (column: number) => [-1, 0].includes(column);
const getAllRemovedRowsBeforeRowIndex = (
rowIndex: number,
removedRowsIndexs: number[],
) => removedRowsIndexs.filter(r => r <= rowIndex);
export const getDatagridRowDataIndex = (
rowIndex: number,
removedRowsIndexs: number[],
) =>
rowIndex +
getAllRemovedRowsBeforeRowIndex(rowIndex, removedRowsIndexs).length;