2
0
mirror of https://github.com/frappe/books.git synced 2025-02-04 13:08:29 +00:00
books/src/utils/ui.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

328 lines
7.6 KiB
TypeScript
Raw Normal View History

2022-04-20 12:08:47 +05:30
/**
* Utils to do UI stuff such as opening dialogs, toasts, etc.
* Basically anything that may directly or indirectly import a Vue file.
*/
import { ipcRenderer } from 'electron';
import { t } from 'fyo';
import { Doc } from 'fyo/model/doc';
2022-04-20 12:08:47 +05:30
import { Action } from 'fyo/model/types';
import { getActions } from 'fyo/utils';
import { handleErrorWithDialog } from 'src/errorHandling';
import { fyo } from 'src/initFyo';
import router from 'src/router';
import { IPC_ACTIONS } from 'utils/messages';
import { App, createApp, h } from 'vue';
import { RouteLocationRaw } from 'vue-router';
import { stringifyCircular } from './';
import {
MessageDialogOptions,
QuickEditOptions,
SettingsTab,
ToastOptions,
} from './types';
export async function openQuickEdit({
schemaName,
name,
2022-04-28 12:04:55 +05:30
hideFields = [],
showFields = [],
2022-04-20 12:08:47 +05:30
defaults = {},
}: QuickEditOptions) {
const currentRoute = router.currentRoute.value;
const query = currentRoute.query;
let method: 'push' | 'replace' = 'push';
2022-04-28 12:04:55 +05:30
if (query.edit && query.schemaName === schemaName) {
2022-04-20 12:08:47 +05:30
method = 'replace';
}
2022-04-28 12:04:55 +05:30
if (query.name === name) {
return;
}
2022-04-20 12:08:47 +05:30
const forWhat = (defaults?.for ?? []) as string[];
if (forWhat[0] === 'not in') {
const purpose = forWhat[1]?.[0];
defaults = Object.assign({
for:
purpose === 'sales'
? 'purchases'
: purpose === 'purchases'
? 'sales'
: 'both',
});
}
if (forWhat[0] === 'not in' && forWhat[1] === 'sales') {
defaults = Object.assign({ for: 'purchases' });
}
router[method]({
query: {
edit: 1,
2022-04-28 12:04:55 +05:30
schemaName,
2022-04-20 12:08:47 +05:30
name,
2022-04-28 12:04:55 +05:30
showFields,
2022-04-20 12:08:47 +05:30
hideFields,
2022-04-28 12:04:55 +05:30
defaults: stringifyCircular(defaults),
2022-04-20 12:08:47 +05:30
},
});
}
export async function showMessageDialog({
message,
detail,
buttons = [],
}: MessageDialogOptions) {
const options = {
message,
detail,
buttons: buttons.map((a) => a.label),
};
const { response } = (await ipcRenderer.invoke(
IPC_ACTIONS.GET_DIALOG_RESPONSE,
options
)) as { response: number };
const button = buttons[response];
if (!button?.action) {
return null;
2022-04-20 12:08:47 +05:30
}
return await button.action();
2022-04-20 12:08:47 +05:30
}
export async function showToast(options: ToastOptions) {
const Toast = (await import('src/components/Toast.vue')).default;
const toast = createApp({
render() {
return h(Toast, { ...options });
},
});
replaceAndAppendMount(toast, 'toast-target');
}
function replaceAndAppendMount(app: App<Element>, replaceId: string) {
const fragment = document.createDocumentFragment();
const target = document.getElementById(replaceId);
if (target === null) {
return;
}
const parent = target.parentElement;
const clone = target.cloneNode();
// @ts-ignore
app.mount(fragment);
target.replaceWith(fragment);
parent!.append(clone);
}
export function openSettings(tab: SettingsTab) {
routeTo({ path: '/settings', query: { tab } });
}
export async function routeTo(route: string | RouteLocationRaw) {
2022-04-20 12:08:47 +05:30
let routeOptions = route;
if (
typeof route === 'string' &&
route === router.currentRoute.value.fullPath
) {
return;
}
if (typeof route === 'string') {
routeOptions = { path: route };
}
await router.push(routeOptions);
2022-04-20 12:08:47 +05:30
}
export async function deleteDocWithPrompt(doc: Doc) {
const schemaLabel = fyo.schemaMap[doc.schemaName]!.label;
let detail = t`This action is permanent.`;
if (doc.isTransactional) {
detail = t`This action is permanent and will delete associated ledger entries.`;
}
return await showMessageDialog({
message: t`Delete ${schemaLabel} ${doc.name!}?`,
detail,
buttons: [
{
label: t`Delete`,
async action() {
try {
await doc.delete();
return true;
} catch (err) {
handleErrorWithDialog(err as Error, doc);
return false;
}
2022-04-20 12:08:47 +05:30
},
},
{
label: t`Cancel`,
action() {
return false;
2022-04-20 12:08:47 +05:30
},
},
],
2022-04-20 12:08:47 +05:30
});
}
export async function cancelDocWithPrompt(doc: Doc) {
let detail = t`This action is permanent`;
if (['SalesInvoice', 'PurchaseInvoice'].includes(doc.schemaName)) {
const payments = (
await fyo.db.getAll('Payment', {
fields: ['name'],
filters: { cancelled: false },
})
).map(({ name }) => name);
const query = (
await fyo.db.getAll('PaymentFor', {
fields: ['parent'],
filters: {
referenceName: doc.name!,
},
})
).filter(({ parent }) => payments.includes(parent));
const paymentList = [...new Set(query.map(({ parent }) => parent))];
if (paymentList.length === 1) {
detail = t`This action is permanent and will cancel the following payment: ${
paymentList[0] as string
}`;
} else if (paymentList.length > 1) {
detail = t`This action is permanent and will cancel the following payments: ${paymentList.join(
', '
)}`;
}
}
const schemaLabel = fyo.schemaMap[doc.schemaName]!.label;
return await showMessageDialog({
message: t`Cancel ${schemaLabel} ${doc.name!}?`,
detail,
buttons: [
{
label: t`Yes`,
async action() {
try {
await doc.cancel();
return true;
} catch (err) {
handleErrorWithDialog(err as Error, doc);
return false;
}
2022-04-20 12:08:47 +05:30
},
},
{
label: t`No`,
action() {
return false;
2022-04-20 12:08:47 +05:30
},
},
],
2022-04-20 12:08:47 +05:30
});
}
export function getActionsForDocument(doc?: Doc): Action[] {
if (!doc) return [];
const actions: Action[] = [
...getActions(doc),
2022-04-20 12:08:47 +05:30
getDuplicateAction(doc),
getDeleteAction(doc),
getCancelAction(doc),
];
return actions
.filter((d) => d.condition?.(doc) ?? true)
.map((d) => {
return {
label: d.label,
component: d.component,
action: d.action,
};
});
}
function getCancelAction(doc: Doc): Action {
return {
label: t`Cancel`,
component: {
template: '<span class="text-red-700">{{ t`Cancel` }}</span>',
},
condition: (doc: Doc) => doc.isSubmitted,
async action() {
const res = await cancelDocWithPrompt(doc);
if (res) {
router.push(`/list/${doc.schemaName}`);
}
2022-04-20 12:08:47 +05:30
},
};
}
function getDeleteAction(doc: Doc): Action {
return {
label: t`Delete`,
component: {
template: '<span class="text-red-700">{{ t`Delete` }}</span>',
},
condition: (doc: Doc) =>
(!doc.notInserted && !doc.schema.isSubmittable && !doc.schema.isSingle) ||
doc.isCancelled,
async action() {
const res = await deleteDocWithPrompt(doc);
if (res) {
routeTo(`/list/${doc.schemaName}`);
}
},
2022-04-20 12:08:47 +05:30
};
}
2022-04-20 12:08:47 +05:30
function getDuplicateAction(doc: Doc): Action {
const isSubmittable = !!doc.schema.isSubmittable;
return {
label: t`Duplicate`,
condition: (doc: Doc) =>
!!(
((isSubmittable && doc && doc.submitted) || !isSubmittable) &&
!doc.notInserted &&
2022-04-20 12:08:47 +05:30
!(doc.cancelled || false)
),
async action() {
await showMessageDialog({
2022-04-20 12:08:47 +05:30
message: t`Duplicate ${doc.schemaName} ${doc.name!}?`,
buttons: [
{
label: t`Yes`,
async action() {
try {
doc.duplicate();
return true;
} catch (err) {
handleErrorWithDialog(err as Error, doc);
return false;
}
2022-04-20 12:08:47 +05:30
},
},
{
label: t`No`,
action() {
return false;
2022-04-20 12:08:47 +05:30
},
},
],
});
},
};
}