code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
<template>
<div class="text-sm">
<template v-for="df in formFields">
<!-- Table Field Form (Eg: PaymentFor) -->
<Table
v-if="df.fieldtype === 'Table'"
:key="`${df.fieldname}-table`"
ref="controls"
size="small"
:df="df"
:value="(doc[df.fieldname] ?? []) as unknown[]"
@change="async (value) => await onChange(df, value)"
/>
<!-- Regular Field Form -->
<div
v-else
:key="`${df.fieldname}-regular`"
class="grid items-center border-b dark:border-gray-800"
:style="{
...style,
height: getFieldHeight(df),
}"
>
<div class="ps-4 flex text-gray-600 dark:text-gray-400">
{{ df.label }}
</div>
<div
class="py-2 pe-4"
:class="{
'ps-2': df.fieldtype === 'AttachImage',
}"
>
<FormControl
ref="controls"
size="small"
:df="df"
:value="doc[df.fieldname]"
:class="{ 'p-2': df.fieldtype === 'Check' }"
:text-end="false"
@change="async (value) => await onChange(df, value)"
/>
<div
v-if="errors[df.fieldname]"
class="text-sm text-red-600 mt-2 ps-2"
>
{{ errors[df.fieldname] }}
</div>
</div>
</div>
</template>
</div>
</template>
<script lang="ts">
import { Doc } from 'fyo/model/doc';
import FormControl from 'src/components/Controls/FormControl.vue';
import { fyo } from 'src/initFyo';
import { getErrorMessage } from 'src/utils';
import { evaluateHidden } from 'src/utils/doc';
import Table from './Controls/Table.vue';
import { defineComponent } from 'vue';
import { Field } from 'schemas/types';
import { PropType } from 'vue';
import { DocValue } from 'fyo/core/types';
export default defineComponent({
name: 'TwoColumnForm',
components: {
FormControl,
Table,
},
props: {
doc: { type: Doc, required: true },
fields: { type: Array as PropType<Field[]>, default: () => [] },
columnRatio: {
type: Array as PropType<number[]>,
default: () => [1, 1],
},
},
data() {
return {
formFields: [],
errors: {},
} as { formFields: Field[]; errors: Record<string, string> };
},
computed: {
style() {
let templateColumns = (this.columnRatio || [1, 1])
.map((r) => `minmax(0, ${r}fr)`)
.join(' ');
return {
'grid-template-columns': templateColumns,
};
},
},
watch: {
doc() {
this.setFormFields();
},
},
mounted() {
this.setFormFields();
if (fyo.store.isDevelopment) {
// @ts-ignore
window.tcf = this;
}
},
methods: {
getFieldHeight(field: Field) {
if (['AttachImage', 'Text'].includes(field.fieldtype)) {
return 'calc((var(--h-row-mid) + 1px) * 2)';
}
if (this.errors[field.fieldname]) {
return 'calc((var(--h-row-mid) + 1px) * 2)';
}
return 'calc(var(--h-row-mid) + 1px)';
},
async onChange(field: Field, value: DocValue) {
const { fieldname } = field;
delete this.errors[fieldname];
let isSet = false;
try {
isSet = await this.doc.set(fieldname, value);
} catch (err) {
if (!(err instanceof Error)) {
return;
}
this.errors[fieldname] = getErrorMessage(err, this.doc);
}
if (isSet) {
this.setFormFields();
}
},
setFormFields() {
let fieldList = this.fields;
if (fieldList.length === 0) {
fieldList = this.doc.quickEditFields;
}
if (fieldList.length === 0) {
fieldList = this.doc.schema.fields.filter((f) => f.required);
}
this.formFields = fieldList.filter(
(field) => field && !evaluateHidden(field, this.doc)
);
},
},
});
</script>
|
2302_79757062/books
|
src/components/TwoColumnForm.vue
|
Vue
|
agpl-3.0
| 3,956
|
<template>
<div
class="
relative
window-drag
flex
items-center
border-b
dark:bg-gray-900
text-gray-900
dark:text-gray-100
border-gray-100
dark:border-gray-800
"
style="height: 28px"
>
<Fb class="ms-2" />
<p v-if="companyName && dbPath" class="mx-auto text-sm">
{{ companyName }} - {{ dbPath }}
</p>
<div
v-if="!isFullscreen"
class="absolute window-no-drag flex h-full items-center right-0"
>
<div
class="
flex
items-center
px-4
h-full
hover:bg-gray-300
dark:hover:bg-gray-875
"
@click="minimizeWindow"
>
<feather-icon name="minus" class="h-4 w-4 flex-shrink-0" />
</div>
<div
class="
flex
items-center
px-4
h-full
hover:bg-gray-300
dark:hover:bg-gray-875
"
@click="toggleMaximize"
>
<feather-icon
v-if="isMax"
name="minimize"
class="h-3 w-3 flex-shrink-0"
/>
<feather-icon v-else name="square" class="h-3 w-3 flex-shrink-0" />
</div>
<div
class="flex items-center px-4 h-full hover:bg-red-600 hover:text-white"
@click="closeWindow"
>
<feather-icon name="x" class="h-4 w-4 flex-shrink-0" />
</div>
</div>
</div>
</template>
<script>
import Fb from './Icons/18/fb.vue';
export default {
name: 'WindowsTitleBar',
components: { Fb },
props: {
dbPath: String,
companyName: String,
},
data() {
return {
isMax: Boolean,
isFullscreen: Boolean,
};
},
mounted() {
this.getIsMaximized();
this.getIsFullscreen();
window.addEventListener('resize', this.getIsFullscreen);
document.addEventListener('webkitfullscreenchange', this.getIsFullscreen);
document.addEventListener('mozfullscreenchange', this.getIsFullscreen);
document.addEventListener('fullscreenchange', this.getIsFullscreen);
document.addEventListener('MSFullscreenChange', this.getIsFullscreen);
},
destroyed() {
window.removeEventListener('resize', this.getIsFullscreen);
document.removeEventListener(
'webkitfullscreenchange',
this.getIsFullscreen
);
document.removeEventListener('mozfullscreenchange', this.getIsFullscreen);
document.removeEventListener('fullscreenchange', this.getIsFullscreen);
document.removeEventListener('MSFullscreenChange', this.getIsFullscreen);
},
methods: {
minimizeWindow() {
ipc.minimizeWindow();
},
toggleMaximize() {
ipc.toggleMaximize();
this.getIsMaximized();
},
closeWindow() {
ipc.closeWindow();
},
getIsMaximized() {
ipc
.isMaximized()
.then((result) => {
this.isMax = result;
})
.catch((error) => {
console.error(error);
});
},
getIsFullscreen() {
ipc
.isFullscreen()
.then((result) => {
this.isFullscreen = result;
})
.catch((error) => {
console.error(error);
});
},
},
};
</script>
|
2302_79757062/books
|
src/components/WindowsTitleBar.vue
|
Vue
|
agpl-3.0
| 3,215
|
<template>
<div class="custom-scroll custom-scroll-thumb1">
<slot></slot>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'WithScroll',
emits: ['scroll'],
data() {
return { listener: undefined } as { listener?: () => void };
},
mounted() {
this.listener = () => {
let { scrollLeft, scrollTop } = this.$el;
this.$emit('scroll', { scrollLeft, scrollTop });
};
this.$el.addEventListener('scroll', this.listener);
},
beforeUnmount() {
if (!this.listener) {
return;
}
this.$el.removeEventListener('scroll', this.listener);
delete this.listener;
},
});
</script>
|
2302_79757062/books
|
src/components/WithScroll.vue
|
Vue
|
agpl-3.0
| 701
|
import { t } from 'fyo';
import type { Doc } from 'fyo/model/doc';
import { BaseError } from 'fyo/utils/errors';
import { ErrorLog } from 'fyo/utils/types';
import { truncate } from 'lodash';
import { showDialog } from 'src/utils/interactive';
import { fyo } from './initFyo';
import router from './router';
import { getErrorMessage, stringifyCircular } from './utils';
import type { DialogOptions, ToastOptions } from './utils/types';
function shouldNotStore(error: Error) {
const shouldLog = (error as BaseError).shouldStore ?? true;
return !shouldLog;
}
export async function sendError(errorLogObj: ErrorLog) {
if (!errorLogObj.stack) {
return;
}
errorLogObj.more ??= {};
errorLogObj.more.path ??= router.currentRoute.value.fullPath;
const body = {
error_name: errorLogObj.name,
message: errorLogObj.message,
stack: errorLogObj.stack,
platform: fyo.store.platform,
version: fyo.store.appVersion,
language: fyo.store.language,
instance_id: fyo.store.instanceId,
device_id: fyo.store.deviceId,
open_count: fyo.store.openCount,
country_code: fyo.singles.SystemSettings?.countryCode,
more: stringifyCircular(errorLogObj.more),
};
if (fyo.store.isDevelopment) {
// eslint-disable-next-line no-console
console.log('sendError', body);
}
await ipc.sendError(JSON.stringify(body));
}
function getToastProps(errorLogObj: ErrorLog) {
const props: ToastOptions = {
message: errorLogObj.name ?? t`Error`,
type: 'error',
actionText: t`Report Error`,
action: () => reportIssue(errorLogObj),
};
return props;
}
export function getErrorLogObject(
error: Error,
more: Record<string, unknown>
): ErrorLog {
const { name, stack, message, cause } = error;
if (cause) {
more.cause = cause;
}
const errorLogObj = { name, stack, message, more };
fyo.errorLog.push(errorLogObj);
return errorLogObj;
}
export async function handleError(
logToConsole: boolean,
error: Error,
more: Record<string, unknown> = {},
notifyUser = true
) {
if (logToConsole) {
// eslint-disable-next-line no-console
console.error(error);
}
if (shouldNotStore(error)) {
return;
}
const errorLogObj = getErrorLogObject(error, more);
await sendError(errorLogObj);
if (notifyUser) {
const toastProps = getToastProps(errorLogObj);
const { showToast } = await import('src/utils/interactive');
showToast(toastProps);
}
}
export async function handleErrorWithDialog(
error: unknown,
doc?: Doc,
reportError?: boolean,
dontThrow?: boolean
) {
if (!(error instanceof Error)) {
return;
}
const errorMessage = getErrorMessage(error, doc);
await handleError(false, error, { errorMessage, doc });
const label = getErrorLabel(error);
const options: DialogOptions = {
title: label,
detail: errorMessage,
type: 'error',
};
if (reportError) {
options.detail = truncate(String(options.detail), { length: 128 });
options.buttons = [
{
label: t`Report`,
action() {
reportIssue(getErrorLogObject(error, { errorMessage }));
},
isPrimary: true,
},
{
label: t`Cancel`,
action() {
return null;
},
isEscape: true,
},
];
}
await showDialog(options);
if (dontThrow) {
if (fyo.store.isDevelopment) {
// eslint-disable-next-line no-console
console.error(error);
}
return;
}
throw error;
}
export async function showErrorDialog(title?: string, content?: string) {
// To be used for show stopper errors
title ??= t`Error`;
content ??= t`Something has gone terribly wrong. Please check the console and raise an issue.`;
await ipc.showError(title, content);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function getErrorHandled<T extends (...args: any[]) => Promise<any>>(
func: T
) {
type Return = ReturnType<T> extends Promise<infer P> ? P : true;
return async function errorHandled(...args: Parameters<T>): Promise<Return> {
try {
return (await func(...args)) as Return;
} catch (error) {
await handleError(false, error as Error, {
functionName: func.name,
functionArgs: args,
});
throw error;
}
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function getErrorHandledSync<T extends (...args: any[]) => any>(
func: T
) {
type Return = ReturnType<T> extends Promise<infer P> ? P : ReturnType<T>;
return function errorHandledSync(...args: Parameters<T>) {
try {
return func(...args) as Return;
} catch (error) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
handleError(false, error as Error, {
functionName: func.name,
functionArgs: args,
});
}
};
}
function getIssueUrlQuery(errorLogObj?: ErrorLog): string {
const baseUrl = 'https://github.com/frappe/books/issues/new?labels=bug';
const body = [
'<h2>Description</h2>',
'Add some description...',
'',
'<h2>Steps to Reproduce</h2>',
'Add steps to reproduce the error...',
'',
'<h2>Info</h2>',
'',
];
if (errorLogObj) {
body.push(`**Error**: _${errorLogObj.name}: ${errorLogObj.message}_`, '');
}
if (errorLogObj?.stack) {
body.push('**Stack**:', '```', errorLogObj.stack, '```', '');
}
body.push(`**Version**: \`${fyo.store.appVersion}\``);
body.push(`**Platform**: \`${fyo.store.platform}\``);
body.push(`**Path**: \`${router.currentRoute.value.fullPath}\``);
body.push(`**Language**: \`${fyo.config.get('language') ?? '-'}\``);
if (fyo.singles.SystemSettings?.countryCode) {
body.push(`**Country**: \`${fyo.singles.SystemSettings.countryCode}\``);
}
const url = [baseUrl, `body=${body.join('\n')}`].join('&');
return encodeURI(url);
}
export function reportIssue(errorLogObj?: ErrorLog) {
const urlQuery = getIssueUrlQuery(errorLogObj);
ipc.openExternalUrl(urlQuery);
}
function getErrorLabel(error: Error) {
const name = error.name;
if (!name) {
return t`Error`;
}
if (name === 'BaseError') {
return t`Error`;
}
if (name === 'ValidationError') {
return t`Validation Error`;
}
if (name === 'NotFoundError') {
return t`Not Found`;
}
if (name === 'ForbiddenError') {
return t`Forbidden Error`;
}
if (name === 'DuplicateEntryError') {
return t`Duplicate Entry`;
}
if (name === 'LinkValidationError') {
return t`Link Validation Error`;
}
if (name === 'MandatoryError') {
return t`Mandatory Error`;
}
if (name === 'DatabaseError') {
return t`Database Error`;
}
if (name === 'CannotCommitError') {
return t`Cannot Commit Error`;
}
if (name === 'NotImplemented') {
return t`Error`;
}
if (name === 'ToDebugError') {
return t`Error`;
}
return t`Error`;
}
|
2302_79757062/books
|
src/errorHandling.ts
|
TypeScript
|
agpl-3.0
| 6,909
|
import { Fyo } from 'fyo';
import { Converter } from 'fyo/core/converter';
import { DocValue, DocValueMap } from 'fyo/core/types';
import { Doc } from 'fyo/model/doc';
import { getEmptyValuesByFieldTypes } from 'fyo/utils';
import { ValidationError } from 'fyo/utils/errors';
import {
Field,
FieldType,
FieldTypeEnum,
OptionField,
RawValue,
Schema,
TargetField,
} from 'schemas/types';
import { generateCSV, parseCSV } from 'utils/csvParser';
import { getValueMapFromList } from 'utils/index';
export type TemplateField = Field & TemplateFieldProps;
type TemplateFieldProps = {
schemaName: string;
schemaLabel: string;
fieldKey: string;
parentSchemaChildField?: TargetField;
};
type ValueMatrixItem =
| {
value: DocValue;
rawValue?: RawValue;
error?: boolean;
}
| { value?: DocValue; rawValue: RawValue; error?: boolean };
type ValueMatrix = ValueMatrixItem[][];
const skippedFieldsTypes: FieldType[] = [
FieldTypeEnum.AttachImage,
FieldTypeEnum.Attachment,
FieldTypeEnum.Table,
];
/**
* Tool that
* - Can make bulk entries for any kind of Doc
* - Takes in unstructured CSV data, converts it into Docs
* - Saves and or Submits the converted Docs
*/
export class Importer {
schemaName: string;
fyo: Fyo;
/**
* List of template fields that have been assigned a column, in
* the order they have been assigned.
*/
assignedTemplateFields: (string | null)[];
/**
* Map of all the template fields that can be imported.
*/
templateFieldsMap: Map<string, TemplateField>;
/**
* Map of Fields that have been picked, i.e.
* - Fields which will be included in the template
* - Fields for which values will be provided
*/
templateFieldsPicked: Map<string, boolean>;
/**
* Whether the schema type being imported has table fields
*/
hasChildTables: boolean;
/**
* Matrix containing the raw values which will be converted to
* doc values before importing.
*/
valueMatrix: ValueMatrix;
/**
* Data from the valueMatrix rows will be converted into Docs
* which will be stored in this array.
*/
docs: Doc[];
/**
* Used if an options field is imported where the import data
* provided maybe the label and not the value
*/
optionsMap: {
values: Record<string, Set<string>>;
labelValueMap: Record<string, Record<string, string>>;
};
constructor(schemaName: string, fyo: Fyo) {
if (!fyo.schemaMap[schemaName]) {
throw new ValidationError(
`Invalid schemaName ${schemaName} found in importer`
);
}
this.hasChildTables = false;
this.schemaName = schemaName;
this.fyo = fyo;
this.docs = [];
this.valueMatrix = [];
this.optionsMap = {
values: {},
labelValueMap: {},
};
const templateFields = getTemplateFields(schemaName, fyo, this);
this.assignedTemplateFields = templateFields.map((f) => f.fieldKey);
this.templateFieldsMap = new Map();
this.templateFieldsPicked = new Map();
templateFields.forEach((f) => {
this.templateFieldsMap.set(f.fieldKey, f);
this.templateFieldsPicked.set(f.fieldKey, true);
});
}
selectFile(data: string): boolean {
try {
const parsed = parseCSV(data);
this.selectParsed(parsed);
} catch {
return false;
}
return true;
}
async checkLinks() {
const tfKeys = this.assignedTemplateFields
.map((key, index) => ({
key,
index,
tf: this.templateFieldsMap.get(key ?? ''),
}))
.filter(({ key, tf }) => {
if (!key || !tf) {
return false;
}
return tf.fieldtype === FieldTypeEnum.Link;
}) as { key: string; index: number; tf: TemplateField }[];
const linksNames: Map<string, Set<string>> = new Map();
for (const row of this.valueMatrix) {
for (const { tf, index } of tfKeys) {
const target = (tf as TargetField).target;
const value = row[index]?.value;
if (typeof value !== 'string' || !value) {
continue;
}
if (!linksNames.has(target)) {
linksNames.set(target, new Set());
}
linksNames.get(target)?.add(value);
}
}
const doesNotExist = [];
for (const [target, values] of linksNames.entries()) {
for (const value of values) {
const exists = await this.fyo.db.exists(target, value);
if (exists) {
continue;
}
doesNotExist.push({
schemaName: target,
schemaLabel: this.fyo.schemaMap[this.schemaName]?.label,
name: value,
});
}
}
return doesNotExist;
}
checkCellErrors() {
const assigned = this.assignedTemplateFields
.map((key, index) => ({
key,
index,
tf: this.templateFieldsMap.get(key ?? ''),
}))
.filter(({ key, tf }) => !!key && !!tf) as {
key: string;
index: number;
tf: TemplateField;
}[];
const cellErrors = [];
for (let i = 0; i < this.valueMatrix.length; i++) {
const row = this.valueMatrix[i];
for (const { tf, index } of assigned) {
if (!row[index]?.error) {
continue;
}
const rowLabel = this.fyo.t`Row ${i + 1}`;
const columnLabel = getColumnLabel(tf);
cellErrors.push(`(${rowLabel}, ${columnLabel})`);
}
}
return cellErrors;
}
populateDocs() {
const { dataMap, childTableMap } =
this.getDataAndChildTableMapFromValueMatrix();
const schema = this.fyo.schemaMap[this.schemaName];
const targetFieldnameMap = schema?.fields
.filter((f) => f.fieldtype === FieldTypeEnum.Table)
.reduce((acc, f) => {
const { target, fieldname } = f as TargetField;
acc[target] = fieldname;
return acc;
}, {} as Record<string, string>);
for (const [name, data] of dataMap.entries()) {
const doc = this.fyo.doc.getNewDoc(this.schemaName, data, false);
for (const schemaName in targetFieldnameMap) {
const fieldname = targetFieldnameMap[schemaName];
const childTable = childTableMap[name]?.[schemaName];
if (!childTable) {
continue;
}
for (const childData of childTable.values()) {
doc.push(fieldname, childData);
}
}
this.docs.push(doc);
}
}
getDataAndChildTableMapFromValueMatrix() {
/**
* Record key is the doc.name value
*/
const dataMap: Map<string, DocValueMap> = new Map();
/**
* Record key is doc.name, childSchemaName, childDoc.name
*/
const childTableMap: Record<
string,
Record<string, Map<string, DocValueMap>>
> = {};
const nameIndices = this.assignedTemplateFields
.map((key, index) => ({ key, index }))
.filter((f) => f.key?.endsWith('.name'))
.reduce((acc, f) => {
if (f.key == null) {
return acc;
}
const schemaName = f.key.split('.')[0];
acc[schemaName] = f.index;
return acc;
}, {} as Record<string, number>);
const nameIndex = nameIndices?.[this.schemaName];
if (nameIndex < 0) {
return { dataMap, childTableMap };
}
for (let i = 0; i < this.valueMatrix.length; i++) {
const row = this.valueMatrix[i];
const name = row[nameIndex]?.value;
if (typeof name !== 'string') {
continue;
}
for (let j = 0; j < row.length; j++) {
const key = this.assignedTemplateFields[j];
const tf = this.templateFieldsMap.get(key ?? '');
if (!tf || !key) {
continue;
}
const isChild = this.fyo.schemaMap[tf.schemaName]?.isChild;
const vmi = row[j];
if (vmi.value == null) {
continue;
}
if (!isChild && !dataMap.has(name)) {
dataMap.set(name, {});
}
if (!isChild) {
dataMap.get(name)![tf.fieldname] = vmi.value;
continue;
}
const childNameIndex = nameIndices[tf.schemaName];
let childName = row[childNameIndex]?.value;
if (typeof childName !== 'string') {
childName = `${tf.schemaName}-${i}`;
}
childTableMap[name] ??= {};
childTableMap[name][tf.schemaName] ??= new Map();
const childMap = childTableMap[name][tf.schemaName];
if (!childMap.has(childName)) {
childMap.set(childName, {});
}
const childDocValueMap = childMap.get(childName);
if (!childDocValueMap) {
continue;
}
childDocValueMap[tf.fieldname] = vmi.value;
}
}
return { dataMap, childTableMap };
}
selectParsed(parsed: string[][]): void {
if (!parsed?.length) {
return;
}
let startIndex = -1;
let templateFieldsAssigned;
for (let i = 3; i >= 0; i--) {
const row = parsed[i];
if (!row?.length) {
continue;
}
templateFieldsAssigned = this.assignTemplateFieldsFromParsedRow(row);
if (templateFieldsAssigned) {
startIndex = i + 1;
break;
}
}
if (!templateFieldsAssigned) {
this.clearAndResizeAssignedTemplateFields(parsed[0].length);
}
if (startIndex === -1) {
startIndex = 0;
}
this.assignValueMatrixFromParsed(parsed.slice(startIndex));
}
clearAndResizeAssignedTemplateFields(size: number) {
for (let i = 0; i < size; i++) {
if (i >= this.assignedTemplateFields.length) {
this.assignedTemplateFields.push(null);
} else {
this.assignedTemplateFields[i] = null;
}
}
}
assignValueMatrixFromParsed(parsed: string[][]) {
if (!parsed?.length) {
return;
}
for (const row of parsed) {
this.pushToValueMatrixFromParsedRow(row);
}
}
pushToValueMatrixFromParsedRow(row: string[]) {
const vmRow: ValueMatrix[number] = [];
for (let i = 0; i < row.length; i++) {
const rawValue = row[i];
const index = Number(i);
if (index >= this.assignedTemplateFields.length) {
this.assignedTemplateFields.push(null);
}
vmRow.push(this.getValueMatrixItem(index, rawValue));
}
this.valueMatrix.push(vmRow);
}
setTemplateField(index: number, key: string | null) {
if (index >= this.assignedTemplateFields.length) {
this.assignedTemplateFields.push(key);
} else {
this.assignedTemplateFields[index] = key;
}
this.updateValueMatrixColumn(index);
}
updateValueMatrixColumn(index: number) {
for (const row of this.valueMatrix) {
const vmi = this.getValueMatrixItem(index, row[index].rawValue ?? null);
if (index >= row.length) {
row.push(vmi);
} else {
row[index] = vmi;
}
}
}
getValueMatrixItem(index: number, rawValue: RawValue) {
const vmi: ValueMatrixItem = { rawValue };
const key = this.assignedTemplateFields[index];
if (!key) {
return vmi;
}
const tf = this.templateFieldsMap.get(key);
if (!tf) {
return vmi;
}
if (vmi.rawValue === '') {
vmi.value = null;
return vmi;
}
if ('options' in tf && typeof vmi.rawValue === 'string') {
return this.getOptionFieldVmi(vmi, tf);
}
try {
vmi.value = Converter.toDocValue(rawValue, tf, this.fyo);
} catch {
vmi.error = true;
}
return vmi;
}
getOptionFieldVmi(
{ rawValue }: ValueMatrixItem,
tf: OptionField & TemplateFieldProps
): ValueMatrixItem {
if (typeof rawValue !== 'string') {
return { error: true, value: null, rawValue };
}
if (!tf?.options.length) {
return { value: null, rawValue };
}
if (!this.optionsMap.labelValueMap[tf.fieldKey]) {
const values = new Set(tf.options.map(({ value }) => value));
const labelValueMap = getValueMapFromList(tf.options, 'label', 'value');
this.optionsMap.labelValueMap[tf.fieldKey] = labelValueMap;
this.optionsMap.values[tf.fieldKey] = values;
}
const hasValue = this.optionsMap.values[tf.fieldKey].has(rawValue);
if (hasValue) {
return { value: rawValue, rawValue };
}
const value = this.optionsMap.labelValueMap[tf.fieldKey][rawValue];
if (value) {
return { value, rawValue };
}
return { error: true, value: null, rawValue };
}
assignTemplateFieldsFromParsedRow(row: string[]): boolean {
const isKeyRow = row.some((key) => this.templateFieldsMap.has(key));
if (!isKeyRow) {
return false;
}
for (let i = 0; i < row.length; i++) {
const value = row[i];
const tf = this.templateFieldsMap.get(value);
let key: string | null = value;
if (!tf) {
key = null;
}
if (key !== null && !this.templateFieldsPicked.get(value)) {
key = null;
}
if (Number(i) >= this.assignedTemplateFields.length) {
this.assignedTemplateFields.push(key);
} else {
this.assignedTemplateFields[i] = key;
}
}
return true;
}
addRow() {
const valueRow: ValueMatrix[number] = this.assignedTemplateFields.map(
(key) => {
key ??= '';
const { fieldtype } = this.templateFieldsMap.get(key) ?? {};
let value = null;
if (fieldtype) {
value = getEmptyValuesByFieldTypes(fieldtype, this.fyo);
}
return { value };
}
);
this.valueMatrix.push(valueRow);
}
removeRow(index: number) {
this.valueMatrix = this.valueMatrix.filter((_, i) => i !== index);
}
getCSVTemplate(): string {
const schemaLabels: string[] = [];
const fieldLabels: string[] = [];
const fieldKey: string[] = [];
for (const [name, picked] of this.templateFieldsPicked.entries()) {
if (!picked) {
continue;
}
const field = this.templateFieldsMap.get(name);
if (!field) {
continue;
}
schemaLabels.push(field.schemaLabel);
fieldLabels.push(field.label);
fieldKey.push(field.fieldKey);
}
return generateCSV([schemaLabels, fieldLabels, fieldKey]);
}
}
function getTemplateFields(
schemaName: string,
fyo: Fyo,
importer: Importer
): TemplateField[] {
const schemas: { schema: Schema; parentSchemaChildField?: TargetField }[] = [
{ schema: fyo.schemaMap[schemaName]! },
];
const fields: TemplateField[] = [];
const targetSchemaFieldMap =
fyo.schemaMap[importer.schemaName]?.fields.reduce((acc, f) => {
if (!(f as TargetField).target) {
return acc;
}
acc[f.fieldname] = f;
return acc;
}, {} as Record<string, Field>) ?? {};
while (schemas.length) {
const { schema, parentSchemaChildField } = schemas.pop() ?? {};
if (!schema) {
continue;
}
for (const field of schema.fields) {
if (shouldSkipField(field, schema)) {
continue;
}
if (field.fieldtype === FieldTypeEnum.Table) {
importer.hasChildTables = true;
schemas.push({
schema: fyo.schemaMap[field.target]!,
parentSchemaChildField: field,
});
}
if (skippedFieldsTypes.includes(field.fieldtype)) {
continue;
}
const tf = { ...field };
if (tf.readOnly) {
tf.readOnly = false;
}
if (schema.isChild && tf.fieldname === 'name') {
tf.required = false;
}
if (
schema.isChild &&
tf.required &&
!targetSchemaFieldMap[tf.schemaName ?? '']?.required
) {
tf.required = false;
}
const schemaName = schema.name;
const schemaLabel = schema.label;
const fieldKey = `${schema.name}.${field.fieldname}`;
fields.push({
...tf,
schemaName,
schemaLabel,
fieldKey,
parentSchemaChildField,
});
}
}
return fields;
}
export function getColumnLabel(field: TemplateField): string {
if (field.parentSchemaChildField) {
return `${field.label} (${field.parentSchemaChildField.label})`;
}
return field.label;
}
function shouldSkipField(field: Field, schema: Schema): boolean {
if (field.computed || field.meta) {
return true;
}
if (schema.naming === 'numberSeries' && field.fieldname === 'name') {
return false;
}
if (field.hidden) {
return true;
}
if (field.readOnly && !field.required) {
return true;
}
return false;
}
|
2302_79757062/books
|
src/importer.ts
|
TypeScript
|
agpl-3.0
| 16,443
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Frappe Books</title>
</head>
<body></body>
<script type="module" src="./renderer.ts"></script>
</html>
|
2302_79757062/books
|
src/index.html
|
HTML
|
agpl-3.0
| 328
|
import { Fyo } from 'fyo';
/**
* Global fyo: this is meant to be used only by the app. For
* testing purposes a separate instance of fyo should be initialized.
*/
export const fyo = new Fyo({ isTest: false, isElectron: true });
|
2302_79757062/books
|
src/initFyo.ts
|
TypeScript
|
agpl-3.0
| 233
|
<template>
<div class="flex flex-col h-full">
<PageHeader :title="t`Chart of Accounts`">
<Button v-if="!isAllExpanded" @click="expand">{{ t`Expand` }}</Button>
<Button v-if="!isAllCollapsed" @click="collapse">{{
t`Collapse`
}}</Button>
</PageHeader>
<!-- Chart of Accounts -->
<div
v-if="root"
class="
flex-1 flex flex-col
overflow-y-auto
mb-4
custom-scroll custom-scroll-thumb1
"
>
<!-- Chart of Accounts Indented List -->
<template v-for="account in allAccounts" :key="account.name">
<!-- Account List Item -->
<div
class="
py-2
cursor-pointer
hover:bg-gray-50
dark:hover:bg-gray-890 dark:text-gray-25
group
flex
items-center
border-b
dark:border-gray-800
flex-shrink-0
pe-4
"
:class="[
account.level !== 0 ? 'text-base' : 'text-lg',
isQuickEditOpen(account) ? 'bg-gray-200 dark:bg-gray-900' : '',
]"
:style="getItemStyle(account.level)"
@click="onClick(account)"
>
<component :is="getIconComponent(!!account.isGroup, account.name)" />
<div class="flex items-baseline">
<div
class="ms-4"
:class="[!account.parentAccount && 'font-semibold']"
>
{{ account.name }}
</div>
<!-- Add Account Buttons on Group Hover -->
<div class="ms-6 hidden group-hover:block">
<button
v-if="account.isGroup"
class="
text-xs text-gray-800
dark:text-gray-400
hover:text-gray-900
dark:hover:text-gray-100
focus:outline-none
"
@click.stop="addAccount(account, 'addingAccount')"
>
{{ t`Add Account` }}
</button>
<button
v-if="account.isGroup"
class="
ms-3
text-xs text-gray-800
dark:text-gray-400
hover:text-gray-900
dark:hover:text-gray-100
focus:outline-none
"
@click.stop="addAccount(account, 'addingGroupAccount')"
>
{{ t`Add Group` }}
</button>
<button
class="
ms-3
text-xs text-gray-800
dark:text-gray-400
hover:text-gray-900
dark:hover:text-gray-100
focus:outline-none
"
@click.stop="deleteAccount(account)"
>
{{ account.isGroup ? t`Delete Group` : t`Delete Account` }}
</button>
</div>
</div>
<!-- Account Balance String -->
<p
v-if="!account.isGroup"
class="ms-auto text-base text-gray-800 dark:text-gray-400"
>
{{ getBalanceString(account) }}
</p>
</div>
<!-- Add Account/Group -->
<div
v-if="account.addingAccount || account.addingGroupAccount"
:key="account.name + '-adding-account'"
class="
px-4
border-b
dark:border-gray-800
cursor-pointer
hover:bg-gray-50
dark:hover:bg-gray-890
group
flex
items-center
text-base
"
:style="getGroupStyle(account.level + 1)"
>
<component :is="getIconComponent(account.addingGroupAccount)" />
<div class="flex ms-4 h-row-mid items-center">
<input
:ref="account.name"
v-model="newAccountName"
class="
focus:outline-none
bg-transparent
dark:placeholder-gray-600 dark:text-gray-400
"
:class="{ 'text-gray-600 dark:text-gray-400': insertingAccount }"
:placeholder="t`New Account`"
type="text"
:disabled="insertingAccount"
@keydown.esc="cancelAddingAccount(account)"
@keydown.enter="
(e) => createNewAccount(account, account.addingGroupAccount)
"
/>
<button
v-if="!insertingAccount"
class="
ms-4
text-xs text-gray-800
dark:text-gray-400
hover:text-gray-900
dark:hover:text-gray-100
focus:outline-none
"
@click="
(e) => createNewAccount(account, account.addingGroupAccount)
"
>
{{ t`Save` }}
</button>
<button
v-if="!insertingAccount"
class="
ms-4
text-xs text-gray-800
dark:text-gray-400
hover:text-gray-900
dark:hover:text-gray-100
focus:outline-none
"
@click="cancelAddingAccount(account)"
>
{{ t`Cancel` }}
</button>
</div>
</div>
</template>
</div>
</div>
</template>
<script lang="ts">
import { t } from 'fyo';
import { isCredit } from 'models/helpers';
import { ModelNameEnum } from 'models/types';
import PageHeader from 'src/components/PageHeader.vue';
import { fyo } from 'src/initFyo';
import { languageDirectionKey } from 'src/utils/injectionKeys';
import { docsPathMap } from 'src/utils/misc';
import { docsPathRef } from 'src/utils/refs';
import { commongDocDelete, openQuickEdit } from 'src/utils/ui';
import { getMapFromList, removeAtIndex } from 'utils/index';
import { defineComponent, nextTick } from 'vue';
import Button from '../components/Button.vue';
import { inject } from 'vue';
import { handleErrorWithDialog } from '../errorHandling';
import { AccountRootType, AccountType } from 'models/baseModels/Account/types';
import { TreeViewSettings } from 'fyo/model/types';
import { Doc } from 'fyo/model/doc';
import { Component } from 'vue';
import { uicolors } from 'src/utils/colors';
import { showDialog } from 'src/utils/interactive';
type AccountItem = {
name: string;
parentAccount: string;
rootType: AccountRootType;
accountType: AccountType;
level: number;
location: number[];
isGroup?: boolean;
children: AccountItem[];
expanded: boolean;
addingAccount: boolean;
addingGroupAccount: boolean;
};
type AccKey = 'addingAccount' | 'addingGroupAccount';
export default defineComponent({
components: {
Button,
PageHeader,
},
props: {
darkMode: { type: Boolean, default: false },
},
setup() {
return {
languageDirection: inject(languageDirectionKey),
};
},
data() {
return {
isAllCollapsed: true,
isAllExpanded: false,
root: null as null | { label: string; balance: number; currency: string },
accounts: [] as AccountItem[],
schemaName: 'Account',
newAccountName: '',
insertingAccount: false,
totals: {} as Record<string, { totalDebit: number; totalCredit: number }>,
refetchTotals: false,
settings: null as null | TreeViewSettings,
};
},
computed: {
allAccounts() {
const allAccounts: AccountItem[] = [];
(function getAccounts(
accounts: AccountItem[],
level: number,
location: number[]
) {
for (let i = 0; i < accounts.length; i++) {
const account = accounts[i];
account.level = level;
account.location = [...location, i];
allAccounts.push(account);
if (account.children != null && account.expanded) {
getAccounts(account.children, level + 1, account.location);
}
}
})(this.accounts, 0, []);
return allAccounts;
},
},
async mounted() {
await this.setTotalDebitAndCredit();
fyo.doc.observer.on('sync:AccountingLedgerEntry', () => {
this.refetchTotals = true;
});
},
async activated() {
await this.fetchAccounts();
if (fyo.store.isDevelopment) {
// @ts-ignore
window.coa = this;
}
docsPathRef.value = docsPathMap.ChartOfAccounts!;
if (this.refetchTotals) {
await this.setTotalDebitAndCredit();
this.refetchTotals = false;
}
},
deactivated() {
docsPathRef.value = '';
},
methods: {
async expand() {
await this.toggleAll(this.accounts, true);
this.isAllCollapsed = false;
this.isAllExpanded = true;
},
async collapse() {
await this.toggleAll(this.accounts, false);
this.isAllExpanded = false;
this.isAllCollapsed = true;
},
async toggleAll(accounts: AccountItem | AccountItem[], expand: boolean) {
if (!Array.isArray(accounts)) {
await this.toggle(accounts, expand);
accounts = accounts.children ?? [];
}
for (const account of accounts) {
await this.toggleAll(account, expand);
}
},
async toggle(account: AccountItem, expand: boolean) {
if (account.expanded === expand || !account.isGroup) {
return;
}
await this.toggleChildren(account);
},
getBalance(account: AccountItem) {
const total = this.totals[account.name];
if (!total) {
return 0;
}
const { totalCredit, totalDebit } = total;
if (isCredit(account.rootType)) {
return totalCredit - totalDebit;
}
return totalDebit - totalCredit;
},
getBalanceString(account: AccountItem) {
const suffix = isCredit(account.rootType) ? t`Cr.` : t`Dr.`;
const balance = this.getBalance(account);
return `${fyo.format(balance, 'Currency')} ${suffix}`;
},
async setTotalDebitAndCredit() {
const totals = await this.fyo.db.getTotalCreditAndDebit();
this.totals = getMapFromList(totals, 'account');
},
async fetchAccounts() {
this.settings =
fyo.models[ModelNameEnum.Account]?.getTreeSettings(fyo) ?? null;
const currency = this.fyo.singles.SystemSettings?.currency ?? '';
const label = (await this.settings?.getRootLabel()) ?? '';
this.root = {
label,
balance: 0,
currency,
};
this.accounts = await this.getChildren();
},
async onClick(account: AccountItem) {
let shouldOpen = !account.isGroup;
if (account.isGroup) {
shouldOpen = !(await this.toggleChildren(account));
}
if (account.isGroup && account.expanded) {
this.isAllCollapsed = false;
}
if (account.isGroup && !account.expanded) {
this.isAllExpanded = false;
}
if (!shouldOpen) {
return;
}
const doc = await fyo.doc.getDoc(ModelNameEnum.Account, account.name);
this.setOpenAccountDocListener(doc, account);
await openQuickEdit({ doc });
},
setOpenAccountDocListener(
doc: Doc,
account?: AccountItem,
parentAccount?: AccountItem
) {
if (doc.hasListener('afterDelete')) {
return;
}
doc.once('afterDelete', () => {
this.removeAccount(doc.name!, account, parentAccount);
});
},
async deleteAccount(account: AccountItem) {
const canDelete = await this.canDeleteAccount(account);
if (!canDelete) {
return;
}
const doc = await fyo.doc.getDoc(ModelNameEnum.Account, account.name);
this.setOpenAccountDocListener(doc, account);
await commongDocDelete(doc, false);
},
async canDeleteAccount(account: AccountItem) {
if (account.isGroup && !account.children?.length) {
await this.fetchChildren(account);
}
if (!account.children?.length) {
return true;
}
await showDialog({
type: 'error',
title: t`Cannot Delete Account`,
detail: t`${account.name} has linked child accounts.`,
});
return false;
},
removeAccount(
name: string,
account?: AccountItem,
parentAccount?: AccountItem
) {
if (account == null && parentAccount == null) {
return;
}
if (account == null && parentAccount) {
account = parentAccount.children.find((ch) => ch?.name === name);
}
if (account == null) {
return;
}
const indices = account.location.slice(1).map((i) => Number(i));
let i = Number(account.location[0]);
let parent = this.accounts[i];
let children = this.accounts[i].children;
while (indices.length > 1) {
i = indices.shift()!;
parent = children[i];
children = children[i].children;
}
i = indices[0];
if (children[i].name !== name) {
return;
}
parent.children = removeAtIndex(children, i);
},
async toggleChildren(account: AccountItem) {
const hasChildren = await this.fetchChildren(account);
if (!hasChildren) {
return false;
}
account.expanded = !account.expanded;
if (!account.expanded) {
account.addingAccount = false;
account.addingGroupAccount = false;
}
return true;
},
async fetchChildren(account: AccountItem, force = false) {
if (account.children == null || force) {
account.children = await this.getChildren(account.name);
}
return !!account?.children?.length;
},
async getChildren(parent: null | string = null): Promise<AccountItem[]> {
const children = await fyo.db.getAll(ModelNameEnum.Account, {
filters: {
parentAccount: parent,
},
fields: ['name', 'parentAccount', 'isGroup', 'rootType', 'accountType'],
orderBy: 'name',
order: 'asc',
});
return children.map((d) => {
d.expanded = false;
d.addingAccount = false;
d.addingGroupAccount = false;
return d as unknown as AccountItem;
});
},
async addAccount(parentAccount: AccountItem, key: AccKey) {
if (!parentAccount.expanded) {
await this.fetchChildren(parentAccount);
parentAccount.expanded = true;
}
// activate editing of type 'key' and deactivate other type
let otherKey: AccKey =
key === 'addingAccount' ? 'addingGroupAccount' : 'addingAccount';
parentAccount[key] = true;
parentAccount[otherKey] = false;
await nextTick();
let input = (this.$refs[parentAccount.name] as HTMLInputElement[])[0];
input.focus();
},
cancelAddingAccount(parentAccount: AccountItem) {
parentAccount.addingAccount = false;
parentAccount.addingGroupAccount = false;
this.newAccountName = '';
},
async createNewAccount(parentAccount: AccountItem, isGroup: boolean) {
// freeze input
this.insertingAccount = true;
const accountName = this.newAccountName.trim();
const doc = fyo.doc.getNewDoc('Account');
try {
let { name, rootType, accountType } = parentAccount;
await doc.set({
name: accountName,
parentAccount: name,
rootType,
accountType,
isGroup,
});
await doc.sync();
// turn off editing
parentAccount.addingAccount = false;
parentAccount.addingGroupAccount = false;
// update accounts
await this.fetchChildren(parentAccount, true);
// open quick edit
await openQuickEdit({ doc });
this.setOpenAccountDocListener(doc, undefined, parentAccount);
// unfreeze input
this.insertingAccount = false;
this.newAccountName = '';
} catch (e) {
// unfreeze input
this.insertingAccount = false;
await handleErrorWithDialog(e, doc);
}
},
isQuickEditOpen(account: AccountItem) {
let { edit, schemaName, name } = this.$route.query;
return !!(edit && schemaName === 'Account' && name === account.name);
},
getIconComponent(isGroup: boolean, name?: string): Component {
let lightColor = this.darkMode ? uicolors.gray[600] : uicolors.gray[400];
let darkColor = this.darkMode ? uicolors.gray[400] : uicolors.gray[700];
let icons = {
'Application of Funds (Assets)': `<svg class="w-4 h-4" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd">
<path d="M15.333 5.333H.667A.667.667 0 000 6v9.333c0 .368.299.667.667.667h14.666a.667.667 0 00.667-.667V6a.667.667 0 00-.667-.667zM8 12.667a2 2 0 110-4 2 2 0 010 4z" fill="${darkColor}" fill-rule="nonzero"/>
<path d="M14 2.667V4H2V2.667h12zM11.333 0v1.333H4.667V0h6.666z" fill="${lightColor}"/>
</g>
</svg>`,
Expenses: `<svg class="w-4 h-4" viewBox="0 0 14 16" xmlns="http://www.w3.org/2000/svg">
<path d="M13.668 0v15.333a.666.666 0 01-.666.667h-12a.666.666 0 01-.667-.667V0l2.667 2 2-2 2 2 2-2 2 2 2.666-2zM9.964 4.273H4.386l-.311 1.133h1.62c.933 0 1.474.362 1.67.963H4.373l-.298 1.053h3.324c-.175.673-.767 1.044-1.705 1.044H4.182l.008.83L7.241 13h1.556v-.072L6.01 9.514c1.751-.106 2.574-.942 2.748-2.092h.904l.298-1.053H8.75a2.375 2.375 0 00-.43-1.044l1.342.009.302-1.061z" fill="${darkColor}" fill-rule="evenodd"/>
</svg>`,
Income: `<svg class="w-4 h-4" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd">
<path d="M16 12.859V14c0 1.105-2.09 2-4.667 2-2.494 0-4.531-.839-4.66-1.894L6.667 14v-1.141C7.73 13.574 9.366 14 11.333 14c1.968 0 3.602-.426 4.667-1.141zm0-3.334v1.142c0 1.104-2.09 2-4.667 2-2.494 0-4.531-.839-4.66-1.894l-.006-.106V9.525c1.064.716 2.699 1.142 4.666 1.142 1.968 0 3.602-.426 4.667-1.142zm-4.667-4.192c2.578 0 4.667.896 4.667 2 0 1.105-2.09 2-4.667 2s-4.666-.895-4.666-2c0-1.104 2.089-2 4.666-2z" fill="${darkColor}"/>
<path d="M0 10.859C1.065 11.574 2.7 12 4.667 12l.337-.005.33-.013v1.995c-.219.014-.44.023-.667.023-2.495 0-4.532-.839-4.66-1.894L0 12v-1.141zm0-2.192V7.525c1.065.716 2.7 1.142 4.667 1.142l.337-.005.33-.013v1.995c-.219.013-.44.023-.667.023-2.495 0-4.532-.839-4.66-1.894L0 8.667V7.525zm0-4.475c1.065.715 2.7 1.141 4.667 1.141.694 0 1.345-.056 1.946-.156-.806.56-1.27 1.292-1.278 2.134-.219.013-.441.022-.668.022-2.578 0-4.667-.895-4.667-2zM4.667 0c2.577 0 4.666.895 4.666 2S7.244 4 4.667 4C2.089 4 0 3.105 0 2s2.09-2 4.667-2z" fill="${lightColor}"/>
</g>
</svg>`,
'Source of Funds (Liabilities)': `<svg class="w-4 h-4" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd">
<path d="M7.332 11.36l4.666-3.734 2 1.6V.666A.667.667 0 0013.332 0h-12a.667.667 0 00-.667.667v14.666c0 .369.298.667.667.667h6v-4.64zm-4-7.36H11.3v1.333H3.332V4zm2.666 8H3.332v-1.333h2.666V12zM3.332 8.667V7.333h5.333v1.334H3.332z" fill="${darkColor}"/>
<path d="M15.332 12l-3.334-2.667L8.665 12v3.333c0 .369.298.667.667.667h2v-2h1.333v2h2a.667.667 0 00.667-.667V12z" fill="${lightColor}"/>
</g>
</svg>`,
};
let leaf = `<svg class="w-2 h-2" viewBox="0 0 8 8" xmlns="http://www.w3.org/2000/svg">
<circle stroke="${darkColor}" cx="4" cy="4" r="3.5" fill="none" fill-rule="evenodd"/>
</svg>`;
let folder = `<svg class="w-3 h-3" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
<path d="M8.333 3.367L6.333.7H.667A.667.667 0 000 1.367v12a2 2 0 002 2h12a2 2 0 002-2V4.033a.667.667 0 00-.667-.666h-7z" fill="${darkColor}" fill-rule="evenodd"/>
</svg>`;
let icon = isGroup ? folder : leaf;
return {
template: icons[name as keyof typeof icons] || icon,
};
},
getItemStyle(level: number) {
const styles: Record<string, string> = {
height: 'calc(var(--h-row-mid) + 1px)',
};
if (this.languageDirection === 'rtl') {
styles['padding-right'] = `calc(1rem + 2rem * ${level})`;
} else {
styles['padding-left'] = `calc(1rem + 2rem * ${level})`;
}
return styles;
},
getGroupStyle(level: number) {
const styles: Record<string, string> = {
height: 'height: calc(var(--h-row-mid) + 1px)',
};
if (this.languageDirection === 'rtl') {
styles['padding-right'] = `calc(1rem + 2rem * ${level})`;
} else {
styles['padding-left'] = `calc(1rem + 2rem * ${level})`;
}
return styles;
},
},
});
</script>
|
2302_79757062/books
|
src/pages/ChartOfAccounts.vue
|
Vue
|
agpl-3.0
| 20,869
|
<template>
<FormContainer :use-full-width="useFullWidth">
<template v-if="hasDoc" #header-left>
<Barcode
v-if="canShowBarcode"
class="h-8"
@item-selected="(name:string) => {
// @ts-ignore
doc?.addItem(name);
}"
/>
<ExchangeRate
v-if="canShowExchangeRate"
:disabled="doc?.isSubmitted || doc?.isCancelled"
:from-currency="fromCurrency"
:to-currency="toCurrency"
:exchange-rate="exchangeRate"
@change="
async (exchangeRate: number) =>
await doc.set('exchangeRate', exchangeRate)
"
/>
<p
v-if="schema.label && !(canShowBarcode || canShowExchangeRate)"
class="text-xl font-semibold items-center text-gray-600"
>
{{ schema.label }}
</p>
</template>
<template v-if="hasDoc" #header>
<Button
v-if="canShowLinks"
:icon="true"
:title="t`View linked entries`"
@click="showLinks = true"
>
<feather-icon name="link" class="w-4 h-4"></feather-icon>
</Button>
<Button
v-if="canPrint"
ref="printButton"
:icon="true"
:title="t`Open Print View`"
@click="routeTo(`/print/${doc.schemaName}/${doc.name}`)"
>
<feather-icon name="printer" class="w-4 h-4"></feather-icon>
</Button>
<Button
:icon="true"
:title="t`Toggle between form and full width`"
@click="toggleWidth"
>
<feather-icon
:name="useFullWidth ? 'minimize' : 'maximize'"
class="w-4 h-4"
></feather-icon>
</Button>
<DropdownWithActions
v-for="group of groupedActions"
:key="group.label"
:type="group.type"
:actions="group.actions"
>
<p v-if="group.group">
{{ group.group }}
</p>
<feather-icon v-else name="more-horizontal" class="w-4 h-4" />
</DropdownWithActions>
<Button v-if="doc?.canSave" type="primary" @click="sync">
{{ t`Save` }}
</Button>
<Button v-else-if="doc?.canSubmit" type="primary" @click="submit">{{
t`Submit`
}}</Button>
</template>
<template #body>
<FormHeader
:form-title="title"
class="
sticky
top-0
bg-white
dark:bg-gray-890
border-b
dark:border-gray-800
"
>
<StatusPill v-if="hasDoc" :doc="doc" />
</FormHeader>
<!-- Section Container -->
<div
v-if="hasDoc"
class="overflow-auto custom-scroll custom-scroll-thumb1"
>
<CommonFormSection
v-for="([n, fields], idx) in activeGroup.entries()"
:key="n + idx"
ref="section"
class="p-4"
:class="
idx !== 0 && activeGroup.size > 1
? 'border-t dark:border-gray-800'
: ''
"
:show-title="activeGroup.size > 1 && n !== t`Default`"
:title="n"
:fields="fields"
:doc="doc"
:errors="errors"
@editrow="(doc: Doc) => showRowEditForm(doc)"
@value-change="onValueChange"
@row-change="updateGroupedFields"
/>
</div>
<!-- Tab Bar -->
<div
v-if="groupedFields && groupedFields.size > 1"
class="
mt-auto
px-4
pb-4
flex
gap-8
border-t
dark:border-gray-800
flex-shrink-0
sticky
bottom-0
bg-white
dark:bg-gray-875
"
>
<div
v-for="key of groupedFields.keys()"
:key="key"
class="text-sm cursor-pointer"
:class="
key === activeTab
? 'text-gray-900 dark:text-gray-25 font-semibold border-t-2 border-gray-800 dark:border-gray-100'
: 'text-gray-700 dark:text-gray-200 '
"
:style="{
paddingTop: key === activeTab ? 'calc(1rem - 2px)' : '1rem',
}"
@click="activeTab = key"
>
{{ key }}
</div>
</div>
</template>
<template #quickedit>
<Transition name="quickedit">
<LinkedEntries
v-if="showLinks && canShowLinks"
:doc="doc"
@close="showLinks = false"
/>
</Transition>
<Transition name="quickedit">
<RowEditForm
v-if="row && !showLinks"
:doc="doc"
:fieldname="row.fieldname"
:index="row.index"
@previous="(i:number) => row!.index = i"
@next="(i:number) => row!.index = i"
@close="() => (row = null)"
/>
</Transition>
</template>
</FormContainer>
</template>
<script lang="ts">
import { DocValue } from 'fyo/core/types';
import { Doc } from 'fyo/model/doc';
import { DEFAULT_CURRENCY } from 'fyo/utils/consts';
import { ValidationError } from 'fyo/utils/errors';
import { getDocStatus } from 'models/helpers';
import { ModelNameEnum } from 'models/types';
import { Field, Schema } from 'schemas/types';
import Button from 'src/components/Button.vue';
import Barcode from 'src/components/Controls/Barcode.vue';
import ExchangeRate from 'src/components/Controls/ExchangeRate.vue';
import DropdownWithActions from 'src/components/DropdownWithActions.vue';
import FormContainer from 'src/components/FormContainer.vue';
import FormHeader from 'src/components/FormHeader.vue';
import StatusPill from 'src/components/StatusPill.vue';
import { getErrorMessage } from 'src/utils';
import { shortcutsKey } from 'src/utils/injectionKeys';
import { docsPathMap } from 'src/utils/misc';
import { docsPathRef } from 'src/utils/refs';
import { ActionGroup, DocRef, UIGroupedFields } from 'src/utils/types';
import {
commonDocSubmit,
commonDocSync,
getDocFromNameIfExistsElseNew,
getFieldsGroupedByTabAndSection,
getFormRoute,
getGroupedActionsForDoc,
isPrintable,
routeTo,
} from 'src/utils/ui';
import { useDocShortcuts } from 'src/utils/vueUtils';
import { computed, defineComponent, inject, nextTick, ref } from 'vue';
import CommonFormSection from './CommonFormSection.vue';
import LinkedEntries from './LinkedEntries.vue';
import RowEditForm from './RowEditForm.vue';
export default defineComponent({
components: {
FormContainer,
FormHeader,
CommonFormSection,
Button,
DropdownWithActions,
Barcode,
ExchangeRate,
LinkedEntries,
RowEditForm,
StatusPill,
},
provide() {
return {
doc: computed(() => this.docOrNull),
};
},
props: {
name: { type: String, default: '' },
schemaName: { type: String, default: ModelNameEnum.SalesInvoice },
},
setup() {
const shortcuts = inject(shortcutsKey);
const docOrNull = ref(null) as DocRef;
let context = 'CommonForm';
if (shortcuts) {
context = useDocShortcuts(shortcuts, docOrNull, 'CommonForm', true);
}
return {
docOrNull,
shortcuts,
context,
printButton: ref<InstanceType<typeof Button> | null>(null),
};
},
data() {
return {
errors: {},
activeTab: this.t`Default`,
groupedFields: null,
isPrintable: false,
showLinks: false,
useFullWidth: false,
row: null,
} as {
errors: Record<string, string>;
activeTab: string;
groupedFields: null | UIGroupedFields;
isPrintable: boolean;
showLinks: boolean;
useFullWidth: boolean;
row: null | { index: number; fieldname: string };
};
},
computed: {
canShowBarcode(): boolean {
if (!this.fyo.singles.InventorySettings?.enableBarcodes) {
return false;
}
if (!this.hasDoc) {
return false;
}
if (this.doc.isSubmitted || this.doc.isCancelled) {
return false;
}
// @ts-ignore
return typeof this.doc?.addItem === 'function';
},
canShowExchangeRate(): boolean {
return this.hasDoc && !!this.doc.isMultiCurrency;
},
exchangeRate(): number {
if (!this.hasDoc || typeof this.doc.exchangeRate !== 'number') {
return 1;
}
return this.doc.exchangeRate;
},
fromCurrency(): string {
const currency = this.doc?.currency;
if (typeof currency !== 'string') {
return this.toCurrency;
}
return currency;
},
toCurrency(): string {
const currency = this.fyo.singles.SystemSettings?.currency;
if (typeof currency !== 'string') {
return DEFAULT_CURRENCY;
}
return currency;
},
canPrint(): boolean {
if (!this.hasDoc) {
return false;
}
return !this.doc.isCancelled && !this.doc.dirty && this.isPrintable;
},
canShowLinks(): boolean {
if (!this.hasDoc) {
return false;
}
if (this.doc.schema.isSubmittable && !this.doc.isSubmitted) {
return false;
}
return this.doc.inserted;
},
hasDoc(): boolean {
return this.docOrNull instanceof Doc;
},
status(): string {
if (!this.hasDoc) {
return '';
}
return getDocStatus(this.doc);
},
doc(): Doc {
const doc = this.docOrNull;
if (!doc) {
throw new ValidationError(
this.t`Doc ${this.schema.label} ${this.name} not set`
);
}
return doc;
},
title(): string {
if (this.schema.isSubmittable && this.docOrNull?.notInserted) {
return this.t`New Entry`;
}
return this.docOrNull?.name || this.t`New Entry`;
},
schema(): Schema {
const schema = this.fyo.schemaMap[this.schemaName];
if (!schema) {
throw new ValidationError(`no schema found with ${this.schemaName}`);
}
return schema;
},
activeGroup(): Map<string, Field[]> {
if (!this.groupedFields) {
return new Map();
}
const group = this.groupedFields.get(this.activeTab);
if (!group) {
const tab = [...this.groupedFields.keys()][0];
return this.groupedFields.get(tab) ?? new Map<string, Field[]>();
}
return group;
},
groupedActions(): ActionGroup[] {
if (!this.hasDoc) {
return [];
}
return getGroupedActionsForDoc(this.doc);
},
},
beforeMount() {
this.useFullWidth = !!this.fyo.singles.Misc?.useFullWidth;
},
async mounted() {
if (this.fyo.store.isDevelopment) {
// @ts-ignore
window.cf = this;
}
await this.setDoc();
this.replacePathAfterSync();
this.updateGroupedFields();
if (this.groupedFields) {
this.activeTab = [...this.groupedFields.keys()][0];
}
this.isPrintable = await isPrintable(this.schemaName);
},
activated(): void {
this.useFullWidth = !!this.fyo.singles.Misc?.useFullWidth;
docsPathRef.value = docsPathMap[this.schemaName] ?? '';
this.shortcuts?.pmod.set(this.context, ['KeyP'], () => {
if (!this.canPrint) {
return;
}
this.printButton?.$el.click();
});
this.shortcuts?.pmod.set(this.context, ['KeyL'], () => {
if (!this.canShowLinks && !this.showLinks) {
return;
}
this.showLinks = !this.showLinks;
});
},
deactivated(): void {
docsPathRef.value = '';
this.showLinks = false;
this.row = null;
},
methods: {
routeTo,
async toggleWidth() {
const value = !this.useFullWidth;
await this.fyo.singles.Misc?.setAndSync('useFullWidth', value);
this.useFullWidth = value;
},
updateGroupedFields(): void {
if (!this.hasDoc) {
return;
}
this.groupedFields = getFieldsGroupedByTabAndSection(
this.schema,
this.doc
);
},
async sync(useDialog?: boolean) {
if (await commonDocSync(this.doc, useDialog)) {
this.updateGroupedFields();
}
},
async submit() {
if (await commonDocSubmit(this.doc)) {
this.updateGroupedFields();
}
},
async setDoc() {
if (this.hasDoc) {
return;
}
this.docOrNull = await getDocFromNameIfExistsElseNew(
this.schemaName,
this.name
);
},
replacePathAfterSync() {
if (!this.hasDoc || this.doc.inserted) {
return;
}
this.doc.once('afterSync', async () => {
const route = getFormRoute(this.schemaName, this.doc.name!);
await this.$router.replace(route);
});
},
async showRowEditForm(doc: Doc) {
if (this.showLinks) {
this.showLinks = false;
await nextTick();
}
const index = doc.idx;
const fieldname = doc.parentFieldname;
if (typeof index === 'number' && typeof fieldname === 'string') {
this.row = { index, fieldname };
}
},
async onValueChange(field: Field, value: DocValue) {
const { fieldname } = field;
delete this.errors[fieldname];
try {
await this.doc.set(fieldname, value);
} catch (err) {
if (!(err instanceof Error)) {
return;
}
this.errors[fieldname] = getErrorMessage(err, this.doc);
}
this.updateGroupedFields();
},
},
});
</script>
|
2302_79757062/books
|
src/pages/CommonForm/CommonForm.vue
|
Vue
|
agpl-3.0
| 13,296
|
<template>
<div v-if="(fields ?? []).length > 0">
<div
v-if="showTitle && title"
class="flex justify-between items-center select-none"
:class="[collapsed ? '' : 'mb-4', collapsible ? 'cursor-pointer' : '']"
@click="toggleCollapsed"
>
<h2 class="text-base text-gray-900 dark:text-gray-25 font-semibold">
{{ title }}
</h2>
<feather-icon
v-if="collapsible"
:name="collapsed ? 'chevron-up' : 'chevron-down'"
class="w-4 h-4 text-gray-600 dark:text-gray-400"
/>
</div>
<div v-if="!collapsed" class="grid gap-4 gap-x-8 grid-cols-2">
<div
v-for="field of fields"
:key="field.fieldname"
:class="[
field.fieldtype === 'Table' ? 'col-span-2 text-base' : '',
field.fieldtype === 'AttachImage' ? 'row-span-2' : '',
field.fieldtype === 'Check' ? 'mt-auto' : 'mb-auto',
]"
>
<Table
v-if="field.fieldtype === 'Table'"
ref="fields"
:show-label="true"
:border="true"
:df="field"
:value="tableValue(doc[field.fieldname])"
@editrow="(doc: Doc) => $emit('editrow', doc)"
@change="(value: DocValue) => $emit('value-change', field, value)"
@row-change="(field:Field, value:DocValue, parentfield:Field) => $emit('row-change',field, value, parentfield)"
/>
<FormControl
v-else
:ref="field.fieldname === 'name' ? 'nameField' : 'fields'"
:size="field.fieldtype === 'AttachImage' ? 'form' : undefined"
:show-label="true"
:border="true"
:df="field"
:value="doc[field.fieldname]"
@editrow="(doc: Doc) => $emit('editrow', doc)"
@change="(value: DocValue) => $emit('value-change', field, value)"
@row-change="(field:Field, value:DocValue, parentfield:Field) => $emit('row-change',field, value, parentfield)"
/>
<div v-if="errors?.[field.fieldname]" class="text-sm text-red-600 mt-1">
{{ errors[field.fieldname] }}
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { DocValue } from 'fyo/core/types';
import { Doc } from 'fyo/model/doc';
import { Field } from 'schemas/types';
import FormControl from 'src/components/Controls/FormControl.vue';
import Table from 'src/components/Controls/Table.vue';
import { focusOrSelectFormControl } from 'src/utils/ui';
import { defineComponent, PropType } from 'vue';
export default defineComponent({
components: { FormControl, Table },
props: {
title: { type: String, default: '' },
errors: {
type: Object as PropType<Record<string, string>>,
required: true,
},
showTitle: Boolean,
doc: { type: Object as PropType<Doc>, required: true },
collapsible: { type: Boolean, default: true },
fields: { type: Array as PropType<Field[]>, required: true },
},
emits: ['editrow', 'value-change', 'row-change'],
data() {
return { collapsed: false } as {
collapsed: boolean;
};
},
mounted() {
focusOrSelectFormControl(this.doc, this.$refs.nameField);
},
methods: {
tableValue(value: unknown): unknown[] {
if (Array.isArray(value)) {
return value;
}
return [];
},
toggleCollapsed() {
if (!this.collapsible) {
return;
}
this.collapsed = !this.collapsed;
},
},
});
</script>
|
2302_79757062/books
|
src/pages/CommonForm/CommonFormSection.vue
|
Vue
|
agpl-3.0
| 3,523
|
<template>
<div
class="
w-quick-edit
bg-white
dark:bg-gray-850
border-l
dark:border-gray-800
overflow-y-auto
custom-scroll custom-scroll-thumb2
"
>
<!-- Page Header -->
<div
class="
flex
items-center
justify-between
px-4
h-row-largest
sticky
top-0
bg-white
dark:bg-gray-850
"
style="z-index: 1"
>
<div class="flex items-center justify-between w-full">
<Button :icon="true" @click="$emit('close')">
<feather-icon name="x" class="w-4 h-4" />
</Button>
<p class="text-xl font-semibold text-gray-600 dark:text-gray-400">
{{ t`Linked Entries` }}
</p>
</div>
</div>
<!-- Linked Entry List -->
<div
v-if="sequence.length"
class="
w-full
overflow-y-auto
custom-scroll custom-scroll-thumb2
border-t
dark:border-gray-800
"
>
<div
v-for="sn of sequence"
:key="sn"
class="border-b dark:border-gray-800 p-4 overflow-auto"
>
<!-- Header with count and schema label -->
<div
class="flex justify-between cursor-pointer"
:class="entries[sn].collapsed ? '' : 'pb-4'"
@click="entries[sn].collapsed = !entries[sn].collapsed"
>
<h2
class="
text-base text-gray-600
dark:text-gray-400
font-semibold
select-none
"
>
{{ fyo.schemaMap[sn]?.label ?? sn
}}<span class="font-normal">{{
` – ${entries[sn].details.length}`
}}</span>
</h2>
<feather-icon
:name="entries[sn].collapsed ? 'chevron-up' : 'chevron-down'"
class="w-4 h-4 text-gray-600 dark:text-gray-400"
/>
</div>
<!-- Entry list -->
<div
v-show="!entries[sn].collapsed"
class="
entry-container
rounded-md
border
dark:border-gray-800
overflow-hidden
"
>
<!-- Entry -->
<div
v-for="e of entries[sn].details"
:key="String(e.name) + sn"
class="
p-2
text-sm
cursor-pointer
border-b
last:border-0
dark:border-gray-800
hover:bg-gray-50
dark:hover:bg-gray-875
"
@click="routeTo(sn, String(e.name))"
>
<div class="flex justify-between">
<!-- Name -->
<p class="font-semibold dark:text-gray-25">
{{ e.name }}
</p>
<!-- Date -->
<p v-if="e.date" class="text-xs text-gray-600 dark:text-gray-400">
{{ fyo.format(e.date, 'Date') }}
</p>
</div>
<div class="flex gap-2 mt-1 pill-container flex-wrap">
<!-- Credit or Debit (GLE) -->
<p
v-if="isPesa(e.credit) && e.credit.isPositive()"
class="pill"
:class="colorClass('gray')"
>
{{ t`Cr. ${fyo.format(e.credit, 'Currency')}` }}
</p>
<p
v-else-if="isPesa(e.debit) && e.debit.isPositive()"
class="pill"
:class="colorClass('gray')"
>
{{ t`Dr. ${fyo.format(e.debit, 'Currency')}` }}
</p>
<!-- Party or EntryType or Account -->
<p
v-if="e.party || e.entryType || e.account"
class="pill"
:class="colorClass('gray')"
>
{{ e.party || e.entryType || e.account }}
</p>
<p v-if="e.item" class="pill" :class="colorClass('gray')">
{{ e.item }}
</p>
<p v-if="e.location" class="pill" :class="colorClass('gray')">
{{ e.location }}
</p>
<!-- Amounts -->
<p
v-if="
isPesa(e.outstandingAmount) &&
e.outstandingAmount.isPositive()
"
class="pill no-scrollbar"
:class="colorClass('orange')"
>
{{ t`Unpaid ${fyo.format(e.outstandingAmount, 'Currency')}` }}
</p>
<p
v-else-if="isPesa(e.grandTotal) && e.grandTotal.isPositive()"
class="pill no-scrollbar"
:class="colorClass('green')"
>
{{ fyo.format(e.grandTotal, 'Currency') }}
</p>
<p
v-else-if="isPesa(e.amount) && e.amount.isPositive()"
class="pill no-scrollbar"
:class="colorClass('green')"
>
{{ fyo.format(e.amount, 'Currency') }}
</p>
<!-- Quantities -->
<p
v-if="e.stockNotTransferred"
class="pill no-scrollbar"
:class="colorClass('orange')"
>
{{
t`Pending qty. ${fyo.format(e.stockNotTransferred, 'Float')}`
}}
</p>
<p
v-else-if="typeof e.quantity === 'number' && e.quantity"
class="pill no-scrollbar"
:class="colorClass('gray')"
>
{{ t`Qty. ${fyo.format(e.quantity, 'Float')}` }}
</p>
</div>
</div>
</div>
</div>
</div>
<p v-else class="p-4 text-sm text-gray-600 dark:text-gray-400">
{{ t`No linked entries found` }}
</p>
</div>
</template>
<script lang="ts">
import { Doc } from 'fyo/model/doc';
import { isPesa } from 'fyo/utils';
import { ModelNameEnum } from 'models/types';
import Button from 'src/components/Button.vue';
import { getBgTextColorClass } from 'src/utils/colors';
import { getLinkedEntries } from 'src/utils/doc';
import { shortcutsKey } from 'src/utils/injectionKeys';
import { getFormRoute, routeTo } from 'src/utils/ui';
import { PropType, defineComponent, inject } from 'vue';
const COMPONENT_NAME = 'LinkedEntries';
export default defineComponent({
components: { Button },
props: { doc: { type: Object as PropType<Doc>, required: true } },
emits: ['close'],
setup() {
return { shortcuts: inject(shortcutsKey) };
},
data() {
return { entries: {} } as {
entries: Record<
string,
{ collapsed: boolean; details: Record<string, unknown>[] }
>;
};
},
computed: {
sequence(): string[] {
const seq: string[] = linkSequence.filter(
(s) => !!this.entries[s]?.details?.length
);
for (const s in this.entries) {
if (seq.includes(s)) {
continue;
}
seq.push(s);
}
return seq;
},
},
async mounted() {
await this.setLinkedEntries();
this.shortcuts?.set(COMPONENT_NAME, ['Escape'], () => this.$emit('close'));
},
unmounted() {
this.shortcuts?.delete(COMPONENT_NAME);
},
methods: {
isPesa,
colorClass: getBgTextColorClass,
async routeTo(schemaName: string, name: string) {
const route = getFormRoute(schemaName, name);
await routeTo(route);
},
async setLinkedEntries() {
const linkedEntries = await getLinkedEntries(this.doc);
for (const key in linkedEntries) {
const collapsed = false;
const entryNames = linkedEntries[key];
if (!entryNames.length) {
continue;
}
const fields = linkEntryDisplayFields[key] ?? ['name'];
const details = await this.fyo.db.getAll(key, {
fields,
filters: { name: ['in', entryNames] },
});
this.entries[key] = {
collapsed,
details,
};
}
},
},
});
const linkSequence = [
// Invoices
ModelNameEnum.SalesInvoice,
ModelNameEnum.PurchaseInvoice,
// Stock Transfers
ModelNameEnum.Shipment,
ModelNameEnum.PurchaseReceipt,
// Other Transactional
ModelNameEnum.Payment,
ModelNameEnum.JournalEntry,
ModelNameEnum.StockMovement,
// Non Transfers
ModelNameEnum.Party,
ModelNameEnum.Item,
ModelNameEnum.Account,
ModelNameEnum.Location,
// Ledgers
ModelNameEnum.AccountingLedgerEntry,
ModelNameEnum.StockLedgerEntry,
];
const linkEntryDisplayFields: Record<string, string[]> = {
// Invoices
[ModelNameEnum.SalesInvoice]: [
'name',
'date',
'party',
'grandTotal',
'outstandingAmount',
'stockNotTransferred',
],
[ModelNameEnum.PurchaseInvoice]: [
'name',
'date',
'party',
'grandTotal',
'outstandingAmount',
'stockNotTransferred',
],
// Stock Transfers
[ModelNameEnum.Shipment]: ['name', 'date', 'party', 'grandTotal'],
[ModelNameEnum.PurchaseReceipt]: ['name', 'date', 'party', 'grandTotal'],
// Other Transactional
[ModelNameEnum.Payment]: ['name', 'date', 'party', 'amount'],
[ModelNameEnum.JournalEntry]: ['name', 'date', 'entryType'],
[ModelNameEnum.StockMovement]: ['name', 'date', 'amount'],
// Ledgers
[ModelNameEnum.AccountingLedgerEntry]: [
'name',
'date',
'account',
'credit',
'debit',
],
[ModelNameEnum.StockLedgerEntry]: [
'name',
'date',
'item',
'location',
'quantity',
],
};
</script>
<style scoped>
.pill-container:empty {
display: none;
}
</style>
|
2302_79757062/books
|
src/pages/CommonForm/LinkedEntries.vue
|
Vue
|
agpl-3.0
| 9,693
|
<template>
<div
class="
border-s
dark:border-gray-800
h-full
overflow-auto
w-quick-edit
bg-white
dark:bg-gray-890
custom-scroll custom-scroll-thumb2
"
>
<!-- Row Edit Tool bar -->
<div
class="
sticky
top-0
border-b
dark:border-gray-800
bg-white
dark:bg-gray-890
"
style="z-index: 1"
>
<div class="flex items-center justify-between px-4 h-row-largest">
<!-- Close Button -->
<Button :icon="true" @click="$emit('close')">
<feather-icon name="x" class="w-4 h-4" />
</Button>
<!-- Actions, Badge and Status Change Buttons -->
<div class="flex items-stretch gap-2">
<Button
v-if="previous >= 0"
:icon="true"
@click="$emit('previous', previous)"
>
<feather-icon name="chevron-left" class="w-4 h-4" />
</Button>
<Button v-if="next >= 0" :icon="true" @click="$emit('next', next)">
<feather-icon name="chevron-right" class="w-4 h-4" />
</Button>
</div>
</div>
<FormHeader
class="border-t dark:border-gray-800"
:form-title="t`Row ${index + 1}`"
:form-sub-title="fieldlabel"
/>
</div>
<TwoColumnForm
ref="form"
class="w-full"
:doc="row"
:fields="fields"
:column-ratio="[1.1, 2]"
/>
</div>
</template>
<script lang="ts">
import { Doc } from 'fyo/model/doc';
import { ValueError } from 'fyo/utils/errors';
import Button from 'src/components/Button.vue';
import FormHeader from 'src/components/FormHeader.vue';
import TwoColumnForm from 'src/components/TwoColumnForm.vue';
import { shortcutsKey } from 'src/utils/injectionKeys';
import { computed } from 'vue';
import { inject } from 'vue';
import { defineComponent } from 'vue';
const COMPONENT_NAME = 'RowEditForm';
export default defineComponent({
components: { Button, TwoColumnForm, FormHeader },
provide() {
return {
doc: computed(() => this.row),
};
},
props: {
doc: { type: Doc, required: true },
index: { type: Number, required: true },
fieldname: { type: String, required: true },
},
emits: ['next', 'previous', 'close'],
setup() {
return { shortcuts: inject(shortcutsKey) };
},
computed: {
fieldlabel() {
return (
this.fyo.getField(this.doc.schemaName, this.fieldname)?.label ?? ''
);
},
row() {
const rows = this.doc.get(this.fieldname);
if (Array.isArray(rows) && rows[this.index] instanceof Doc) {
return rows[this.index];
}
const label = `${this.doc.name ?? '_name'}.${this.fieldname}[${
this.index
}]`;
throw new ValueError(this.t`Invalid value found for ${label}`);
},
fields() {
const fieldnames = this.row.schema.quickEditFields ?? [];
return fieldnames.map((f) => this.fyo.getField(this.row.schemaName, f));
},
previous(): number {
return this.index - 1;
},
next() {
const rows = this.doc.get(this.fieldname);
if (!Array.isArray(rows)) {
return -1;
}
if (rows.length - 1 === this.index) {
return -1;
}
return this.index + 1;
},
},
mounted() {
this.shortcuts?.set(COMPONENT_NAME, ['Escape'], () => this.$emit('close'));
},
unmounted() {
this.shortcuts?.delete(COMPONENT_NAME);
},
});
</script>
|
2302_79757062/books
|
src/pages/CommonForm/RowEditForm.vue
|
Vue
|
agpl-3.0
| 3,501
|
<template>
<div>
<PageHeader :title="t`Customize Form`">
<DropdownWithActions :actions="[]" :disabled="false" :title="t`More`" />
<Button :title="t`Save Customizations`" type="primary">
{{ t`Save` }}
</Button>
</PageHeader>
<div class="flex text-base w-full flex-col">
<!-- Select Entry Type -->
<div
class="
h-row-largest
flex flex-row
justify-start
items-center
w-full
gap-2
border-b
dark:border-gray-800
p-4
"
>
<AutoComplete
:df="{
fieldname: 'formType',
label: t`Form Type`,
fieldtype: 'AutoComplete',
options: customizableSchemas,
}"
input-class="bg-transparent text-gray-900 dark:text-gray-100 text-base"
class="w-40"
:border="true"
:value="formType"
size="small"
@change="setEntryType"
/>
<p v-if="errorMessage" class="text-base ms-2 text-red-500">
{{ errorMessage }}
</p>
<p
v-else-if="helpMessage"
class="text-base ms-2 text-gray-700 dark:text-gray-300"
>
{{ helpMessage }}
</p>
</div>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import DropdownWithActions from 'src/components/DropdownWithActions.vue';
import Button from 'src/components/Button.vue';
import PageHeader from 'src/components/PageHeader.vue';
import AutoComplete from 'src/components/Controls/AutoComplete.vue';
import { ModelNameEnum } from 'models/types';
export default defineComponent({
components: { PageHeader, Button, DropdownWithActions, AutoComplete },
data() {
return { errorMessage: '', formType: '' };
},
computed: {
customizableSchemas() {
const schemaNames = Object.keys(this.fyo.schemaMap).filter(
(schemaName) => {
const schema = this.fyo.schemaMap[schemaName];
if (!schema) {
return false;
}
if (schema?.isSingle) {
return false;
}
return ![
ModelNameEnum.NumberSeries,
ModelNameEnum.SingleValue,
ModelNameEnum.SetupWizard,
ModelNameEnum.PatchRun,
].includes(schemaName as ModelNameEnum);
}
);
return schemaNames.map((sn) => ({
value: sn,
label: this.fyo.schemaMap[sn]?.label ?? sn,
}));
},
helpMessage() {
if (!this.formType) {
return this.t`Select a form type to customize`;
}
return '';
},
},
methods: {
setEntryType(type: string) {
this.formType = type;
},
},
});
</script>
|
2302_79757062/books
|
src/pages/CustomizeForm/CustomizeForm.vue
|
Vue
|
agpl-3.0
| 2,787
|
<script lang="ts">
import { PeriodKey } from 'src/utils/types';
import { PropType } from 'vue';
import { defineComponent } from 'vue';
export default defineComponent({
props: {
commonPeriod: { type: String as PropType<PeriodKey>, default: 'This Year' },
},
emits: ['period-change'],
data() {
return {
period: 'This Year' as PeriodKey,
periodOptions: [
'This Year',
'YTD',
'This Quarter',
'This Month',
] as PeriodKey[],
};
},
watch: {
period: 'periodChange',
commonPeriod(val: PeriodKey) {
if (!this.periodOptions.includes(val)) {
return;
}
this.period = val;
},
},
methods: {
async periodChange() {
this.$emit('period-change', this.period);
await this.setData();
},
async setData() {
return Promise.resolve(null);
},
},
});
</script>
|
2302_79757062/books
|
src/pages/Dashboard/BaseDashboardChart.vue
|
Vue
|
agpl-3.0
| 889
|
<template>
<div>
<!-- Title and Period Selector -->
<div class="flex items-center justify-between">
<div class="font-semibold text-base dark:text-white">
{{ t`Cashflow` }}
</div>
<!-- Chart Legend -->
<div v-if="hasData" class="flex text-base gap-8">
<div class="flex items-center gap-2">
<span
class="w-3 h-3 rounded-sm inline-block bg-blue-500 dark:bg-blue-600"
/>
<span class="text-gray-900 dark:text-gray-25">{{ t`Inflow` }}</span>
</div>
<div class="flex items-center gap-2">
<span
class="w-3 h-3 rounded-sm inline-block bg-pink-500 dark:bg-pink-600"
/>
<span class="text-gray-900 dark:text-gray-25">{{ t`Outflow` }}</span>
</div>
</div>
<div v-else class="w-16 h-5 bg-gray-200 dark:bg-gray-700 rounded" />
<PeriodSelector
v-if="hasData"
:value="period"
:options="periodOptions"
@change="(value) => (period = value)"
/>
<div v-else class="w-20 h-5 bg-gray-200 dark:bg-gray-700 rounded" />
</div>
<!-- Line Chart -->
<LineChart
v-if="chartData.points.length"
class="mt-4"
:aspect-ratio="4.15"
:colors="chartData.colors"
:gridColor="chartData.gridColor"
:fontColor="chartData.fontColor"
:points="chartData.points"
:x-labels="chartData.xLabels"
:format="chartData.format"
:format-x="chartData.formatX"
:y-max="chartData.yMax"
:draw-labels="hasData"
:show-tooltip="hasData"
/>
</div>
</template>
<script lang="ts">
import { AccountTypeEnum } from 'models/baseModels/Account/types';
import { ModelNameEnum } from 'models/types';
import LineChart from 'src/components/Charts/LineChart.vue';
import { fyo } from 'src/initFyo';
import { formatXLabels, getYMax } from 'src/utils/chart';
import { uicolors } from 'src/utils/colors';
import { getDatesAndPeriodList } from 'src/utils/misc';
import DashboardChartBase from './BaseDashboardChart.vue';
import PeriodSelector from './PeriodSelector.vue';
import { defineComponent } from 'vue';
import { getMapFromList } from 'utils/index';
import { PeriodKey } from 'src/utils/types';
// Linting broken in this file cause of `extends: ...`
/*
eslint-disable @typescript-eslint/no-unsafe-argument,
@typescript-eslint/no-unsafe-return
*/
export default defineComponent({
name: 'Cashflow',
components: {
PeriodSelector,
LineChart,
},
props: {
darkMode: { type: Boolean, default: false },
},
extends: DashboardChartBase,
data: () => ({
data: [] as { inflow: number; outflow: number; yearmonth: string }[],
periodList: [],
periodOptions: ['This Year', 'This Quarter', 'YTD'],
hasData: false,
}),
computed: {
chartData() {
let data = this.data;
let colors = [
uicolors.blue[this.darkMode ? '600' : '500'],
uicolors.pink[this.darkMode ? '600' : '500'],
];
if (!this.hasData) {
data = dummyData;
colors = [
this.darkMode ? uicolors.gray['700'] : uicolors.gray['200'],
this.darkMode ? uicolors.gray['800'] : uicolors.gray['100'],
];
}
const xLabels = data.map((cf) => cf.yearmonth);
const points = (['inflow', 'outflow'] as const).map((k) =>
data.map((d) => d[k])
);
const format = (value: number) => fyo.format(value ?? 0, 'Currency');
const yMax = getYMax(points);
return {
points,
xLabels,
colors,
format,
yMax,
formatX: formatXLabels,
gridColor: this.darkMode ? 'rgba(200, 200, 200, 0.2)' : undefined,
fontColor: this.darkMode ? uicolors.gray['400'] : undefined,
};
},
},
async activated() {
await this.setData();
if (!this.hasData) {
await this.setHasData();
}
},
methods: {
async setData() {
const { periodList, fromDate, toDate } = getDatesAndPeriodList(
this.period as PeriodKey
);
const data = await fyo.db.getCashflow(fromDate.toISO(), toDate.toISO());
const dataMap = getMapFromList(data, 'yearmonth');
this.data = periodList.map((p) => {
const key = p.toFormat('yyyy-MM');
const item = dataMap[key];
if (item) {
return item;
}
return {
inflow: 0,
outflow: 0,
yearmonth: key,
};
});
},
async setHasData() {
const accounts = await fyo.db.getAllRaw('Account', {
filters: {
accountType: ['in', [AccountTypeEnum.Cash, AccountTypeEnum.Bank]],
},
});
const accountNames = accounts.map((a) => a.name as string);
const count = await fyo.db.count(ModelNameEnum.AccountingLedgerEntry, {
filters: { account: ['in', accountNames] },
});
this.hasData = count > 0;
},
},
});
const dummyData = [
{
inflow: 100,
outflow: 250,
yearmonth: '2021-05',
},
{
inflow: 350,
outflow: 100,
yearmonth: '2021-06',
},
{
inflow: 50,
outflow: 300,
yearmonth: '2021-07',
},
{
inflow: 320,
outflow: 100,
yearmonth: '2021-08',
},
];
</script>
|
2302_79757062/books
|
src/pages/Dashboard/Cashflow.vue
|
Vue
|
agpl-3.0
| 5,250
|
<template>
<div class="h-screen" style="width: var(--w-desk)">
<PageHeader :title="t`Dashboard`">
<div
class="
border
dark:border-gray-900
rounded
bg-gray-50
dark:bg-gray-890
focus-within:bg-gray-100
dark:focus-within:bg-gray-900
flex
items-center
"
>
<PeriodSelector
class="px-3"
:value="period"
:options="['This Year', 'This Quarter', 'This Month', 'YTD']"
@change="(value) => (period = value)"
/>
</div>
</PageHeader>
<div
class="no-scrollbar overflow-auto dark:bg-gray-875"
style="height: calc(100vh - var(--h-row-largest) - 1px)"
>
<div style="min-width: var(--w-desk-fixed)" class="overflow-auto">
<Cashflow
class="p-4"
:common-period="period"
:darkMode="darkMode"
@period-change="handlePeriodChange"
/>
<hr class="dark:border-gray-800" />
<div class="flex w-full">
<UnpaidInvoices
:schema-name="'SalesInvoice'"
:common-period="period"
:darkMode="darkMode"
class="border-e dark:border-gray-800"
@period-change="handlePeriodChange"
/>
<UnpaidInvoices
:schema-name="'PurchaseInvoice'"
:common-period="period"
:darkMode="darkMode"
@period-change="handlePeriodChange"
/>
</div>
<hr class="dark:border-gray-800" />
<div class="flex">
<ProfitAndLoss
class="w-full p-4 border-e dark:border-gray-800"
:common-period="period"
:darkMode="darkMode"
@period-change="handlePeriodChange"
/>
<Expenses
class="w-full p-4"
:common-period="period"
:darkMode="darkMode"
@period-change="handlePeriodChange"
/>
</div>
<hr class="dark:border-gray-800" />
</div>
</div>
</div>
</template>
<script>
import PageHeader from 'src/components/PageHeader.vue';
import UnpaidInvoices from './UnpaidInvoices.vue';
import Cashflow from './Cashflow.vue';
import Expenses from './Expenses.vue';
import PeriodSelector from './PeriodSelector.vue';
import ProfitAndLoss from './ProfitAndLoss.vue';
import { docsPathRef } from 'src/utils/refs';
export default {
name: 'Dashboard',
components: {
PageHeader,
Cashflow,
ProfitAndLoss,
Expenses,
PeriodSelector,
UnpaidInvoices,
},
props: {
darkMode: { type: Boolean, default: false },
},
data() {
return { period: 'This Year' };
},
activated() {
docsPathRef.value = 'books/dashboard';
},
deactivated() {
docsPathRef.value = '';
},
methods: {
handlePeriodChange(period) {
if (period === this.period) {
return;
}
this.period = '';
},
},
};
</script>
|
2302_79757062/books
|
src/pages/Dashboard/Dashboard.vue
|
Vue
|
agpl-3.0
| 2,989
|
<template>
<div class="flex flex-col h-full">
<SectionHeader>
<template #title>{{ t`Top Expenses` }}</template>
<template #action>
<PeriodSelector :value="period" @change="(value) => (period = value)" />
</template>
</SectionHeader>
<div v-show="hasData" class="flex relative">
<!-- Chart Legend -->
<div class="w-1/2 flex flex-col gap-4 justify-center dark:text-gray-25">
<!-- Ledgend Item -->
<div
v-for="(d, i) in expenses"
:key="d.account"
class="flex items-center text-sm"
@mouseover="active = i"
@mouseleave="active = null"
>
<div class="w-3 h-3 rounded-sm flex-shrink-0" :class="d.class" />
<p class="ms-2 overflow-x-auto whitespace-nowrap no-scrollbar w-28">
{{ d.account }}
</p>
<p class="whitespace-nowrap flex-shrink-0 ms-auto">
{{ fyo.format(d?.total ?? 0, 'Currency') }}
</p>
</div>
</div>
<DonutChart
class="w-1/2 my-auto"
:active="active"
:sectors="sectors"
:offset-x="3"
:thickness="10"
:text-offset-x="6.5"
:value-formatter="(value: number) => fyo.format(value, 'Currency')"
:total-label="t`Total Spending`"
:darkMode="darkMode"
@change="(value: number) => (active = value)"
/>
</div>
<!-- Empty Message -->
<div
v-if="expenses.length === 0"
class="flex-1 w-full h-full flex-center my-20"
>
<span class="text-base text-gray-600 dark:text-gray-500">
{{ t`No expenses in this period` }}
</span>
</div>
</div>
</template>
<script lang="ts">
import { truncate } from 'lodash';
import { fyo } from 'src/initFyo';
import { uicolors } from 'src/utils/colors';
import { getDatesAndPeriodList } from 'src/utils/misc';
import { defineComponent } from 'vue';
import DonutChart from '../../components/Charts/DonutChart.vue';
import DashboardChartBase from './BaseDashboardChart.vue';
import PeriodSelector from './PeriodSelector.vue';
import SectionHeader from './SectionHeader.vue';
// Linting broken in this file cause of `extends: ...`
/*
eslint-disable @typescript-eslint/no-unsafe-argument,
@typescript-eslint/no-unsafe-return,
@typescript-eslint/restrict-plus-operands
*/
export default defineComponent({
name: 'Expenses',
components: {
DonutChart,
PeriodSelector,
SectionHeader,
},
props: {
darkMode: { type: Boolean, default: false },
},
extends: DashboardChartBase,
data: () => ({
active: null as null | number,
expenses: [] as {
account: string;
total: number;
color: { color: string; darkColor: string };
class: { class: string; darkClass: string };
}[],
}),
computed: {
totalExpense(): number {
return this.expenses.reduce((sum, expense) => sum + expense.total, 0);
},
hasData(): boolean {
return this.expenses.length > 0;
},
sectors(): {
color: { color: string; darkColor: string };
label: string;
value: number;
}[] {
return this.expenses.map(({ account, color, total }) => ({
color,
label: truncate(account, { length: 21 }),
value: total,
}));
},
},
activated() {
this.setData();
},
methods: {
async setData() {
const { fromDate, toDate } = getDatesAndPeriodList(this.period);
let topExpenses = await fyo.db.getTopExpenses(
fromDate.toISO(),
toDate.toISO()
);
const shades = [
{ class: 'bg-pink-500', hex: uicolors.pink['500'] },
{ class: 'bg-pink-400', hex: uicolors.pink['400'] },
{ class: 'bg-pink-300', hex: uicolors.pink['300'] },
{ class: 'bg-pink-200', hex: uicolors.pink['200'] },
{ class: 'bg-pink-100', hex: uicolors.pink['100'] },
];
const darkshades = [
{ class: 'bg-pink-600', hex: uicolors.pink['600'] },
{ class: 'bg-pink-500', hex: uicolors.pink['500'] },
{ class: 'bg-pink-400', hex: uicolors.pink['400'] },
{ class: 'bg-pink-300', hex: uicolors.pink['300'] },
{
class: 'bg-pink-200 dark:bg-opacity-80',
hex: uicolors.pink['200'] + 'CC',
},
];
this.expenses = topExpenses
.filter((e) => e.total > 0)
.map((d, i) => {
return {
account: d.account,
total: d.total,
color: { color: shades[i].hex, darkColor: darkshades[i].hex },
class: { class: shades[i].class, darkClass: darkshades[i].class },
};
});
},
},
});
</script>
|
2302_79757062/books
|
src/pages/Dashboard/Expenses.vue
|
Vue
|
agpl-3.0
| 4,678
|
<template>
<Dropdown ref="dropdown" class="text-sm" :items="periodOptions" right>
<template
#default="{
toggleDropdown,
highlightItemUp,
highlightItemDown,
selectHighlightedItem,
}"
>
<div
class="
text-sm
flex
focus:outline-none
hover:text-gray-800
dark:hover:text-gray-100
focus:text-gray-800
dark:focus:text-gray-100
items-center
py-1
rounded-md
leading-relaxed
cursor-pointer
"
:class="
!value
? 'text-gray-600 dark:text-gray-500'
: 'text-gray-900 dark:text-gray-300'
"
tabindex="0"
@click="toggleDropdown()"
@keydown.down="highlightItemDown"
@keydown.up="highlightItemUp"
@keydown.enter="selectHighlightedItem"
>
{{ periodSelectorMap?.[value] ?? value }}
<feather-icon name="chevron-down" class="ms-1 w-3 h-3" />
</div>
</template>
</Dropdown>
</template>
<script lang="ts">
import { t } from 'fyo';
import Dropdown from 'src/components/Dropdown.vue';
import { PeriodKey } from 'src/utils/types';
import { PropType } from 'vue';
import { defineComponent } from 'vue';
export default defineComponent({
name: 'PeriodSelector',
components: {
Dropdown,
},
props: {
value: { type: String as PropType<PeriodKey>, default: 'This Year' },
options: {
type: Array as PropType<PeriodKey[]>,
default: () => ['This Year', 'This Quarter', 'This Month', 'YTD'],
},
},
emits: ['change'],
data() {
return {
periodSelectorMap: {} as Record<PeriodKey | '', string>,
periodOptions: [] as { label: string; action: () => void }[],
};
},
mounted() {
this.periodSelectorMap = {
'': t`Set Period`,
'This Year': t`This Year`,
YTD: t`Year to Date`,
'This Quarter': t`This Quarter`,
'This Month': t`This Month`,
};
this.periodOptions = this.options.map((option) => {
let label = this.periodSelectorMap[option] ?? option;
return {
label,
action: () => this.selectOption(option),
};
});
},
methods: {
selectOption(value: PeriodKey) {
this.$emit('change', value);
(this.$refs.dropdown as InstanceType<typeof Dropdown>).toggleDropdown(
false
);
},
},
});
</script>
|
2302_79757062/books
|
src/pages/Dashboard/PeriodSelector.vue
|
Vue
|
agpl-3.0
| 2,447
|
<template>
<div class="flex flex-col h-full">
<SectionHeader>
<template #title>{{ t`Profit and Loss` }}</template>
<template #action>
<PeriodSelector
:value="period"
:options="periodOptions"
@change="(value) => (period = value)"
/>
</template>
</SectionHeader>
<BarChart
v-if="hasData"
class="mt-4"
:aspect-ratio="2.05"
:colors="chartData.colors"
:gridColor="chartData.gridColor"
:fontColor="chartData.fontColor"
:points="chartData.points"
:x-labels="chartData.xLabels"
:format="chartData.format"
:format-x="chartData.formatX"
:y-max="chartData.yMax"
:y-min="chartData.yMin"
/>
<div v-else class="flex-1 w-full h-full flex-center my-20">
<span class="text-base text-gray-600 dark:text-gray-500">
{{ t`No transactions yet` }}
</span>
</div>
</div>
</template>
<script lang="ts">
import BarChart from 'src/components/Charts/BarChart.vue';
import { fyo } from 'src/initFyo';
import { formatXLabels, getYMax, getYMin } from 'src/utils/chart';
import { uicolors } from 'src/utils/colors';
import { getDatesAndPeriodList } from 'src/utils/misc';
import { getValueMapFromList } from 'utils';
import DashboardChartBase from './BaseDashboardChart.vue';
import PeriodSelector from './PeriodSelector.vue';
import SectionHeader from './SectionHeader.vue';
import { defineComponent } from 'vue';
// Linting broken in this file cause of `extends: ...`
/*
eslint-disable @typescript-eslint/no-unsafe-argument,
@typescript-eslint/no-unsafe-return
*/
export default defineComponent({
name: 'ProfitAndLoss',
components: {
PeriodSelector,
SectionHeader,
BarChart,
},
props: {
darkMode: { type: Boolean, default: false },
},
extends: DashboardChartBase,
data: () => ({
data: [] as { yearmonth: string; balance: number }[],
hasData: false,
periodOptions: ['This Year', 'This Quarter', 'YTD'],
}),
computed: {
chartData() {
const points = [this.data.map((d) => d.balance)];
const colors = [
{
positive: uicolors.blue[this.darkMode ? '600' : '500'],
negative: uicolors.pink[this.darkMode ? '600' : '500'],
},
];
const format = (value: number) => fyo.format(value ?? 0, 'Currency');
const yMax = getYMax(points);
const yMin = getYMin(points);
return {
xLabels: this.data.map((d) => d.yearmonth),
points,
format,
colors,
yMax,
yMin,
formatX: formatXLabels,
gridColor: this.darkMode ? 'rgba(200, 200, 200, 0.2)' : undefined,
fontColor: this.darkMode ? uicolors.gray['400'] : undefined,
zeroLineColor: this.darkMode ? uicolors.gray['400'] : undefined,
};
},
},
activated() {
this.setData();
},
methods: {
async setData() {
const { fromDate, toDate, periodList } = getDatesAndPeriodList(
this.period
);
const data = await fyo.db.getIncomeAndExpenses(
fromDate.toISO(),
toDate.toISO()
);
const incomes = getValueMapFromList(data.income, 'yearmonth', 'balance');
const expenses = getValueMapFromList(
data.expense,
'yearmonth',
'balance'
);
this.data = periodList.map((d) => {
const key = d.toFormat('yyyy-MM');
const inc = incomes[key] ?? 0;
const exp = expenses[key] ?? 0;
return { yearmonth: key, balance: inc - exp };
});
this.hasData = data.income.length > 0 || data.expense.length > 0;
},
},
});
</script>
|
2302_79757062/books
|
src/pages/Dashboard/ProfitAndLoss.vue
|
Vue
|
agpl-3.0
| 3,653
|
<template>
<div class="flex items-baseline justify-between dark:text-white">
<span class="font-semibold text-base"><slot name="title"></slot></span>
<slot name="action"></slot>
</div>
</template>
|
2302_79757062/books
|
src/pages/Dashboard/SectionHeader.vue
|
Vue
|
agpl-3.0
| 208
|
<template>
<div class="flex-col justify-between w-full p-4">
<!-- Title and Period Selector -->
<SectionHeader>
<template #title>{{ title }}</template>
<template #action>
<PeriodSelector :value="period" @change="(value) => (period = value)" />
</template>
</SectionHeader>
<!-- Widget Body -->
<div class="mt-4">
<!-- Paid & Unpaid Amounts -->
<div class="flex justify-between">
<!-- Paid -->
<div
class="text-sm font-medium dark:text-gray-25"
:class="{
'bg-gray-200 dark:bg-gray-700 text-gray-200 dark:text-gray-700 rounded':
!count,
'cursor-pointer': paidCount > 0,
}"
:title="paidCount > 0 ? t`View Paid Invoices` : ''"
@click="() => routeToInvoices('paid')"
>
{{ fyo.format(paid, 'Currency') }}
<span
:class="{ 'text-gray-900 dark:text-gray-200 font-normal': count }"
>{{ t`Paid` }}</span
>
</div>
<!-- Unpaid -->
<div
class="text-sm font-medium dark:text-gray-25"
:class="{
'bg-gray-200 dark:bg-gray-700 text-gray-200 dark:text-gray-700 rounded':
!count,
'cursor-pointer': unpaidCount > 0,
}"
:title="unpaidCount > 0 ? t`View Unpaid Invoices` : ''"
@click="() => routeToInvoices('unpaid')"
>
{{ fyo.format(unpaid, 'Currency') }}
<span
:class="{ 'text-gray-900 dark:text-gray-200 font-normal': count }"
>{{ t`Unpaid` }}</span
>
</div>
</div>
<!-- Widget Bar -->
<div
class="mt-2 relative rounded overflow-hidden"
@mouseenter="show = true"
@mouseleave="show = false"
>
<div class="w-full h-4" :class="unpaidColor"></div>
<div
class="absolute inset-0 h-4"
:class="paidColor"
:style="`width: ${barWidth}%`"
></div>
</div>
</div>
<MouseFollower
v-if="hasData"
:offset="15"
:show="show"
placement="top"
class="
text-sm
shadow-md
px-2
py-1
bg-white
dark:bg-gray-900
text-gray-900
dark:text-white
border-s-4
"
:style="{ borderColor: colors }"
>
<div class="flex justify-between gap-4">
<p>{{ t`Paid` }}</p>
<p class="font-semibold">{{ paidCount ?? 0 }}</p>
</div>
<div v-if="unpaidCount > 0" class="flex justify-between gap-4">
<p>{{ t`Unpaid` }}</p>
<p class="font-semibold">{{ unpaidCount ?? 0 }}</p>
</div>
</MouseFollower>
</div>
</template>
<script lang="ts">
import { t } from 'fyo';
import { DateTime } from 'luxon';
import { ModelNameEnum } from 'models/types';
import MouseFollower from 'src/components/MouseFollower.vue';
import { fyo } from 'src/initFyo';
import { uicolors } from 'src/utils/colors';
import { getDatesAndPeriodList } from 'src/utils/misc';
import { PeriodKey } from 'src/utils/types';
import { routeTo } from 'src/utils/ui';
import { safeParseFloat } from 'utils/index';
import { PropType, defineComponent } from 'vue';
import BaseDashboardChart from './BaseDashboardChart.vue';
import PeriodSelector from './PeriodSelector.vue';
import SectionHeader from './SectionHeader.vue';
// Linting broken in this file cause of `extends: ...`
/*
eslint-disable @typescript-eslint/no-unsafe-argument,
@typescript-eslint/restrict-template-expressions,
@typescript-eslint/no-unsafe-return
*/
export default defineComponent({
name: 'UnpaidInvoices',
components: {
PeriodSelector,
SectionHeader,
MouseFollower,
},
extends: BaseDashboardChart,
props: {
schemaName: { type: String as PropType<string>, required: true },
darkMode: { type: Boolean, default: false },
},
data() {
return {
show: false,
total: 0,
unpaid: 0,
hasData: false,
paid: 0,
count: 0,
unpaidCount: 0,
paidCount: 0,
barWidth: 40,
period: 'This Year',
} as {
show: boolean;
period: PeriodKey;
total: number;
unpaid: number;
hasData: boolean;
paid: number;
count: number;
unpaidCount: number;
paidCount: number;
barWidth: number;
};
},
computed: {
title(): string {
return fyo.schemaMap[this.schemaName]?.label ?? '';
},
color(): 'blue' | 'pink' {
if (this.schemaName === ModelNameEnum.SalesInvoice) {
return 'blue';
}
return 'pink';
},
colors(): string {
return uicolors[this.color][this.darkMode ? '600' : '500'];
},
paidColor(): string {
if (!this.hasData) {
return this.darkMode ? 'bg-gray-700' : 'bg-gray-400';
}
return `bg-${this.color}-${this.darkMode ? '600' : '500'}`;
},
unpaidColor(): string {
if (!this.hasData) {
return `bg-gray-${this.darkMode ? '800' : '200'}`;
}
return `bg-${this.color}-${this.darkMode ? '700 bg-opacity-20' : '200'}`;
},
},
async activated() {
await this.setData();
},
methods: {
async routeToInvoices(type: 'paid' | 'unpaid') {
if (type === 'paid' && !this.paidCount) {
return;
}
if (type === 'unpaid' && !this.unpaidCount) {
return;
}
const zero = this.fyo.pesa(0).store;
const filters = { outstandingAmount: ['=', zero] };
const schemaLabel = fyo.schemaMap[this.schemaName]?.label ?? '';
let label = t`Paid ${schemaLabel}`;
if (type === 'unpaid') {
filters.outstandingAmount[0] = '!=';
label = t`Unpaid ${schemaLabel}`;
}
const path = `/list/${this.schemaName}/${label}`;
const query = { filters: JSON.stringify(filters) };
await routeTo({ path, query });
},
async setData() {
const { fromDate, toDate } = getDatesAndPeriodList(this.period);
const { total, outstanding } = await fyo.db.getTotalOutstanding(
this.schemaName,
fromDate.toISO(),
toDate.toISO()
);
const { countTotal, countOutstanding } = await this.getCounts(
this.schemaName,
fromDate,
toDate
);
this.total = total ?? 0;
this.unpaid = outstanding ?? 0;
this.paid = total - outstanding;
this.hasData = countTotal > 0;
this.count = countTotal;
this.paidCount = countTotal - countOutstanding;
this.unpaidCount = countOutstanding;
this.barWidth = (this.paid / (this.total || 1)) * 100;
},
async newInvoice() {
const doc = fyo.doc.getNewDoc(this.schemaName);
await routeTo(`/edit/${this.schemaName}/${doc.name!}`);
},
async getCounts(schemaName: string, fromDate: DateTime, toDate: DateTime) {
const outstandingAmounts = await fyo.db.getAllRaw(schemaName, {
fields: ['outstandingAmount'],
filters: {
cancelled: false,
submitted: true,
date: ['<=', toDate.toISO(), '>=', fromDate.toISO()],
},
});
const isOutstanding = outstandingAmounts.map((o) =>
safeParseFloat(o.outstandingAmount)
);
return {
countTotal: isOutstanding.length,
countOutstanding: isOutstanding.filter((o) => o > 0).length,
};
},
},
});
</script>
|
2302_79757062/books
|
src/pages/Dashboard/UnpaidInvoices.vue
|
Vue
|
agpl-3.0
| 7,422
|
<template>
<div
class="flex-1 flex justify-center items-center bg-gray-25 dark:bg-gray-900"
:class="{
'pointer-events-none': loadingDatabase,
'window-drag': platform !== 'Windows',
}"
>
<div
class="
w-full w-form
shadow-lg
rounded-lg
border
dark:border-gray-800
relative
bg-white
dark:bg-gray-875
"
style="height: 700px"
>
<!-- Welcome to Frappe Books -->
<div class="px-4 py-4">
<h1 class="text-2xl font-semibold select-none dark:text-gray-25">
{{ t`Welcome to Frappe Books` }}
</h1>
<p class="text-gray-600 dark:text-gray-400 text-base select-none">
{{
t`Create a new company or select an existing one from your computer`
}}
</p>
</div>
<hr class="dark:border-gray-800" />
<!-- New File (Blue Icon) -->
<div
data-testid="create-new-file"
class="px-4 h-row-largest flex flex-row items-center gap-4 p-2"
:class="
creatingDemo
? ''
: 'hover:bg-gray-50 dark:hover:bg-gray-890 cursor-pointer'
"
@click="newDatabase"
>
<div class="w-8 h-8 rounded-full bg-blue-500 relative flex-center">
<feather-icon
name="plus"
class="text-white dark:text-gray-900 w-5 h-5"
/>
</div>
<div>
<p class="font-medium dark:text-gray-200">
{{ t`New Company` }}
</p>
<p class="text-sm text-gray-600 dark:text-gray-400">
{{ t`Create a new company and store it on your computer` }}
</p>
</div>
</div>
<!-- Existing File (Green Icon) -->
<div
class="px-4 h-row-largest flex flex-row items-center gap-4 p-2"
:class="
creatingDemo
? ''
: 'hover:bg-gray-50 dark:hover:bg-gray-890 cursor-pointer'
"
@click="existingDatabase"
>
<div
class="
w-8
h-8
rounded-full
bg-green-500
dark:bg-green-600
relative
flex-center
"
>
<feather-icon
name="upload"
class="w-4 h-4 text-white dark:text-gray-900"
/>
</div>
<div>
<p class="font-medium dark:text-gray-200">
{{ t`Existing Company` }}
</p>
<p class="text-sm text-gray-600 dark:text-gray-400">
{{ t`Load an existing company from your computer` }}
</p>
</div>
</div>
<!-- Create Demo (Pink Icon) -->
<div
v-if="!files?.length"
class="px-4 h-row-largest flex flex-row items-center gap-4 p-2"
:class="
creatingDemo
? ''
: 'hover:bg-gray-50 dark:hover:bg-gray-890 cursor-pointer'
"
@click="createDemo"
>
<div
class="
w-8
h-8
rounded-full
bg-pink-500
dark:bg-pink-600
relative
flex-center
"
>
<feather-icon name="monitor" class="w-4 h-4 text-white" />
</div>
<div>
<p class="font-medium dark:text-gray-200">
{{ t`Create Demo` }}
</p>
<p class="text-sm text-gray-600 dark:text-gray-400">
{{ t`Create a demo company to try out Frappe Books` }}
</p>
</div>
</div>
<hr class="dark:border-gray-800" />
<!-- File List -->
<div class="overflow-y-auto" style="max-height: 340px">
<div
v-for="(file, i) in files"
:key="file.dbPath"
class="h-row-largest px-4 flex gap-4 items-center"
:class="
creatingDemo
? ''
: 'hover:bg-gray-50 dark:hover:bg-gray-890 cursor-pointer'
"
:title="t`${file.companyName} stored at ${file.dbPath}`"
@click="selectFile(file)"
>
<div
class="
w-8
h-8
rounded-full
flex
justify-center
items-center
bg-gray-200
dark:bg-gray-800
text-gray-500
font-semibold
flex-shrink-0
text-base
"
>
{{ i + 1 }}
</div>
<div class="w-full">
<div class="flex justify-between overflow-x-auto items-baseline">
<h2 class="font-medium dark:text-gray-200">
{{ file.companyName }}
</h2>
<p
class="
whitespace-nowrap
text-sm text-gray-600
dark:text-gray-400
"
>
{{ formatDate(file.modified) }}
</p>
</div>
<p
class="
text-sm text-gray-600
dark:text-gray-400
overflow-x-auto
no-scrollbar
whitespace-nowrap
"
>
{{ truncate(file.dbPath) }}
</p>
</div>
<button
class="
ms-auto
p-2
hover:bg-red-200
dark:hover:bg-red-900 dark:hover:bg-opacity-40
rounded-full
w-8
h-8
text-gray-600
dark:text-gray-400
hover:text-red-400
dark:hover:text-red-200
"
@click.stop="() => deleteDb(i)"
>
<feather-icon name="x" class="w-4 h-4" />
</button>
</div>
</div>
<hr v-if="files?.length" class="dark:border-gray-800" />
<!-- Language Selector -->
<div
class="
w-full
flex
justify-between
items-center
absolute
p-4
text-gray-900
dark:text-gray-100
"
style="top: 100%; transform: translateY(-100%)"
>
<LanguageSelector v-show="!creatingDemo" class="text-sm w-28" />
<button
v-if="files?.length"
class="
text-sm
bg-gray-100
dark:bg-gray-890
hover:bg-gray-200
dark:hover:bg-gray-900
rounded
px-4
py-1.5
w-28
h-8
no-scrollbar
overflow-x-auto
whitespace-nowrap
"
:disabled="creatingDemo"
@click="createDemo"
>
{{ creatingDemo ? t`Please Wait` : t`Create Demo` }}
</button>
</div>
</div>
<Loading
v-if="creatingDemo"
:open="creatingDemo"
:show-x="false"
:full-width="true"
:percent="creationPercent"
:message="creationMessage"
/>
<!-- Base Count Selection when Dev -->
<Modal :open-modal="openModal" @closemodal="openModal = false">
<div class="p-4 text-gray-900 dark:text-gray-100 w-form">
<h2 class="text-xl font-semibold select-none">Set Base Count</h2>
<p class="text-base mt-2">
Base Count is a lower bound on the number of entries made when
creating the dummy instance.
</p>
<div class="flex my-12 justify-center items-baseline gap-4 text-base">
<label for="basecount" class="text-gray-600 dark:text-gray-400"
>Base Count</label
>
<input
v-model="baseCount"
type="number"
name="basecount"
class="
bg-gray-100
dark:bg-gray-875
focus:bg-gray-200
dark:focus:bg-gray-890
rounded-md
px-2
py-1
outline-none
"
/>
</div>
<div class="flex justify-between">
<Button @click="openModal = false">Cancel</Button>
<Button
type="primary"
@click="
() => {
openModal = false;
startDummyInstanceSetup();
}
"
>Create</Button
>
</div>
</div>
</Modal>
</div>
</template>
<script lang="ts">
import { setupDummyInstance } from 'dummy';
import { t } from 'fyo';
import { Verb } from 'fyo/telemetry/types';
import { DateTime } from 'luxon';
import Button from 'src/components/Button.vue';
import LanguageSelector from 'src/components/Controls/LanguageSelector.vue';
import FeatherIcon from 'src/components/FeatherIcon.vue';
import Loading from 'src/components/Loading.vue';
import Modal from 'src/components/Modal.vue';
import { fyo } from 'src/initFyo';
import { showDialog } from 'src/utils/interactive';
import { updateConfigFiles } from 'src/utils/misc';
import { deleteDb, getSavePath, getSelectedFilePath } from 'src/utils/ui';
import type { ConfigFilesWithModified } from 'utils/types';
import { defineComponent } from 'vue';
export default defineComponent({
name: 'DatabaseSelector',
components: {
LanguageSelector,
Loading,
FeatherIcon,
Modal,
Button,
},
emits: ['file-selected', 'new-database'],
data() {
return {
openModal: false,
baseCount: 100,
creationMessage: '',
creationPercent: 0,
creatingDemo: false,
loadingDatabase: false,
files: [],
} as {
openModal: boolean;
baseCount: number;
creationMessage: string;
creationPercent: number;
creatingDemo: boolean;
loadingDatabase: boolean;
files: ConfigFilesWithModified[];
};
},
async mounted() {
await this.setFiles();
if (fyo.store.isDevelopment) {
// @ts-ignore
window.ds = this;
}
},
methods: {
truncate(value: string) {
if (value.length < 72) {
return value;
}
return '...' + value.slice(value.length - 72);
},
formatDate(isoDate: string) {
return DateTime.fromISO(isoDate).toRelative();
},
async deleteDb(i: number) {
const file = this.files[i];
const setFiles = this.setFiles.bind(this);
await showDialog({
title: t`Delete ${file.companyName}?`,
detail: t`Database file: ${file.dbPath}`,
type: 'warning',
buttons: [
{
label: this.t`Yes`,
async action() {
await deleteDb(file.dbPath);
await setFiles();
},
isPrimary: true,
},
{
label: this.t`No`,
action() {
return null;
},
isEscape: true,
},
],
});
},
async createDemo() {
if (!fyo.store.isDevelopment) {
await this.startDummyInstanceSetup();
} else {
this.openModal = true;
}
},
async startDummyInstanceSetup() {
const { filePath, canceled } = await getSavePath('demo', 'db');
if (canceled || !filePath) {
return;
}
this.creatingDemo = true;
await setupDummyInstance(
filePath,
fyo,
1,
this.baseCount,
(message, percent) => {
this.creationMessage = message;
this.creationPercent = percent;
}
);
updateConfigFiles(fyo);
await fyo.purgeCache();
await this.setFiles();
this.fyo.telemetry.log(Verb.Created, 'dummy-instance');
this.creatingDemo = false;
this.$emit('file-selected', filePath);
},
async setFiles() {
const dbList = await ipc.getDbList();
this.files = dbList?.sort(
(a, b) => Date.parse(b.modified) - Date.parse(a.modified)
);
},
newDatabase() {
if (this.creatingDemo) {
return;
}
this.$emit('new-database');
},
async existingDatabase() {
if (this.creatingDemo) {
return;
}
const filePath = (await getSelectedFilePath())?.filePaths?.[0];
this.emitFileSelected(filePath);
},
selectFile(file: ConfigFilesWithModified) {
if (this.creatingDemo) {
return;
}
this.emitFileSelected(file.dbPath);
},
emitFileSelected(filePath: string) {
if (!filePath) {
return;
}
this.$emit('file-selected', filePath);
},
},
});
</script>
|
2302_79757062/books
|
src/pages/DatabaseSelector.vue
|
Vue
|
agpl-3.0
| 12,554
|
<script setup lang="ts">
import { showSidebar } from 'src/utils/refs';
import { toggleSidebar } from 'src/utils/ui';
</script>
<template>
<div class="flex overflow-hidden">
<Transition name="sidebar">
<!-- eslint-disable vue/require-explicit-emits -->
<Sidebar
v-show="showSidebar"
class="
flex-shrink-0
border-e
dark:border-gray-800
whitespace-nowrap
w-sidebar
"
:darkMode="darkMode"
@change-db-file="$emit('change-db-file')"
/>
</Transition>
<div
class="
flex flex-1
overflow-y-hidden
custom-scroll custom-scroll-thumb1
bg-white
dark:bg-gray-875
"
>
<router-view v-slot="{ Component }">
<keep-alive>
<component
:is="Component"
:key="$route.path"
:darkMode="darkMode"
class="flex-1"
/>
</keep-alive>
</router-view>
<router-view v-slot="{ Component, route }" name="edit">
<Transition name="quickedit">
<div v-if="route?.query?.edit">
<component
:is="Component"
:key="route.query.schemaName + route.query.name"
:darkMode="darkMode"
/>
</div>
</Transition>
</router-view>
</div>
<!-- Show Sidebar Button -->
<button
v-show="!showSidebar"
class="
absolute
bottom-0
start-0
text-gray-600
dark:text-gray-400
hover:bg-gray-100
dark:hover:bg-gray-900
rounded
rtl-rotate-180
p-1
m-4
opacity-0
hover:opacity-100 hover:shadow-md
"
@click="() => toggleSidebar()"
>
<feather-icon name="chevrons-right" class="w-4 h-4" />
</button>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import Sidebar from '../components/Sidebar.vue';
export default defineComponent({
name: 'Desk',
components: {
Sidebar,
},
props: {
darkMode: { type: Boolean, default: false },
},
emits: ['change-db-file'],
});
</script>
<style scoped>
.sidebar-enter-from,
.sidebar-leave-to {
opacity: 0;
transform: translateX(calc(-1 * var(--w-sidebar)));
width: 0px;
}
[dir='rtl'] .sidebar-leave-to {
opacity: 0;
transform: translateX(calc(1 * var(--w-sidebar)));
width: 0px;
}
.sidebar-enter-to,
.sidebar-leave-from {
opacity: 1;
transform: translateX(0px);
width: var(--w-sidebar);
}
.sidebar-enter-active,
.sidebar-leave-active {
transition: all 150ms ease-out;
}
</style>
|
2302_79757062/books
|
src/pages/Desk.vue
|
Vue
|
agpl-3.0
| 2,647
|
<template>
<div class="flex flex-col overflow-y-hidden">
<PageHeader :title="t`Set Up Your Workspace`" />
<div
class="
flex-1
overflow-y-auto overflow-x-hidden
custom-scroll custom-scroll-thumb1
"
>
<div
v-for="section in sections"
:key="section.label"
class="p-4 border-b dark:border-gray-800"
>
<h2 class="font-medium dark:text-gray-25">{{ section.label }}</h2>
<div class="flex mt-4 gap-4">
<div
v-for="item in section.items"
:key="item.label"
class="w-full md:w-1/3 sm:w-1/2"
>
<div
class="
flex flex-col
justify-between
h-40
p-4
border
dark:border-gray-800 dark:text-gray-50
rounded-lg
"
@mouseenter="() => (activeCard = item.key)"
@mouseleave="() => (activeCard = null)"
>
<div>
<component
:is="getIconComponent(item)"
v-show="activeCard !== item.key && !isCompleted(item)"
class="mb-4"
/>
<Icon
v-show="isCompleted(item)"
name="green-check"
size="24"
class="w-5 h-5 mb-4"
/>
<h3 class="font-medium">{{ item.label }}</h3>
<p class="mt-2 text-sm text-gray-800 dark:text-gray-400">
{{ item.description }}
</p>
</div>
<div
v-show="activeCard === item.key && !isCompleted(item)"
class="flex mt-2 overflow-hidden"
>
<Button
v-if="item.action"
class="leading-tight text-base"
type="primary"
@click="handleAction(item)"
>
{{ t`Set Up` }}
</Button>
<Button
v-if="item.documentation"
class="leading-tight text-base"
:class="{ 'ms-4': item.action }"
@click="handleDocumentation(item)"
>
{{ t`Documentation` }}
</Button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import { DocValue } from 'fyo/core/types';
import Button from 'src/components/Button.vue';
import Icon from 'src/components/Icon.vue';
import PageHeader from 'src/components/PageHeader.vue';
import { fyo } from 'src/initFyo';
import { getGetStartedConfig } from 'src/utils/getStartedConfig';
import { GetStartedConfigItem } from 'src/utils/types';
import { Component, defineComponent, h } from 'vue';
type ListItem = GetStartedConfigItem['items'][number];
export default defineComponent({
name: 'GetStarted',
components: {
PageHeader,
Button,
Icon,
},
props: {
darkMode: { type: Boolean, default: false },
},
data() {
return {
activeCard: null as string | null,
sections: getGetStartedConfig(),
};
},
async activated() {
await fyo.doc.getDoc('GetStarted');
await this.checkForCompletedTasks();
},
methods: {
async handleDocumentation({ key, documentation }: ListItem) {
if (documentation) {
ipc.openLink(documentation);
}
switch (key) {
case 'Opening Balances':
await this.updateChecks({ openingBalanceChecked: true });
break;
}
},
async handleAction({ key, action }: ListItem) {
if (action) {
action();
this.activeCard = null;
}
switch (key) {
case 'Print':
await this.updateChecks({ printSetup: true });
break;
case 'General':
await this.updateChecks({ companySetup: true });
break;
case 'System':
await this.updateChecks({ systemSetup: true });
break;
case 'Review Accounts':
await this.updateChecks({ chartOfAccountsReviewed: true });
break;
case 'Add Taxes':
await this.updateChecks({ taxesAdded: true });
break;
}
},
async checkIsOnboardingComplete() {
if (fyo.singles.GetStarted?.onboardingComplete) {
return true;
}
const doc = await fyo.doc.getDoc('GetStarted');
const onboardingComplete = fyo.schemaMap.GetStarted?.fields
.filter(({ fieldname }) => fieldname !== 'onboardingComplete')
.map(({ fieldname }) => doc.get(fieldname))
.every(Boolean);
if (onboardingComplete) {
await this.updateChecks({ onboardingComplete });
const systemSettings = await fyo.doc.getDoc('SystemSettings');
await systemSettings.set('hideGetStarted', true);
await systemSettings.sync();
}
return onboardingComplete;
},
async checkForCompletedTasks() {
let toUpdate: Record<string, DocValue> = {};
if (await this.checkIsOnboardingComplete()) {
return;
}
if (!fyo.singles.GetStarted?.salesItemCreated) {
const count = await fyo.db.count('Item', { filters: { for: 'Sales' } });
toUpdate.salesItemCreated = count > 0;
}
if (!fyo.singles.GetStarted?.purchaseItemCreated) {
const count = await fyo.db.count('Item', {
filters: { for: 'Purchases' },
});
toUpdate.purchaseItemCreated = count > 0;
}
if (!fyo.singles.GetStarted?.invoiceCreated) {
const count = await fyo.db.count('SalesInvoice');
toUpdate.invoiceCreated = count > 0;
}
if (!fyo.singles.GetStarted?.customerCreated) {
const count = await fyo.db.count('Party', {
filters: { role: 'Customer' },
});
toUpdate.customerCreated = count > 0;
}
if (!fyo.singles.GetStarted?.billCreated) {
const count = await fyo.db.count('SalesInvoice');
toUpdate.billCreated = count > 0;
}
if (!fyo.singles.GetStarted?.supplierCreated) {
const count = await fyo.db.count('Party', {
filters: { role: 'Supplier' },
});
toUpdate.supplierCreated = count > 0;
}
await this.updateChecks(toUpdate);
},
async updateChecks(toUpdate: Record<string, DocValue>) {
await fyo.singles.GetStarted?.setAndSync(toUpdate);
await fyo.doc.getDoc('GetStarted');
},
isCompleted(item: ListItem) {
return fyo.singles.GetStarted?.get(item.fieldname) || false;
},
getIconComponent(item: ListItem) {
let completed = fyo.singles.GetStarted?.[item.fieldname] || false;
let name = completed ? 'green-check' : item.icon;
let size = completed ? '24' : '18';
return {
name,
render() {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
return h(Icon, {
...Object.assign(
{
name,
size,
},
this.$attrs
),
});
},
} as Component;
},
},
});
</script>
|
2302_79757062/books
|
src/pages/GetStarted.vue
|
Vue
|
agpl-3.0
| 7,304
|
<template>
<div class="flex flex-col overflow-hidden w-full">
<!-- Header -->
<PageHeader :title="t`Import Wizard`">
<DropdownWithActions
v-if="hasImporter"
:actions="actions"
:disabled="isMakingEntries"
:title="t`More`"
/>
<Button
v-if="hasImporter"
:title="t`Add Row`"
:disabled="isMakingEntries"
:icon="true"
@click="() => importer.addRow()"
>
<feather-icon name="plus" class="w-4 h-4" />
</Button>
<Button
v-if="hasImporter"
:title="t`Save Template`"
:icon="true"
@click="saveTemplate"
>
<feather-icon name="download" class="w-4 h-4" />
</Button>
<Button
v-if="canImportData"
:title="t`Import Data`"
type="primary"
:disabled="errorMessage.length > 0 || isMakingEntries"
@click="importData"
>
{{ t`Import Data` }}
</Button>
<Button
v-if="importType && !canImportData"
:title="t`Select File`"
type="primary"
@click="selectFile"
>
{{ t`Select File` }}
</Button>
</PageHeader>
<!-- Main Body of the Wizard -->
<div class="flex text-base w-full flex-col">
<!-- Select Import Type -->
<div
class="
h-row-largest
flex flex-row
justify-start
items-center
w-full
gap-2
border-b
dark:border-gray-800
p-4
"
>
<AutoComplete
:df="{
fieldname: 'importType',
label: t`Import Type`,
fieldtype: 'AutoComplete',
options: importableSchemaNames.map((value) => ({
value,
label: fyo.schemaMap[value]?.label ?? value,
})),
}"
class="w-40"
:border="true"
:value="importType"
size="small"
@change="setImportType"
/>
<p v-if="errorMessage.length > 0" class="text-base ms-2 text-red-500">
{{ errorMessage }}
</p>
<p
v-else
class="text-base ms-2"
:class="
fileName
? 'text-gray-900 dark:text-gray-25 font-semibold'
: 'text-gray-700 dark:text-gray-200'
"
>
<span v-if="fileName" class="font-normal">{{ t`Selected` }} </span>
{{ helperMessage }}{{ fileName ? ',' : '' }}
<span v-if="fileName" class="font-normal">
{{ t`check values and click on` }} </span
>{{ ' ' }}<span v-if="fileName">{{ t`Import Data.` }}</span>
<span
v-if="hasImporter && importer.valueMatrix.length > 0"
class="font-normal"
>{{
' ' +
(importer.valueMatrix.length === 2
? t`${importer.valueMatrix.length} row added.`
: t`${importer.valueMatrix.length} rows added.`)
}}</span
>
</p>
</div>
<!-- Assignment Row and Value Grid container -->
<div
v-if="hasImporter"
class="overflow-auto custom-scroll custom-scroll-thumb1"
style="max-height: calc(100vh - (2 * var(--h-row-largest)) - 2px)"
>
<!-- Column Assignment Row -->
<div
class="
grid
sticky
top-0
py-4
pe-4
bg-white
dark:bg-gray-875
border-b border-e
dark:border-gray-800
gap-4
"
style="z-index: 1; width: fit-content"
:style="gridTemplateColumn"
>
<div class="index-cell">#</div>
<Select
v-for="index in columnIterator"
:key="index"
class="flex-shrink-0"
size="small"
:border="true"
:df="gridColumnTitleDf"
:value="importer.assignedTemplateFields[index]!"
@change="(value: string | null) => importer.setTemplateField(index, value)"
/>
</div>
<!-- Values Grid -->
<div
v-if="importer.valueMatrix.length"
class="
grid
py-4
pe-4
bg-white
dark:bg-gray-875
gap-4
border-e
last:border-b
dark:border-gray-800
"
style="width: fit-content"
:style="gridTemplateColumn"
>
<!-- Grid Value Row Cells, Allow Editing Values -->
<template v-for="(row, ridx) of importer.valueMatrix" :key="ridx">
<div
class="index-cell group cursor-pointer"
@click="importer.removeRow(ridx)"
>
<feather-icon
name="x"
class="w-4 h-4 hidden group-hover:inline-block -me-1"
:button="true"
/>
<span class="group-hover:hidden">
{{ ridx + 1 }}
</span>
</div>
<template
v-for="(val, cidx) of row.slice(0, columnCount)"
:key="`cell-${ridx}-${cidx}`"
>
<!-- Raw Data Field if Column is Not Assigned -->
<Data
v-if="!importer.assignedTemplateFields[cidx]"
:title="getFieldTitle(val)"
:df="{
fieldtype: 'Data',
fieldname: 'tempField',
label: t`Temporary`,
placeholder: t`Select column`,
}"
size="small"
:border="true"
:value="
val.value != null
? String(val.value)
: val.rawValue != null
? String(val.rawValue)
: ''
"
:read-only="true"
/>
<!-- FormControl Field if Column is Assigned -->
<FormControl
v-else
:class="
val.error
? 'border border-red-300 dark:border-red-600 rounded-md'
: ''
"
:title="getFieldTitle(val)"
:df="
importer.templateFieldsMap.get(
importer.assignedTemplateFields[cidx]!
)
"
size="small"
:rows="1"
:border="true"
:value="val.error ? null : val.value"
:read-only="false"
@change="(value: DocValue)=> {
importer.valueMatrix[ridx][cidx]!.error = false
importer.valueMatrix[ridx][cidx]!.value = value
}"
/>
</template>
</template>
</div>
<div
v-else
class="
ps-4
text-gray-700
dark:text-gray-300
sticky
left-0
flex
items-center
"
style="height: 62.5px"
>
{{ t`No rows added. Select a file or add rows.` }}
</div>
</div>
</div>
<!-- Loading Bar when Saving Docs -->
<Loading
v-if="isMakingEntries"
:open="isMakingEntries"
:percent="percentLoading"
:message="messageLoading"
/>
<!-- Pick Column Modal -->
<Modal
:open-modal="showColumnPicker"
@closemodal="showColumnPicker = false"
>
<div class="w-form">
<!-- Pick Column Header -->
<FormHeader :form-title="t`Pick Import Columns`" />
<hr class="dark:border-gray-800" />
<!-- Pick Column Checkboxes -->
<div
v-for="[key, value] of columnPickerFieldsMap.entries()"
:key="key"
class="p-4 max-h-80 overflow-auto custom-scroll custom-scroll-thumb1"
>
<h2 class="text-sm font-semibold text-gray-800 dark:text-gray-200">
{{ key }}
</h2>
<div
class="grid grid-cols-3 border dark:border-gray-800 rounded mt-1"
>
<div
v-for="tf of value"
:key="tf.fieldKey"
class="flex items-center"
>
<Check
:df="{
fieldtype: 'Check',
fieldname: tf.fieldname,
label: tf.label,
}"
:show-label="true"
:read-only="tf.required"
:value="importer.templateFieldsPicked.get(tf.fieldKey)"
@change="(value:boolean) => pickColumn(tf.fieldKey, value)"
/>
<p v-if="tf.required" class="w-0 text-red-600 -ml-4">*</p>
</div>
</div>
</div>
<!-- Pick Column Footer -->
<hr class="dark:border-gray-800" />
<div class="p-4 flex justify-between items-center">
<p class="text-sm text-gray-600 dark:text-gray-400">
{{ t`${numColumnsPicked} fields selected` }}
</p>
<Button type="primary" @click="showColumnPicker = false">{{
t`Done`
}}</Button>
</div>
</div>
</Modal>
<!-- Import Completed Modal -->
<Modal :open-modal="complete" @closemodal="clear">
<div class="w-form">
<!-- Import Completed Header -->
<FormHeader :form-title="t`Import Complete`" />
<hr class="dark:border-gray-800" />
<!-- Success -->
<div v-if="success.length > 0">
<!-- Success Section Header -->
<div class="flex justify-between px-4 pt-4 pb-1">
<p class="text-base font-semibold dark:text-gray-200">
{{ t`Success` }}
</p>
<p class="text-sm text-gray-600 dark:text-gray-400">
{{
success.length === 1
? t`${success.length} entry imported`
: t`${success.length} entries imported`
}}
</p>
</div>
<!-- Success Body -->
<div class="max-h-40 overflow-auto text-gray-900 dark:text-gray-50">
<div
v-for="(name, i) of success"
:key="name"
class="px-4 py-1 grid grid-cols-2 text-base gap-4"
style="grid-template-columns: 1rem auto"
>
<div class="text-end">{{ i + 1 }}.</div>
<p class="whitespace-nowrap overflow-auto no-scrollbar">
{{ name }}
</p>
</div>
</div>
<hr class="dark:border-gray-800" />
</div>
<!-- Failed -->
<div v-if="failed.length > 0">
<!-- Failed Section Header -->
<div class="flex justify-between px-4 pt-4 pb-1">
<p class="text-base font-semibold">{{ t`Failed` }}</p>
<p class="text-sm text-gray-600 dark:text-gray-400">
{{
failed.length === 1
? t`${failed.length} entry failed`
: t`${failed.length} entries failed`
}}
</p>
</div>
<!-- Failed Body -->
<div class="max-h-40 overflow-auto text-gray-900 dark:text-gray-50">
<div
v-for="(f, i) of failed"
:key="f.name"
class="px-4 py-1 grid grid-cols-2 text-base gap-4"
style="grid-template-columns: 1rem 8rem auto"
>
<div class="text-end">{{ i + 1 }}.</div>
<p class="whitespace-nowrap overflow-auto no-scrollbar">
{{ f.name }}
</p>
<p class="whitespace-nowrap overflow-auto no-scrollbar">
{{ f.error.message }}
</p>
</div>
</div>
<hr />
</div>
<!-- Fallback Div -->
<div
v-if="failed.length === 0 && success.length === 0"
class="p-4 text-base dark:text-gray-200"
>
{{ t`No entries were imported.` }}
</div>
<!-- Footer Button -->
<div class="flex justify-between p-4">
<Button
v-if="failed.length > 0"
@click="clearSuccessfullyImportedEntries"
>{{ t`Fix Failed` }}</Button
>
<Button
v-if="failed.length === 0 && success.length > 0"
@click="showMe"
>{{ t`Show Me` }}</Button
>
<Button @click="clear">{{ t`Done` }}</Button>
</div>
</div>
</Modal>
</div>
</template>
<script lang="ts">
import { DocValue } from 'fyo/core/types';
import { Action } from 'fyo/model/types';
import { Verb } from 'fyo/telemetry/types';
import { ValidationError } from 'fyo/utils/errors';
import { ModelNameEnum } from 'models/types';
import { OptionField, RawValue, SelectOption } from 'schemas/types';
import Button from 'src/components/Button.vue';
import AutoComplete from 'src/components/Controls/AutoComplete.vue';
import Check from 'src/components/Controls/Check.vue';
import Data from 'src/components/Controls/Data.vue';
import FormControl from 'src/components/Controls/FormControl.vue';
import Select from 'src/components/Controls/Select.vue';
import DropdownWithActions from 'src/components/DropdownWithActions.vue';
import FormHeader from 'src/components/FormHeader.vue';
import Modal from 'src/components/Modal.vue';
import PageHeader from 'src/components/PageHeader.vue';
import { Importer, TemplateField, getColumnLabel } from 'src/importer';
import { fyo } from 'src/initFyo';
import { showDialog } from 'src/utils/interactive';
import { docsPathMap } from 'src/utils/misc';
import { docsPathRef } from 'src/utils/refs';
import { getSavePath, selectTextFile } from 'src/utils/ui';
import { defineComponent } from 'vue';
import Loading from '../components/Loading.vue';
type ImportWizardData = {
showColumnPicker: boolean;
complete: boolean;
success: string[];
successOldName: string[];
failed: { name: string; error: Error }[];
file: null | { name: string; filePath: string; text: string };
nullOrImporter: null | Importer;
importType: string;
isMakingEntries: boolean;
percentLoading: number;
messageLoading: string;
};
export default defineComponent({
components: {
PageHeader,
FormControl,
Button,
DropdownWithActions,
Loading,
AutoComplete,
Data,
Modal,
FormHeader,
Check,
Select,
},
data() {
return {
showColumnPicker: false,
complete: false,
success: [],
successOldName: [],
failed: [],
file: null,
nullOrImporter: null,
importType: '',
isMakingEntries: false,
percentLoading: 0,
messageLoading: '',
} as ImportWizardData;
},
computed: {
gridTemplateColumn(): string {
return `grid-template-columns: 4rem repeat(${this.columnCount}, 10rem)`;
},
duplicates(): string[] {
if (!this.hasImporter) {
return [];
}
const dupes = new Set<string>();
const assignedSet = new Set<string>();
for (const key of this.importer.assignedTemplateFields) {
if (!key) {
continue;
}
const tf = this.importer.templateFieldsMap.get(key);
if (assignedSet.has(key) && tf) {
dupes.add(getColumnLabel(tf));
}
assignedSet.add(key);
}
return Array.from(dupes);
},
requiredNotSelected(): string[] {
if (!this.hasImporter) {
return [];
}
const assigned = new Set(this.importer.assignedTemplateFields);
return [...this.importer.templateFieldsMap.values()]
.filter((f) => {
if (assigned.has(f.fieldKey) || !f.required) {
return false;
}
if (f.parentSchemaChildField && !f.parentSchemaChildField.required) {
return false;
}
return f.required;
})
.map((f) => getColumnLabel(f));
},
errorMessage(): string {
if (this.duplicates.length) {
return this.t`Duplicate columns found: ${this.duplicates.join(', ')}`;
}
if (this.requiredNotSelected.length) {
return this
.t`Required fields not selected: ${this.requiredNotSelected.join(
', '
)}`;
}
return '';
},
canImportData(): boolean {
if (!this.hasImporter) {
return false;
}
return this.importer.valueMatrix.length > 0;
},
canSelectFile(): boolean {
return !this.file;
},
columnCount(): number {
if (!this.hasImporter) {
return 0;
}
if (!this.file) {
return this.numColumnsPicked;
}
if (!this.importer.valueMatrix.length) {
return this.importer.assignedTemplateFields.length;
}
return Math.min(
this.importer.assignedTemplateFields.length,
this.importer.valueMatrix[0].length
);
},
columnIterator(): number[] {
return Array(this.columnCount)
.fill(null)
.map((_, i) => i);
},
hasImporter(): boolean {
return !!this.nullOrImporter;
},
numColumnsPicked(): number {
return [...this.importer.templateFieldsPicked.values()].filter(Boolean)
.length;
},
columnPickerFieldsMap(): Map<string, TemplateField[]> {
const map: Map<string, TemplateField[]> = new Map();
for (const value of this.importer.templateFieldsMap.values()) {
let label = value.schemaLabel;
if (value.parentSchemaChildField) {
label = `${value.parentSchemaChildField.label} (${value.schemaLabel})`;
}
if (!map.has(label)) {
map.set(label, []);
}
map.get(label)!.push(value);
}
return map;
},
importer(): Importer {
if (!this.nullOrImporter) {
throw new ValidationError(this.t`Importer not set, reload tool`, false);
}
return this.nullOrImporter as Importer;
},
importableSchemaNames(): ModelNameEnum[] {
const importables = [
ModelNameEnum.SalesInvoice,
ModelNameEnum.PurchaseInvoice,
ModelNameEnum.Payment,
ModelNameEnum.Party,
ModelNameEnum.Item,
ModelNameEnum.JournalEntry,
ModelNameEnum.Tax,
ModelNameEnum.Account,
ModelNameEnum.Address,
ModelNameEnum.NumberSeries,
];
const hasInventory = fyo.doc.singles.AccountingSettings?.enableInventory;
if (hasInventory) {
importables.push(
ModelNameEnum.StockMovement,
ModelNameEnum.Shipment,
ModelNameEnum.PurchaseReceipt,
ModelNameEnum.Location
);
}
return importables;
},
actions(): Action[] {
const actions: Action[] = [];
let selectFileLabel = this.t`Select File`;
if (this.file) {
selectFileLabel = this.t`Change File`;
}
if (this.canImportData) {
actions.push({
label: selectFileLabel,
component: {
template: `<span>{{ "${selectFileLabel}" }}</span>`,
},
action: this.selectFile.bind(this),
});
}
const pickColumnsAction = {
label: this.t`Pick Import Columns`,
component: {
template: '<span>{{ t`Pick Import Columns` }}</span>',
},
action: () => (this.showColumnPicker = true),
};
const cancelAction = {
label: this.t`Cancel`,
component: {
template: '<span class="text-red-700" >{{ t`Cancel` }}</span>',
},
action: this.clear.bind(this),
};
actions.push(pickColumnsAction, cancelAction);
return actions;
},
fileName(): string {
if (!this.file) {
return '';
}
return this.file.name;
},
helperMessage(): string {
if (!this.importType) {
return this.t`Set an Import Type`;
} else if (!this.fileName) {
return '';
}
return this.fileName;
},
isSubmittable(): boolean {
const schemaName = this.importer.schemaName;
return fyo.schemaMap[schemaName]?.isSubmittable ?? false;
},
gridColumnTitleDf(): OptionField {
const options: SelectOption[] = [];
for (const field of this.importer.templateFieldsMap.values()) {
const value = field.fieldKey;
if (!this.importer.templateFieldsPicked.get(value)) {
continue;
}
const label = getColumnLabel(field);
options.push({ value, label });
}
options.push({ value: '', label: this.t`None` });
return {
fieldname: 'col',
fieldtype: 'Select',
options,
} as OptionField;
},
pickedArray(): string[] {
return [...this.importer.templateFieldsPicked.entries()]
.filter(([, picked]) => picked)
.map(([key]) => key);
},
},
watch: {
columnCount(val) {
if (!this.hasImporter) {
return;
}
const possiblyAssigned = this.importer.assignedTemplateFields.length;
if (val >= this.importer.assignedTemplateFields.length) {
return;
}
for (let i = val; i < possiblyAssigned; i++) {
this.importer.assignedTemplateFields[i] = null;
}
},
},
mounted() {
if (fyo.store.isDevelopment) {
// @ts-ignore
window.iw = this;
}
},
activated(): void {
docsPathRef.value = docsPathMap.ImportWizard ?? '';
},
deactivated(): void {
docsPathRef.value = '';
if (!this.complete) {
return;
}
this.clear();
},
methods: {
getFieldTitle(vmi: {
value?: DocValue;
rawValue?: RawValue;
error?: boolean;
}): string {
const title: string[] = [];
if (vmi.value != null) {
title.push(this.t`Value: ${String(vmi.value)}`);
}
if (vmi.rawValue != null) {
title.push(this.t`Raw Value: ${String(vmi.rawValue)}`);
}
if (vmi.error) {
title.push(this.t`Conversion Error`);
}
if (!title.length) {
return this.t`No Value`;
}
return title.join(', ');
},
pickColumn(fieldKey: string, value: boolean): void {
this.importer.templateFieldsPicked.set(fieldKey, value);
if (value) {
return;
}
const idx = this.importer.assignedTemplateFields.findIndex(
(f) => f === fieldKey
);
if (idx >= 0) {
this.importer.assignedTemplateFields[idx] = null;
this.reassignTemplateFields();
}
},
reassignTemplateFields(): void {
if (this.importer.valueMatrix.length) {
return;
}
for (
let idx = 0;
idx < this.importer.assignedTemplateFields.length;
idx++
) {
this.importer.assignedTemplateFields[idx] = null;
}
let idx = 0;
for (const [fieldKey, value] of this.importer.templateFieldsPicked) {
if (!value) {
continue;
}
this.importer.assignedTemplateFields[idx] = fieldKey;
idx += 1;
}
},
async showMe(): Promise<void> {
const schemaName = this.importer.schemaName;
this.clear();
await this.$router.push(`/list/${schemaName}`);
},
clear(): void {
this.file = null;
this.success = [];
this.successOldName = [];
this.failed = [];
this.nullOrImporter = null;
this.importType = '';
this.complete = false;
this.isMakingEntries = false;
this.percentLoading = 0;
this.messageLoading = '';
},
async saveTemplate(): Promise<void> {
const template = this.importer.getCSVTemplate();
const templateName = this.importType + ' ' + this.t`Template`;
const { canceled, filePath } = await getSavePath(templateName, 'csv');
if (canceled || !filePath) {
return;
}
await ipc.saveData(template, filePath);
},
async preImportValidations(): Promise<boolean> {
const title = this.t`Cannot Import`;
if (this.errorMessage.length) {
await showDialog({
title,
type: 'error',
detail: this.errorMessage,
});
return false;
}
const cellErrors = this.importer.checkCellErrors();
if (cellErrors.length) {
await showDialog({
title,
type: 'error',
detail: this.t`Following cells have errors: ${cellErrors.join(
', '
)}.`,
});
return false;
}
const absentLinks = await this.importer.checkLinks();
if (absentLinks.length) {
await showDialog({
title,
type: 'error',
detail: this.t`Following links do not exist: ${absentLinks
.map((l) => `(${l.schemaLabel ?? l.schemaName}, ${l.name})`)
.join(', ')}.`,
});
return false;
}
return true;
},
async importData(): Promise<void> {
const isValid = await this.preImportValidations();
if (!isValid || this.isMakingEntries || this.complete) {
return;
}
this.isMakingEntries = true;
this.importer.populateDocs();
const shouldSubmit = await this.askShouldSubmit();
let doneCount = 0;
for (const doc of this.importer.docs) {
this.setLoadingStatus(doneCount, this.importer.docs.length);
const oldName = doc.name ?? '';
try {
await doc.sync();
if (shouldSubmit) {
await doc.submit();
}
doneCount += 1;
this.success.push(doc.name!);
this.successOldName.push(oldName);
} catch (error) {
if (error instanceof Error) {
this.failed.push({ name: doc.name!, error });
}
}
}
this.fyo.telemetry.log(Verb.Imported, this.importer.schemaName);
this.isMakingEntries = false;
this.complete = true;
},
async askShouldSubmit(): Promise<boolean> {
if (!this.fyo.schemaMap[this.importType]?.isSubmittable) {
return false;
}
let shouldSubmit = false;
await showDialog({
title: this.t`Submit entries?`,
type: 'info',
details: this.t`Should entries be submitted after syncing?`,
buttons: [
{
label: this.t`Yes`,
action() {
shouldSubmit = true;
},
isPrimary: true,
},
{
label: this.t`No`,
action() {
return null;
},
isEscape: true,
},
],
});
return shouldSubmit;
},
clearSuccessfullyImportedEntries() {
const schemaName = this.importer.schemaName;
const nameFieldKey = `${schemaName}.name`;
const nameIndex = this.importer.assignedTemplateFields.findIndex(
(n) => n === nameFieldKey
);
const failedEntriesValueMatrix = this.importer.valueMatrix.filter(
(row) => {
const value = row[nameIndex].value;
if (typeof value !== 'string') {
return false;
}
return !this.successOldName.includes(value);
}
);
this.setImportType(this.importType);
this.importer.valueMatrix = failedEntriesValueMatrix;
},
setImportType(importType: string): void {
this.clear();
if (!importType) {
return;
}
this.importType = importType;
this.nullOrImporter = new Importer(importType, fyo);
},
setLoadingStatus(entriesMade: number, totalEntries: number): void {
this.percentLoading = entriesMade / totalEntries;
this.messageLoading = this.isMakingEntries
? `${entriesMade} entries made out of ${totalEntries}...`
: '';
},
async selectFile(): Promise<void> {
const { text, name, filePath } = await selectTextFile([
{ name: 'CSV', extensions: ['csv'] },
]);
if (!text) {
return;
}
const isValid = this.importer.selectFile(text);
if (!isValid) {
await showDialog({
title: this.t`Cannot read file`,
detail: this.t`Bad import data, could not read file.`,
type: 'error',
});
return;
}
this.file = {
name,
filePath,
text,
};
},
},
});
</script>
<style scoped>
.index-cell {
@apply flex pe-4 justify-end items-center border-e last:border-b dark:border-gray-800 bg-white dark:bg-gray-875 sticky left-0 -my-4 text-gray-600 dark:text-gray-400;
}
</style>
|
2302_79757062/books
|
src/pages/ImportWizard.vue
|
Vue
|
agpl-3.0
| 28,773
|
<template>
<div class="text-base flex flex-col overflow-hidden">
<!-- Title Row -->
<div
class="flex items-center"
:style="{
paddingRight: dataSlice.length > 13 ? 'var(--w-scrollbar)' : '',
}"
>
<p class="w-8 text-end me-4 text-gray-700 dark:text-gray-400">#</p>
<Row
class="flex-1 text-gray-700 dark:text-gray-400 h-row-mid"
:column-count="columns.length"
gap="1rem"
>
<div
v-for="(column, i) in columns"
:key="column.label"
class="
overflow-x-auto
no-scrollbar
whitespace-nowrap
h-row
items-center
flex
"
:class="{
'ms-auto': isNumeric(column.fieldtype),
'pe-4': i === columns.length - 1,
}"
>
{{ column.label }}
</div>
</Row>
</div>
<hr class="dark:border-gray-800" />
<!-- Data Rows -->
<div
v-if="dataSlice.length !== 0"
class="
overflow-y-auto
dark:dark-scroll
custom-scroll custom-scroll-thumb1
"
>
<div v-for="(row, i) in dataSlice" :key="(row.name as string)">
<!-- Row Content -->
<div class="flex hover:bg-gray-50 dark:hover:bg-gray-850 items-center">
<p class="w-8 text-end me-4 text-gray-900 dark:text-gray-25">
{{ i + pageStart + 1 }}
</p>
<Row
gap="1rem"
class="
cursor-pointer
text-gray-900
dark:text-gray-300
flex-1
h-row-mid
"
:column-count="columns.length"
@click="$emit('openDoc', row.name)"
>
<ListCell
v-for="(column, c) in columns"
:key="column.label"
:class="{
'text-end': isNumeric(column.fieldtype),
'pe-4': c === columns.length - 1,
}"
:row="(row as RenderData)"
:column="column"
/>
</Row>
</div>
<hr
v-if="!(i === dataSlice.length - 1 && i > 13)"
class="dark:border-gray-800"
/>
</div>
</div>
<!-- Pagination Footer -->
<div v-if="data?.length" class="mt-auto">
<hr class="dark:border-gray-800" />
<Paginator
:item-count="data.length"
class="px-4"
@index-change="setPageIndices"
/>
</div>
<!-- Empty State -->
<div
v-if="!data?.length"
class="flex flex-col items-center justify-center my-auto"
>
<img src="../../assets/img/list-empty-state.svg" alt="" class="w-24" />
<p class="my-3 text-gray-800 dark:text-gray-200">
{{ t`No entries found` }}
</p>
<Button v-if="canCreate" type="primary" @click="$emit('makeNewDoc')">
{{ t`Make Entry` }}
</Button>
</div>
</div>
</template>
<script lang="ts">
import { ListViewSettings, RenderData } from 'fyo/model/types';
import { cloneDeep } from 'lodash';
import Button from 'src/components/Button.vue';
import Paginator from 'src/components/Paginator.vue';
import Row from 'src/components/Row.vue';
import { fyo } from 'src/initFyo';
import { isNumeric } from 'src/utils';
import { QueryFilter } from 'utils/db/types';
import { PropType, defineComponent } from 'vue';
import ListCell from './ListCell.vue';
export default defineComponent({
name: 'List',
components: {
Row,
ListCell,
Button,
Paginator,
},
props: {
listConfig: {
type: Object as PropType<ListViewSettings | undefined>,
default: () => ({ columns: [] }),
},
filters: {
type: Object as PropType<QueryFilter>,
default: () => ({}),
},
schemaName: { type: String, required: true },
canCreate: Boolean,
},
emits: ['openDoc', 'makeNewDoc', 'updatedData'],
data() {
return {
data: [] as RenderData[],
pageStart: 0,
pageEnd: 0,
};
},
computed: {
dataSlice() {
return this.data.slice(this.pageStart, this.pageEnd);
},
count() {
return this.pageEnd - this.pageStart + 1;
},
columns() {
let columns = this.listConfig?.columns ?? [];
if (columns.length === 0) {
columns = fyo.schemaMap[this.schemaName]?.quickEditFields ?? [];
columns = [...new Set(['name', ...columns])];
}
return columns
.map((fieldname) => {
if (typeof fieldname === 'object') {
return fieldname;
}
return fyo.getField(this.schemaName, fieldname);
})
.filter(Boolean);
},
},
watch: {
async schemaName(oldValue, newValue) {
if (oldValue === newValue) {
return;
}
await this.updateData();
},
},
async mounted() {
await this.updateData();
this.setUpdateListeners();
},
methods: {
isNumeric,
setPageIndices({ start, end }: { start: number; end: number }) {
this.pageStart = start;
this.pageEnd = end;
},
setUpdateListeners() {
if (!this.schemaName) {
return;
}
const listener = async () => {
await this.updateData();
};
if (fyo.schemaMap[this.schemaName]?.isSubmittable) {
fyo.doc.observer.on(`submit:${this.schemaName}`, listener);
fyo.doc.observer.on(`revert:${this.schemaName}`, listener);
}
fyo.doc.observer.on(`sync:${this.schemaName}`, listener);
fyo.db.observer.on(`delete:${this.schemaName}`, listener);
fyo.doc.observer.on(`rename:${this.schemaName}`, listener);
},
async updateData(filters?: Record<string, unknown>) {
if (!filters) {
filters = { ...this.filters };
}
// Unproxy the filters
filters = cloneDeep(filters);
const orderBy = ['created'];
if (fyo.db.fieldMap[this.schemaName]['date']) {
orderBy.unshift('date');
}
const tableData = await fyo.db.getAll(this.schemaName, {
fields: ['*'],
filters: filters as QueryFilter,
orderBy,
});
this.data = tableData.map((d) => ({
...d,
schema: fyo.schemaMap[this.schemaName],
})) as RenderData[];
this.$emit('updatedData', filters);
},
},
});
</script>
|
2302_79757062/books
|
src/pages/ListView/List.vue
|
Vue
|
agpl-3.0
| 6,349
|
<template>
<div class="flex items-center truncate" :class="cellClass">
<span v-if="!customRenderer" class="truncate">{{ columnValue }}</span>
<component :is="(customRenderer as {})" v-else />
</div>
</template>
<script lang="ts">
import { ColumnConfig, RenderData } from 'fyo/model/types';
import { Field } from 'schemas/types';
import { fyo } from 'src/initFyo';
import { isNumeric } from 'src/utils';
import { defineComponent, PropType } from 'vue';
type Column = ColumnConfig | Field;
function isField(column: ColumnConfig | Field): column is Field {
if ((column as ColumnConfig).display || (column as ColumnConfig).render) {
return false;
}
return true;
}
export default defineComponent({
name: 'ListCell',
props: {
row: { type: Object as PropType<RenderData>, required: true },
column: { type: Object as PropType<Column>, required: true },
},
computed: {
columnValue(): string {
const column = this.column;
const value = this.row[this.column.fieldname];
if (isField(column)) {
return fyo.format(value, column);
}
return column.display?.(value, fyo) ?? '';
},
customRenderer() {
const { render } = this.column as ColumnConfig;
if (!render) {
return;
}
return render(this.row);
},
cellClass() {
return isNumeric(this.column.fieldtype) ? 'justify-end' : '';
},
},
});
</script>
|
2302_79757062/books
|
src/pages/ListView/ListCell.vue
|
Vue
|
agpl-3.0
| 1,428
|
<template>
<div class="flex flex-col">
<PageHeader :title="title">
<Button ref="exportButton" :icon="false" @click="openExportModal = true">
{{ t`Export` }}
</Button>
<FilterDropdown
ref="filterDropdown"
:schema-name="schemaName"
@change="applyFilter"
/>
<Button
v-if="canCreate"
ref="makeNewDocButton"
:icon="true"
type="primary"
:padding="false"
class="px-3"
@click="makeNewDoc"
>
<feather-icon name="plus" class="w-4 h-4" />
</Button>
</PageHeader>
<List
ref="list"
:schema-name="schemaName"
:list-config="listConfig"
:filters="filters"
:can-create="canCreate"
class="flex-1 flex h-full"
@open-doc="openDoc"
@updated-data="updatedData"
@make-new-doc="makeNewDoc"
/>
<Modal :open-modal="openExportModal" @closemodal="openExportModal = false">
<ExportWizard
class="w-form"
:schema-name="schemaName"
:title="pageTitle"
:list-filters="listFilters"
/>
</Modal>
</div>
</template>
<script lang="ts">
import { Field } from 'schemas/types';
import Button from 'src/components/Button.vue';
import ExportWizard from 'src/components/ExportWizard.vue';
import FilterDropdown from 'src/components/FilterDropdown.vue';
import Modal from 'src/components/Modal.vue';
import PageHeader from 'src/components/PageHeader.vue';
import { fyo } from 'src/initFyo';
import { shortcutsKey } from 'src/utils/injectionKeys';
import {
docsPathMap,
getCreateFiltersFromListViewFilters,
} from 'src/utils/misc';
import { docsPathRef } from 'src/utils/refs';
import { getFormRoute, routeTo } from 'src/utils/ui';
import { QueryFilter } from 'utils/db/types';
import { defineComponent, inject, ref } from 'vue';
import List from './List.vue';
export default defineComponent({
name: 'ListView',
components: {
PageHeader,
List,
Button,
FilterDropdown,
Modal,
ExportWizard,
},
props: {
schemaName: { type: String, required: true },
filters: { type: Object, default: undefined },
pageTitle: { type: String, default: '' },
},
setup() {
return {
shortcuts: inject(shortcutsKey),
list: ref<InstanceType<typeof List> | null>(null),
makeNewDocButton: ref<InstanceType<typeof Button> | null>(null),
exportButton: ref<InstanceType<typeof Button> | null>(null),
filterDropdown: ref<InstanceType<typeof FilterDropdown> | null>(null),
};
},
data() {
return {
listConfig: undefined,
openExportModal: false,
listFilters: {},
} as {
listConfig: undefined | ReturnType<typeof getListConfig>;
openExportModal: boolean;
listFilters: QueryFilter;
};
},
computed: {
context(): string {
return 'ListView-' + this.schemaName;
},
title(): string {
if (this.pageTitle) {
return this.pageTitle;
}
return fyo.schemaMap[this.schemaName]?.label ?? this.schemaName;
},
fields(): Field[] {
return fyo.schemaMap[this.schemaName]?.fields ?? [];
},
canCreate(): boolean {
return fyo.schemaMap[this.schemaName]?.create !== false;
},
},
activated() {
if (typeof this.filters === 'object') {
this.filterDropdown?.setFilter(this.filters, true);
}
this.listConfig = getListConfig(this.schemaName);
docsPathRef.value =
docsPathMap[this.schemaName] ?? docsPathMap.Entries ?? '';
if (this.fyo.store.isDevelopment) {
// @ts-ignore
window.lv = this;
}
this.setShortcuts();
},
deactivated() {
docsPathRef.value = '';
this.shortcuts?.delete(this.context);
},
methods: {
setShortcuts() {
if (!this.shortcuts) {
return;
}
this.shortcuts.pmod.set(this.context, ['KeyN'], () =>
this.makeNewDocButton?.$el.click()
);
this.shortcuts.pmod.set(this.context, ['KeyE'], () =>
this.exportButton?.$el.click()
);
},
updatedData(listFilters: QueryFilter) {
this.listFilters = listFilters;
},
async openDoc(name: string) {
const route = getFormRoute(this.schemaName, name);
await routeTo(route);
},
async makeNewDoc() {
if (!this.canCreate) {
return;
}
const filters = getCreateFiltersFromListViewFilters(this.filters ?? {});
const doc = fyo.doc.getNewDoc(this.schemaName, filters);
const route = getFormRoute(this.schemaName, doc.name!);
await routeTo(route);
},
applyFilter(filters: QueryFilter) {
this.list?.updateData(filters);
},
},
});
function getListConfig(schemaName: string) {
const listConfig = fyo.models[schemaName]?.getListViewSettings?.(fyo);
if (listConfig?.columns === undefined) {
return {
columns: ['name'],
};
}
return listConfig;
}
</script>
|
2302_79757062/books
|
src/pages/ListView/ListView.vue
|
Vue
|
agpl-3.0
| 4,930
|
<template>
<Modal :open-modal="openModal" class="w-3/6 p-4">
<h1 class="text-xl font-semibold text-center dark:text-gray-100 pb-4">
Close POS Shift
</h1>
<h2 class="mt-4 mb-2 text-lg font-medium dark:text-gray-100">
Closing Cash
</h2>
<Table
v-if="isValuesSeeded"
class="text-base"
:df="getField('closingCash')"
:show-header="true"
:border="true"
:value="posShiftDoc?.closingCash ?? []"
:read-only="false"
@row-change="handleChange"
/>
<h2 class="mt-6 mb-2 text-lg dark:text-gray-100 font-medium">
Closing Amounts
</h2>
<Table
v-if="isValuesSeeded"
class="text-base"
:df="getField('closingAmounts')"
:show-header="true"
:border="true"
:value="posShiftDoc?.closingAmounts"
:read-only="true"
@row-change="handleChange"
/>
<div class="mt-4 grid grid-cols-2 gap-4 items-end">
<Button
class="w-full py-5 bg-red-500 dark:bg-red-700"
@click="$emit('toggleModal', 'ShiftClose', false)"
>
<slot>
<p class="uppercase text-lg text-white font-semibold">
{{ t`Cancel` }}
</p>
</slot>
</Button>
<Button
class="w-full py-5 bg-green-500 dark:bg-green-700"
@click="handleSubmit"
>
<slot>
<p class="uppercase text-lg text-white font-semibold">
{{ t`Submit` }}
</p>
</slot>
</Button>
</div>
</Modal>
</template>
<script lang="ts">
import Button from 'src/components/Button.vue';
import Modal from 'src/components/Modal.vue';
import Table from 'src/components/Controls/Table.vue';
import { ModelNameEnum } from 'models/types';
import { Money } from 'pesa';
import { OpeningAmounts } from 'models/inventory/Point of Sale/OpeningAmounts';
import { POSShift } from 'models/inventory/Point of Sale/POSShift';
import { computed } from 'vue';
import { defineComponent } from 'vue';
import { fyo } from 'src/initFyo';
import { showToast } from 'src/utils/interactive';
import { t } from 'fyo';
import {
validateClosingAmounts,
transferPOSCashAndWriteOff,
} from 'src/utils/pos';
export default defineComponent({
name: 'ClosePOSShiftModal',
components: { Button, Modal, Table },
provide() {
return {
doc: computed(() => this.posShiftDoc),
};
},
props: {
openModal: {
default: false,
type: Boolean,
},
},
emits: ['toggleModal'],
data() {
return {
isValuesSeeded: false,
posShiftDoc: undefined as POSShift | undefined,
transactedAmount: {} as Record<string, Money> | undefined,
};
},
watch: {
openModal: {
async handler() {
await this.setTransactedAmount();
await this.seedClosingAmounts();
},
},
},
async activated() {
this.posShiftDoc = fyo.singles[ModelNameEnum.POSShift];
await this.seedValues();
await this.setTransactedAmount();
},
methods: {
async setTransactedAmount() {
if (!fyo.singles.POSShift?.openingDate) {
return;
}
const fromDate = fyo.singles.POSShift?.openingDate;
this.transactedAmount = await fyo.db.getPOSTransactedAmount(
fromDate,
new Date(),
fyo.singles.POSShift.closingDate as Date
);
},
seedClosingCash() {
if (!this.posShiftDoc) {
return;
}
this.posShiftDoc.closingCash = [];
this.posShiftDoc?.openingCash?.map(async (row) => {
await this.posShiftDoc?.append('closingCash', {
count: row.count,
denomination: row.denomination as Money,
});
});
},
async seedClosingAmounts() {
if (!this.posShiftDoc) {
return;
}
this.posShiftDoc.closingAmounts = [];
await this.posShiftDoc.sync();
const openingAmounts = this.posShiftDoc
.openingAmounts as OpeningAmounts[];
for (const row of openingAmounts) {
if (!row.paymentMethod) {
return;
}
let expectedAmount = fyo.pesa(0);
if (row.paymentMethod === 'Cash') {
expectedAmount = expectedAmount.add(
this.posShiftDoc.openingCashAmount as Money
);
}
if (row.paymentMethod === 'Transfer') {
expectedAmount = expectedAmount.add(
this.posShiftDoc.openingTransferAmount as Money
);
}
if (this.transactedAmount) {
expectedAmount = expectedAmount.add(
this.transactedAmount[row.paymentMethod]
);
}
await this.posShiftDoc.append('closingAmounts', {
paymentMethod: row.paymentMethod,
openingAmount: row.amount,
closingAmount: fyo.pesa(0),
expectedAmount: expectedAmount,
differenceAmount: fyo.pesa(0),
});
await this.posShiftDoc.sync();
}
},
async seedValues() {
this.isValuesSeeded = false;
this.seedClosingCash();
await this.seedClosingAmounts();
this.isValuesSeeded = true;
},
getField(fieldname: string) {
return fyo.getField(ModelNameEnum.POSShift, fieldname);
},
async handleChange() {
await this.posShiftDoc?.sync();
},
async handleSubmit() {
try {
validateClosingAmounts(this.posShiftDoc as POSShift);
await this.posShiftDoc?.set('isShiftOpen', false);
await this.posShiftDoc?.set('closingDate', new Date());
await this.posShiftDoc?.sync();
await transferPOSCashAndWriteOff(fyo, this.posShiftDoc as POSShift);
this.$emit('toggleModal', 'ShiftClose');
} catch (error) {
return showToast({
type: 'error',
message: t`${error as string}`,
duration: 'short',
});
}
},
},
});
</script>
|
2302_79757062/books
|
src/pages/POS/ClosePOSShiftModal.vue
|
Vue
|
agpl-3.0
| 5,851
|
<template>
<Modal class="w-3/6 p-4">
<h1 class="text-xl font-semibold text-center dark:text-gray-100 pb-4">
Open POS Shift
</h1>
<div class="grid grid-cols-12 gap-6">
<div class="col-span-6">
<h2 class="text-lg font-medium dark:text-gray-100">
Cash In Denominations
</h2>
<Table
v-if="isValuesSeeded"
class="mt-4 text-base"
:df="getField('openingCash')"
:show-header="true"
:border="true"
:value="posShiftDoc?.openingCash"
@row-change="handleChange"
/>
</div>
<div class="col-span-6">
<h2 class="text-lg font-medium dark:text-gray-100">Opening Amount</h2>
<Table
v-if="isValuesSeeded"
class="mt-4 text-base"
:df="getField('openingAmounts')"
:show-header="true"
:border="true"
:max-rows-before-overflow="4"
:value="posShiftDoc?.openingAmounts"
:read-only="true"
@row-change="handleChange"
/>
<div class="mt-4 grid grid-cols-2 gap-4 items-end">
<Button
class="w-full py-5 bg-red-500 dark:bg-red-700"
@click="$router.back()"
>
<slot>
<p class="uppercase text-lg text-white font-semibold">
{{ t`Back` }}
</p>
</slot>
</Button>
<Button
class="w-full py-5 bg-green-500 dark:bg-green-700"
@click="handleSubmit"
>
<slot>
<p class="uppercase text-lg text-white font-semibold">
{{ t`Submit` }}
</p>
</slot>
</Button>
</div>
</div>
</div>
</Modal>
</template>
<script lang="ts">
import Button from 'src/components/Button.vue';
import Modal from 'src/components/Modal.vue';
import Table from 'src/components/Controls/Table.vue';
import { AccountTypeEnum } from 'models/baseModels/Account/types';
import { ModelNameEnum } from 'models/types';
import { Money } from 'pesa';
import { POSShift } from 'models/inventory/Point of Sale/POSShift';
import { computed } from 'vue';
import { defineComponent } from 'vue';
import { fyo } from 'src/initFyo';
import { showToast } from 'src/utils/interactive';
import { t } from 'fyo';
import { ValidationError } from 'fyo/utils/errors';
export default defineComponent({
name: 'OpenPOSShift',
components: { Button, Modal, Table },
provide() {
return {
doc: computed(() => this.posShiftDoc),
};
},
emits: ['toggleModal'],
data() {
return {
posShiftDoc: undefined as POSShift | undefined,
isValuesSeeded: false,
};
},
computed: {
getDefaultCashDenominations() {
return this.fyo.singles.Defaults?.posCashDenominations;
},
posCashAccount() {
return fyo.singles.POSSettings?.cashAccount;
},
posOpeningCashAmount(): Money {
return this.posShiftDoc?.openingCashAmount as Money;
},
},
async mounted() {
this.isValuesSeeded = false;
this.posShiftDoc = fyo.singles[ModelNameEnum.POSShift];
await this.seedDefaults();
this.isValuesSeeded = true;
},
methods: {
async seedDefaultCashDenomiations() {
if (!this.posShiftDoc) {
return;
}
this.posShiftDoc.openingCash = [];
await this.posShiftDoc.sync();
const denominations = this.getDefaultCashDenominations;
if (!denominations) {
return;
}
for (const row of denominations) {
await this.posShiftDoc.append('openingCash', {
denomination: row.denomination,
count: 0,
});
await this.posShiftDoc.sync();
}
},
async seedPaymentMethods() {
if (!this.posShiftDoc) {
return;
}
this.posShiftDoc.openingAmounts = [];
await this.posShiftDoc.sync();
await this.posShiftDoc.set('openingAmounts', [
{
paymentMethod: 'Cash',
amount: fyo.pesa(0),
},
{
paymentMethod: 'Transfer',
amount: fyo.pesa(0),
},
]);
await this.posShiftDoc.sync();
},
async seedDefaults() {
if (!!this.posShiftDoc?.isShiftOpen) {
return;
}
await this.seedDefaultCashDenomiations();
await this.seedPaymentMethods();
},
getField(fieldname: string) {
return this.fyo.getField(ModelNameEnum.POSShift, fieldname);
},
setOpeningCashAmount() {
if (!this.posShiftDoc?.openingAmounts) {
return;
}
this.posShiftDoc.openingAmounts.map((row) => {
if (row.paymentMethod === 'Cash') {
row.amount = this.posShiftDoc?.openingCashAmount as Money;
}
});
},
async handleChange() {
await this.posShiftDoc?.sync();
this.setOpeningCashAmount();
},
async handleSubmit() {
try {
if (this.posShiftDoc?.openingCashAmount.isNegative()) {
throw new ValidationError(
t`Opening Cash Amount can not be negative.`
);
}
await this.posShiftDoc?.setMultiple({
isShiftOpen: true,
openingDate: new Date(),
});
await this.posShiftDoc?.sync();
if (!this.posShiftDoc?.openingCashAmount.isZero()) {
const jvDoc = fyo.doc.getNewDoc(ModelNameEnum.JournalEntry, {
entryType: 'Journal Entry',
});
await jvDoc.append('accounts', {
account: this.posCashAccount,
debit: this.posShiftDoc?.openingCashAmount as Money,
credit: this.fyo.pesa(0),
});
await jvDoc.append('accounts', {
account: AccountTypeEnum.Cash,
debit: this.fyo.pesa(0),
credit: this.posShiftDoc?.openingCashAmount as Money,
});
await (await jvDoc.sync()).submit();
}
this.$emit('toggleModal', 'ShiftOpen');
} catch (error) {
showToast({
type: 'error',
message: t`${error as string}`,
duration: 'short',
});
return;
}
},
},
});
</script>
|
2302_79757062/books
|
src/pages/POS/OpenPOSShiftModal.vue
|
Vue
|
agpl-3.0
| 6,192
|
<template>
<div class="">
<PageHeader :title="t`Point of Sale`">
<slot>
<Button
class="bg-red-500 dark:bg-red-700"
@click="toggleModal('ShiftClose')"
>
<span class="font-medium text-white">{{ t`Close POS Shift ` }}</span>
</Button>
</slot>
</PageHeader>
<OpenPOSShiftModal
v-if="!isPosShiftOpen"
:open-modal="!isPosShiftOpen"
@toggle-modal="toggleModal"
/>
<ClosePOSShiftModal
:open-modal="openShiftCloseModal"
@toggle-modal="toggleModal"
/>
<PaymentModal
:open-modal="openPaymentModal"
@create-transaction="createTransaction"
@toggle-modal="toggleModal"
@set-cash-amount="setCashAmount"
@set-transfer-amount="setTransferAmount"
@set-transfer-ref-no="setTransferRefNo"
@set-transfer-clearance-date="setTransferClearanceDate"
/>
<div
class="bg-gray-25 dark:bg-gray-875 gap-2 grid grid-cols-12 p-4"
style="height: calc(100vh - var(--h-row-largest))"
>
<div
class="
bg-white
dark:bg-gray-850
border
dark:border-gray-800
col-span-5
rounded-md
"
>
<div class="rounded-md p-4 col-span-5">
<div class="flex gap-x-2">
<!-- Item Search -->
<Link
:class="
fyo.singles.InventorySettings?.enableBarcodes
? 'flex-shrink-0 w-2/3'
: 'w-full'
"
:df="{
label: t`Search an Item`,
fieldtype: 'Link',
fieldname: 'item',
target: 'Item',
}"
:border="true"
:value="itemSearchTerm"
@keyup.enter="
async () => await addItem(await getItem(itemSearchTerm))
"
@change="(item: string) =>itemSearchTerm= item"
/>
<Barcode
v-if="fyo.singles.InventorySettings?.enableBarcodes"
class="w-1/3"
@item-selected="
async (name: string) => {
await addItem(await getItem(name));
}
"
/>
</div>
<ItemsTable @add-item="addItem" />
</div>
</div>
<div class="col-span-7">
<div class="flex flex-col gap-3" style="height: calc(100vh - 6rem)">
<div
class="
bg-white
dark:bg-gray-850
border
dark:border-gray-800
grow
h-full
p-4
rounded-md
"
>
<!-- Customer Search -->
<Link
v-if="sinvDoc.fieldMap"
class="flex-shrink-0"
:border="true"
:value="sinvDoc.party"
:df="sinvDoc.fieldMap.party"
@change="(value:string) => (sinvDoc.party = value)"
/>
<SelectedItemTable />
</div>
<div
class="
bg-white
dark:bg-gray-850
border
dark:border-gray-800
p-4
rounded-md
"
>
<div class="w-full grid grid-cols-2 gap-y-2 gap-x-3">
<div class="">
<div class="grid grid-cols-2 gap-2">
<FloatingLabelFloatInput
:df="{
label: t`Total Quantity`,
fieldtype: 'Int',
fieldname: 'totalQuantity',
minvalue: 0,
maxvalue: 1000,
}"
size="large"
:value="totalQuantity"
:read-only="true"
:text-right="true"
/>
<FloatingLabelCurrencyInput
:df="{
label: t`Add'l Discounts`,
fieldtype: 'Int',
fieldname: 'additionalDiscount',
minvalue: 0,
}"
size="large"
:value="additionalDiscounts"
:read-only="true"
:text-right="true"
@change="(amount:Money)=> additionalDiscounts= amount"
/>
</div>
<div class="mt-4 grid grid-cols-2 gap-2">
<FloatingLabelCurrencyInput
:df="{
label: t`Item Discounts`,
fieldtype: 'Currency',
fieldname: 'itemDiscounts',
}"
size="large"
:value="itemDiscounts"
:read-only="true"
:text-right="true"
/>
<FloatingLabelCurrencyInput
v-if="sinvDoc.fieldMap"
:df="sinvDoc.fieldMap.grandTotal"
size="large"
:value="sinvDoc.grandTotal"
:read-only="true"
:text-right="true"
/>
</div>
</div>
<div class="">
<Button
class="w-full bg-red-500 dark:bg-red-700 py-6"
:disabled="!sinvDoc.items?.length"
@click="clearValues"
>
<slot>
<p class="uppercase text-lg text-white font-semibold">
{{ t`Cancel` }}
</p>
</slot>
</Button>
<Button
class="mt-4 w-full bg-green-500 dark:bg-green-700 py-6"
:disabled="disablePayButton"
@click="toggleModal('Payment', true)"
>
<slot>
<p class="uppercase text-lg text-white font-semibold">
{{ t`Pay` }}
</p>
</slot>
</Button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import Button from 'src/components/Button.vue';
import ClosePOSShiftModal from './ClosePOSShiftModal.vue';
import FloatingLabelCurrencyInput from 'src/components/POS/FloatingLabelCurrencyInput.vue';
import FloatingLabelFloatInput from 'src/components/POS/FloatingLabelFloatInput.vue';
import ItemsTable from 'src/components/POS/ItemsTable.vue';
import Link from 'src/components/Controls/Link.vue';
import OpenPOSShiftModal from './OpenPOSShiftModal.vue';
import PageHeader from 'src/components/PageHeader.vue';
import PaymentModal from './PaymentModal.vue';
import SelectedItemTable from 'src/components/POS/SelectedItemTable.vue';
import { computed, defineComponent } from 'vue';
import { fyo } from 'src/initFyo';
import { routeTo, toggleSidebar } from 'src/utils/ui';
import { ModelNameEnum } from 'models/types';
import { SalesInvoice } from 'models/baseModels/SalesInvoice/SalesInvoice';
import { t } from 'fyo';
import {
ItemQtyMap,
ItemSerialNumbers,
POSItem,
} from 'src/components/POS/types';
import { Item } from 'models/baseModels/Item/Item';
import { ModalName } from 'src/components/POS/types';
import { Money } from 'pesa';
import { Payment } from 'models/baseModels/Payment/Payment';
import { SalesInvoiceItem } from 'models/baseModels/SalesInvoiceItem/SalesInvoiceItem';
import { Shipment } from 'models/inventory/Shipment';
import { showToast } from 'src/utils/interactive';
import {
getItem,
getItemDiscounts,
getItemQtyMap,
getTotalQuantity,
getTotalTaxedAmount,
validateIsPosSettingsSet,
validateShipment,
validateSinv,
} from 'src/utils/pos';
import Barcode from 'src/components/Controls/Barcode.vue';
import { getPricingRule } from 'models/helpers';
export default defineComponent({
name: 'POS',
components: {
Button,
ClosePOSShiftModal,
FloatingLabelCurrencyInput,
FloatingLabelFloatInput,
ItemsTable,
Link,
OpenPOSShiftModal,
PageHeader,
PaymentModal,
SelectedItemTable,
Barcode,
},
provide() {
return {
cashAmount: computed(() => this.cashAmount),
doc: computed(() => this.sinvDoc),
isDiscountingEnabled: computed(() => this.isDiscountingEnabled),
itemDiscounts: computed(() => this.itemDiscounts),
itemQtyMap: computed(() => this.itemQtyMap),
itemSerialNumbers: computed(() => this.itemSerialNumbers),
sinvDoc: computed(() => this.sinvDoc),
totalTaxedAmount: computed(() => this.totalTaxedAmount),
transferAmount: computed(() => this.transferAmount),
transferClearanceDate: computed(() => this.transferClearanceDate),
transferRefNo: computed(() => this.transferRefNo),
};
},
data() {
return {
isItemsSeeded: false,
openPaymentModal: false,
openShiftCloseModal: false,
openShiftOpenModal: false,
additionalDiscounts: fyo.pesa(0),
cashAmount: fyo.pesa(0),
itemDiscounts: fyo.pesa(0),
totalTaxedAmount: fyo.pesa(0),
transferAmount: fyo.pesa(0),
totalQuantity: 0,
defaultCustomer: undefined as string | undefined,
itemSearchTerm: '',
transferRefNo: undefined as string | undefined,
transferClearanceDate: undefined as Date | undefined,
itemQtyMap: {} as ItemQtyMap,
itemSerialNumbers: {} as ItemSerialNumbers,
paymentDoc: {} as Payment,
sinvDoc: {} as SalesInvoice,
};
},
computed: {
defaultPOSCashAccount: () =>
fyo.singles.POSSettings?.cashAccount ?? undefined,
isDiscountingEnabled(): boolean {
return !!fyo.singles.AccountingSettings?.enableDiscounting;
},
isPosShiftOpen: () => !!fyo.singles.POSShift?.isShiftOpen,
isPaymentAmountSet(): boolean {
if (this.sinvDoc.grandTotal?.isZero()) {
return true;
}
if (this.cashAmount.isZero() && this.transferAmount.isZero()) {
return false;
}
return true;
},
disablePayButton(): boolean {
if (!this.sinvDoc.items?.length) {
return true;
}
if (!this.sinvDoc.party) {
return true;
}
return false;
},
},
watch: {
sinvDoc: {
handler() {
this.updateValues();
},
deep: true,
},
},
async activated() {
toggleSidebar(false);
validateIsPosSettingsSet(fyo);
this.setSinvDoc();
this.setDefaultCustomer();
await this.setItemQtyMap();
},
deactivated() {
toggleSidebar(true);
},
methods: {
setCashAmount(amount: Money) {
this.cashAmount = amount;
},
setDefaultCustomer() {
this.defaultCustomer = this.fyo.singles.Defaults?.posCustomer ?? '';
this.sinvDoc.party = this.defaultCustomer;
},
setItemDiscounts() {
this.itemDiscounts = getItemDiscounts(
this.sinvDoc.items as SalesInvoiceItem[]
);
},
async setItemQtyMap() {
this.itemQtyMap = await getItemQtyMap();
},
setSinvDoc() {
this.sinvDoc = this.fyo.doc.getNewDoc(ModelNameEnum.SalesInvoice, {
account: 'Debtors',
party: this.sinvDoc.party ?? this.defaultCustomer,
isPOS: true,
}) as SalesInvoice;
},
setTotalQuantity() {
this.totalQuantity = getTotalQuantity(
this.sinvDoc.items as SalesInvoiceItem[]
);
},
setTotalTaxedAmount() {
this.totalTaxedAmount = getTotalTaxedAmount(this.sinvDoc as SalesInvoice);
},
setTransferAmount(amount: Money = fyo.pesa(0)) {
this.transferAmount = amount;
},
setTransferClearanceDate(date: Date) {
this.transferClearanceDate = date;
},
setTransferRefNo(ref: string) {
this.transferRefNo = ref;
},
removeFreeItems() {
if (!this.sinvDoc || !this.sinvDoc.items) {
return;
}
if (!!this.sinvDoc.isPricingRuleApplied) {
return;
}
for (const item of this.sinvDoc.items) {
if (item.isFreeItem) {
this.sinvDoc.items = this.sinvDoc.items?.filter(
(invoiceItem) => invoiceItem.name !== item.name
);
}
}
},
async addItem(item: POSItem | Item | undefined) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
await this.sinvDoc.runFormulas();
if (!item) {
return;
}
if (
!this.itemQtyMap[item.name as string] ||
this.itemQtyMap[item.name as string].availableQty === 0
) {
showToast({
type: 'error',
message: t`Item ${item.name as string} has Zero Quantity`,
duration: 'short',
});
return;
}
const existingItems =
this.sinvDoc.items?.filter(
(invoiceItem) =>
invoiceItem.item === item.name && !invoiceItem.isFreeItem
) ?? [];
if (item.hasBatch) {
for (const invItem of existingItems) {
const itemQty = invItem.quantity ?? 0;
const qtyInBatch =
this.itemQtyMap[invItem.item as string][invItem.batch as string] ??
0;
if (itemQty < qtyInBatch) {
invItem.quantity = (invItem.quantity as number) + 1;
invItem.rate = item.rate as Money;
await this.applyPricingRule();
await this.sinvDoc.runFormulas();
return;
}
}
try {
await this.sinvDoc.append('items', {
rate: item.rate as Money,
item: item.name,
});
} catch (error) {
showToast({
type: 'error',
message: t`${error as string}`,
});
}
return;
}
if (existingItems.length) {
existingItems[0].rate = item.rate as Money;
existingItems[0].quantity = (existingItems[0].quantity as number) + 1;
await this.applyPricingRule();
await this.sinvDoc.runFormulas();
return;
}
await this.sinvDoc.append('items', {
rate: item.rate as Money,
item: item.name,
});
await this.applyPricingRule();
await this.sinvDoc.runFormulas();
},
async createTransaction(shouldPrint = false) {
try {
await this.validate();
await this.submitSinvDoc(shouldPrint);
await this.makePayment();
await this.makeStockTransfer();
await this.afterTransaction();
} catch (error) {
showToast({
type: 'error',
message: t`${error as string}`,
});
}
},
async makePayment() {
this.paymentDoc = this.sinvDoc.getPayment() as Payment;
const paymentMethod = this.cashAmount.isZero() ? 'Transfer' : 'Cash';
await this.paymentDoc.set('paymentMethod', paymentMethod);
if (paymentMethod === 'Transfer') {
await this.paymentDoc.setMultiple({
amount: this.transferAmount as Money,
referenceId: this.transferRefNo,
clearanceDate: this.transferClearanceDate,
});
}
if (paymentMethod === 'Cash') {
await this.paymentDoc.setMultiple({
paymentAccount: this.defaultPOSCashAccount,
amount: this.cashAmount as Money,
});
}
this.paymentDoc.once('afterSubmit', () => {
showToast({
type: 'success',
message: t`Payment ${this.paymentDoc.name as string} is Saved`,
duration: 'short',
});
});
try {
await this.paymentDoc?.sync();
await this.paymentDoc?.submit();
} catch (error) {
return showToast({
type: 'error',
message: t`${error as string}`,
});
}
},
async makeStockTransfer() {
const shipmentDoc = (await this.sinvDoc.getStockTransfer()) as Shipment;
if (!shipmentDoc.items) {
return;
}
for (const item of shipmentDoc.items) {
item.location = fyo.singles.POSSettings?.inventory;
item.serialNumber =
this.itemSerialNumbers[item.item as string] ?? undefined;
}
shipmentDoc.once('afterSubmit', () => {
showToast({
type: 'success',
message: t`Shipment ${shipmentDoc.name as string} is Submitted`,
duration: 'short',
});
});
try {
await shipmentDoc.sync();
await shipmentDoc.submit();
} catch (error) {
return showToast({
type: 'error',
message: t`${error as string}`,
});
}
},
async submitSinvDoc(shouldPrint: boolean) {
this.sinvDoc.once('afterSubmit', async () => {
showToast({
type: 'success',
message: t`Sales Invoice ${this.sinvDoc.name as string} is Submitted`,
duration: 'short',
});
if (shouldPrint) {
await routeTo(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`/print/${this.sinvDoc.schemaName}/${this.sinvDoc.name}`
);
}
});
try {
await this.validate();
await this.sinvDoc.runFormulas();
await this.sinvDoc.sync();
await this.sinvDoc.submit();
} catch (error) {
return showToast({
type: 'error',
message: t`${error as string}`,
});
}
},
async afterTransaction() {
await this.setItemQtyMap();
this.clearValues();
this.setSinvDoc();
this.toggleModal('Payment', false);
},
clearValues() {
this.setSinvDoc();
this.itemSerialNumbers = {};
this.cashAmount = fyo.pesa(0);
this.transferAmount = fyo.pesa(0);
},
toggleModal(modal: ModalName, value?: boolean) {
if (value) {
return (this[`open${modal}Modal`] = value);
}
return (this[`open${modal}Modal`] = !this[`open${modal}Modal`]);
},
updateValues() {
this.setTotalQuantity();
this.setItemDiscounts();
this.setTotalTaxedAmount();
},
async validate() {
validateSinv(this.sinvDoc as SalesInvoice, this.itemQtyMap);
await validateShipment(this.itemSerialNumbers);
},
async applyPricingRule() {
const hasPricingRules = await getPricingRule(
this.sinvDoc as SalesInvoice
);
if (!hasPricingRules || !hasPricingRules.length) {
this.sinvDoc.pricingRuleDetail = undefined;
this.sinvDoc.isPricingRuleApplied = false;
this.removeFreeItems();
return;
}
setTimeout(async () => {
const appliedPricingRuleCount = this.sinvDoc?.items?.filter(
(val) => val.isFreeItem
).length;
if (appliedPricingRuleCount !== hasPricingRules?.length) {
await this.sinvDoc.appendPricingRuleDetail(hasPricingRules);
await this.sinvDoc.applyProductDiscount();
}
}, 1);
},
getItem,
},
});
</script>
|
2302_79757062/books
|
src/pages/POS/POS.vue
|
Vue
|
agpl-3.0
| 19,147
|
<template>
<Modal class="w-2/6 ml-auto mr-3.5" :set-close-listener="false">
<div v-if="sinvDoc.fieldMap" class="px-4 py-6 grid" style="height: 95vh">
<div class="grid grid-cols-2 gap-6">
<Currency
:df="fyo.fieldMap.PaymentFor.amount"
:read-only="!transferAmount.isZero()"
:border="true"
:text-right="true"
:value="cashAmount"
@change="(amount:Money)=> $emit('setCashAmount', amount)"
/>
<Button
class="w-full py-5 bg-teal-500"
@click="setCashOrTransferAmount"
>
<slot>
<p class="uppercase text-lg text-white font-semibold">
{{ t`Cash` }}
</p>
</slot>
</Button>
<Currency
:df="fyo.fieldMap.PaymentFor.amount"
:read-only="!cashAmount.isZero()"
:border="true"
:text-right="true"
:value="transferAmount"
@change="(value:Money)=> $emit('setTransferAmount', value)"
/>
<Button
class="w-full py-5 bg-teal-500"
@click="setCashOrTransferAmount('Transfer')"
>
<slot>
<p class="uppercase text-lg text-white font-semibold">
{{ t`Transfer` }}
</p>
</slot>
</Button>
</div>
<div class="mt-8 grid grid-cols-2 gap-6">
<Data
v-show="!transferAmount.isZero()"
:df="fyo.fieldMap.Payment.referenceId"
:show-label="true"
:border="true"
:required="!transferAmount.isZero()"
:value="transferRefNo"
@change="(value:string) => $emit('setTransferRefNo', value)"
/>
<Date
v-show="!transferAmount.isZero()"
:df="fyo.fieldMap.Payment.clearanceDate"
:show-label="true"
:border="true"
:required="!transferAmount.isZero()"
:value="transferClearanceDate"
@change="(value:Date) => $emit('setTransferClearanceDate', value)"
/>
</div>
<div class="mt-14 grid grid-cols-2 gap-6">
<Currency
v-show="showPaidChange"
:df="{
label: t`Paid Change`,
fieldtype: 'Currency',
fieldname: 'paidChange',
}"
:read-only="true"
:show-label="true"
:border="true"
:text-right="true"
:value="paidChange"
/>
<Currency
v-show="showBalanceAmount"
:df="{
label: t`Balance Amount`,
fieldtype: 'Currency',
fieldname: 'balanceAmount',
}"
:read-only="true"
:show-label="true"
:border="true"
:text-right="true"
:value="balanceAmount"
/>
</div>
<div
class="mb-14 row-start-4 row-span-2 grid grid-cols-2 gap-x-6 gap-y-11"
>
<Currency
:df="sinvDoc.fieldMap.netTotal"
:read-only="true"
:show-label="true"
:border="true"
:text-right="true"
:value="sinvDoc?.netTotal"
/>
<Currency
:df="{
label: t`Taxes and Charges`,
fieldtype: 'Currency',
fieldname: 'taxesAndCharges',
}"
:read-only="true"
:show-label="true"
:border="true"
:text-right="true"
:value="totalTaxedAmount"
/>
<Currency
:df="sinvDoc.fieldMap.baseGrandTotal"
:read-only="true"
:show-label="true"
:border="true"
:text-right="true"
:value="sinvDoc?.baseGrandTotal"
/>
<Currency
v-if="isDiscountingEnabled"
:df="sinvDoc.fieldMap.discountAmount"
:read-only="true"
:show-label="true"
:border="true"
:text-right="true"
:value="itemDiscounts"
/>
<Currency
:df="sinvDoc.fieldMap.grandTotal"
:read-only="true"
:show-label="true"
:border="true"
:text-right="true"
:value="sinvDoc?.grandTotal"
/>
</div>
<div class="row-start-6 grid grid-cols-2 gap-4 mt-auto">
<div class="col-span-2">
<Button
class="w-full bg-red-500"
style="padding: 1.35rem"
@click="$emit('toggleModal', 'Payment')"
>
<slot>
<p class="uppercase text-lg text-white font-semibold">
{{ t`Cancel` }}
</p>
</slot>
</Button>
</div>
<div class="col-span-1">
<Button
class="w-full bg-blue-500"
style="padding: 1.35rem"
:disabled="disableSubmitButton"
@click="$emit('createTransaction')"
>
<slot>
<p class="uppercase text-lg text-white font-semibold">
{{ t`Submit` }}
</p>
</slot>
</Button>
</div>
<div class="col-span-1">
<Button
class="w-full bg-green-500"
style="padding: 1.35rem"
:disabled="disableSubmitButton"
@click="$emit('createTransaction', true)"
>
<slot>
<p class="uppercase text-lg text-white font-semibold">
{{ t`Submit & Print` }}
</p>
</slot>
</Button>
</div>
</div>
</div>
</Modal>
</template>
<script lang="ts">
import Button from 'src/components/Button.vue';
import Currency from 'src/components/Controls/Currency.vue';
import Data from 'src/components/Controls/Data.vue';
import Date from 'src/components/Controls/Date.vue';
import Modal from 'src/components/Modal.vue';
import { Money } from 'pesa';
import { SalesInvoice } from 'models/baseModels/SalesInvoice/SalesInvoice';
import { defineComponent, inject } from 'vue';
import { fyo } from 'src/initFyo';
export default defineComponent({
name: 'PaymentModal',
components: {
Modal,
Currency,
Button,
Data,
Date,
},
emits: [
'createTransaction',
'setCashAmount',
'setTransferAmount',
'setTransferClearanceDate',
'setTransferRefNo',
'toggleModal',
],
setup() {
return {
cashAmount: inject('cashAmount') as Money,
isDiscountingEnabled: inject('isDiscountingEnabled') as boolean,
itemDiscounts: inject('itemDiscounts') as Money,
transferAmount: inject('transferAmount') as Money,
sinvDoc: inject('sinvDoc') as SalesInvoice,
transferRefNo: inject('transferRefNo') as string,
transferClearanceDate: inject('transferClearanceDate') as Date,
totalTaxedAmount: inject('totalTaxedAmount') as Money,
};
},
computed: {
balanceAmount(): Money {
const grandTotal = this.sinvDoc?.grandTotal ?? fyo.pesa(0);
if (this.cashAmount.isZero()) {
return grandTotal.sub(this.transferAmount);
}
return grandTotal.sub(this.cashAmount);
},
paidChange(): Money {
const grandTotal = this.sinvDoc?.grandTotal ?? fyo.pesa(0);
if (this.cashAmount.isZero()) {
return this.transferAmount.sub(grandTotal);
}
return this.cashAmount.sub(grandTotal);
},
showBalanceAmount(): boolean {
if (
this.cashAmount.eq(fyo.pesa(0)) &&
this.transferAmount.eq(fyo.pesa(0))
) {
return false;
}
if (this.cashAmount.gte(this.sinvDoc?.grandTotal ?? fyo.pesa(0))) {
return false;
}
if (this.transferAmount.gte(this.sinvDoc?.grandTotal ?? fyo.pesa(0))) {
return false;
}
return true;
},
showPaidChange(): boolean {
if (
this.cashAmount.eq(fyo.pesa(0)) &&
this.transferAmount.eq(fyo.pesa(0))
) {
return false;
}
if (this.cashAmount.gt(this.sinvDoc?.grandTotal ?? fyo.pesa(0))) {
return true;
}
if (this.transferAmount.gt(this.sinvDoc?.grandTotal ?? fyo.pesa(0))) {
return true;
}
return false;
},
disableSubmitButton(): boolean {
if (
!this.sinvDoc.grandTotal?.isZero() &&
this.transferAmount.isZero() &&
this.cashAmount.isZero()
) {
return true;
}
if (
this.cashAmount.isZero() &&
(!this.transferRefNo || !this.transferClearanceDate)
) {
return true;
}
return false;
},
},
methods: {
setCashOrTransferAmount(paymentMethod = 'Cash') {
if (paymentMethod === 'Transfer') {
this.$emit('setCashAmount', fyo.pesa(0));
this.$emit('setTransferAmount', this.sinvDoc?.grandTotal);
return;
}
this.$emit('setTransferAmount', fyo.pesa(0));
this.$emit('setCashAmount', this.sinvDoc?.grandTotal);
},
},
});
</script>
|
2302_79757062/books
|
src/pages/POS/PaymentModal.vue
|
Vue
|
agpl-3.0
| 8,931
|
<template>
<div class="flex flex-col flex-1 bg-gray-25 dark:bg-gray-875">
<PageHeader :border="true" :title="t`Print View`">
<AutoComplete
v-if="templateList.length"
:df="{
fieldtype: 'AutoComplete',
fieldname: 'templateName',
label: t`Template Name`,
options: templateList.map((n) => ({ label: n, value: n })),
}"
input-class="text-base py-0 h-8"
class="w-40"
:border="true"
:value="templateName ?? ''"
@change="onTemplateNameChange"
/>
<DropdownWithActions :actions="actions" :title="t`More`" />
<Button class="text-xs" type="primary" @click="savePDF">
{{ t`Save as PDF` }}
</Button>
</PageHeader>
<!-- Template Display Area -->
<div class="overflow-auto custom-scroll custom-scroll-thumb1 p-4">
<!-- Display Hints -->
<div
v-if="helperMessage"
class="text-sm text-gray-700 dark:text-gray-300"
>
{{ helperMessage }}
</div>
<!-- Template Container -->
<PrintContainer
v-if="printProps"
ref="printContainer"
:print-schema-name="schemaName"
:template="printProps.template"
:values="printProps.values"
:scale="scale"
:width="templateDoc?.width"
:height="templateDoc?.height"
/>
</div>
</div>
</template>
<script lang="ts">
import { Doc } from 'fyo/model/doc';
import { Action } from 'fyo/model/types';
import { PrintTemplate } from 'models/baseModels/PrintTemplate';
import { ModelNameEnum } from 'models/types';
import Button from 'src/components/Button.vue';
import AutoComplete from 'src/components/Controls/AutoComplete.vue';
import DropdownWithActions from 'src/components/DropdownWithActions.vue';
import PageHeader from 'src/components/PageHeader.vue';
import { handleErrorWithDialog } from 'src/errorHandling';
import { fyo } from 'src/initFyo';
import { getPrintTemplatePropValues } from 'src/utils/printTemplates';
import { showSidebar } from 'src/utils/refs';
import { PrintValues } from 'src/utils/types';
import { getFormRoute, openSettings, routeTo } from 'src/utils/ui';
import { defineComponent } from 'vue';
import PrintContainer from '../TemplateBuilder/PrintContainer.vue';
export default defineComponent({
name: 'PrintView',
components: {
PageHeader,
Button,
AutoComplete,
PrintContainer,
DropdownWithActions,
},
props: {
schemaName: { type: String, required: true },
name: { type: String, required: true },
},
data() {
return {
doc: null,
scale: 1,
values: null,
templateDoc: null,
templateName: null,
templateList: [],
} as {
doc: null | Doc;
scale: number;
values: null | PrintValues;
templateDoc: null | PrintTemplate;
templateName: null | string;
templateList: string[];
};
},
computed: {
helperMessage() {
if (!this.templateList.length) {
const label =
this.fyo.schemaMap[this.schemaName]?.label ?? this.schemaName;
return this.t`No Print Templates not found for entry type ${label}`;
}
if (!this.templateDoc) {
return this.t`Please select a Print Template`;
}
return '';
},
printProps(): null | { template: string; values: PrintValues } {
const values = this.values;
if (!values) {
return null;
}
const template = this.templateDoc?.template;
if (!template) {
return null;
}
return { values, template };
},
actions(): Action[] {
const actions = [
{
label: this.t`Print Settings`,
group: this.t`View`,
async action() {
await openSettings(ModelNameEnum.PrintSettings);
},
},
{
label: this.t`New Template`,
group: this.t`Create`,
action: async () => {
const doc = this.fyo.doc.getNewDoc(ModelNameEnum.PrintTemplate, {
type: this.schemaName,
});
const route = getFormRoute(doc.schemaName, doc.name!);
await routeTo(route);
},
},
];
const templateDocName = this.templateDoc?.name;
if (templateDocName) {
actions.push({
label: templateDocName,
group: this.t`View`,
action: async () => {
const route = getFormRoute(
ModelNameEnum.PrintTemplate,
templateDocName
);
await routeTo(route);
},
});
actions.push({
label: this.t`Duplicate Template`,
group: this.t`Create`,
action: async () => {
const doc = this.fyo.doc.getNewDoc(ModelNameEnum.PrintTemplate, {
type: this.schemaName,
template: this.templateDoc?.template,
});
const route = getFormRoute(doc.schemaName, doc.name!);
await routeTo(route);
},
});
}
return actions;
},
},
async mounted() {
await this.initialize();
if (fyo.store.isDevelopment) {
// @ts-ignore
window.pv = this;
}
},
async activated() {
await this.initialize();
},
unmounted() {
this.reset();
},
deactivated() {
this.reset();
},
methods: {
async initialize() {
this.doc = await fyo.doc.getDoc(this.schemaName, this.name);
await this.setTemplateList();
await this.setTemplateFromDefault();
if (!this.templateDoc && this.templateList.length) {
await this.onTemplateNameChange(this.templateList[0]);
}
if (this.doc) {
this.values = await getPrintTemplatePropValues(this.doc as Doc);
}
},
setScale() {
this.scale = 1;
const width = (this.templateDoc?.width ?? 21) * 37.8;
let containerWidth = window.innerWidth - 32;
if (showSidebar.value) {
containerWidth -= 12 * 16;
}
this.scale = Math.min(containerWidth / width, 1);
},
reset() {
this.doc = null;
this.values = null;
this.templateList = [];
this.templateDoc = null;
this.scale = 1;
},
async onTemplateNameChange(value: string | null): Promise<void> {
if (!value) {
this.templateDoc = null;
return;
}
this.templateName = value;
try {
this.templateDoc = (await this.fyo.doc.getDoc(
ModelNameEnum.PrintTemplate,
this.templateName
)) as PrintTemplate;
} catch (error) {
await handleErrorWithDialog(error);
}
this.setScale();
},
async setTemplateList(): Promise<void> {
const list = (await this.fyo.db.getAllRaw(ModelNameEnum.PrintTemplate, {
filters: { type: this.schemaName },
})) as { name: string }[];
this.templateList = list.map(({ name }) => name);
},
async savePDF() {
const printContainer = this.$refs.printContainer as {
savePDF: (name?: string) => Promise<void>;
};
if (!printContainer?.savePDF) {
return;
}
await printContainer.savePDF(this.doc?.name);
},
async setTemplateFromDefault() {
const defaultName =
this.schemaName[0].toLowerCase() +
this.schemaName.slice(1) +
ModelNameEnum.PrintTemplate;
const name = this.fyo.singles.Defaults?.get(defaultName);
if (typeof name !== 'string') {
return;
}
await this.onTemplateNameChange(name);
},
},
});
</script>
|
2302_79757062/books
|
src/pages/PrintView/PrintView.vue
|
Vue
|
agpl-3.0
| 7,600
|
<template>
<div class="flex flex-col w-full h-full">
<PageHeader :title="t`Print ${title}`">
<Button class="text-xs" type="primary" @click="savePDF">
{{ t`Save as PDF` }}
</Button>
</PageHeader>
<div
class="outer-container overflow-y-auto custom-scroll custom-scroll-thumb1"
>
<!-- Report Print Display Area -->
<div
class="
p-4
bg-gray-25
dark:bg-gray-890
overflow-auto
flex
justify-center
custom-scroll custom-scroll-thumb1
"
>
<!-- Report Print Display Container -->
<ScaledContainer
ref="scaledContainer"
class="shadow-lg border bg-white"
:scale="scale"
:width="size.width"
:height="size.height"
:show-overflow="true"
>
<div class="bg-white mx-auto">
<div class="p-2">
<div class="font-semibold text-xl w-full flex justify-between">
<h1>
{{ `${fyo.singles.PrintSettings?.companyName}` }}
</h1>
<p class="text-gray-600">
{{ title }}
</p>
</div>
</div>
<!-- Report Data -->
<div class="grid" :style="rowStyles">
<template v-for="(row, r) of matrix" :key="`row-${r}`">
<div
v-for="(cell, c) of row"
:key="`cell-${r}.${c}`"
:class="cellClasses(cell.idx, r)"
class="text-sm p-2"
style="min-height: 2rem"
>
{{ cell.value }}
</div>
</template>
</div>
<div class="border-t p-2">
<p class="text-xs text-right w-full">
{{ fyo.format(new Date(), 'Datetime') }}
</p>
</div>
</div>
</ScaledContainer>
</div>
<!-- Report Print Settings -->
<div v-if="report" class="border-l dark:border-gray-800 flex flex-col">
<p class="p-4 text-sm text-gray-600 dark:text-gray-400">
{{
[
t`Hidden values will be visible on Print on.`,
t`Report will use more than one page if required.`,
].join(' ')
}}
</p>
<!-- Row Selection -->
<div class="p-4 border-t dark:border-gray-800">
<Int
:show-label="true"
:border="true"
:df="{
label: t`Start From Row Index`,
fieldtype: 'Int',
fieldname: 'numRows',
minvalue: 1,
maxvalue: report?.reportData.length ?? 1000,
}"
:value="start"
@change="(v) => (start = v)"
/>
<Int
class="mt-4"
:show-label="true"
:border="true"
:df="{
label: t`Number of Rows`,
fieldtype: 'Int',
fieldname: 'numRows',
minvalue: 0,
maxvalue: report?.reportData.length ?? 1000,
}"
:value="limit"
@change="(v) => (limit = v)"
/>
</div>
<!-- Size Selection -->
<div class="border-t dark:border-gray-800 p-4">
<Select
:show-label="true"
:border="true"
:df="printSizeDf"
:value="printSize"
@change="(v) => (printSize = v)"
/>
<Check
class="mt-4"
:show-label="true"
:border="true"
:df="{
label: t`Is Landscape`,
fieldname: 'isLandscape',
fieldtype: 'Check',
}"
:value="isLandscape"
@change="(v) => (isLandscape = v)"
/>
</div>
<!-- Pick Columns -->
<div class="border-t dark:border-gray-800 p-4">
<h2 class="text-sm text-gray-600 dark:text-gray-400">
{{ t`Pick Columns` }}
</h2>
<div
class="border dark:border-gray-800 rounded grid grid-cols-2 mt-1"
>
<Check
v-for="(col, i) of report?.columns"
:key="col.fieldname"
:show-label="true"
:df="{
label: col.label,
fieldname: col.fieldname,
fieldtype: 'Check',
}"
:value="columnSelection[i]"
@change="(v) => (columnSelection[i] = v)"
/>
</div>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import { Verb } from 'fyo/telemetry/types';
import { Report } from 'reports/Report';
import { reports } from 'reports/index';
import { OptionField } from 'schemas/types';
import Button from 'src/components/Button.vue';
import Check from 'src/components/Controls/Check.vue';
import Int from 'src/components/Controls/Int.vue';
import Select from 'src/components/Controls/Select.vue';
import PageHeader from 'src/components/PageHeader.vue';
import { getReport } from 'src/utils/misc';
import { getPathAndMakePDF } from 'src/utils/printTemplates';
import { showSidebar } from 'src/utils/refs';
import { paperSizeMap, printSizes } from 'src/utils/ui';
import { PropType, defineComponent } from 'vue';
import ScaledContainer from '../TemplateBuilder/ScaledContainer.vue';
export default defineComponent({
components: { PageHeader, Button, Check, Int, ScaledContainer, Select },
props: {
reportName: {
type: String as PropType<keyof typeof reports>,
required: true,
},
},
data() {
return {
start: 1,
limit: 0,
printSize: 'A4' as typeof printSizes[number],
isLandscape: false,
scale: 0.65,
report: null as null | Report,
columnSelection: [] as boolean[],
};
},
computed: {
title(): string {
return reports[this.reportName]?.title ?? this.t`Report`;
},
printSizeDf(): OptionField {
return {
label: 'Print Size',
fieldname: 'printSize',
fieldtype: 'Select',
options: printSizes
.filter((p) => p !== 'Custom')
.map((name) => ({ value: name, label: name })),
};
},
matrix(): { value: string; idx: number }[][] {
if (!this.report) {
return [];
}
const columns = this.report.columns
.map((col, idx) => ({ value: col.label, idx }))
.filter((_, i) => this.columnSelection[i]);
const matrix: { value: string; idx: number }[][] = [columns];
const start = Math.max(this.start - 1, 0);
const end = Math.min(start + this.limit, this.report.reportData.length);
const slice = this.report.reportData.slice(start, end);
for (let i = 0; i < slice.length; i++) {
const row = slice[i];
matrix.push([]);
for (let j = 0; j < row.cells.length; j++) {
if (!this.columnSelection[j]) {
continue;
}
const value = row.cells[j].value;
matrix.at(-1)?.push({ value, idx: Number(j) });
}
}
return matrix;
},
rowStyles(): Record<string, string> {
const style: Record<string, string> = {};
const numColumns = this.columnSelection.filter(Boolean).length;
style['grid-template-columns'] = `repeat(${numColumns}, minmax(0, auto))`;
return style;
},
size(): { width: number; height: number } {
const size = paperSizeMap[this.printSize];
const long = size.width > size.height ? size.width : size.height;
const short = size.width <= size.height ? size.width : size.height;
if (this.isLandscape) {
return { width: long, height: short };
}
return { width: short, height: long };
},
},
watch: {
size() {
this.setScale();
},
},
async mounted() {
this.report = await getReport(this.reportName);
this.limit = this.report.reportData.length;
this.columnSelection = this.report.columns.map(() => true);
this.setScale();
// @ts-ignore
window.rpv = this;
},
methods: {
setScale() {
const width = this.size.width * 37.2;
let containerWidth = window.innerWidth - 26 * 16;
if (showSidebar.value) {
containerWidth -= 12 * 16;
}
this.scale = Math.min(containerWidth / width, 1);
},
async savePDF(): Promise<void> {
// @ts-ignore
const innerHTML = this.$refs.scaledContainer.$el.children[0].innerHTML;
if (typeof innerHTML !== 'string') {
return;
}
const name = this.title + ' - ' + this.fyo.format(new Date(), 'Date');
await getPathAndMakePDF(
name,
innerHTML,
this.size.width,
this.size.height
);
this.fyo.telemetry.log(Verb.Printed, this.report!.reportName);
},
cellClasses(cIdx: number, rIdx: number): string[] {
const classes: string[] = [];
if (!this.report) {
return classes;
}
const col = this.report.columns[cIdx];
const isFirst = cIdx === 0;
if (col.align) {
classes.push(`text-${col.align}`);
}
if (rIdx === 0) {
classes.push('font-semibold');
}
classes.push('border-t');
if (!isFirst) {
classes.push('border-l');
}
return classes;
},
},
});
</script>
<style scoped>
.outer-container {
display: grid;
grid-template-columns: auto var(--w-quick-edit);
@apply h-full overflow-auto;
}
</style>
|
2302_79757062/books
|
src/pages/PrintView/ReportPrintView.vue
|
Vue
|
agpl-3.0
| 9,629
|
<template>
<div
class="
border-s
dark:border-gray-800
h-full
overflow-auto
w-quick-edit
bg-white
dark:bg-gray-850
"
>
<!-- Quick edit Tool bar -->
<div
class="
flex
items-center
justify-between
px-4
h-row-largest
sticky
top-0
bg-white
dark:bg-gray-850
"
style="z-index: 1"
>
<!-- Close Button -->
<Button :icon="true" @click="routeToPrevious">
<feather-icon name="x" class="w-4 h-4" />
</Button>
<!-- Save & Submit Buttons -->
<Button v-if="doc?.canSave" :icon="true" type="primary" @click="sync">
{{ t`Save` }}
</Button>
<Button
v-else-if="doc?.canSubmit"
:icon="true"
type="primary"
@click="submit"
>
{{ t`Submit` }}
</Button>
</div>
<!-- Name and image -->
<div
v-if="doc && (titleField || imageField)"
class="items-center border-b border-t dark:border-gray-800"
:class="imageField ? 'grid' : 'flex justify-center'"
:style="{
height: `calc(var(--h-row-mid) * ${!!imageField ? '2 + 1px' : '1'})`,
gridTemplateColumns: `minmax(0, 1.1fr) minmax(0, 2fr)`,
}"
>
<AttachImage
v-if="imageField"
class="ms-4"
:df="imageField"
:value="String(doc[imageField.fieldname] ?? '')"
:letter-placeholder="letterPlaceHolder"
@change="(value) => valueChange(imageField as Field, value)"
/>
<FormControl
v-if="titleField"
ref="titleControl"
:class="!!imageField ? 'me-4' : 'w-full mx-4'"
:input-class="[
'font-semibold text-xl',
!!imageField ? '' : 'text-center',
]"
size="small"
:df="titleField"
:value="doc[titleField.fieldname]"
:read-only="doc.inserted || doc.schema.naming !== 'manual'"
@change="(value) => valueChange(titleField as Field, value)"
/>
</div>
<!-- Rest of the form -->
<TwoColumnForm
v-if="doc"
ref="form"
class="w-full"
:doc="doc"
:fields="fields"
:column-ratio="[1.1, 2]"
/>
</div>
</template>
<script lang="ts">
import { DocValue } from 'fyo/core/types';
import { Field, Schema } from 'schemas/types';
import Button from 'src/components/Button.vue';
import AttachImage from 'src/components/Controls/AttachImage.vue';
import FormControl from 'src/components/Controls/FormControl.vue';
import TwoColumnForm from 'src/components/TwoColumnForm.vue';
import { fyo } from 'src/initFyo';
import { shortcutsKey } from 'src/utils/injectionKeys';
import { DocRef } from 'src/utils/types';
import {
commonDocSubmit,
commonDocSync,
focusOrSelectFormControl,
} from 'src/utils/ui';
import { useDocShortcuts } from 'src/utils/vueUtils';
import { computed, defineComponent, inject, ref } from 'vue';
export default defineComponent({
name: 'QuickEditForm',
components: {
Button,
FormControl,
TwoColumnForm,
AttachImage,
},
provide() {
return {
doc: computed(() => this.doc),
};
},
props: {
name: { type: String, required: true },
schemaName: { type: String, required: true },
hideFields: { type: Array, default: () => [] },
showFields: { type: Array, default: () => [] },
},
emits: ['close'],
setup() {
const doc = ref(null) as DocRef;
const shortcuts = inject(shortcutsKey);
let context = 'QuickEditForm';
if (shortcuts) {
context = useDocShortcuts(shortcuts, doc, context, true);
}
return {
form: ref<InstanceType<typeof TwoColumnForm> | null>(null),
doc,
context,
shortcuts,
};
},
data() {
return {
titleField: null,
imageField: null,
} as {
titleField: null | Field;
imageField: null | Field;
};
},
computed: {
letterPlaceHolder() {
if (!this.doc) {
return '';
}
const fn = this.titleField?.fieldname ?? 'name';
const value = this.doc.get(fn);
if (typeof value === 'string') {
return value[0];
}
return '';
},
schema(): Schema {
return fyo.schemaMap[this.schemaName]!;
},
fields() {
if (!this.schema) {
return [];
}
const fieldnames = (this.schema.quickEditFields ?? ['name']).filter(
(f) => !this.hideFields.includes(f)
);
if (this.showFields?.length) {
fieldnames.push(
...this.schema.fields
.map((f) => f.fieldname)
.filter((f) => this.showFields.includes(f))
);
}
return fieldnames.map((f) => fyo.getField(this.schemaName, f));
},
},
activated() {
this.setShortcuts();
},
// eslint-disable-next-line @typescript-eslint/no-misused-promises
async mounted() {
await this.initialize();
if (fyo.store.isDevelopment) {
// @ts-ignore
window.qef = this;
}
this.setShortcuts();
},
methods: {
setShortcuts() {
this.shortcuts?.set(this.context, ['Escape'], async () => {
await this.routeToPrevious();
});
},
async initialize() {
if (!this.schema) {
return;
}
this.setFields();
await this.setDoc();
if (!this.doc) {
return;
}
focusOrSelectFormControl(this.doc, this.$refs.titleControl, false);
},
setFields() {
const titleFieldName = this.schema.titleField ?? 'name';
this.titleField = fyo.getField(this.schemaName, titleFieldName) ?? null;
this.imageField = fyo.getField(this.schemaName, 'image') ?? null;
},
async setDoc() {
try {
this.doc = await fyo.doc.getDoc(this.schemaName, this.name);
} catch (e) {
return this.$router.back();
}
},
valueChange(field: Field, value: DocValue) {
this.form?.onChange(field, value);
},
async sync() {
if (!this.doc) {
return;
}
await commonDocSync(this.doc);
},
async submit() {
if (!this.doc) {
return;
}
await commonDocSubmit(this.doc);
},
async routeToPrevious() {
if (this.doc?.dirty && this.doc?.inserted) {
await this.doc.load();
}
if (this.doc && this.doc.notInserted) {
await this.doc.delete();
}
this.$router.back();
},
},
});
</script>
|
2302_79757062/books
|
src/pages/QuickEditForm.vue
|
Vue
|
agpl-3.0
| 6,458
|
<template>
<div class="flex flex-col w-full h-full">
<PageHeader :title="title">
<DropdownWithActions
v-for="group of groupedActions"
:key="group.label"
:icon="false"
:type="group.type"
:actions="group.actions"
class="text-xs"
>
{{ group.group }}
</DropdownWithActions>
<Button
ref="printButton"
:icon="true"
:title="t`Open Report Print View`"
@click="routeTo(`/report-print/${reportClassName}`)"
>
<feather-icon name="printer" class="w-4 h-4"></feather-icon>
</Button>
</PageHeader>
<!-- Filters -->
<div
v-if="report && report.filters.length"
class="grid grid-cols-5 gap-4 p-4 border-b dark:border-gray-800"
>
<FormControl
v-for="field in report.filters"
:key="field.fieldname + '-filter'"
:border="true"
size="small"
:class="[field.fieldtype === 'Check' ? 'self-end' : '']"
:show-label="true"
:df="field"
:value="report.get(field.fieldname)"
:read-only="loading"
@change="async (value) => await report?.set(field.fieldname, value)"
/>
</div>
<!-- Report Body -->
<ListReport v-if="report" :report="report" class="" />
</div>
</template>
<script lang="ts">
import { t } from 'fyo';
import { DocValue } from 'fyo/core/types';
import { reports } from 'reports';
import { Report } from 'reports/Report';
import Button from 'src/components/Button.vue';
import FormControl from 'src/components/Controls/FormControl.vue';
import DropdownWithActions from 'src/components/DropdownWithActions.vue';
import PageHeader from 'src/components/PageHeader.vue';
import ListReport from 'src/components/Report/ListReport.vue';
import { fyo } from 'src/initFyo';
import { shortcutsKey } from 'src/utils/injectionKeys';
import { docsPathMap, getReport } from 'src/utils/misc';
import { docsPathRef } from 'src/utils/refs';
import { ActionGroup } from 'src/utils/types';
import { routeTo } from 'src/utils/ui';
import { PropType, computed, defineComponent, inject } from 'vue';
export default defineComponent({
components: {
PageHeader,
FormControl,
ListReport,
DropdownWithActions,
Button,
},
provide() {
return {
report: computed(() => this.report),
};
},
props: {
reportClassName: {
type: String as PropType<keyof typeof reports>,
required: true,
},
defaultFilters: {
type: String,
default: '{}',
},
},
setup() {
return { shortcuts: inject(shortcutsKey) };
},
data() {
return {
loading: false,
report: null as null | Report,
};
},
computed: {
title() {
return reports[this.reportClassName]?.title ?? t`Report`;
},
groupedActions() {
const actions = this.report?.getActions() ?? [];
const actionsMap = actions.reduce((acc, ac) => {
if (!ac.group) {
ac.group = 'none';
}
acc[ac.group] ??= {
group: ac.group,
label: ac.label ?? '',
type: ac.type ?? 'secondary',
actions: [],
};
acc[ac.group].actions.push(ac);
return acc;
}, {} as Record<string, ActionGroup>);
return Object.values(actionsMap);
},
},
// eslint-disable-next-line @typescript-eslint/no-misused-promises
async activated() {
docsPathRef.value =
docsPathMap[this.reportClassName] ?? docsPathMap.Reports!;
await this.setReportData();
const filters = JSON.parse(this.defaultFilters) as Record<string, DocValue>;
const filterKeys = Object.keys(filters);
for (const key of filterKeys) {
await this.report?.set(key, filters[key]);
}
if (filterKeys.length) {
await this.report?.updateData();
}
if (fyo.store.isDevelopment) {
// @ts-ignore
window.rep = this;
}
this.shortcuts?.pmod.set(this.reportClassName, ['KeyP'], async () => {
await routeTo(`/report-print/${this.reportClassName}`);
});
},
deactivated() {
docsPathRef.value = '';
this.shortcuts?.delete(this.reportClassName);
},
methods: {
routeTo,
async setReportData() {
if (this.report === null) {
this.report = await getReport(this.reportClassName);
}
if (!this.report.reportData.length) {
await this.report.setReportData();
} else if (this.report.shouldRefresh) {
await this.report.setReportData(undefined, true);
}
},
},
});
</script>
|
2302_79757062/books
|
src/pages/Report.vue
|
Vue
|
agpl-3.0
| 4,553
|
<template>
<FormContainer>
<template #header>
<Button v-if="canSave" type="primary" @click="sync">
{{ t`Save` }}
</Button>
</template>
<template #body>
<FormHeader
:form-title="tabLabels[activeTab] ?? ''"
:form-sub-title="t`Settings`"
class="
sticky
top-0
bg-white
dark:bg-gray-890
border-b
dark:border-gray-800
"
>
</FormHeader>
<!-- Section Container -->
<div v-if="doc" class="overflow-auto custom-scroll custom-scroll-thumb1">
<CommonFormSection
v-for="([name, fields], idx) in activeGroup.entries()"
:key="name + idx"
ref="section"
class="p-4"
:class="
idx !== 0 && activeGroup.size > 1
? 'border-t dark:border-gray-800'
: ''
"
:show-title="activeGroup.size > 1 && name !== t`Default`"
:title="name"
:fields="fields"
:doc="doc"
:errors="errors"
@value-change="onValueChange"
/>
</div>
<!-- Tab Bar -->
<div
v-if="groupedFields && groupedFields.size > 1"
class="
mt-auto
px-4
pb-4
flex
gap-8
border-t
dark:border-gray-800
flex-shrink-0
sticky
bottom-0
bg-white
dark:bg-gray-890
"
>
<div
v-for="key of groupedFields.keys()"
:key="key"
class="text-sm cursor-pointer"
:class="
key === activeTab
? 'text-gray-900 dark:text-gray-25 font-semibold border-t-2 border-gray-800 dark:border-gray-100'
: 'text-gray-700 dark:text-gray-200 '
"
:style="{
paddingTop: key === activeTab ? 'calc(1rem - 2px)' : '1rem',
}"
@click="activeTab = key"
>
{{ tabLabels[key] }}
</div>
</div>
</template>
</FormContainer>
</template>
<script lang="ts">
import { DocValue } from 'fyo/core/types';
import { Doc } from 'fyo/model/doc';
import { ValidationError } from 'fyo/utils/errors';
import { ModelNameEnum } from 'models/types';
import { Field, Schema } from 'schemas/types';
import Button from 'src/components/Button.vue';
import FormContainer from 'src/components/FormContainer.vue';
import FormHeader from 'src/components/FormHeader.vue';
import { handleErrorWithDialog } from 'src/errorHandling';
import { getErrorMessage } from 'src/utils';
import { evaluateHidden } from 'src/utils/doc';
import { shortcutsKey } from 'src/utils/injectionKeys';
import { showDialog } from 'src/utils/interactive';
import { docsPathMap } from 'src/utils/misc';
import { docsPathRef } from 'src/utils/refs';
import { UIGroupedFields } from 'src/utils/types';
import { computed, defineComponent, inject } from 'vue';
import CommonFormSection from '../CommonForm/CommonFormSection.vue';
const COMPONENT_NAME = 'Settings';
export default defineComponent({
components: { FormContainer, Button, FormHeader, CommonFormSection },
provide() {
return { doc: computed(() => this.doc) };
},
setup() {
return {
shortcuts: inject(shortcutsKey),
};
},
data() {
return {
errors: {},
activeTab: ModelNameEnum.AccountingSettings,
groupedFields: null,
} as {
errors: Record<string, string>;
activeTab: string;
groupedFields: null | UIGroupedFields;
};
},
computed: {
canSave() {
return [
ModelNameEnum.AccountingSettings,
ModelNameEnum.InventorySettings,
ModelNameEnum.Defaults,
ModelNameEnum.POSSettings,
ModelNameEnum.PrintSettings,
ModelNameEnum.SystemSettings,
].some((s) => this.fyo.singles[s]?.canSave);
},
doc(): Doc | null {
const doc = this.fyo.singles[this.activeTab];
if (!doc) {
return null;
}
return doc;
},
tabLabels(): Record<string, string> {
return {
[ModelNameEnum.AccountingSettings]: this.t`General`,
[ModelNameEnum.PrintSettings]: this.t`Print`,
[ModelNameEnum.InventorySettings]: this.t`Inventory`,
[ModelNameEnum.Defaults]: this.t`Defaults`,
[ModelNameEnum.POSSettings]: this.t`POS Settings`,
[ModelNameEnum.SystemSettings]: this.t`System`,
};
},
schemas(): Schema[] {
const enableInventory =
!!this.fyo.singles.AccountingSettings?.enableInventory;
const enablePOS = !!this.fyo.singles.InventorySettings?.enablePointOfSale;
return [
ModelNameEnum.AccountingSettings,
ModelNameEnum.InventorySettings,
ModelNameEnum.Defaults,
ModelNameEnum.POSSettings,
ModelNameEnum.PrintSettings,
ModelNameEnum.SystemSettings,
]
.filter((s) => {
if (s === ModelNameEnum.InventorySettings && !enableInventory) {
return false;
}
if (s === ModelNameEnum.POSSettings && !enablePOS) {
return false;
}
return true;
})
.map((s) => this.fyo.schemaMap[s]!);
},
activeGroup(): Map<string, Field[]> {
if (!this.groupedFields) {
return new Map();
}
const group = this.groupedFields.get(this.activeTab);
if (!group) {
throw new ValidationError(
`Tab group ${this.activeTab} has no value set`
);
}
return group;
},
},
mounted() {
if (this.fyo.store.isDevelopment) {
// @ts-ignore
window.settings = this;
}
this.update();
},
activated(): void {
const tab = this.$route.query.tab;
if (typeof tab === 'string' && this.tabLabels[tab]) {
this.activeTab = tab;
}
docsPathRef.value = docsPathMap.Settings ?? '';
this.shortcuts?.pmod.set(COMPONENT_NAME, ['KeyS'], async () => {
if (!this.canSave) {
return;
}
await this.sync();
});
},
async deactivated(): Promise<void> {
docsPathRef.value = '';
this.shortcuts?.delete(COMPONENT_NAME);
if (!this.canSave) {
return;
}
await this.reset();
},
methods: {
async reset() {
const resetableDocs = this.schemas
.map(({ name }) => this.fyo.singles[name])
.filter((doc) => doc?.dirty) as Doc[];
for (const doc of resetableDocs) {
await doc.load();
}
this.update();
},
async sync(): Promise<void> {
const syncableDocs = this.schemas
.map(({ name }) => this.fyo.singles[name])
.filter((doc) => doc?.canSave) as Doc[];
for (const doc of syncableDocs) {
await this.syncDoc(doc);
}
this.update();
await showDialog({
title: this.t`Reload Frappe Books?`,
detail: this.t`Changes made to settings will be visible on reload.`,
type: 'info',
buttons: [
{
label: this.t`Yes`,
isPrimary: true,
action: ipc.reloadWindow.bind(ipc),
},
{
label: this.t`No`,
action: () => null,
isEscape: true,
},
],
});
},
async syncDoc(doc: Doc): Promise<void> {
try {
await doc.sync();
this.updateGroupedFields();
} catch (error) {
await handleErrorWithDialog(error, doc);
}
},
async onValueChange(field: Field, value: DocValue): Promise<void> {
const { fieldname } = field;
delete this.errors[fieldname];
try {
await this.doc?.set(fieldname, value);
} catch (err) {
if (!(err instanceof Error)) {
return;
}
this.errors[fieldname] = getErrorMessage(err, this.doc ?? undefined);
}
this.update();
},
update(): void {
this.updateGroupedFields();
},
updateGroupedFields(): void {
const grouped: UIGroupedFields = new Map();
const fields: Field[] = this.schemas.map((s) => s.fields).flat();
for (const field of fields) {
const schemaName = field.schemaName!;
if (!grouped.has(schemaName)) {
grouped.set(schemaName, new Map());
}
const tabbed = grouped.get(schemaName)!;
const section = field.section ?? this.t`Miscellaneous`;
if (!tabbed.has(section)) {
tabbed.set(section, []);
}
if (field.meta) {
continue;
}
const doc = this.fyo.singles[schemaName];
if (evaluateHidden(field, doc)) {
continue;
}
tabbed.get(section)!.push(field);
}
this.groupedFields = grouped;
},
},
});
</script>
|
2302_79757062/books
|
src/pages/Settings/Settings.vue
|
Vue
|
agpl-3.0
| 8,777
|
<template>
<FormContainer
:show-header="false"
class="justify-content items-center h-full"
:class="{ 'window-drag': platform !== 'Windows' }"
>
<template #body>
<FormHeader
:form-title="t`Set up your organization`"
class="
sticky
top-0
bg-white
dark:bg-gray-890
border-b
dark:border-gray-800
"
>
</FormHeader>
<!-- Section Container -->
<div
v-if="hasDoc"
class="overflow-auto custom-scroll custom-scroll-thumb1"
>
<CommonFormSection
v-for="([name, fields], idx) in activeGroup.entries()"
:key="name + idx"
ref="section"
class="p-4"
:class="
idx !== 0 && activeGroup.size > 1
? 'border-t dark:border-gray-800'
: ''
"
:show-title="activeGroup.size > 1 && name !== t`Default`"
:title="name"
:fields="fields"
:doc="doc"
:errors="errors"
:collapsible="false"
@value-change="onValueChange"
/>
</div>
<!-- Buttons Bar -->
<div
class="
mt-auto
p-4
flex
items-center
justify-between
border-t
dark:border-gray-800
flex-shrink-0
sticky
bottom-0
bg-white
dark:bg-gray-890
"
>
<p v-if="loading" class="text-base text-gray-600 dark:text-gray-400">
{{ t`Loading instance...` }}
</p>
<Button
v-if="!loading"
class="w-24 border dark:border-gray-800"
@click="cancel"
>{{ t`Cancel` }}</Button
>
<Button
v-if="fyo.store.isDevelopment && !loading"
class="w-24 ml-auto mr-4 border dark:border-gray-800"
:disabled="loading"
@click="fill"
>{{ t`Fill` }}</Button
>
<Button
type="primary"
class="w-24"
data-testid="submit-button"
:disabled="!areAllValuesFilled || loading"
@click="submit"
>{{ t`Submit` }}</Button
>
</div>
</template>
</FormContainer>
</template>
<script lang="ts">
import { DocValue } from 'fyo/core/types';
import { Doc } from 'fyo/model/doc';
import { Verb } from 'fyo/telemetry/types';
import { TranslationString } from 'fyo/utils/translation';
import { ModelNameEnum } from 'models/types';
import { Field } from 'schemas/types';
import Button from 'src/components/Button.vue';
import FormContainer from 'src/components/FormContainer.vue';
import FormHeader from 'src/components/FormHeader.vue';
import { getErrorMessage } from 'src/utils';
import { showDialog } from 'src/utils/interactive';
import { getSetupWizardDoc } from 'src/utils/misc';
import { getFieldsGroupedByTabAndSection } from 'src/utils/ui';
import { computed, defineComponent } from 'vue';
import CommonFormSection from '../CommonForm/CommonFormSection.vue';
export default defineComponent({
name: 'SetupWizard',
components: {
Button,
FormContainer,
FormHeader,
CommonFormSection,
},
provide() {
return {
doc: computed(() => this.docOrNull),
};
},
emits: ['setup-complete', 'setup-canceled'],
data() {
return {
docOrNull: null,
errors: {},
loading: false,
} as {
errors: Record<string, string>;
docOrNull: null | Doc;
loading: boolean;
};
},
computed: {
hasDoc(): boolean {
return this.docOrNull instanceof Doc;
},
doc(): Doc {
if (this.docOrNull instanceof Doc) {
return this.docOrNull;
}
throw new Error(`Doc is null`);
},
areAllValuesFilled(): boolean {
if (!this.hasDoc) {
return false;
}
const values = this.doc.schema.fields
.filter((f) => f.required)
.map((f) => this.doc[f.fieldname]);
return values.every(Boolean);
},
activeGroup(): Map<string, Field[]> {
if (!this.hasDoc) {
return new Map();
}
const groupedFields = getFieldsGroupedByTabAndSection(
this.doc.schema,
this.doc
);
return [...groupedFields.values()][0];
},
},
async mounted() {
const languageMap = TranslationString.prototype.languageMap;
this.docOrNull = getSetupWizardDoc(languageMap);
if (!this.fyo.db.isConnected) {
await this.fyo.db.init();
}
if (this.fyo.store.isDevelopment) {
// @ts-ignore
window.sw = this;
}
this.fyo.telemetry.log(Verb.Started, ModelNameEnum.SetupWizard);
},
methods: {
async fill() {
if (!this.hasDoc) {
return;
}
await this.doc.set('companyName', "Lin's Things");
await this.doc.set('email', 'lin@lthings.com');
await this.doc.set('fullname', 'Lin Slovenly');
await this.doc.set('bankName', 'Max Finance');
await this.doc.set('country', 'India');
},
async onValueChange(field: Field, value: DocValue) {
if (!this.hasDoc) {
return;
}
const { fieldname } = field;
delete this.errors[fieldname];
try {
await this.doc.set(fieldname, value);
} catch (err) {
if (!(err instanceof Error)) {
return;
}
this.errors[fieldname] = getErrorMessage(err, this.doc);
}
},
async submit() {
if (!this.hasDoc) {
return;
}
if (!this.areAllValuesFilled) {
return await showDialog({
title: this.t`Mandatory Error`,
detail: this.t`Please fill all values.`,
type: 'error',
});
}
this.loading = true;
this.fyo.telemetry.log(Verb.Completed, ModelNameEnum.SetupWizard);
this.$emit('setup-complete', this.doc.getValidDict());
},
cancel() {
this.fyo.telemetry.log(Verb.Cancelled, ModelNameEnum.SetupWizard);
this.$emit('setup-canceled');
},
},
});
</script>
|
2302_79757062/books
|
src/pages/SetupWizard/SetupWizard.vue
|
Vue
|
agpl-3.0
| 6,049
|
<template>
<ScaledContainer
ref="scaledContainer"
:scale="Math.max(scale, 0.1)"
:width="width"
:height="height"
class="mx-auto shadow-lg border"
>
<ErrorBoundary
v-if="!error"
:propagate="false"
@error-captured="handleErrorCaptured"
>
<!-- Template -->
<component
:is="templateComponent"
class="flex-1 bg-white"
:doc="values.doc"
:print="values.print"
/>
</ErrorBoundary>
<!-- Compilation Error -->
<div
v-else
class="
h-full
bg-red-100
dark:bg-red-900 dark:bg-opacity-50
w-full
text-2xl text-gray-900
dark:text-gray-25
flex flex-col
gap-4
"
>
<h1
class="
text-4xl
font-bold
text-red-500
dark:text-red-200
p-4
border-b border-red-200
dark:border-red-900
"
>
{{ error.name }}
</h1>
<p class="px-4 font-semibold">{{ error.message }}</p>
<pre
v-if="error.detail"
class="px-4 text-xl text-gray-700 dark:text-gray-400"
>{{ error.detail }}</pre
>
</div>
</ScaledContainer>
</template>
<script lang="ts">
import {
compile,
CompilerError,
generateCodeFrame,
SourceLocation,
} from '@vue/compiler-dom';
import { Verb } from 'fyo/telemetry/types';
import ErrorBoundary from 'src/components/ErrorBoundary.vue';
import { getPathAndMakePDF } from 'src/utils/printTemplates';
import { PrintValues } from 'src/utils/types';
import { defineComponent, PropType } from 'vue';
import ScaledContainer from './ScaledContainer.vue';
export const baseSafeTemplate = `<main class="h-full w-full bg-white">
<p class="p-4 text-red-500">
<span class="font-bold">ERROR</span>: Template failed to load due to errors.
</p>
</main>
`;
export default defineComponent({
components: { ScaledContainer, ErrorBoundary },
props: {
template: { type: String, required: true },
printSchemaName: { type: String, required: true },
scale: { type: Number, default: 0.65 },
width: { type: Number, default: 21 },
height: { type: Number, default: 29.7 },
values: {
type: Object as PropType<PrintValues>,
required: true,
},
},
data() {
return { error: null } as {
error: null | { name: string; message: string; detail?: string };
};
},
computed: {
templateComponent() {
let template = this.template;
if (this.error) {
template = baseSafeTemplate;
}
return {
template,
props: ['doc', 'print'],
computed: {
fyo() {
return {};
},
platform() {
return '';
},
},
// eslint-disable-next-line @typescript-eslint/ban-types
} as {};
},
},
watch: {
template(value: string) {
this.compile(value);
},
},
mounted() {
this.compile(this.template);
},
methods: {
compile(template: string) {
/**
* Note: This is a hacky method to prevent
* broken templates from reaching the `<component />`
* element.
*
* It's required because the CompilerOptions doesn't
* have an option to capture the errors.
*
* The compile function returns a code that can be
* converted into a render function.
*
* This render function can be used instead
* of passing the template to the `<component />` element
* where it gets compiled again.
*/
this.error = null;
return compile(template, {
hoistStatic: true,
onWarn: this.onError.bind(this),
onError: this.onError.bind(this),
});
},
handleErrorCaptured(error: unknown) {
if (!(error instanceof Error)) {
throw error;
}
const message = error.message;
let name = error.name;
let detail = '';
if (name === 'TypeError' && message.includes('Cannot read')) {
name = this.t`Invalid Key Error`;
detail = this.t`Please check Key Hints for valid key names`;
}
this.error = { name, message, detail };
},
onError({ message, loc }: CompilerError) {
const codeframe = loc ? this.getCodeFrame(loc) : '';
this.error = {
name: this.t`Template Compilation Error`,
detail: codeframe,
message,
};
},
getCodeFrame(loc: SourceLocation) {
return generateCodeFrame(this.template, loc.start.offset, loc.end.offset);
},
async savePDF(name?: string) {
/* eslint-disable */
/**
* To be called through ref by the parent component.
*/
// @ts-ignore
const innerHTML = this.$refs.scaledContainer.$el.children[0].innerHTML;
if (typeof innerHTML !== 'string') {
return;
}
await getPathAndMakePDF(
name ?? this.t`Entry`,
innerHTML,
this.width,
this.height
);
this.fyo.telemetry.log(Verb.Printed, this.printSchemaName);
},
},
});
</script>
|
2302_79757062/books
|
src/pages/TemplateBuilder/PrintContainer.vue
|
Vue
|
agpl-3.0
| 5,112
|
<template>
<div class="overflow-hidden" :style="outerContainerStyle">
<div
:style="innerContainerStyle"
:class="showOverflow ? 'overflow-auto no-scrollbar' : ''"
>
<slot></slot>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
/**
* This Component is required because * CSS transforms (eg
* scale) don't change the area taken by * an element.
*
* So to circumvent this, the outer element needs to have
* the scaled dimensions without applying a CSS transform.
*/
export default defineComponent({
props: {
height: { type: Number, default: 29.7 },
width: { type: Number, default: 21 },
scale: { type: Number, default: 0.65 },
showOverflow: { type: Boolean, default: false },
},
computed: {
innerContainerStyle(): Record<string, string> {
const style: Record<string, string> = {};
style['width'] = `${this.width}cm`;
style['height'] = `${this.height}cm`;
style['transform'] = `scale(${this.scale})`;
style['margin-top'] = `calc(-1 * (${this.height}cm * ${
1 - this.scale
}) / 2)`;
style['margin-left'] = `calc(-1 * (${this.width}cm * ${
1 - this.scale
}) / 2)`;
return style;
},
outerContainerStyle(): Record<string, string> {
const style: Record<string, string> = {};
style['height'] = `calc(${this.scale} * ${this.height}cm)`;
style['width'] = `calc(${this.scale} * ${this.width}cm)`;
return style;
},
},
});
</script>
|
2302_79757062/books
|
src/pages/TemplateBuilder/ScaledContainer.vue
|
Vue
|
agpl-3.0
| 1,531
|
<template>
<div class="w-form">
<FormHeader :form-title="t`Set Print Size`" />
<hr class="dark:border-gray-800" />
<div class="p-4 w-full flex flex-col gap-4">
<p class="text-base text-gray-900 dark:text-gray-100">
{{
t`Select a pre-defined page size, or set a custom page size for your Print Template.`
}}
</p>
<Select
:df="df"
:value="size"
:border="true"
:show-label="true"
@change="sizeChange"
/>
<div class="flex gap-4 w-full">
<Float
class="w-full"
:df="fyo.getField('PrintTemplate', 'height')"
:border="true"
:show-label="true"
:value="height"
@change="(v) => valueChange(v, 'height')"
/>
<Float
class="w-full"
:df="fyo.getField('PrintTemplate', 'width')"
:border="true"
:show-label="true"
:value="width"
@change="(v) => valueChange(v, 'width')"
/>
</div>
</div>
<div class="flex border-t dark:border-gray-800 p-4">
<Button class="ml-auto" type="primary" @click="done">{{
t`Done`
}}</Button>
</div>
</div>
</template>
<script lang="ts">
import { PrintTemplate } from 'models/baseModels/PrintTemplate';
import { OptionField } from 'schemas/types';
import Button from 'src/components/Button.vue';
import Float from 'src/components/Controls/Float.vue';
import Select from 'src/components/Controls/Select.vue';
import FormHeader from 'src/components/FormHeader.vue';
import { paperSizeMap, printSizes } from 'src/utils/ui';
import { defineComponent } from 'vue';
type SizeName = typeof printSizes[number];
export default defineComponent({
components: { Float, FormHeader, Select, Button },
props: { doc: { type: PrintTemplate, required: true } },
emits: ['done'],
data() {
return { size: 'A4', width: 21, height: 29.7 };
},
computed: {
df(): OptionField {
return {
label: 'Page Size',
fieldname: 'size',
fieldtype: 'Select',
options: printSizes.map((value) => ({ value, label: value })),
default: 'A4',
};
},
},
mounted() {
this.width = this.doc.width ?? 21;
this.height = this.doc.height ?? 29.7;
this.size = '';
Object.entries(paperSizeMap).forEach(([name, { width, height }]) => {
if (this.width === width && this.height === height) {
this.size = name;
}
});
this.size ||= 'Custom';
},
methods: {
sizeChange(v: string) {
const size = paperSizeMap[v as SizeName];
if (!size) {
return;
}
this.height = size.height;
this.width = size.width;
},
valueChange(v: number, name: 'width' | 'height') {
if (this[name] === v) {
return;
}
this.size = 'Custom';
this[name] = v;
},
async done() {
await this.doc.set('width', this.width);
await this.doc.set('height', this.height);
this.$emit('done');
},
},
});
</script>
|
2302_79757062/books
|
src/pages/TemplateBuilder/SetPrintSize.vue
|
Vue
|
agpl-3.0
| 3,061
|
<template>
<div class="w-form">
<FormHeader :form-title="t`Set Print Size`" />
<hr class="dark:border-gray-800" />
<div class="p-4 w-full flex flex-col gap-4">
<p class="text-base text-gray-900 dark:text-gray-100">
{{ t`Select the template type.` }}
</p>
<Select
:df="df"
:value="type"
:border="true"
:show-label="true"
@change="typeChange"
/>
</div>
<div class="flex border-t dark:border-gray-800 p-4">
<Button class="ml-auto" type="primary" @click="done">{{
t`Done`
}}</Button>
</div>
</div>
</template>
<script lang="ts">
import { PrintTemplate } from 'models/baseModels/PrintTemplate';
import { OptionField } from 'schemas/types';
import Button from 'src/components/Button.vue';
import Select from 'src/components/Controls/Select.vue';
import FormHeader from 'src/components/FormHeader.vue';
import { defineComponent } from 'vue';
export default defineComponent({
components: { FormHeader, Select, Button },
props: { doc: { type: PrintTemplate, required: true } },
emits: ['done'],
data() {
return { type: 'SalesInvoice' };
},
computed: {
df(): OptionField {
const options = PrintTemplate.lists.type(this.doc);
return {
...fyo.getField('PrintTemplate', 'type'),
options,
fieldtype: 'Select',
default: options[0].value,
} as OptionField;
},
},
mounted() {
this.type = this.doc.type ?? 'SalesInvoice';
},
methods: {
typeChange(v: string) {
if (this.type === v) {
return;
}
this.type = v;
},
async done() {
await this.doc.set('type', this.type);
this.$emit('done');
},
},
});
</script>
|
2302_79757062/books
|
src/pages/TemplateBuilder/SetType.vue
|
Vue
|
agpl-3.0
| 1,751
|
<template>
<div>
<PageHeader :title="doc && doc.inserted ? doc.name : ''">
<!-- Template Name -->
<template v-if="doc && !doc.inserted" #left>
<FormControl
ref="nameField"
class="w-60 flex-shrink-0"
size="small"
:input-class="['font-semibold text-xl']"
:df="fields.name"
:border="true"
:value="doc!.name"
@change="async (value) => await doc?.set('name', value)"
/>
</template>
<Button v-if="displayDoc && doc?.template" @click="savePDF">
{{ t`Save as PDF` }}
</Button>
<Button
v-if="doc && doc.isCustom && displayDoc"
:title="t`Toggle Edit Mode`"
:icon="true"
@click="toggleEditMode"
>
<feather-icon name="edit" class="w-4 h-4" />
</Button>
<DropdownWithActions v-if="actions.length" :actions="actions" />
<Button v-if="doc?.canSave" type="primary" @click="sync()">
{{ t`Save` }}
</Button>
</PageHeader>
<!-- Template Builder Body -->
<div
v-if="doc"
class="w-full bg-gray-50 dark:bg-gray-875 grid"
:style="templateBuilderBodyStyles"
>
<!-- Template Display Area -->
<div
class="overflow-auto no-scrollbar flex flex-col"
style="height: calc(100vh - var(--h-row-largest) - 1px)"
>
<!-- Template Container -->
<div
v-if="canDisplayPreview"
class="p-4 overflow-auto custom-scroll custom-scroll-thumb1"
>
<PrintContainer
ref="printContainer"
:print-schema-name="displayDoc!.schemaName"
:template="doc.template!"
:values="values!"
:scale="scale"
:height="doc.height"
:width="doc.width"
/>
</div>
<!-- Display Hints -->
<p
v-else-if="helperMessage"
class="text-sm text-gray-700 dark:text-gray-300 p-4"
>
{{ helperMessage }}
</p>
<!-- Bottom Bar -->
<div
class="
w-full
sticky
bottom-0
flex
bg-white
dark:bg-gray-890
border-t
dark:border-gray-800
mt-auto
flex-shrink-0
"
>
<!-- Entry Type -->
<FormControl
:title="fields.type.label"
class="w-40 border-r dark:border-gray-800 flex-shrink-0"
:df="fields.type"
:border="false"
:value="doc.get('type')"
:container-styles="{ 'border-radius': '0px' }"
@change="async (value) => await setType(value)"
/>
<!-- Display Doc -->
<Link
v-if="doc.type"
:title="displayDocField.label"
class="w-40 border-r dark:border-gray-800 flex-shrink-0"
:df="displayDocField"
:border="false"
:value="displayDoc?.name"
:container-styles="{ 'border-radius': '0px' }"
@change="(value: string) => setDisplayDoc(value)"
/>
<!-- Display Scale -->
<div
v-if="canDisplayPreview"
class="flex ml-auto gap-2 px-2 w-36 justify-between flex-shrink-0"
>
<p class="text-sm text-gray-600 dark:text-gray-400 my-auto">
{{ t`Display Scale` }}
</p>
<input
type="number"
class="
my-auto
w-10
text-base text-end
bg-transparent
text-gray-800
focus:text-gray-900
"
:value="scale"
min="0.1"
max="10"
step="0.1"
@change="setScale"
@input="setScale"
/>
</div>
</div>
</div>
<!-- Input Panel Resizer -->
<HorizontalResizer
:initial-x="panelWidth"
:min-x="22 * 16"
:max-x="maxWidth"
style="z-index: 5"
@resize="(x: number) => panelWidth = x"
/>
<!-- Template Panel -->
<div
class="
border-l
dark:border-gray-800
bg-white
dark:bg-gray-890
flex flex-col
"
style="height: calc(100vh - var(--h-row-largest) - 1px)"
>
<!-- Template Editor -->
<div class="min-h-0">
<TemplateEditor
v-if="typeof doc.template === 'string' && hints"
ref="templateEditor"
class="overflow-auto custom-scroll custom-scroll-thumb1 h-full"
:initial-value="doc.template"
:disabled="!doc.isCustom"
:hints="hints"
@input="() => (templateChanged = true)"
@blur="(value: string) => setTemplate(value)"
/>
</div>
<div
v-if="templateChanged"
class="
flex
gap-2
p-2
text-sm text-gray-600
dark:text-gray-400
items-center
mt-auto
border-t
dark:border-gray-800
"
>
<ShortcutKeys :keys="applyChangesShortcut" :simple="true" />
{{ t` to apply changes` }}
</div>
<!-- Value Key Hints Container -->
<div
v-if="hints"
class="border-t dark:border-gray-800 flex-shrink-0"
:class="templateChanged ? '' : 'mt-auto'"
>
<!-- Value Key Toggle -->
<div
class="
flex
justify-between
items-center
cursor-pointer
select-none
p-2
"
@click="toggleShowHints"
>
<h2
class="text-base text-gray-900 dark:text-gray-200 font-semibold"
>
{{ t`Key Hints` }}
</h2>
<feather-icon
:name="showHints ? 'chevron-up' : 'chevron-down'"
class="w-4 h-4 text-gray-600 dark:text-gray-400 resize-none"
/>
</div>
<!-- Value Key Hints -->
<Transition name="hints">
<div
v-if="showHints"
class="
overflow-auto
custom-scroll custom-scroll-thumb1
p-2
border-t
dark:border-gray-800
"
style="max-height: 30vh"
>
<TemplateBuilderHint :hints="hints" />
</div>
</Transition>
</div>
</div>
</div>
<Modal
v-if="doc"
:open-modal="showSizeModal"
@closemodal="showSizeModal = !showSizeModal"
>
<SetPrintSize :doc="doc" @done="showSizeModal = !showSizeModal" />
</Modal>
<Modal
v-if="doc"
:open-modal="showTypeModal"
@closemodal="showTypeModal = !showTypeModal"
>
<SetType :doc="doc" @done="showTypeModal = !showTypeModal" />
</Modal>
</div>
</template>
<script lang="ts">
import { EditorView } from 'codemirror';
import { Doc } from 'fyo/model/doc';
import { PrintTemplate } from 'models/baseModels/PrintTemplate';
import { ModelNameEnum } from 'models/types';
import { saveExportData } from 'reports/commonExporter';
import { Field, TargetField } from 'schemas/types';
import Button from 'src/components/Button.vue';
import FormControl from 'src/components/Controls/FormControl.vue';
import Link from 'src/components/Controls/Link.vue';
import DropdownWithActions from 'src/components/DropdownWithActions.vue';
import HorizontalResizer from 'src/components/HorizontalResizer.vue';
import Modal from 'src/components/Modal.vue';
import PageHeader from 'src/components/PageHeader.vue';
import ShortcutKeys from 'src/components/ShortcutKeys.vue';
import { handleErrorWithDialog } from 'src/errorHandling';
import { shortcutsKey } from 'src/utils/injectionKeys';
import { showDialog, showToast } from 'src/utils/interactive';
import { docsPathMap } from 'src/utils/misc';
import {
PrintTemplateHint,
baseTemplate,
getPrintTemplatePropHints,
getPrintTemplatePropValues,
} from 'src/utils/printTemplates';
import { docsPathRef, showSidebar } from 'src/utils/refs';
import { DocRef, PrintValues } from 'src/utils/types';
import {
ShortcutKey,
focusOrSelectFormControl,
getActionsForDoc,
getDocFromNameIfExistsElseNew,
getSavePath,
openSettings,
selectTextFile,
} from 'src/utils/ui';
import { useDocShortcuts } from 'src/utils/vueUtils';
import { getMapFromList } from 'utils/index';
import { computed, defineComponent, inject, ref } from 'vue';
import PrintContainer from './PrintContainer.vue';
import SetPrintSize from './SetPrintSize.vue';
import SetType from './SetType.vue';
import TemplateBuilderHint from './TemplateBuilderHint.vue';
import TemplateEditor from './TemplateEditor.vue';
export default defineComponent({
components: {
PageHeader,
Button,
DropdownWithActions,
PrintContainer,
HorizontalResizer,
TemplateEditor,
FormControl,
TemplateBuilderHint,
ShortcutKeys,
Link,
Modal,
SetPrintSize,
SetType,
},
provide() {
return { doc: computed(() => this.doc) };
},
props: { name: { type: String, required: true } },
setup() {
const doc = ref(null) as DocRef<PrintTemplate>;
const shortcuts = inject(shortcutsKey);
let context = 'TemplateBuilder';
if (shortcuts) {
context = useDocShortcuts(shortcuts, doc, context, false);
}
return {
doc,
context,
shortcuts,
};
},
data() {
return {
editMode: false,
showHints: false,
hints: undefined,
values: null,
displayDoc: null,
scale: 0.6,
panelWidth: 22 /** rem */ * 16 /** px */,
templateChanged: false,
showTypeModal: false,
showSizeModal: false,
preEditMode: {
scale: 0.6,
showSidebar: true,
panelWidth: 22 * 16,
},
} as {
editMode: boolean;
showHints: boolean;
hints?: PrintTemplateHint;
values: null | PrintValues;
displayDoc: PrintTemplate | null;
showTypeModal: boolean;
showSizeModal: boolean;
scale: number;
panelWidth: number;
templateChanged: boolean;
preEditMode: {
scale: number;
showSidebar: boolean;
panelWidth: number;
};
};
},
computed: {
canDisplayPreview(): boolean {
if (!this.displayDoc || !this.values) {
return false;
}
if (!this.doc?.template) {
return false;
}
return true;
},
applyChangesShortcut() {
return [ShortcutKey.ctrl, ShortcutKey.enter];
},
view(): EditorView | null {
// @ts-ignore
const { view } = this.$refs.templateEditor ?? {};
if (view instanceof EditorView) {
return view;
}
return null;
},
maxWidth() {
return window.innerWidth - 12 * 16 - 100;
},
actions() {
if (!this.doc) {
return [];
}
const actions = getActionsForDoc(this.doc as Doc);
actions.push({
label: this.t`Print Settings`,
group: this.t`View`,
action: async () => {
await openSettings(ModelNameEnum.PrintSettings);
},
});
if (this.doc.isCustom && !this.showTypeModal) {
actions.push({
label: this.t`Set Template Type`,
group: this.t`Action`,
action: () => (this.showTypeModal = true),
});
}
if (this.doc.isCustom && !this.showSizeModal) {
actions.push({
label: this.t`Set Print Size`,
group: this.t`Action`,
action: () => (this.showSizeModal = true),
});
}
if (this.doc.isCustom) {
actions.push({
label: this.t`Select Template File`,
group: this.t`Action`,
action: this.selectFile.bind(this),
});
}
actions.push({
label: this.t`Save Template File`,
group: this.t`Action`,
action: this.saveFile.bind(this),
});
return actions;
},
fields(): Record<string, Field> {
return getMapFromList(
this.fyo.schemaMap.PrintTemplate?.fields ?? [],
'fieldname'
);
},
displayDocField(): TargetField {
const target = this.doc?.type ?? ModelNameEnum.SalesInvoice;
return {
fieldname: 'displayDoc',
label: this.t`Display Doc`,
fieldtype: 'Link',
target,
};
},
helperMessage() {
if (!this.doc) {
return '';
}
if (!this.doc.type) {
return this.t`Select a Template type`;
}
if (!this.displayDoc) {
return this.t`Select a Display Doc to view the Template`;
}
if (!this.doc.template) {
return this.t`Set a Template value to see the Print Template`;
}
return '';
},
templateBuilderBodyStyles(): Record<string, string> {
const styles: Record<string, string> = {};
styles['grid-template-columns'] = `auto 0px ${this.panelWidth}px`;
styles['height'] = 'calc(100vh - var(--h-row-largest) - 1px)';
return styles;
},
},
async mounted() {
await this.initialize();
if (this.fyo.store.isDevelopment) {
// @ts-ignore
window.tb = this;
}
},
async activated(): Promise<void> {
await this.initialize();
docsPathRef.value = docsPathMap.PrintTemplate ?? '';
this.setShortcuts();
},
deactivated(): void {
docsPathRef.value = '';
if (this.editMode) {
this.disableEditMode();
}
if (this.doc?.dirty) {
return;
}
this.reset();
},
methods: {
setShortcuts() {
/**
* Node: Doc Save and Delete shortcuts are in the setup.
*/
if (!this.shortcuts) {
return;
}
this.shortcuts.ctrl.set(
this.context,
['Enter'],
this.setTemplate.bind(this)
);
this.shortcuts.ctrl.set(
this.context,
['KeyE'],
this.toggleEditMode.bind(this)
);
this.shortcuts.ctrl.set(
this.context,
['KeyH'],
this.toggleShowHints.bind(this)
);
this.shortcuts.ctrl.set(this.context, ['Equal'], () =>
this.setScale(this.scale + 0.1)
);
this.shortcuts.ctrl.set(this.context, ['Minus'], () =>
this.setScale(this.scale - 0.1)
);
},
async initialize() {
await this.setDoc();
if (this.doc?.type) {
this.hints = getPrintTemplatePropHints(this.doc.type, this.fyo);
}
focusOrSelectFormControl(this.doc as Doc, this.$refs.nameField, false);
if (!this.doc?.template) {
await this.doc?.set('template', baseTemplate);
}
await this.setDisplayInitialDoc();
},
reset() {
this.doc = null;
this.displayDoc = null;
},
getTemplateEditorState() {
const fallback = this.doc?.template ?? '';
if (!this.view) {
return fallback;
}
return this.view.state.doc.toString();
},
async setTemplate(value?: string) {
this.templateChanged = false;
if (!this.doc?.isCustom) {
return;
}
value ??= this.getTemplateEditorState();
await this.doc?.set('template', value);
},
setScale(e: Event | number) {
let value = this.scale;
if (typeof e === 'number') {
value = Number(e.toFixed(2));
} else if (e instanceof Event && e.target instanceof HTMLInputElement) {
value = Number(e.target.value);
}
this.scale = Math.max(Math.min(value, 10), 0.15);
},
toggleShowHints() {
this.showHints = !this.showHints;
},
toggleEditMode() {
if (!this.doc?.isCustom) {
return;
}
let message = this.t`Please set a Display Doc`;
if (!this.displayDoc) {
return showToast({ type: 'warning', message, duration: 'short' });
}
this.editMode = !this.editMode;
if (this.editMode) {
return this.enableEditMode();
}
this.disableEditMode();
},
enableEditMode() {
this.preEditMode.showSidebar = showSidebar.value;
this.preEditMode.panelWidth = this.panelWidth;
this.preEditMode.scale = this.scale;
this.panelWidth = Math.max(window.innerWidth / 2, this.panelWidth);
showSidebar.value = false;
this.scale = this.getEditModeScale();
this.view?.focus();
},
disableEditMode() {
showSidebar.value = this.preEditMode.showSidebar;
this.panelWidth = this.preEditMode.panelWidth;
this.scale = this.preEditMode.scale;
},
getEditModeScale(): number {
// @ts-ignore
const div = this.$refs.printContainer.$el as unknown;
if (!(div instanceof HTMLDivElement)) {
return this.scale;
}
const padding = 16 * 2 /** p-4 */ + 16 * 0.6; /** w-scrollbar */
const targetWidth = window.innerWidth / 2 - padding;
const currentWidth = div.getBoundingClientRect().width;
const targetScale = (targetWidth * this.scale) / currentWidth;
return Number(targetScale.toFixed(2));
},
savePDF() {
const printContainer = this.$refs.printContainer as {
savePDF: (name?: string) => void;
};
if (!printContainer?.savePDF) {
return;
}
printContainer.savePDF(this.displayDoc?.name);
},
async setDisplayInitialDoc() {
const schemaName = this.doc?.type;
if (!schemaName || this.displayDoc?.schemaName === schemaName) {
return;
}
const names = (await this.fyo.db.getAll(schemaName, {
limit: 1,
order: 'desc',
orderBy: 'created',
filters: { cancelled: false },
})) as { name: string }[];
const name = names[0]?.name;
if (!name) {
const label = this.fyo.schemaMap[schemaName]?.label ?? schemaName;
await showDialog({
title: this.t`No Display Entries Found`,
detail: this
.t`Please create a ${label} entry to view Template Preview.`,
type: 'warning',
});
return;
}
await this.setDisplayDoc(name);
},
async sync() {
const doc = this.doc;
if (!doc) {
return;
}
try {
await doc.sync();
} catch (error) {
await handleErrorWithDialog(error, doc as Doc);
}
},
async setDoc() {
if (this.doc) {
return;
}
this.doc = (await getDocFromNameIfExistsElseNew(
ModelNameEnum.PrintTemplate,
this.name
)) as PrintTemplate;
},
async setType(value: unknown) {
if (typeof value !== 'string') {
return;
}
await this.doc?.set('type', value);
await this.setDisplayInitialDoc();
},
async setDisplayDoc(value: string) {
if (!value) {
delete this.hints;
this.values = null;
this.displayDoc = null;
return;
}
const schemaName = this.doc?.type;
if (!schemaName) {
return;
}
const displayDoc = await getDocFromNameIfExistsElseNew(schemaName, value);
this.hints = getPrintTemplatePropHints(schemaName, this.fyo);
this.values = await getPrintTemplatePropValues(displayDoc);
this.displayDoc = displayDoc;
},
async selectFile() {
const { name: fileName, text } = await selectTextFile([
{ name: 'Template', extensions: ['template.html', 'html'] },
]);
if (!text) {
return;
}
await this.doc?.set('template', text);
this.view?.dispatch({
changes: { from: 0, to: this.view.state.doc.length, insert: text },
});
if (this.doc?.inserted) {
return;
}
let name: string | null = null;
if (fileName.endsWith('.template.html')) {
name = fileName.split('.template.html')[0];
}
if (!name && fileName.endsWith('.html')) {
name = fileName.split('.html')[0];
}
if (!name) {
return;
}
await this.doc?.set('name', name);
},
async saveFile() {
const name = this.doc?.name;
const template = this.getTemplateEditorState();
if (!name) {
return showToast({
type: 'warning',
message: this.t`Print Template Name not set`,
});
}
if (!template) {
return showToast({
type: 'warning',
message: this.t`Print Template is empty`,
});
}
const { canceled, filePath } = await getSavePath(name, 'template.html');
if (canceled || !filePath) {
return;
}
await saveExportData(template, filePath, this.t`Template file saved`);
},
},
});
</script>
<style scoped>
.hints-enter-from,
.hints-leave-to {
opacity: 0;
height: 0px;
}
.hints-enter-to,
.hints-leave-from {
opacity: 1;
height: 30vh;
}
.hints-enter-active,
.hints-leave-active {
transition: all 150ms ease-out;
}
</style>
|
2302_79757062/books
|
src/pages/TemplateBuilder/TemplateBuilder.vue
|
Vue
|
agpl-3.0
| 21,177
|
<template>
<div :class="level > 0 ? 'ms-2 ps-2 border-l dark:border-gray-800' : ''">
<template v-for="r of rows" :key="r.key">
<div
class="
flex
gap-2
text-sm text-gray-600
dark:text-gray-400
whitespace-nowrap
overflow-auto
no-scrollbar
"
:class="[typeof r.value === 'object' ? 'cursor-pointer' : '']"
@click="r.collapsed = !r.collapsed"
>
<div class="">{{ getKey(r) }}</div>
<div
v-if="!r.isCollapsible"
class="font-semibold text-gray-800 dark:text-gray-200"
>
{{ r.value }}
</div>
<div
v-else-if="Array.isArray(r.value)"
class="
text-blue-600
dark:text-blue-100
bg-blue-100
dark:bg-blue-600
border-white
dark:border-blue-600
border
tracking-tighter
rounded
text-xs
px-1
"
>
Array
</div>
<div
v-else
class="
text-pink-600
dark:text-pink-100
bg-pink-100
dark:bg-pink-600
border-white
dark:border-pink-600
border
tracking-tighter
rounded
text-xs
px-1
"
>
Object
</div>
<feather-icon
v-if="r.isCollapsible"
:name="r.collapsed ? 'chevron-up' : 'chevron-down'"
class="w-4 h-4 ms-auto"
/>
</div>
<div v-if="!r.collapsed && typeof r.value === 'object'">
<TemplateBuilderHint
:prefix="getKey(r)"
:hints="Array.isArray(r.value) ? r.value[0] : r.value"
:level="level + 1"
/>
</div>
</template>
</div>
</template>
<script lang="ts">
import { PrintTemplateHint } from 'src/utils/printTemplates';
import { PropType } from 'vue';
import { defineComponent } from 'vue';
type HintRow = {
key: string;
value: PrintTemplateHint[string];
isCollapsible: boolean;
collapsed: boolean;
};
export default defineComponent({
name: 'TemplateBuilderHint',
props: {
prefix: { type: String, default: '' },
hints: {
type: Object as PropType<PrintTemplateHint>,
required: true,
},
level: { type: Number, default: 0 },
},
data() {
return { rows: [] } as {
rows: HintRow[];
};
},
mounted() {
this.rows = Object.entries(this.hints)
.map(([key, value]) => ({
key,
value,
isCollapsible: typeof value === 'object',
collapsed: this.level > 0,
}))
.sort((a, b) => Number(a.isCollapsible) - Number(b.isCollapsible));
},
methods: {
getKey(row: HintRow) {
const isArray = Array.isArray(row.value);
if (isArray) {
return `${this.prefix}.${row.key}[number]`;
}
if (this.prefix.length) {
return `${this.prefix}.${row.key}`;
}
return row.key;
},
},
});
</script>
|
2302_79757062/books
|
src/pages/TemplateBuilder/TemplateBuilderHint.vue
|
Vue
|
agpl-3.0
| 3,092
|
<template>
<div
ref="container"
class="bg-white dark:bg-gray-875 text-gray-900 dark:text-gray-100"
></div>
</template>
<script lang="ts">
import { autocompletion, CompletionContext } from '@codemirror/autocomplete';
import { vue } from '@codemirror/lang-vue';
import {
HighlightStyle,
syntaxHighlighting,
syntaxTree,
} from '@codemirror/language';
import { Compartment, EditorState } from '@codemirror/state';
import { EditorView, ViewUpdate } from '@codemirror/view';
import { tags } from '@lezer/highlight';
import { basicSetup } from 'codemirror';
import { uicolors } from 'src/utils/colors';
import { defineComponent, markRaw } from 'vue';
export default defineComponent({
props: {
initialValue: { type: String, required: true },
disabled: { type: Boolean, default: false },
hints: { type: Object, default: undefined },
},
emits: ['input', 'blur'],
data() {
return { state: null, view: null, compartments: {} } as {
state: EditorState | null;
view: EditorView | null;
compartments: Record<string, Compartment>;
};
},
computed: {
container() {
const { container } = this.$refs;
if (container instanceof HTMLDivElement) {
return container;
}
throw new Error('ref container is not a div element');
},
},
watch: {
disabled(value: boolean) {
this.setDisabled(value);
},
},
mounted() {
if (!this.view) {
this.init();
}
if (this.fyo.store.isDevelopment) {
// @ts-ignore
window.te = this;
}
},
methods: {
init() {
const readOnly = new Compartment();
const editable = new Compartment();
const highlightStyle = HighlightStyle.define([
{ tag: tags.typeName, color: uicolors.pink[600] },
{ tag: tags.angleBracket, color: uicolors.pink[600] },
{ tag: tags.attributeName, color: uicolors.gray[500] },
{ tag: tags.attributeValue, color: uicolors.blue[500] },
{ tag: tags.comment, color: uicolors.gray[500], fontStyle: 'italic' },
{ tag: tags.keyword, color: uicolors.orange[600] },
{ tag: tags.variableName, color: uicolors.teal[600] },
{ tag: tags.string, color: uicolors.blue[700] },
]);
const completions = getCompletionsFromHints(this.hints ?? {});
const view = new EditorView({
doc: this.initialValue,
extensions: [
EditorView.updateListener.of(this.updateListener.bind(this)),
readOnly.of(EditorState.readOnly.of(this.disabled)),
editable.of(EditorView.editable.of(!this.disabled)),
basicSetup,
vue(),
syntaxHighlighting(highlightStyle),
autocompletion({ override: [completions] }),
],
parent: this.container,
});
this.view = markRaw(view);
const compartments = { readOnly, editable };
this.compartments = markRaw(compartments);
},
updateListener(update: ViewUpdate) {
if (update.docChanged) {
this.$emit('input', this.view?.state.doc.toString() ?? '');
}
if (update.focusChanged && !this.view?.hasFocus) {
this.$emit('blur', this.view?.state.doc.toString() ?? '');
}
},
setDisabled(value: boolean) {
const { readOnly, editable } = this.compartments;
this.view?.dispatch({
effects: [
readOnly.reconfigure(EditorState.readOnly.of(value)),
editable.reconfigure(EditorView.editable.of(!value)),
],
});
},
},
});
function getCompletionsFromHints(hints: Record<string, unknown>) {
const options = hintsToCompletionOptions(hints);
return function completions(context: CompletionContext) {
let word = context.matchBefore(/\w*/);
if (word == null) {
return null;
}
const node = syntaxTree(context.state).resolveInner(context.pos);
const aptLocation = ['ScriptAttributeValue', 'SingleExpression'];
if (!aptLocation.includes(node.name)) {
return null;
}
if (word.from === word.to && !context.explicit) {
return null;
}
return {
from: word.from,
options,
};
};
}
type CompletionOption = {
label: string;
type: string;
detail: string;
};
function hintsToCompletionOptions(
hints: object,
prefix?: string
): CompletionOption[] {
prefix ??= '';
const list: CompletionOption[] = [];
for (const [key, value] of Object.entries(hints)) {
const option = getCompletionOption(key, value, prefix);
if (option === null) {
continue;
}
if (Array.isArray(option)) {
list.push(...option);
continue;
}
list.push(option);
}
return list;
}
function getCompletionOption(
key: string,
value: unknown,
prefix: string
): null | CompletionOption | CompletionOption[] {
let label = key;
if (prefix.length) {
label = prefix + '.' + key;
}
if (Array.isArray(value)) {
return {
label,
type: 'variable',
detail: 'Child Table',
};
}
if (typeof value === 'string') {
return {
label,
type: 'variable',
detail: value,
};
}
if (typeof value === 'object' && value !== null) {
return hintsToCompletionOptions(value, label);
}
return null;
}
</script>
<style>
.cm-line {
font-weight: 600;
}
.cm-gutter {
@apply bg-gray-50 dark:bg-gray-850;
}
.cm-gutters {
border: none black !important;
border-right: 1px solid theme('colors.gray.200') !important;
}
.dark .cm-gutters {
border: none white !important;
border-right: 1px solid theme('colors.gray.800') !important;
}
.cm-activeLine,
.cm-activeLineGutter {
background-color: #72839216 !important;
}
.cm-tooltip-autocomplete {
background-color: white !important;
border: 1px solid theme('colors.gray.200') !important;
@apply rounded shadow-lg overflow-hidden text-gray-900;
}
.dark .cm-tooltip-autocomplete {
background-color: black !important;
border: 1px solid theme('colors.gray.800') !important;
@apply rounded shadow-lg overflow-hidden text-gray-100;
}
.cm-panels {
border-top: 1px solid theme('colors.gray.200') !important;
background-color: theme('colors.gray.50') !important;
color: theme('colors.gray.800') !important;
}
.cm-button {
background-image: none !important;
background-color: theme('colors.gray.200') !important;
color: theme('colors.gray.700') !important;
border: none !important;
}
.cm-textfield {
border: 1px solid theme('colors.gray.200') !important;
}
</style>
|
2302_79757062/books
|
src/pages/TemplateBuilder/TemplateEditor.vue
|
Vue
|
agpl-3.0
| 6,494
|
import { Fyo } from 'fyo';
export type TaxType = 'GST' | 'IGST' | 'Exempt-GST' | 'Exempt-IGST';
export async function createIndianRecords(fyo: Fyo) {
await createTaxes(fyo);
}
async function createTaxes(fyo: Fyo) {
const GSTs = {
GST: [28, 18, 12, 6, 5, 3, 0.25, 0],
IGST: [28, 18, 12, 6, 5, 3, 0.25, 0],
'Exempt-GST': [0],
'Exempt-IGST': [0],
};
for (const type of Object.keys(GSTs)) {
for (const percent of GSTs[type as TaxType]) {
const name = `${type}-${percent}`;
const details = getTaxDetails(type as TaxType, percent);
const newTax = fyo.doc.getNewDoc('Tax', { name, details });
await newTax.sync();
}
}
}
function getTaxDetails(type: TaxType, percent: number) {
if (type === 'GST') {
return [
{
account: 'CGST',
rate: percent / 2,
},
{
account: 'SGST',
rate: percent / 2,
},
];
}
return [
{
account: type.toString().split('-')[0],
rate: percent,
},
];
}
|
2302_79757062/books
|
src/regional/in/in.ts
|
TypeScript
|
agpl-3.0
| 1,019
|
import { Fyo } from 'fyo';
import { createIndianRecords } from './in/in';
export async function createRegionalRecords(country: string, fyo: Fyo) {
if (country === 'India') {
await createIndianRecords(fyo);
}
return;
}
|
2302_79757062/books
|
src/regional/index.ts
|
TypeScript
|
agpl-3.0
| 230
|
import { Directive } from 'vue';
type OutsideClickCallback = (e: Event) => void;
const instanceMap: Map<HTMLElement, OutsideClickCallback> = new Map();
export const outsideClickDirective: Directive<
HTMLElement,
OutsideClickCallback
> = {
beforeMount(el, binding) {
const clickHandler = function (e: Event) {
onDocumentClick(e, el, binding.value);
};
removeHandlerIfPresent(el);
instanceMap.set(el, clickHandler);
document.addEventListener('click', clickHandler);
},
unmounted(el) {
removeHandlerIfPresent(el);
},
};
function onDocumentClick(e: Event, el: HTMLElement, fn: OutsideClickCallback) {
const target = e.target as Node;
if (el !== target && !el.contains(target)) {
fn?.(e);
}
}
function removeHandlerIfPresent(el: HTMLElement) {
const clickHandler = instanceMap.get(el);
if (!clickHandler) {
return;
}
instanceMap.delete(el);
document.removeEventListener('click', clickHandler);
}
|
2302_79757062/books
|
src/renderer/helpers.ts
|
TypeScript
|
agpl-3.0
| 963
|
import { handleError } from 'src/errorHandling';
import { fyo } from 'src/initFyo';
export default function registerIpcRendererListeners() {
ipc.registerMainProcessErrorListener(
(_, error: unknown, more?: Record<string, unknown>) => {
if (!(error instanceof Error)) {
throw error;
}
if (!more) {
more = {};
}
if (typeof more !== 'object') {
more = { more };
}
more.isMainProcess = true;
more.notifyUser ??= true;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
handleError(true, error, more, !!more.notifyUser);
}
);
ipc.registerConsoleLogListener((_, ...stuff: unknown[]) => {
if (!fyo.store.isDevelopment) {
return;
}
if (fyo.store.isDevelopment) {
// eslint-disable-next-line no-console
console.log(...stuff);
}
});
document.addEventListener('visibilitychange', () => {
const { visibilityState } = document;
if (visibilityState === 'visible' && !fyo.telemetry.started) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
fyo.telemetry.start();
}
if (visibilityState !== 'hidden') {
return;
}
fyo.telemetry.stop();
});
}
|
2302_79757062/books
|
src/renderer/registerIpcRendererListeners.ts
|
TypeScript
|
agpl-3.0
| 1,252
|
import { CUSTOM_EVENTS } from 'utils/messages';
import { UnexpectedLogObject } from 'utils/types';
import { App as VueApp, createApp } from 'vue';
import App from './App.vue';
import Badge from './components/Badge.vue';
import FeatherIcon from './components/FeatherIcon.vue';
import { handleError, sendError } from './errorHandling';
import { fyo } from './initFyo';
import { outsideClickDirective } from './renderer/helpers';
import registerIpcRendererListeners from './renderer/registerIpcRendererListeners';
import router from './router';
import { stringifyCircular } from './utils';
import { setLanguageMap } from './utils/language';
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(async () => {
const language = fyo.config.get('language') as string;
if (language) {
await setLanguageMap(language);
}
fyo.store.language = language || 'English';
registerIpcRendererListeners();
const { isDevelopment, platform, version } = await ipc.getEnv();
fyo.store.isDevelopment = isDevelopment;
fyo.store.appVersion = version;
fyo.store.platform = platform;
const platformName = getPlatformName(platform);
setOnWindow(isDevelopment);
const app = createApp({
template: '<App/>',
});
app.config.unwrapInjectedRef = true;
setErrorHandlers(app);
app.use(router);
app.component('App', App);
app.component('FeatherIcon', FeatherIcon);
app.component('Badge', Badge);
app.directive('on-outside-click', outsideClickDirective);
app.mixin({
computed: {
fyo() {
return fyo;
},
platform() {
return platformName;
},
},
methods: {
t: fyo.t,
T: fyo.T,
},
});
await fyo.telemetry.logOpened();
app.mount('body');
})();
function setErrorHandlers(app: VueApp) {
window.onerror = (message, source, lineno, colno, error) => {
error = error ?? new Error('triggered in window.onerror');
// eslint-disable-next-line @typescript-eslint/no-floating-promises
handleError(true, error, { message, source, lineno, colno });
};
window.onunhandledrejection = (event: PromiseRejectionEvent) => {
let error: Error;
if (event.reason instanceof Error) {
error = event.reason;
} else {
error = new Error(String(event.reason));
}
// eslint-disable-next-line no-console
handleError(true, error).catch((err) => console.error(err));
};
window.addEventListener(CUSTOM_EVENTS.LOG_UNEXPECTED, (event) => {
const details = (event as CustomEvent)?.detail as UnexpectedLogObject;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
sendError(details);
});
app.config.errorHandler = (err, vm, info) => {
const more: Record<string, unknown> = {
info,
};
if (vm) {
const { fullPath, params } = vm.$route;
more.fullPath = fullPath;
more.params = stringifyCircular(params ?? {});
more.props = stringifyCircular(vm.$props ?? {}, true, true);
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
handleError(false, err as Error, more);
// eslint-disable-next-line no-console
console.error(err, vm, info);
};
}
function setOnWindow(isDevelopment: boolean) {
if (!isDevelopment) {
return;
}
// @ts-ignore
window.router = router;
// @ts-ignore
window.fyo = fyo;
}
function getPlatformName(platform: string) {
switch (platform) {
case 'win32':
return 'Windows';
case 'darwin':
return 'Mac';
case 'linux':
return 'Linux';
default:
return 'Linux';
}
}
|
2302_79757062/books
|
src/renderer.ts
|
TypeScript
|
agpl-3.0
| 3,576
|
import ChartOfAccounts from 'src/pages/ChartOfAccounts.vue';
import CommonForm from 'src/pages/CommonForm/CommonForm.vue';
import Dashboard from 'src/pages/Dashboard/Dashboard.vue';
import GetStarted from 'src/pages/GetStarted.vue';
import ImportWizard from 'src/pages/ImportWizard.vue';
import ListView from 'src/pages/ListView/ListView.vue';
import PrintView from 'src/pages/PrintView/PrintView.vue';
import ReportPrintView from 'src/pages/PrintView/ReportPrintView.vue';
import QuickEditForm from 'src/pages/QuickEditForm.vue';
import Report from 'src/pages/Report.vue';
import Settings from 'src/pages/Settings/Settings.vue';
import TemplateBuilder from 'src/pages/TemplateBuilder/TemplateBuilder.vue';
import CustomizeForm from 'src/pages/CustomizeForm/CustomizeForm.vue';
import POS from 'src/pages/POS/POS.vue';
import type { HistoryState } from 'vue-router';
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { historyState } from './utils/refs';
const routes: RouteRecordRaw[] = [
{
path: '/',
component: Dashboard,
},
{
path: '/get-started',
component: GetStarted,
},
{
path: `/edit/:schemaName/:name`,
name: `CommonForm`,
components: {
default: CommonForm,
edit: QuickEditForm,
},
props: {
default: (route) => ({
schemaName: route.params.schemaName,
name: route.params.name,
}),
edit: (route) => route.query,
},
},
{
path: '/list/:schemaName/:pageTitle?',
name: 'ListView',
components: {
default: ListView,
edit: QuickEditForm,
},
props: {
default: (route) => {
const { schemaName } = route.params;
const pageTitle = route.params.pageTitle ?? '';
const filters = {};
const filterString = route.query.filters;
if (typeof filterString === 'string') {
Object.assign(filters, JSON.parse(filterString));
}
return {
schemaName,
filters,
pageTitle,
};
},
edit: (route) => route.query,
},
},
{
path: '/print/:schemaName/:name',
name: 'PrintView',
component: PrintView,
props: true,
},
{
path: '/report-print/:reportName',
name: 'ReportPrintView',
component: ReportPrintView,
props: true,
},
{
path: '/report/:reportClassName',
name: 'Report',
component: Report,
props: true,
},
{
path: '/chart-of-accounts',
name: 'Chart Of Accounts',
components: {
default: ChartOfAccounts,
edit: QuickEditForm,
},
props: {
default: true,
edit: (route) => route.query,
},
},
{
path: '/import-wizard',
name: 'Import Wizard',
component: ImportWizard,
},
{
path: '/template-builder/:name',
name: 'Template Builder',
component: TemplateBuilder,
props: true,
},
{
path: '/customize-form',
name: 'Customize Form',
component: CustomizeForm,
},
{
path: '/settings',
name: 'Settings',
components: {
default: Settings,
edit: QuickEditForm,
},
props: {
default: true,
edit: (route) => route.query,
},
},
{
path: '/pos',
name: 'Point of Sale',
components: {
default: POS,
edit: QuickEditForm,
},
props: {
default: true,
edit: (route) => route.query,
},
},
];
const router = createRouter({ routes, history: createWebHistory() });
router.afterEach(({ fullPath }) => {
const state = history.state as HistoryState;
historyState.forward = !!state.forward;
historyState.back = !!state.back;
if (fullPath.includes('index.html')) {
return;
}
localStorage.setItem('lastRoute', fullPath);
});
export default router;
|
2302_79757062/books
|
src/router.ts
|
TypeScript
|
agpl-3.0
| 3,767
|
import { Fyo } from 'fyo';
import {
AccountRootType,
COAChildAccount,
COARootAccount,
COATree,
} from 'models/baseModels/Account/types';
import { getCOAList } from 'models/baseModels/SetupWizard/SetupWizard';
import { getStandardCOA } from './standardCOA';
const accountFields = ['accountType', 'accountNumber', 'rootType', 'isGroup'];
export class CreateCOA {
fyo: Fyo;
chartOfAccounts: string;
constructor(chartOfAccounts: string, fyo: Fyo) {
this.chartOfAccounts = chartOfAccounts;
this.fyo = fyo;
}
async run() {
const chart = await getCOA(this.chartOfAccounts);
await this.createCOAAccounts(chart, null, '', true);
}
async createCOAAccounts(
children: COATree | COARootAccount | COAChildAccount,
parentAccount: string | null,
rootType: AccountRootType | '',
rootAccount: boolean
) {
for (const rootName in children) {
if (accountFields.includes(rootName)) {
continue;
}
const child = children[rootName];
if (rootAccount) {
rootType = (child as COARootAccount).rootType;
}
const accountType = (child as COAChildAccount).accountType ?? '';
const accountNumber = (child as COAChildAccount).accountNumber;
const accountName = getAccountName(rootName, accountNumber);
const isGroup = identifyIsGroup(
child as COAChildAccount | COARootAccount
);
const doc = this.fyo.doc.getNewDoc('Account', {
name: accountName,
parentAccount,
isGroup,
rootType,
accountType,
});
await doc.sync();
await this.createCOAAccounts(
child as COAChildAccount,
accountName,
rootType,
false
);
}
}
}
function identifyIsGroup(child: COARootAccount | COAChildAccount): boolean {
if (child.isGroup !== undefined) {
return child.isGroup as boolean;
}
const keys = Object.keys(child);
const children = keys.filter((key) => !accountFields.includes(key));
if (children.length) {
return true;
}
return false;
}
async function getCOA(chartOfAccounts: string): Promise<COATree> {
const coaList = getCOAList();
const coa = coaList.find(({ name }) => name === chartOfAccounts);
const conCode = coa?.countryCode;
if (!conCode) {
return getStandardCOA();
}
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const countryCoa = (await import(`../../fixtures/verified/${conCode}.json`))
.default as { tree: COATree };
return countryCoa.tree;
} catch (e) {
return getStandardCOA();
}
}
function getAccountName(accountName: string, accountNumber?: string) {
if (accountNumber) {
return `${accountName} - ${accountNumber}`;
}
return accountName;
}
|
2302_79757062/books
|
src/setup/createCOA.ts
|
TypeScript
|
agpl-3.0
| 2,777
|
import { Fyo } from 'fyo';
import { DocValueMap } from 'fyo/core/types';
import { Doc } from 'fyo/model/doc';
import { createNumberSeries } from 'fyo/model/naming';
import {
DEFAULT_CURRENCY,
DEFAULT_LOCALE,
DEFAULT_SERIES_START,
} from 'fyo/utils/consts';
import {
AccountRootTypeEnum,
AccountTypeEnum,
} from 'models/baseModels/Account/types';
import { AccountingSettings } from 'models/baseModels/AccountingSettings/AccountingSettings';
import { numberSeriesDefaultsMap } from 'models/baseModels/Defaults/Defaults';
import { InventorySettings } from 'models/inventory/InventorySettings';
import { ValuationMethod } from 'models/inventory/types';
import { ModelNameEnum } from 'models/types';
import { createRegionalRecords } from 'src/regional';
import {
initializeInstance,
setCurrencySymbols,
} from 'src/utils/initialization';
import { getRandomString } from 'utils';
import { getDefaultLocations, getDefaultUOMs } from 'utils/defaults';
import { getCountryCodeFromCountry, getCountryInfo } from 'utils/misc';
import { CountryInfo } from 'utils/types';
import { CreateCOA } from './createCOA';
import { SetupWizardOptions } from './types';
export default async function setupInstance(
dbPath: string,
setupWizardOptions: SetupWizardOptions,
fyo: Fyo
) {
const { companyName, country, bankName, chartOfAccounts } =
setupWizardOptions;
fyo.store.skipTelemetryLogging = true;
await initializeDatabase(dbPath, country, fyo);
await updateSystemSettings(setupWizardOptions, fyo);
await updateAccountingSettings(setupWizardOptions, fyo);
await updatePrintSettings(setupWizardOptions, fyo);
await createCurrencyRecords(fyo);
await createAccountRecords(bankName, country, chartOfAccounts, fyo);
await createRegionalRecords(country, fyo);
await createDefaultEntries(fyo);
await createDefaultNumberSeries(fyo);
await updateInventorySettings(fyo);
if (fyo.isElectron) {
const { updatePrintTemplates } = await import('src/utils/printTemplates');
await updatePrintTemplates(fyo);
}
await completeSetup(companyName, fyo);
if (!Object.keys(fyo.currencySymbols).length) {
await setCurrencySymbols(fyo);
}
fyo.store.skipTelemetryLogging = false;
}
async function createDefaultEntries(fyo: Fyo) {
/**
* Create default UOM entries
*/
for (const uom of getDefaultUOMs(fyo)) {
await checkAndCreateDoc(ModelNameEnum.UOM, uom, fyo);
}
for (const loc of getDefaultLocations(fyo)) {
await checkAndCreateDoc(ModelNameEnum.Location, loc, fyo);
}
}
async function initializeDatabase(dbPath: string, country: string, fyo: Fyo) {
const countryCode = getCountryCodeFromCountry(country);
await initializeInstance(dbPath, true, countryCode, fyo);
}
async function updateAccountingSettings(
{
companyName,
country,
fullname,
email,
bankName,
fiscalYearStart,
fiscalYearEnd,
}: SetupWizardOptions,
fyo: Fyo
) {
const accountingSettings = (await fyo.doc.getDoc(
'AccountingSettings'
)) as AccountingSettings;
await accountingSettings.setAndSync({
companyName,
country,
fullname,
email,
bankName,
fiscalYearStart,
fiscalYearEnd,
});
return accountingSettings;
}
async function updatePrintSettings(
{ logo, companyName, email }: SetupWizardOptions,
fyo: Fyo
) {
const printSettings = await fyo.doc.getDoc('PrintSettings');
await printSettings.setAndSync({
logo,
companyName,
email,
displayLogo: logo ? true : false,
});
}
async function updateSystemSettings(
{ country, currency: companyCurrency }: SetupWizardOptions,
fyo: Fyo
) {
const countryInfo = getCountryInfo();
const countryOptions = countryInfo[country] as CountryInfo;
const currency =
companyCurrency ?? countryOptions.currency ?? DEFAULT_CURRENCY;
const locale = countryOptions.locale ?? DEFAULT_LOCALE;
const countryCode = getCountryCodeFromCountry(country);
const systemSettings = await fyo.doc.getDoc('SystemSettings');
const instanceId = getRandomString();
await systemSettings.setAndSync({
locale,
currency,
instanceId,
countryCode,
});
}
async function createCurrencyRecords(fyo: Fyo) {
const promises: Promise<Doc | undefined>[] = [];
const queue: string[] = [];
const countrySettings = Object.values(getCountryInfo()) as CountryInfo[];
for (const country of countrySettings) {
const {
currency,
currency_fraction,
currency_fraction_units,
smallest_currency_fraction_value,
currency_symbol,
} = country;
if (!currency || queue.includes(currency)) {
continue;
}
const docObject = {
name: currency,
fraction: currency_fraction ?? '',
fractionUnits: currency_fraction_units ?? 100,
smallestValue: smallest_currency_fraction_value ?? 0.01,
symbol: currency_symbol ?? '',
};
const doc = checkAndCreateDoc('Currency', docObject, fyo);
promises.push(doc);
queue.push(currency);
}
return Promise.all(promises);
}
async function createAccountRecords(
bankName: string,
country: string,
chartOfAccounts: string,
fyo: Fyo
) {
const createCOA = new CreateCOA(chartOfAccounts, fyo);
await createCOA.run();
const parentAccount = await getBankAccountParentName(country, fyo);
const bankAccountDoc = {
name: bankName,
rootType: AccountRootTypeEnum.Asset,
parentAccount,
accountType: 'Bank',
isGroup: false,
};
await checkAndCreateDoc('Account', bankAccountDoc, fyo);
await createDiscountAccount(fyo);
await setDefaultAccounts(fyo);
}
export async function createDiscountAccount(fyo: Fyo) {
const incomeAccountName = fyo.t`Indirect Income`;
const accountExists = await fyo.db.exists(
ModelNameEnum.Account,
incomeAccountName
);
if (!accountExists) {
return;
}
const discountAccountName = fyo.t`Discounts`;
const discountAccountDoc = {
name: discountAccountName,
rootType: AccountRootTypeEnum.Income,
parentAccount: incomeAccountName,
accountType: 'Income Account',
isGroup: false,
};
await checkAndCreateDoc(ModelNameEnum.Account, discountAccountDoc, fyo);
await fyo.singles.AccountingSettings!.setAndSync(
'discountAccount',
discountAccountName
);
}
async function setDefaultAccounts(fyo: Fyo) {
await setDefaultAccount('writeOffAccount', fyo.t`Write Off`, fyo);
const isSet = await setDefaultAccount(
'roundOffAccount',
fyo.t`Rounded Off`,
fyo
);
if (!isSet) {
await setDefaultAccount('roundOffAccount', fyo.t`Round Off`, fyo);
}
}
async function setDefaultAccount(key: string, accountName: string, fyo: Fyo) {
const accountExists = await fyo.db.exists(ModelNameEnum.Account, accountName);
if (!accountExists) {
return false;
}
await fyo.singles.AccountingSettings!.setAndSync(key, accountName);
return true;
}
async function completeSetup(companyName: string, fyo: Fyo) {
await fyo.singles.AccountingSettings!.setAndSync('setupComplete', true);
}
async function checkAndCreateDoc(
schemaName: string,
docObject: DocValueMap,
fyo: Fyo
): Promise<Doc | undefined> {
const canCreate = await checkIfExactRecordAbsent(schemaName, docObject, fyo);
if (!canCreate) {
return;
}
const doc = fyo.doc.getNewDoc(schemaName, docObject);
return doc.sync();
}
async function checkIfExactRecordAbsent(
schemaName: string,
docMap: DocValueMap,
fyo: Fyo
) {
const name = docMap.name as string;
const newDocObject = Object.assign({}, docMap);
const rows = await fyo.db.getAllRaw(schemaName, {
fields: ['*'],
filters: { name },
});
if (rows.length === 0) {
return true;
}
const storedDocObject = rows[0];
const matchList = Object.keys(newDocObject).map((key) => {
const newValue = newDocObject[key];
const storedValue = storedDocObject[key];
return newValue == storedValue; // Should not be type sensitive.
});
if (!matchList.every(Boolean)) {
await fyo.db.delete(schemaName, name);
return true;
}
return false;
}
async function getBankAccountParentName(country: string, fyo: Fyo) {
const parentBankAccount = await fyo.db.getAllRaw('Account', {
fields: ['*'],
filters: { isGroup: true, accountType: 'Bank' },
});
if (parentBankAccount.length === 0) {
// This should not happen if the fixtures are correct.
return 'Bank Accounts';
} else if (parentBankAccount.length > 1) {
switch (country) {
case 'Indonesia':
return 'Bank Rupiah - 1121.000';
default:
break;
}
}
return parentBankAccount[0].name;
}
async function createDefaultNumberSeries(fyo: Fyo) {
const numberSeriesFields = Object.values(fyo.schemaMap)
.map((f) => f?.fields)
.flat()
.filter((f) => f?.fieldname === 'numberSeries');
for (const field of numberSeriesFields) {
const defaultValue = field?.default as string | undefined;
const schemaName = field?.schemaName;
if (!defaultValue || !schemaName) {
continue;
}
await createNumberSeries(
defaultValue,
schemaName,
DEFAULT_SERIES_START,
fyo
);
const defaultKey = numberSeriesDefaultsMap[schemaName];
if (!defaultKey || fyo.singles.Defaults?.[defaultKey]) {
continue;
}
await fyo.singles.Defaults?.setAndSync(defaultKey as string, defaultValue);
}
}
async function updateInventorySettings(fyo: Fyo) {
const inventorySettings = (await fyo.doc.getDoc(
ModelNameEnum.InventorySettings
)) as InventorySettings;
if (!inventorySettings.valuationMethod) {
await inventorySettings.set('valuationMethod', ValuationMethod.FIFO);
}
const accountTypeDefaultMap = {
[AccountTypeEnum.Stock]: 'stockInHand',
[AccountTypeEnum['Stock Received But Not Billed']]:
'stockReceivedButNotBilled',
[AccountTypeEnum['Cost of Goods Sold']]: 'costOfGoodsSold',
} as Record<string, string>;
for (const accountType in accountTypeDefaultMap) {
const accounts = (await fyo.db.getAllRaw('Account', {
filters: { accountType, isGroup: false },
})) as { name: string }[];
if (!accounts.length) {
continue;
}
const settingName = accountTypeDefaultMap[accountType]!;
await inventorySettings.set(settingName, accounts[0].name);
}
const location = fyo.t`Stores`;
if (await fyo.db.exists(ModelNameEnum.Location, location)) {
await inventorySettings.set('defaultLocation', location);
}
await inventorySettings.sync();
}
|
2302_79757062/books
|
src/setup/setupInstance.ts
|
TypeScript
|
agpl-3.0
| 10,481
|
import { t } from 'fyo';
import { COATree } from 'models/baseModels/Account/types';
export function getStandardCOA(): COATree {
return {
[t`Application of Funds (Assets)`]: {
[t`Current Assets`]: {
[t`Accounts Receivable`]: {
[t`Debtors`]: {
accountType: 'Receivable',
},
},
[t`Bank Accounts`]: {
accountType: 'Bank',
isGroup: true,
},
[t`Cash In Hand`]: {
[t`Cash`]: {
accountType: 'Cash',
},
accountType: 'Cash',
},
[t`Loans and Advances (Assets)`]: {
isGroup: true,
},
[t`Securities and Deposits`]: {
[t`Earnest Money`]: {},
},
[t`Stock Assets`]: {
[t`Stock In Hand`]: {
accountType: 'Stock',
},
accountType: 'Stock',
},
[t`Tax Assets`]: {
isGroup: true,
},
},
[t`Fixed Assets`]: {
[t`Capital Equipments`]: {
accountType: 'Fixed Asset',
},
[t`Electronic Equipments`]: {
accountType: 'Fixed Asset',
},
[t`Furnitures and Fixtures`]: {
accountType: 'Fixed Asset',
},
[t`Office Equipments`]: {
accountType: 'Fixed Asset',
},
[t`Plants and Machineries`]: {
accountType: 'Fixed Asset',
},
[t`Buildings`]: {
accountType: 'Fixed Asset',
},
[t`Softwares`]: {
accountType: 'Fixed Asset',
},
[t`Accumulated Depreciation`]: {
accountType: 'Accumulated Depreciation',
},
},
[t`Investments`]: {
isGroup: true,
},
[t`Temporary Accounts`]: {
[t`Temporary Opening`]: {
accountType: 'Temporary',
},
},
rootType: 'Asset',
},
[t`Expenses`]: {
[t`Direct Expenses`]: {
[t`Stock Expenses`]: {
[t`Cost of Goods Sold`]: {
accountType: 'Cost of Goods Sold',
},
[t`Expenses Included In Valuation`]: {
accountType: 'Expenses Included In Valuation',
},
[t`Stock Adjustment`]: {
accountType: 'Stock Adjustment',
},
},
},
[t`Indirect Expenses`]: {
[t`Administrative Expenses`]: {},
[t`Commission on Sales`]: {},
[t`Depreciation`]: {
accountType: 'Depreciation',
},
[t`Entertainment Expenses`]: {},
[t`Freight and Forwarding Charges`]: {
accountType: 'Chargeable',
},
[t`Legal Expenses`]: {},
[t`Marketing Expenses`]: {
accountType: 'Chargeable',
},
[t`Miscellaneous Expenses`]: {
accountType: 'Chargeable',
},
[t`Office Maintenance Expenses`]: {},
[t`Office Rent`]: {},
[t`Postal Expenses`]: {},
[t`Print and Stationery`]: {},
[t`Round Off`]: {
accountType: 'Round Off',
},
[t`Salary`]: {},
[t`Sales Expenses`]: {},
[t`Telephone Expenses`]: {},
[t`Travel Expenses`]: {},
[t`Utility Expenses`]: {},
[t`Write Off`]: {},
[t`Exchange Gain/Loss`]: {},
[t`Gain/Loss on Asset Disposal`]: {},
},
rootType: 'Expense',
},
[t`Income`]: {
[t`Direct Income`]: {
[t`Sales`]: {},
[t`Service`]: {},
},
[t`Indirect Income`]: {
isGroup: true,
},
rootType: 'Income',
},
[t`Source of Funds (Liabilities)`]: {
[t`Current Liabilities`]: {
[t`Accounts Payable`]: {
[t`Creditors`]: {
accountType: 'Payable',
},
[t`Payroll Payable`]: {},
},
[t`Stock Liabilities`]: {
[t`Stock Received But Not Billed`]: {
accountType: 'Stock Received But Not Billed',
},
},
[t`Duties and Taxes`]: {
accountType: 'Tax',
isGroup: true,
},
[t`Loans (Liabilities)`]: {
[t`Secured Loans`]: {},
[t`Unsecured Loans`]: {},
[t`Bank Overdraft Account`]: {},
},
},
rootType: 'Liability',
},
[t`Equity`]: {
[t`Capital Stock`]: {
accountType: 'Equity',
},
[t`Dividends Paid`]: {
accountType: 'Equity',
},
[t`Opening Balance Equity`]: {
accountType: 'Equity',
},
[t`Retained Earnings`]: {
accountType: 'Equity',
},
rootType: 'Equity',
},
};
}
|
2302_79757062/books
|
src/setup/standardCOA.ts
|
TypeScript
|
agpl-3.0
| 4,624
|
export interface SetupWizardOptions {
logo: string | null;
companyName: string;
country: string;
fullname: string;
email: string;
bankName: string;
currency: string;
fiscalYearStart: string;
fiscalYearEnd: string;
chartOfAccounts: string;
}
|
2302_79757062/books
|
src/setup/types.ts
|
TypeScript
|
agpl-3.0
| 261
|
@font-face {
font-family: 'Inter';
font-weight: 100 900;
font-display: swap;
font-style: oblique 0deg 10deg;
src: url('../assets/fonts/Inter.var.woff2') format('woff2');
}
* {
outline-color: theme('colors.pink.400');
font-variation-settings: 'slnt' 0deg;
}
.italic {
font-variation-settings: 'slnt' 10deg;
}
@tailwind base;
@tailwind components;
@tailwind utilities;
html {
color: theme('colors.black');
}
html.dark {
color: theme('colors.white');
background-color: theme('colors.gray.900');
}
input[type='number']::-webkit-inner-spin-button {
appearance: none;
}
input[type='date']::-webkit-calendar-picker-indicator {
background-color: theme('colors.gray.900');
}
.window-drag {
-webkit-app-region: drag;
}
.window-no-drag {
-webkit-app-region: no-drag;
}
.grid {
display: grid;
}
.inline-grid {
display: inline-grid;
}
.flex-center {
display: flex;
align-items: center;
justify-content: center;
}
.frappe-chart .chart-legend {
display: none;
}
.no-scrollbar::-webkit-scrollbar {
display: none;
}
:root {
--w-form: 600px;
--w-app: 1200px;
--w-sidebar: 12rem;
--w-desk: calc(100vw - var(--w-sidebar));
--w-desk-fixed: calc(var(--w-app) - var(--w-sidebar));
--w-quick-edit: 22rem;
--w-scrollbar: 0.6rem;
--w-trafficlights: 72px;
/* Row Heights */
--h-row-smallest: 2rem;
--h-row-small: 2.5rem;
--h-row-mid: 3rem;
--h-row-large: 3.5rem;
--h-row-largest: 4rem;
--h-app: 800px;
}
.backdrop {
position: fixed;
top: 0px;
left: 0px;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.1);
backdrop-filter: blur(2px);
}
.w-form {
width: var(--w-form);
}
.w-dialog {
width: 24rem;
}
.w-toast {
width: 24rem;
}
.w-quick-edit {
width: var(--w-quick-edit);
flex-shrink: 0;
}
.h-form {
height: 800px;
}
.h-row-smallest {
height: var(--h-row-smallest);
}
.h-row-small {
height: var(--h-row-small);
}
.h-row-mid {
height: var(--h-row-mid);
}
.h-row-large {
height: var(--h-row-large);
}
.h-row-largest {
height: var(--h-row-largest);
}
.w-sidebar {
width: var(--w-sidebar);
}
.w-desk {
width: var(--w-desk);
}
.show-mandatory::after {
content: '*';
display: inline-block;
width: 0px;
height: 0px;
margin-left: -0.875rem;
vertical-align: -3px;
@apply text-red-500;
}
.custom-scroll::-webkit-scrollbar {
width: var(--w-scrollbar);
height: var(--w-scrollbar);
}
.custom-scroll::-webkit-scrollbar-track:vertical {
border-left: solid 1px theme('colors.gray.100');
}
.custom-scroll::-webkit-scrollbar-track:horizontal {
border-top: solid 1px theme('colors.gray.100');
}
.custom-scroll::-webkit-scrollbar-thumb {
background: theme('colors.gray.100');
}
.custom-scroll::-webkit-scrollbar-thumb:hover {
background: theme('colors.gray.200');
}
.custom-scroll::-webkit-scrollbar-corner {
background: transparent;
}
.dark.custom-scroll::-webkit-scrollbar-track:vertical,
.dark .custom-scroll::-webkit-scrollbar-track:vertical {
border-left-color: theme('colors.gray.800');
}
.dark.custom-scroll::-webkit-scrollbar-track:horizontal,
.dark .custom-scroll::-webkit-scrollbar-track:horizontal {
border-top-color: theme('colors.gray.800');
}
.dark.custom-scroll-thumb1::-webkit-scrollbar-thumb,
.dark .custom-scroll-thumb1::-webkit-scrollbar-thumb {
background: theme('colors.gray.850');
}
.dark.custom-scroll-thumb1::-webkit-scrollbar-thumb:hover,
.dark .custom-scroll-thumb1::-webkit-scrollbar-thumb:hover {
background: theme('colors.gray.800');
}
.dark.custom-scroll-thumb2::-webkit-scrollbar-thumb,
.dark .custom-scroll-thumb2::-webkit-scrollbar-thumb {
background: theme('colors.gray.800');
}
.dark.custom-scroll-thumb2::-webkit-scrollbar-thumb:hover,
.dark .custom-scroll-thumb2::-webkit-scrollbar-thumb:hover {
background: theme('colors.gray.875');
}
/*
Transitions
*/
.quickedit-enter-from,
.quickedit-leave-to {
transform: translateX(var(--w-quick-edit));
width: 0px;
opacity: 0;
}
.quickedit-enter-to,
.quickedit-leave-from {
transform: translateX(0px);
width: var(--w-quick-edit);
opacity: 1;
}
.quickedit-enter-active,
.quickedit-leave-active {
transition: all 150ms ease-out;
}
/*
RTL
*/
[dir='rtl'] .rtl-rotate-180 {
transform: rotate(180deg);
}
[dir='rtl'] .custom-scroll::-webkit-scrollbar-track:vertical {
border-right: solid 1px theme('colors.gray.200');
}
[dir='rtl'].dark.custom-scroll::-webkit-scrollbar-track:vertical,
[dir='rtl'].dark .custom-scroll::-webkit-scrollbar-track:vertical {
border-right: solid 1px theme('colors.gray.850');
}
.pill {
@apply py-0.5 px-1.5 rounded-md text-xs;
width: fit-content;
height: fit-content;
}
|
2302_79757062/books
|
src/styles/index.css
|
CSS
|
agpl-3.0
| 4,668
|
import { DateTime } from 'luxon';
export function prefixFormat(value: number): string {
/*
1,000000,000,000,000,000 = 1 P (Pentillion)
1000,000,000,000,000 = 1 Q (Quadrillion)
1000,000,000,000 = 1 T (Trillion)
1000,000,000 = 1 B (Billion)
1000,000 = 1 M (Million)
1000 = 1 K (Thousand)
1 = 1
*/
if (Math.abs(value) < 1) {
return Math.round(value).toString();
}
const ten = Math.floor(Math.log10(Math.abs(value)));
const three = Math.floor(ten / 3);
const num = Math.round(value / Math.pow(10, three * 3));
const suffix = ['', 'K', 'M', 'B', 'T', 'Q', 'P'][three];
return `${num} ${suffix}`;
}
export function euclideanDistance(
x1: number,
y1: number,
x2: number,
y2: number
): number {
const dsq = Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2);
return Math.sqrt(dsq);
}
function getRoundingConst(val: number): number {
const pow = Math.max(Math.log10(Math.abs(val)) - 1, 0);
return 10 ** Math.floor(pow);
}
function getVal(minOrMaxVal: number): number {
const rc = getRoundingConst(minOrMaxVal);
const sign = minOrMaxVal >= 0 ? 1 : -1;
if (sign === 1) {
return Math.ceil(minOrMaxVal / rc) * rc;
}
return Math.floor(minOrMaxVal / rc) * rc;
}
export function getYMax(points: number[][]): number {
const maxVal = Math.max(...points.flat());
if (maxVal === 0) {
return 0;
}
return getVal(maxVal);
}
export function getYMin(points: number[][]): number {
const minVal = Math.min(...points.flat());
if (minVal === 0) {
return minVal;
}
return getVal(minVal);
}
export function formatXLabels(label: string) {
return DateTime.fromISO(label).toFormat('MMM yy');
}
|
2302_79757062/books
|
src/utils/chart.ts
|
TypeScript
|
agpl-3.0
| 1,738
|
import colors from '../../colors.json';
export const uicolors = colors;
export const indicators = {
GRAY: 'grey',
GREY: 'grey',
BLUE: 'blue',
RED: 'red',
GREEN: 'green',
ORANGE: 'orange',
PURPLE: 'purple',
YELLOW: 'yellow',
BLACK: 'black',
};
const getValidColor = (color: string) => {
const isValid = [
'gray',
'orange',
'green',
'red',
'yellow',
'blue',
'indigo',
'pink',
'purple',
'teal',
].includes(color);
return isValid ? color : 'gray';
};
export function getBgColorClass(color: string) {
const vcolor = getValidColor(color);
return `bg-${vcolor}-200 dark:bg-${vcolor}-700`;
}
export function getColorClass(
color: string,
type: 'bg' | 'text' | 'border',
value = 300,
darkvalue = 600
) {
return `${type}-${getValidColor(color)}-${value} dark:${type}-${getValidColor(
color
)}-${darkvalue}`;
}
export function getTextColorClass(color: string) {
return `text-${getValidColor(color)}-700 dark:text-${getValidColor(
color
)}-200`;
}
export function getBgTextColorClass(color: string) {
const bg = getBgColorClass(color);
const text = getTextColorClass(color);
return [bg, text].join(' ');
}
|
2302_79757062/books
|
src/utils/colors.ts
|
TypeScript
|
agpl-3.0
| 1,198
|
import { Fyo, t } from 'fyo';
type Conn = {
countryCode: string;
error?: Error;
actionSymbol?: typeof dbErrorActionSymbols[keyof typeof dbErrorActionSymbols];
};
export const dbErrorActionSymbols = {
SelectFile: Symbol('select-file'),
CancelSelection: Symbol('cancel-selection'),
} as const;
const dbErrors = {
DirectoryDoesNotExist: 'directory does not exist',
UnableToAcquireConnection: 'Unable to acquire a connection',
} as const;
export async function connectToDatabase(
fyo: Fyo,
dbPath: string,
countryCode?: string
): Promise<Conn> {
try {
return { countryCode: await fyo.db.connectToDatabase(dbPath, countryCode) };
} catch (error) {
if (!(error instanceof Error)) {
throw error;
}
return {
countryCode: '',
error,
actionSymbol: await handleDatabaseConnectionError(error, dbPath),
};
}
}
export async function handleDatabaseConnectionError(
error: Error,
dbPath: string
) {
const message = error.message;
if (typeof message !== 'string') {
throw error;
}
if (message.includes(dbErrors.DirectoryDoesNotExist)) {
return await handleDirectoryDoesNotExist(dbPath);
}
if (message.includes(dbErrors.UnableToAcquireConnection)) {
return await handleUnableToAcquireConnection(dbPath);
}
throw error;
}
async function handleUnableToAcquireConnection(dbPath: string) {
return await showDbErrorDialog(
t`Could not connect to database file ${dbPath}, please select the file manually`
);
}
async function handleDirectoryDoesNotExist(dbPath: string) {
return await showDbErrorDialog(
t`Directory for database file ${dbPath} does not exist, please select the file manually`
);
}
async function showDbErrorDialog(detail: string) {
const { showDialog } = await import('src/utils/interactive');
return showDialog({
type: 'error',
title: t`Cannot Open File`,
detail,
buttons: [
{
label: t`Select File`,
action() {
return dbErrorActionSymbols.SelectFile;
},
isPrimary: true,
},
{
label: t`Cancel`,
action() {
return dbErrorActionSymbols.CancelSelection;
},
isEscape: true,
},
],
});
}
|
2302_79757062/books
|
src/utils/db.ts
|
TypeScript
|
agpl-3.0
| 2,238
|
import { Doc } from 'fyo/model/doc';
import { DynamicLinkField, Field, TargetField } from 'schemas/types';
import { GetAllOptions } from 'utils/db/types';
export function evaluateReadOnly(field: Field, doc?: Doc) {
if (doc?.inserted && field.fieldname === 'numberSeries') {
return true;
}
if (
field.fieldname === 'name' &&
(doc?.inserted || doc?.schema.naming !== 'manual')
) {
return true;
}
if (doc?.isSubmitted || doc?.parentdoc?.isSubmitted) {
return true;
}
if (doc?.isCancelled || doc?.parentdoc?.isCancelled) {
return true;
}
return evaluateFieldMeta(field, doc, 'readOnly');
}
export function evaluateHidden(field: Field, doc?: Doc) {
return evaluateFieldMeta(field, doc, 'hidden');
}
export function evaluateRequired(field: Field, doc?: Doc) {
return evaluateFieldMeta(field, doc, 'required');
}
function evaluateFieldMeta(
field: Field,
doc?: Doc,
meta?: 'required' | 'hidden' | 'readOnly',
defaultValue = false
) {
if (meta === undefined) {
return defaultValue;
}
const value = field[meta];
if (value !== undefined) {
return value;
}
const evalFunction = doc?.[meta]?.[field.fieldname];
if (evalFunction !== undefined) {
return evalFunction();
}
return defaultValue;
}
export async function getLinkedEntries(
doc: Doc
): Promise<Record<string, string[]>> {
// TODO: Normalize this function.
const fyo = doc.fyo;
const target = doc.schemaName;
const linkingFields = Object.values(fyo.schemaMap)
.filter((sch) => !sch?.isSingle)
.map((sch) => sch?.fields)
.flat()
.filter(
(f) => f?.fieldtype === 'Link' && f.target === target
) as TargetField[];
const dynamicLinkingFields = Object.values(fyo.schemaMap)
.filter((sch) => !sch?.isSingle)
.map((sch) => sch?.fields)
.flat()
.filter((f) => f?.fieldtype === 'DynamicLink') as DynamicLinkField[];
type Detail = { name: string; created: string };
type ChildEntryDetail = {
name: string;
parent: string;
parentSchemaName: string;
};
const entries: Record<string, Detail[]> = {};
const childEntries: Record<string, ChildEntryDetail[]> = {};
for (const field of [linkingFields, dynamicLinkingFields].flat()) {
if (!field.schemaName) {
continue;
}
const options: GetAllOptions = {
filters: { [field.fieldname]: doc.name! },
fields: ['name'],
};
if (field.fieldtype === 'DynamicLink') {
options.filters![field.references] = doc.schemaName!;
}
const schema = fyo.schemaMap[field.schemaName];
if (schema?.isChild) {
options.fields!.push('parent', 'parentSchemaName');
} else {
options.fields?.push('created');
}
if (schema?.isSubmittable) {
options.filters!.cancelled = false;
}
const details = (await fyo.db.getAllRaw(field.schemaName, options)) as
| Detail[]
| ChildEntryDetail[];
if (!details.length) {
continue;
}
for (const d of details) {
if ('parent' in d) {
childEntries[field.schemaName] ??= [];
childEntries[field.schemaName]!.push(d);
} else {
entries[field.schemaName] ??= [];
entries[field.schemaName].push(d);
}
}
}
const parents = Object.values(childEntries)
.flat()
.map((c) => `${c.parentSchemaName}.${c.parent}`);
const parentsSet = new Set(parents);
for (const p of parentsSet) {
const i = p.indexOf('.');
const schemaName = p.slice(0, i);
const name = p.slice(i + 1);
const details = (await fyo.db.getAllRaw(schemaName, {
filters: { name },
fields: ['name', 'created'],
})) as Detail[];
entries[schemaName] ??= [];
entries[schemaName].push(...details);
}
const entryMap: Record<string, string[]> = {};
for (const schemaName in entries) {
entryMap[schemaName] = entries[schemaName]
.map((e) => ({ name: e.name, created: new Date(e.created) }))
.sort((a, b) => b.created.valueOf() - a.created.valueOf())
.map((e) => e.name);
}
return entryMap;
}
|
2302_79757062/books
|
src/utils/doc.ts
|
TypeScript
|
agpl-3.0
| 4,070
|
import { Fyo } from 'fyo';
import { RawValueMap } from 'fyo/core/types';
import {
Field,
FieldType,
FieldTypeEnum,
RawValue,
TargetField,
} from 'schemas/types';
import { generateCSV } from 'utils/csvParser';
import { GetAllOptions, QueryFilter } from 'utils/db/types';
import { getMapFromList, safeParseFloat } from 'utils/index';
import { ExportField, ExportTableField } from './types';
const excludedFieldTypes: FieldType[] = [
FieldTypeEnum.AttachImage,
FieldTypeEnum.Attachment,
];
interface CsvHeader {
label: string;
schemaName: string;
fieldname: string;
parentFieldname?: string;
}
export function getExportFields(
fields: Field[],
exclude: string[] = []
): ExportField[] {
return fields
.filter((f) => !f.computed && f.label && !exclude.includes(f.fieldname))
.map((field) => {
const { fieldname, label } = field;
const fieldtype = field.fieldtype as FieldType;
return {
fieldname,
fieldtype,
label,
export: !excludedFieldTypes.includes(fieldtype),
};
});
}
export function getExportTableFields(
fields: Field[],
fyo: Fyo
): ExportTableField[] {
return fields
.filter((f) => f.fieldtype === FieldTypeEnum.Table)
.map((f) => {
const target = (f as TargetField).target;
const tableFields = fyo.schemaMap[target]?.fields ?? [];
const exportTableFields = getExportFields(tableFields, ['name']);
return {
fieldname: f.fieldname,
label: f.label,
target,
fields: exportTableFields,
};
})
.filter((f) => !!f.fields.length);
}
export async function getJsonExportData(
schemaName: string,
fields: ExportField[],
tableFields: ExportTableField[],
limit: number | null,
filters: QueryFilter,
fyo: Fyo
): Promise<string> {
const data = await getExportData(
schemaName,
fields,
tableFields,
limit,
filters,
fyo
);
convertParentDataToJsonExport(data.parentData, data.childTableData);
return JSON.stringify(data.parentData);
}
export async function getCsvExportData(
schemaName: string,
fields: ExportField[],
tableFields: ExportTableField[],
limit: number | null,
filters: QueryFilter,
fyo: Fyo
): Promise<string> {
const { childTableData, parentData } = await getExportData(
schemaName,
fields,
tableFields,
limit,
filters,
fyo
);
/**
* parentNameMap: Record<ParentName, Record<ParentFieldName, Rows[]>>
*/
const parentNameMap = getParentNameMap(childTableData);
const headers = getCsvHeaders(schemaName, fields, tableFields);
const rows: RawValue[][] = [];
for (const parentRow of parentData) {
const parentName = parentRow.name as string;
if (!parentName) {
continue;
}
const baseRowData = headers.parent.map(
(f) => (parentRow[f.fieldname] as RawValue) ?? ''
);
const tableFieldRowMap = parentNameMap[parentName];
if (!tableFieldRowMap || !Object.keys(tableFieldRowMap ?? {}).length) {
rows.push([baseRowData, headers.child.map(() => '')].flat());
continue;
}
for (const tableFieldName in tableFieldRowMap) {
const tableRows = tableFieldRowMap[tableFieldName] ?? [];
for (const tableRow of tableRows) {
const tableRowData = headers.child.map((f) => {
if (f.parentFieldname !== tableFieldName) {
return '';
}
return (tableRow[f.fieldname] as RawValue) ?? '';
});
rows.push([baseRowData, tableRowData].flat());
}
}
}
const flatHeaders = [headers.parent, headers.child].flat();
const labels = flatHeaders.map((f) => f.label);
const keys = flatHeaders.map((f) => `${f.schemaName}.${f.fieldname}`);
rows.unshift(keys);
rows.unshift(labels);
return generateCSV(rows);
}
function getCsvHeaders(
schemaName: string,
fields: ExportField[],
tableFields: ExportTableField[]
) {
const headers = {
parent: [] as CsvHeader[],
child: [] as CsvHeader[],
};
for (const { label, fieldname, fieldtype, export: shouldExport } of fields) {
if (!shouldExport || fieldtype === FieldTypeEnum.Table) {
continue;
}
headers.parent.push({ schemaName, label, fieldname });
}
for (const tf of tableFields) {
if (!fields.find((f) => f.fieldname === tf.fieldname)?.export) {
continue;
}
for (const field of tf.fields) {
if (!field.export) {
continue;
}
headers.child.push({
schemaName: tf.target,
label: field.label,
fieldname: field.fieldname,
parentFieldname: tf.fieldname,
});
}
}
return headers;
}
function getParentNameMap(childTableData: Record<string, RawValueMap[]>) {
const parentNameMap: Record<string, Record<string, RawValueMap[]>> = {};
for (const key in childTableData) {
for (const row of childTableData[key]) {
const parent = row.parent as string;
if (!parent) {
continue;
}
parentNameMap[parent] ??= {};
parentNameMap[parent][key] ??= [];
parentNameMap[parent][key].push(row);
}
}
return parentNameMap;
}
async function getExportData(
schemaName: string,
fields: ExportField[],
tableFields: ExportTableField[],
limit: number | null,
filters: QueryFilter,
fyo: Fyo
) {
const parentData = await getParentData(
schemaName,
filters,
fields,
limit,
fyo
);
const parentNames = parentData.map((f) => f.name as string).filter(Boolean);
const childTableData = await getAllChildTableData(
tableFields,
fields,
parentNames,
fyo
);
return { parentData, childTableData };
}
function convertParentDataToJsonExport(
parentData: RawValueMap[],
childTableData: Record<string, RawValueMap[]>
) {
/**
* Map from List does not create copies. Map is a
* map of references, hence parentData is altered.
*/
const nameMap = getMapFromList(parentData, 'name');
for (const fieldname in childTableData) {
const data = childTableData[fieldname];
for (const row of data) {
const parent = row.parent as string | undefined;
if (!parent || !nameMap?.[parent]) {
continue;
}
nameMap[parent][fieldname] ??= [];
delete row.parent;
delete row.name;
(nameMap[parent][fieldname] as RawValueMap[]).push(row);
}
}
}
async function getParentData(
schemaName: string,
filters: QueryFilter,
fields: ExportField[],
limit: number | null,
fyo: Fyo
) {
const orderBy = ['created'];
if (fyo.db.fieldMap[schemaName]['date']) {
orderBy.unshift('date');
}
const options: GetAllOptions = { filters, orderBy, order: 'desc' };
if (limit) {
options.limit = limit;
}
options.fields = fields
.filter((f) => f.export && f.fieldtype !== FieldTypeEnum.Table)
.map((f) => f.fieldname);
if (!options.fields.includes('name')) {
options.fields.unshift('name');
}
const data = await fyo.db.getAllRaw(schemaName, options);
convertRawPesaToFloat(data, fields);
return data;
}
async function getAllChildTableData(
tableFields: ExportTableField[],
parentFields: ExportField[],
parentNames: string[],
fyo: Fyo
) {
const childTables: Record<string, RawValueMap[]> = {};
// Getting Child Row data
for (const tf of tableFields) {
const f = parentFields.find((f) => f.fieldname === tf.fieldname);
if (!f?.export) {
continue;
}
childTables[tf.fieldname] = await getChildTableData(tf, parentNames, fyo);
}
return childTables;
}
async function getChildTableData(
exportTableField: ExportTableField,
parentNames: string[],
fyo: Fyo
) {
const exportTableFields = exportTableField.fields
.filter((f) => f.export && f.fieldtype !== FieldTypeEnum.Table)
.map((f) => f.fieldname);
if (!exportTableFields.includes('parent')) {
exportTableFields.unshift('parent');
}
const data = await fyo.db.getAllRaw(exportTableField.target, {
orderBy: 'idx',
fields: exportTableFields,
filters: { parent: ['in', parentNames] },
});
convertRawPesaToFloat(data, exportTableField.fields);
return data;
}
function convertRawPesaToFloat(data: RawValueMap[], fields: ExportField[]) {
const currencyFields = fields.filter(
(f) => f.fieldtype === FieldTypeEnum.Currency
);
for (const row of data) {
for (const { fieldname } of currencyFields) {
row[fieldname] = safeParseFloat((row[fieldname] ?? '0') as string);
}
}
}
|
2302_79757062/books
|
src/utils/export.ts
|
TypeScript
|
agpl-3.0
| 8,480
|
import { ModelNameEnum } from 'models/types';
export const routeFilters = {
SalesItems: { for: ['in', ['Sales', 'Both']] },
PurchaseItems: { for: ['in', ['Purchases', 'Both']] },
Items: { for: 'Both' },
PurchasePayments: {
referenceType: ModelNameEnum.PurchaseInvoice,
},
SalesPayments: {
referenceType: ModelNameEnum.SalesInvoice,
},
Suppliers: { role: ['in', ['Supplier', 'Both']] },
Customers: { role: ['in', ['Customer', 'Both']] },
Party: { role: 'Both' },
};
export const createFilters = {
SalesItems: { for: 'Sales' },
PurchaseItems: { for: 'Purchases' },
Items: { for: 'Both' },
PurchasePayments: { paymentType: 'Pay' },
SalesPayments: { paymentType: 'Receive' },
Suppliers: { role: 'Supplier' },
Customers: { role: 'Customer' },
Party: { role: 'Both' },
};
|
2302_79757062/books
|
src/utils/filters.ts
|
TypeScript
|
agpl-3.0
| 812
|
import { t } from 'fyo';
import { ModelNameEnum } from 'models/types';
import { openSettings, routeTo } from './ui';
import { GetStartedConfigItem } from './types';
export function getGetStartedConfig(): GetStartedConfigItem[] {
/* eslint-disable @typescript-eslint/no-misused-promises */
return [
{
label: t`Organisation`,
items: [
{
key: 'General',
label: t`General`,
icon: 'general',
description: t`Set up your company information, email, country and fiscal year`,
fieldname: 'companySetup',
action: () => openSettings(ModelNameEnum.AccountingSettings),
},
{
key: 'Print',
label: t`Print`,
icon: 'invoice',
description: t`Customize your invoices by adding a logo and address details`,
fieldname: 'printSetup',
action: () => openSettings(ModelNameEnum.PrintSettings),
},
{
key: 'System',
label: t`System`,
icon: 'system',
description: t`Setup system defaults like date format and display precision`,
fieldname: 'systemSetup',
action: () => openSettings(ModelNameEnum.SystemSettings),
},
],
},
{
label: t`Accounts`,
items: [
{
key: 'Review Accounts',
label: t`Review Accounts`,
icon: 'review-ac',
description: t`Review your chart of accounts, add any account or tax heads as needed`,
action: () => routeTo('/chart-of-accounts'),
fieldname: 'chartOfAccountsReviewed',
documentation: 'https://docs.frappe.io/books/chart-of-accounts',
},
{
key: 'Opening Balances',
label: t`Opening Balances`,
icon: 'opening-ac',
fieldname: 'openingBalanceChecked',
description: t`Set up your opening balances before performing any accounting entries`,
documentation: 'https://docs.frappe.io/books/setup-opening-balances',
},
{
key: 'Add Taxes',
label: t`Add Taxes`,
icon: 'percentage',
fieldname: 'taxesAdded',
description: t`Set up your tax templates for your sales or purchase transactions`,
action: () => routeTo('/list/Tax'),
documentation:
'https://docs.frappe.io/books/create-initial-entries#add-taxes',
},
],
},
{
label: t`Sales`,
items: [
{
key: 'Add Sales Items',
label: t`Add Items`,
icon: 'item',
description: t`Add products or services that you sell to your customers`,
action: () =>
routeTo({
path: `/list/Item/${t`Sales Items`}`,
query: {
filters: JSON.stringify({ for: 'Sales' }),
},
}),
fieldname: 'salesItemCreated',
documentation:
'https://docs.frappe.io/books/create-initial-entries#add-sales-items',
},
{
key: 'Add Customers',
label: t`Add Customers`,
icon: 'customer',
description: t`Add a few customers to create your first sales invoice`,
action: () =>
routeTo({
path: `/list/Party/${t`Customers`}`,
query: {
filters: JSON.stringify({ role: 'Customer' }),
},
}),
fieldname: 'customerCreated',
documentation:
'https://docs.frappe.io/books/create-initial-entries#add-customers',
},
{
key: 'Create Sales Invoice',
label: t`Create Sales Invoice`,
icon: 'sales-invoice',
description: t`Create your first sales invoice for the created customer`,
action: () => routeTo('/list/SalesInvoice'),
fieldname: 'invoiceCreated',
documentation: 'https://docs.frappe.io/books/sales-invoices',
},
],
},
{
label: t`Purchase`,
items: [
{
key: 'Add Purchase Items',
label: t`Add Items`,
icon: 'item',
description: t`Add products or services that you buy from your suppliers`,
action: () =>
routeTo({
path: `/list/Item/${t`Purchase Items`}`,
query: {
filters: JSON.stringify({ for: 'Purchases' }),
},
}),
fieldname: 'purchaseItemCreated',
},
{
key: 'Add Suppliers',
label: t`Add Suppliers`,
icon: 'supplier',
description: t`Add a few suppliers to create your first purchase invoice`,
action: () =>
routeTo({
path: `/list/Party/${t`Suppliers`}`,
query: { filters: JSON.stringify({ role: 'Supplier' }) },
}),
fieldname: 'supplierCreated',
},
{
key: 'Create Purchase Invoice',
label: t`Create Purchase Invoice`,
icon: 'purchase-invoice',
description: t`Create your first purchase invoice from the created supplier`,
action: () => routeTo('/list/PurchaseInvoice'),
fieldname: 'billCreated',
documentation:
'https://docs.frappe.io/books/purchase-invoices#creating-purchase-invoices',
},
],
},
];
}
|
2302_79757062/books
|
src/utils/getStartedConfig.ts
|
TypeScript
|
agpl-3.0
| 5,405
|
/**
* General purpose utils used by the frontend.
*/
import { t } from 'fyo';
import { Doc } from 'fyo/model/doc';
import { isPesa } from 'fyo/utils';
import {
BaseError,
DuplicateEntryError,
LinkValidationError,
} from 'fyo/utils/errors';
import { Field, FieldType, FieldTypeEnum, NumberField } from 'schemas/types';
import { fyo } from 'src/initFyo';
export function stringifyCircular(
obj: unknown,
ignoreCircular = false,
convertDocument = false
): string {
const cacheKey: string[] = [];
const cacheValue: unknown[] = [];
return JSON.stringify(obj, (key: string, value: unknown) => {
if (typeof value !== 'object' || value === null) {
cacheKey.push(key);
cacheValue.push(value);
return value;
}
if (cacheValue.includes(value)) {
const circularKey: string =
cacheKey[cacheValue.indexOf(value)] || '{self}';
return ignoreCircular ? undefined : `[Circular:${circularKey}]`;
}
cacheKey.push(key);
cacheValue.push(value);
if (convertDocument && value instanceof Doc) {
return value.getValidDict();
}
return value;
});
}
export function fuzzyMatch(input: string, target: string) {
const keywordLetters = [...input];
const candidateLetters = [...target];
let keywordLetter = keywordLetters.shift();
let candidateLetter = candidateLetters.shift();
let isMatch = true;
let distance = 0;
while (keywordLetter && candidateLetter) {
if (keywordLetter === candidateLetter) {
keywordLetter = keywordLetters.shift();
} else if (keywordLetter.toLowerCase() === candidateLetter.toLowerCase()) {
keywordLetter = keywordLetters.shift();
distance += 0.5;
} else {
distance += 1;
}
candidateLetter = candidateLetters.shift();
}
if (keywordLetter !== undefined) {
distance = Number.MAX_SAFE_INTEGER;
isMatch = false;
} else {
distance += candidateLetters.length;
}
return { isMatch, distance };
}
export function convertPesaValuesToFloat(obj: Record<string, unknown>) {
Object.keys(obj).forEach((key) => {
const value = obj[key];
if (!isPesa(value)) {
return;
}
obj[key] = value.float;
});
}
export function getErrorMessage(e: Error, doc?: Doc): string {
const errorMessage = e.message || t`An error occurred.`;
let { schemaName, name } = doc ?? {};
if (!doc) {
schemaName = (e as BaseError).more?.schemaName as string | undefined;
name = (e as BaseError).more?.value as string | undefined;
}
if (!schemaName || !name) {
return errorMessage;
}
const label = fyo.db.schemaMap[schemaName]?.label ?? schemaName;
if (e instanceof LinkValidationError) {
return t`${label} ${name} is linked with existing records.`;
} else if (e instanceof DuplicateEntryError) {
return t`${label} ${name} already exists.`;
}
return errorMessage;
}
export function isNumeric(
fieldtype: FieldType
): fieldtype is NumberField['fieldtype'];
export function isNumeric(fieldtype: Field): fieldtype is NumberField;
export function isNumeric(
fieldtype: Field | FieldType
): fieldtype is NumberField | NumberField['fieldtype'] {
if (typeof fieldtype !== 'string') {
fieldtype = fieldtype?.fieldtype;
}
const numericTypes: FieldType[] = [
FieldTypeEnum.Int,
FieldTypeEnum.Float,
FieldTypeEnum.Currency,
];
return numericTypes.includes(fieldtype);
}
|
2302_79757062/books
|
src/utils/index.ts
|
TypeScript
|
agpl-3.0
| 3,405
|
import { Fyo } from 'fyo';
import { ConfigFile } from 'fyo/core/types';
import { getRegionalModels, models } from 'models/index';
import { ModelNameEnum } from 'models/types';
import { TargetField } from 'schemas/types';
import {
getMapFromList,
getRandomString,
getValueMapFromList,
} from 'utils/index';
export async function initializeInstance(
dbPath: string,
isNew: boolean,
countryCode: string,
fyo: Fyo
) {
if (isNew) {
await closeDbIfConnected(fyo);
countryCode = await fyo.db.createNewDatabase(dbPath, countryCode);
} else if (!fyo.db.isConnected) {
countryCode = await fyo.db.connectToDatabase(dbPath);
}
const regionalModels = await getRegionalModels(countryCode);
await fyo.initializeAndRegister(models, regionalModels);
await checkSingleLinks(fyo);
await setSingles(fyo);
await setCreds(fyo);
await setVersion(fyo);
setDeviceId(fyo);
await setInstanceId(fyo);
await setOpenCount(fyo);
await setCurrencySymbols(fyo);
}
async function closeDbIfConnected(fyo: Fyo) {
if (!fyo.db.isConnected) {
return;
}
await fyo.db.purgeCache();
}
async function setSingles(fyo: Fyo) {
for (const schema of Object.values(fyo.schemaMap)) {
if (!schema?.isSingle || schema.name === ModelNameEnum.SetupWizard) {
continue;
}
await fyo.doc.getDoc(schema.name);
}
}
async function checkSingleLinks(fyo: Fyo) {
/**
* Required cause SingleValue tables don't maintain
* referential integrity. Hence values Linked in the
* Singles table can be deleted.
*
* These deleted links can prevent the db from loading.
*/
const linkFields = Object.values(fyo.db.schemaMap)
.filter((schema) => schema?.isSingle)
.map((schema) => schema!.fields)
.flat()
.filter((field) => field.fieldtype === 'Link' && field.target)
.map((field) => ({
fieldKey: `${field.schemaName!}.${field.fieldname}`,
target: (field as TargetField).target,
}));
const linkFieldsMap = getMapFromList(linkFields, 'fieldKey');
const singleValues = (await fyo.db.getAllRaw('SingleValue', {
fields: ['name', 'parent', 'fieldname', 'value'],
})) as { name: string; parent: string; fieldname: string; value: string }[];
const exists: Record<string, Record<string, boolean>> = {};
for (const { name, fieldname, parent, value } of singleValues) {
const fieldKey = `${parent}.${fieldname}`;
if (!linkFieldsMap[fieldKey]) {
continue;
}
const { target } = linkFieldsMap[fieldKey];
if (typeof value !== 'string' || !value || !target) {
continue;
}
exists[target] ??= {};
if (exists[target][value] === undefined) {
exists[target][value] = await fyo.db.exists(target, value);
}
if (exists[target][value]) {
continue;
}
await fyo.db.delete('SingleValue', name);
}
}
async function setCreds(fyo: Fyo) {
const email = (await fyo.getValue(
ModelNameEnum.AccountingSettings,
'email'
)) as string | undefined;
const user = fyo.auth.user;
fyo.auth.user = email ?? user;
}
async function setVersion(fyo: Fyo) {
const version = (await fyo.getValue(
ModelNameEnum.SystemSettings,
'version'
)) as string | undefined;
const { appVersion } = fyo.store;
if (version !== appVersion) {
const systemSettings = await fyo.doc.getDoc(ModelNameEnum.SystemSettings);
await systemSettings?.setAndSync('version', appVersion);
}
}
function setDeviceId(fyo: Fyo) {
let deviceId = fyo.config.get('deviceId');
if (deviceId === undefined) {
deviceId = getRandomString();
fyo.config.set('deviceId', deviceId);
}
fyo.store.deviceId = deviceId;
}
async function setInstanceId(fyo: Fyo) {
const systemSettings = await fyo.doc.getDoc(ModelNameEnum.SystemSettings);
if (!systemSettings.instanceId) {
await systemSettings.setAndSync('instanceId', getRandomString());
}
fyo.store.instanceId = (await fyo.getValue(
ModelNameEnum.SystemSettings,
'instanceId'
)) as string;
}
export async function setCurrencySymbols(fyo: Fyo) {
const currencies = (await fyo.db.getAll(ModelNameEnum.Currency, {
fields: ['name', 'symbol'],
})) as { name: string; symbol: string }[];
fyo.currencySymbols = getValueMapFromList(
currencies,
'name',
'symbol'
) as Record<string, string | undefined>;
}
async function setOpenCount(fyo: Fyo) {
const misc = await fyo.doc.getDoc(ModelNameEnum.Misc);
let openCount = misc.openCount as number | null;
if (typeof openCount !== 'number') {
openCount = getOpenCountFromFiles(fyo);
}
if (typeof openCount !== 'number') {
openCount = 0;
}
openCount += 1;
await misc.setAndSync('openCount', openCount);
}
function getOpenCountFromFiles(fyo: Fyo) {
const configFile = fyo.config.get('files', []) as ConfigFile[];
for (const file of configFile) {
if (file.id === fyo.singles.SystemSettings?.instanceId) {
return file.openCount ?? 0;
}
}
return null;
}
|
2302_79757062/books
|
src/utils/initialization.ts
|
TypeScript
|
agpl-3.0
| 4,969
|
import type { InjectionKey, Ref } from 'vue';
import type { Search } from './search';
import type { Shortcuts } from './shortcuts';
import type { useKeys } from './vueUtils';
export const languageDirectionKey = Symbol('languageDirection') as InjectionKey<
Ref<'ltr' | 'rtl'>
>;
export const keysKey = Symbol('keys') as InjectionKey<
ReturnType<typeof useKeys>
>;
export const searcherKey = Symbol('searcher') as InjectionKey<
Ref<null | Search>
>;
export const shortcutsKey = Symbol('shortcuts') as InjectionKey<Shortcuts>;
|
2302_79757062/books
|
src/utils/injectionKeys.ts
|
TypeScript
|
agpl-3.0
| 534
|
import { t } from 'fyo';
import Dialog from 'src/components/Dialog.vue';
import Toast from 'src/components/Toast.vue';
import { App, createApp, h } from 'vue';
import { getColorClass } from './colors';
import { DialogButton, DialogOptions, ToastOptions, ToastType } from './types';
export async function showDialog<DO extends DialogOptions>(options: DO) {
const preWrappedButtons: DialogButton[] = options.buttons ?? [
{ label: t`Okay`, action: () => null, isEscape: true },
];
const resultPromise = new Promise((resolve, reject) => {
const buttons = preWrappedButtons.map((config) => {
return {
...config,
action: async () => {
try {
resolve(await config.action());
} catch (error) {
reject(error);
}
},
};
});
const dialogApp = createApp({
render() {
return h(Dialog, { ...options, buttons });
},
});
fragmentMountComponent(dialogApp);
});
return await resultPromise;
}
export function showToast(options: ToastOptions) {
const toastApp = createApp({
render() {
return h(Toast, { ...options });
},
});
fragmentMountComponent(toastApp);
}
function fragmentMountComponent(app: App<Element>) {
const fragment = document.createDocumentFragment();
// @ts-ignore
app.mount(fragment);
document.body.append(fragment);
}
export function getIconConfig(type: ToastType) {
let iconName = 'alert-circle';
if (type === 'warning') {
iconName = 'alert-triangle';
} else if (type === 'success') {
iconName = 'check-circle';
}
const color = {
info: 'blue',
warning: 'orange',
error: 'red',
success: 'green',
}[type];
const iconColor = getColorClass(color ?? 'gray', 'text', 400);
const containerBackground = getColorClass(color ?? 'gray', 'bg', 100);
const containerBorder = getColorClass(color ?? 'gray', 'border', 300);
return { iconName, color, iconColor, containerBorder, containerBackground };
}
|
2302_79757062/books
|
src/utils/interactive.ts
|
TypeScript
|
agpl-3.0
| 2,013
|
import { DEFAULT_LANGUAGE } from 'fyo/utils/consts';
import { setLanguageMapOnTranslationString } from 'fyo/utils/translation';
import { fyo } from 'src/initFyo';
import { systemLanguageRef } from './refs';
// Language: Language Code in books/translations
export const languageCodeMap: Record<string, string> = {
Arabic: 'ar',
Catalan: 'ca-ES',
Danish: 'da',
Dutch: 'nl',
English: 'en',
French: 'fr',
German: 'de',
Gujarati: 'gu',
Hindi: 'hi',
Korean: 'ko',
Nepali: 'np',
Portuguese: 'pt',
'Simplified Chinese': 'zh-CN',
Spanish: 'es',
Swedish: 'sv',
Turkish: 'tr',
};
export async function setLanguageMap(
initLanguage?: string,
dontReload = false
) {
const oldLanguage = fyo.config.get('language') as string;
initLanguage ??= oldLanguage;
const { code, language, usingDefault } = getLanguageCode(
initLanguage,
oldLanguage
);
let success = true;
if (code === 'en') {
setLanguageMapOnTranslationString(undefined);
} else {
success = await fetchAndSetLanguageMap(code);
}
if (success && !usingDefault) {
fyo.config.set('language', language);
systemLanguageRef.value = language;
}
if (!dontReload && success && initLanguage !== oldLanguage) {
ipc.reloadWindow();
}
return success;
}
function getLanguageCode(initLanguage: string, oldLanguage: string) {
let language = initLanguage ?? oldLanguage;
let usingDefault = false;
if (!language) {
language = DEFAULT_LANGUAGE;
usingDefault = true;
}
const code = languageCodeMap[language] ?? 'en';
return { code, language, usingDefault };
}
async function fetchAndSetLanguageMap(code: string) {
const { success, message, languageMap } = await ipc.getLanguageMap(code);
if (!success) {
const { showToast } = await import('src/utils/interactive');
showToast({ type: 'error', message });
} else {
setLanguageMapOnTranslationString(languageMap);
await fyo.db.translateSchemaMap(languageMap);
}
return success;
}
|
2302_79757062/books
|
src/utils/language.ts
|
TypeScript
|
agpl-3.0
| 1,995
|
import { Fyo } from 'fyo';
import { ConfigFile } from 'fyo/core/types';
import { translateSchema } from 'fyo/utils/translation';
import { cloneDeep } from 'lodash';
import { DateTime } from 'luxon';
import { SetupWizard } from 'models/baseModels/SetupWizard/SetupWizard';
import { ModelNameEnum } from 'models/types';
import { reports } from 'reports/index';
import SetupWizardSchema from 'schemas/app/SetupWizard.json';
import { Schema } from 'schemas/types';
import { fyo } from 'src/initFyo';
import { QueryFilter } from 'utils/db/types';
import { schemaTranslateables } from 'utils/translationHelpers';
import type { LanguageMap } from 'utils/types';
import { PeriodKey } from './types';
export function getDatesAndPeriodList(period: PeriodKey): {
periodList: DateTime[];
fromDate: DateTime;
toDate: DateTime;
} {
const toDate: DateTime = DateTime.now().plus({ days: 1 });
let fromDate: DateTime;
if (period === 'This Year') {
fromDate = toDate.minus({ months: 12 });
} else if (period === 'YTD') {
fromDate = DateTime.now().startOf('year');
} else if (period === 'This Quarter') {
fromDate = toDate.minus({ months: 3 });
} else if (period === 'This Month') {
fromDate = toDate.minus({ months: 1 });
} else {
fromDate = toDate.minus({ days: 1 });
}
/**
* periodList: Monthly decrements before toDate until fromDate
*/
const periodList: DateTime[] = [toDate];
while (true) {
const nextDate = periodList.at(0)!.minus({ months: 1 });
if (nextDate.toMillis() < fromDate.toMillis()) {
if (period === 'YTD') {
periodList.unshift(nextDate);
break;
}
break;
}
periodList.unshift(nextDate);
}
periodList.shift();
return {
periodList,
fromDate,
toDate,
};
}
export function getSetupWizardDoc(languageMap?: LanguageMap) {
/**
* This is used cause when setup wizard is running
* the database isn't yet initialized.
*/
const schema = cloneDeep(SetupWizardSchema);
if (languageMap) {
translateSchema(schema, languageMap, schemaTranslateables);
}
return fyo.doc.getNewDoc(
'SetupWizard',
{},
false,
schema as Schema,
SetupWizard
);
}
export function updateConfigFiles(fyo: Fyo): ConfigFile {
const configFiles = fyo.config.get('files', []) as ConfigFile[];
const companyName = fyo.singles.AccountingSettings!.companyName as string;
const id = fyo.singles.SystemSettings!.instanceId as string;
const dbPath = fyo.db.dbPath!;
const openCount = fyo.singles.Misc!.openCount as number;
const fileIndex = configFiles.findIndex((f) => f.id === id);
let newFile = { id, companyName, dbPath, openCount } as ConfigFile;
if (fileIndex === -1) {
configFiles.push(newFile);
} else {
configFiles[fileIndex].companyName = companyName;
configFiles[fileIndex].dbPath = dbPath;
configFiles[fileIndex].openCount = openCount;
newFile = configFiles[fileIndex];
}
fyo.config.set('files', configFiles);
return newFile;
}
export const docsPathMap: Record<string, string | undefined> = {
// Analytics
Dashboard: 'books/dashboard',
Reports: 'books/reports',
GeneralLedger: 'books/general-ledger',
ProfitAndLoss: 'books/profit-and-loss',
BalanceSheet: 'books/balance-sheet',
TrialBalance: 'books/trial-balance',
// Transactions
[ModelNameEnum.SalesInvoice]: 'books/sales-invoices',
[ModelNameEnum.PurchaseInvoice]: 'books/purchase-invoices',
[ModelNameEnum.Payment]: 'books/payments',
[ModelNameEnum.JournalEntry]: 'books/journal-entries',
// Inventory
[ModelNameEnum.StockMovement]: 'books/stock-movement',
[ModelNameEnum.Shipment]: 'books/shipment',
[ModelNameEnum.PurchaseReceipt]: 'books/purchase-receipt',
StockLedger: 'books/stock-ledger',
StockBalance: 'books/stock-balance',
[ModelNameEnum.Batch]: 'books/batches',
// Entries
Entries: 'books/books',
[ModelNameEnum.Party]: 'books/party',
[ModelNameEnum.Item]: 'books/items',
[ModelNameEnum.Tax]: 'books/taxes',
[ModelNameEnum.PrintTemplate]: 'books/print-templates',
// Miscellaneous
Search: 'books/quick-search',
NumberSeries: 'books/number-series',
ImportWizard: 'books/import-wizard',
Settings: 'books/settings',
ChartOfAccounts: 'books/chart-of-accounts',
};
export async function getDataURL(type: string, data: Uint8Array) {
const blob = new Blob([data], { type });
return new Promise<string>((resolve) => {
const fr = new FileReader();
fr.addEventListener('loadend', () => {
resolve(fr.result as string);
});
fr.readAsDataURL(blob);
});
}
export async function convertFileToDataURL(file: File, type: string) {
const buffer = await file.arrayBuffer();
const array = new Uint8Array(buffer);
return await getDataURL(type, array);
}
export function getCreateFiltersFromListViewFilters(filters: QueryFilter) {
const createFilters: Record<string, string | number | boolean | null> = {};
for (const key in filters) {
let value: typeof filters[string] | undefined | number = filters[key];
if (Array.isArray(value) && value[0] === 'in' && Array.isArray(value[1])) {
value = value[1].filter((v) => v !== 'Both')[0];
}
if (value === undefined || Array.isArray(value)) {
continue;
}
createFilters[key] = value;
}
return createFilters;
}
export function getIsMac() {
return navigator.userAgent.indexOf('Mac') !== -1;
}
export async function getReport(name: keyof typeof reports) {
const cachedReport = fyo.store.reports[name];
if (cachedReport) {
return cachedReport;
}
const report = new reports[name](fyo);
await report.initialize();
fyo.store.reports[name] = report;
return report;
}
|
2302_79757062/books
|
src/utils/misc.ts
|
TypeScript
|
agpl-3.0
| 5,702
|
import { Fyo, t } from 'fyo';
import { ValidationError } from 'fyo/utils/errors';
import { AccountTypeEnum } from 'models/baseModels/Account/types';
import { Item } from 'models/baseModels/Item/Item';
import { SalesInvoice } from 'models/baseModels/SalesInvoice/SalesInvoice';
import { SalesInvoiceItem } from 'models/baseModels/SalesInvoiceItem/SalesInvoiceItem';
import { POSShift } from 'models/inventory/Point of Sale/POSShift';
import { ValuationMethod } from 'models/inventory/types';
import { ModelNameEnum } from 'models/types';
import { Money } from 'pesa';
import {
getRawStockLedgerEntries,
getStockBalanceEntries,
getStockLedgerEntries,
} from 'reports/inventory/helpers';
import { ItemQtyMap, ItemSerialNumbers } from 'src/components/POS/types';
import { fyo } from 'src/initFyo';
import { safeParseFloat } from 'utils/index';
import { showToast } from './interactive';
export async function getItemQtyMap(): Promise<ItemQtyMap> {
const itemQtyMap: ItemQtyMap = {};
const valuationMethod =
(fyo.singles.InventorySettings?.valuationMethod as ValuationMethod) ??
ValuationMethod.FIFO;
const rawSLEs = await getRawStockLedgerEntries(fyo);
const rawData = getStockLedgerEntries(rawSLEs, valuationMethod);
const posInventory = fyo.singles.POSSettings?.inventory;
const stockBalance = getStockBalanceEntries(rawData, {
location: posInventory,
});
for (const row of stockBalance) {
if (!itemQtyMap[row.item]) {
itemQtyMap[row.item] = { availableQty: 0 };
}
if (row.batch) {
itemQtyMap[row.item][row.batch] = row.balanceQuantity;
}
itemQtyMap[row.item].availableQty += row.balanceQuantity;
}
return itemQtyMap;
}
export function getTotalQuantity(items: SalesInvoiceItem[]): number {
let totalQuantity = safeParseFloat(0);
if (!items.length) {
return totalQuantity;
}
for (const item of items) {
const quantity = item.quantity ?? 0;
totalQuantity = safeParseFloat(totalQuantity + quantity);
}
return totalQuantity;
}
export function getItemDiscounts(items: SalesInvoiceItem[]): Money {
let itemDiscounts = fyo.pesa(0);
if (!items.length) {
return itemDiscounts;
}
for (const item of items) {
if (!item.itemDiscountAmount?.isZero()) {
itemDiscounts = itemDiscounts.add(item.itemDiscountAmount as Money);
}
if (item.amount && (item.itemDiscountPercent as number) > 1) {
itemDiscounts = itemDiscounts.add(
item.amount.percent(item.itemDiscountPercent as number)
);
}
}
return itemDiscounts;
}
export async function getItem(item: string): Promise<Item | undefined> {
const itemDoc = (await fyo.doc.getDoc(ModelNameEnum.Item, item)) as Item;
if (!itemDoc) {
return;
}
return itemDoc;
}
export function validateSinv(sinvDoc: SalesInvoice, itemQtyMap: ItemQtyMap) {
if (!sinvDoc) {
return;
}
validateSinvItems(sinvDoc.items as SalesInvoiceItem[], itemQtyMap);
}
function validateSinvItems(
sinvItems: SalesInvoiceItem[],
itemQtyMap: ItemQtyMap
) {
for (const item of sinvItems) {
if (!item.quantity || item.quantity < 1) {
throw new ValidationError(
t`Invalid Quantity for Item ${item.item as string}`
);
}
if (!itemQtyMap[item.item as string]) {
throw new ValidationError(t`Item ${item.item as string} not in Stock`);
}
if (item.quantity > itemQtyMap[item.item as string].availableQty) {
throw new ValidationError(
t`Insufficient Quantity. Item ${item.item as string} has only ${
itemQtyMap[item.item as string].availableQty
} quantities available. you selected ${item.quantity}`
);
}
}
}
export async function validateShipment(itemSerialNumbers: ItemSerialNumbers) {
if (!itemSerialNumbers) {
return;
}
for (const idx in itemSerialNumbers) {
const serialNumbers = itemSerialNumbers[idx].split('\n');
for (const serialNumber of serialNumbers) {
const status = await fyo.getValue(
ModelNameEnum.SerialNumber,
serialNumber,
'status'
);
if (status !== 'Active') {
throw new ValidationError(
t`Serial Number ${serialNumber} status is not Active.`
);
}
}
}
}
export function validateIsPosSettingsSet(fyo: Fyo) {
try {
const inventory = fyo.singles.POSSettings?.inventory;
if (!inventory) {
throw new ValidationError(
t`POS Inventory is not set. Please set it on POS Settings`
);
}
const cashAccount = fyo.singles.POSSettings?.cashAccount;
if (!cashAccount) {
throw new ValidationError(
t`POS Counter Cash Account is not set. Please set it on POS Settings`
);
}
const writeOffAccount = fyo.singles.POSSettings?.writeOffAccount;
if (!writeOffAccount) {
throw new ValidationError(
t`POS Write Off Account is not set. Please set it on POS Settings`
);
}
} catch (error) {
showToast({
type: 'error',
message: t`${error as string}`,
duration: 'long',
});
}
}
export function getTotalTaxedAmount(sinvDoc: SalesInvoice): Money {
let totalTaxedAmount = fyo.pesa(0);
if (!sinvDoc.items?.length || !sinvDoc.taxes?.length) {
return totalTaxedAmount;
}
for (const row of sinvDoc.taxes) {
totalTaxedAmount = totalTaxedAmount.add(row.amount as Money);
}
return totalTaxedAmount;
}
export function validateClosingAmounts(posShiftDoc: POSShift) {
try {
if (!posShiftDoc) {
throw new ValidationError(
`POS Shift Document not loaded. Please reload.`
);
}
posShiftDoc.closingAmounts?.map((row) => {
if (row.closingAmount?.isNegative()) {
throw new ValidationError(
t`Closing ${row.paymentMethod as string} Amount can not be negative.`
);
}
});
} catch (error) {}
}
export async function transferPOSCashAndWriteOff(
fyo: Fyo,
posShiftDoc: POSShift
) {
const expectedCashAmount = posShiftDoc.closingAmounts?.find(
(row) => row.paymentMethod === 'Cash'
)?.expectedAmount as Money;
if (expectedCashAmount.isZero()) {
return;
}
const closingCashAmount = posShiftDoc.closingAmounts?.find(
(row) => row.paymentMethod === 'Cash'
)?.closingAmount as Money;
const jvDoc = fyo.doc.getNewDoc(ModelNameEnum.JournalEntry, {
entryType: 'Journal Entry',
});
await jvDoc.append('accounts', {
account: AccountTypeEnum.Cash,
debit: closingCashAmount,
});
await jvDoc.append('accounts', {
account: fyo.singles.POSSettings?.cashAccount,
credit: closingCashAmount,
});
const differenceAmount = posShiftDoc?.closingAmounts?.find(
(row) => row.paymentMethod === 'Cash'
)?.differenceAmount as Money;
if (differenceAmount.isNegative()) {
await jvDoc.append('accounts', {
account: AccountTypeEnum.Cash,
debit: differenceAmount.abs(),
credit: fyo.pesa(0),
});
await jvDoc.append('accounts', {
account: fyo.singles.POSSettings?.writeOffAccount,
debit: fyo.pesa(0),
credit: differenceAmount.abs(),
});
}
if (!differenceAmount.isZero() && differenceAmount.isPositive()) {
await jvDoc.append('accounts', {
account: fyo.singles.POSSettings?.writeOffAccount,
debit: differenceAmount,
credit: fyo.pesa(0),
});
await jvDoc.append('accounts', {
account: AccountTypeEnum.Cash,
debit: fyo.pesa(0),
credit: differenceAmount,
});
}
await (await jvDoc.sync()).submit();
}
export function validateSerialNumberCount(
serialNumbers: string | undefined,
quantity: number,
item: string
) {
let serialNumberCount = 0;
if (serialNumbers) {
serialNumberCount = serialNumbers.split('\n').length;
}
if (quantity !== serialNumberCount) {
const errorMessage = t`Need ${quantity} Serial Numbers for Item ${item}. You have provided ${serialNumberCount}`;
showToast({
type: 'error',
message: errorMessage,
duration: 'long',
});
throw new ValidationError(errorMessage);
}
}
|
2302_79757062/books
|
src/utils/pos.ts
|
TypeScript
|
agpl-3.0
| 8,064
|
import { Fyo, t } from 'fyo';
import { Doc } from 'fyo/model/doc';
import { Invoice } from 'models/baseModels/Invoice/Invoice';
import { ModelNameEnum } from 'models/types';
import { FieldTypeEnum, Schema, TargetField } from 'schemas/types';
import { getValueMapFromList } from 'utils/index';
import { TemplateFile } from 'utils/types';
import { showToast } from './interactive';
import { PrintValues } from './types';
import {
getDocFromNameIfExistsElseNew,
getSavePath,
showExportInFolder,
} from './ui';
export type PrintTemplateHint = {
[key: string]: string | PrintTemplateHint | PrintTemplateHint[];
};
type PrintTemplateData = Record<string, unknown>;
type TemplateUpdateItem = { name: string; template: string; type: string };
const printSettingsFields = [
'logo',
'displayLogo',
'color',
'font',
'email',
'phone',
'address',
'companyName',
];
const accountingSettingsFields = ['gstin', 'taxId'];
export async function getPrintTemplatePropValues(
doc: Doc
): Promise<PrintValues> {
const fyo = doc.fyo;
const values: PrintValues = { doc: {}, print: {} };
values.doc = await getPrintTemplateDocValues(doc);
const printSettings = await fyo.doc.getDoc(ModelNameEnum.PrintSettings);
const printValues = await getPrintTemplateDocValues(
printSettings,
printSettingsFields
);
const accountingSettings = await fyo.doc.getDoc(
ModelNameEnum.AccountingSettings
);
const accountingValues = await getPrintTemplateDocValues(
accountingSettings,
accountingSettingsFields
);
values.print = {
...printValues,
...accountingValues,
};
const discountSchema = ['Invoice', 'Quote'];
if (discountSchema.some((value) => doc.schemaName?.endsWith(value))) {
(values.doc as PrintTemplateData).totalDiscount =
formattedTotalDiscount(doc);
(values.doc as PrintTemplateData).showHSN = showHSN(doc);
}
return values;
}
export function getPrintTemplatePropHints(schemaName: string, fyo: Fyo) {
const hints: PrintTemplateHint = {};
const schema = fyo.schemaMap[schemaName]!;
hints.doc = getPrintTemplateDocHints(schema, fyo);
const printSettingsHints = getPrintTemplateDocHints(
fyo.schemaMap[ModelNameEnum.PrintSettings]!,
fyo,
printSettingsFields
);
const accountingSettingsHints = getPrintTemplateDocHints(
fyo.schemaMap[ModelNameEnum.AccountingSettings]!,
fyo,
accountingSettingsFields
);
hints.print = {
...printSettingsHints,
...accountingSettingsHints,
};
if (schemaName?.endsWith('Invoice')) {
(hints.doc as PrintTemplateData).totalDiscount = fyo.t`Total Discount`;
(hints.doc as PrintTemplateData).showHSN = fyo.t`Show HSN`;
}
return hints;
}
function showHSN(doc: Doc): boolean {
const items = doc.items;
if (!Array.isArray(items)) {
return false;
}
return items.map((i: Doc) => i.hsnCode).every(Boolean);
}
function formattedTotalDiscount(doc: Doc): string {
if (!(doc instanceof Invoice)) {
return '';
}
const totalDiscount = doc.getTotalDiscount();
if (!totalDiscount?.float) {
return '';
}
return doc.fyo.format(totalDiscount, ModelNameEnum.Currency);
}
function getPrintTemplateDocHints(
schema: Schema,
fyo: Fyo,
fieldnames?: string[],
linkLevel?: number
): PrintTemplateHint {
linkLevel ??= 0;
const hints: PrintTemplateHint = {};
const links: PrintTemplateHint = {};
let fields = schema.fields;
if (fieldnames) {
fields = fields.filter((f) => fieldnames.includes(f.fieldname));
}
for (const field of fields) {
const { fieldname, fieldtype, label, meta } = field;
if (fieldtype === FieldTypeEnum.Attachment || meta) {
continue;
}
hints[fieldname] = label ?? fieldname;
const { target } = field as TargetField;
const targetSchema = fyo.schemaMap[target];
if (fieldtype === FieldTypeEnum.Link && targetSchema && linkLevel < 2) {
links[fieldname] = getPrintTemplateDocHints(
targetSchema,
fyo,
undefined,
linkLevel + 1
);
}
if (fieldtype === FieldTypeEnum.Table && targetSchema) {
hints[fieldname] = [getPrintTemplateDocHints(targetSchema, fyo)];
}
}
hints.submitted = fyo.t`Submitted`;
hints.entryType = fyo.t`Entry Type`;
hints.entryLabel = fyo.t`Entry Label`;
if (Object.keys(links).length) {
hints.links = links;
}
return hints;
}
async function getPrintTemplateDocValues(doc: Doc, fieldnames?: string[]) {
const values: PrintTemplateData = {};
if (!(doc instanceof Doc)) {
return values;
}
let fields = doc.schema.fields;
if (fieldnames) {
fields = fields.filter((f) => fieldnames.includes(f.fieldname));
}
// Set Formatted Doc Data
for (const field of fields) {
const { fieldname, fieldtype, meta } = field;
if (fieldtype === FieldTypeEnum.Attachment || meta) {
continue;
}
const value = doc.get(fieldname);
if (!value) {
values[fieldname] = '';
continue;
}
if (!Array.isArray(value)) {
values[fieldname] = doc.fyo.format(value, field, doc);
continue;
}
const table: PrintTemplateData[] = [];
for (const row of value) {
const rowProps = await getPrintTemplateDocValues(row);
table.push(rowProps);
}
values[fieldname] = table;
}
values.submitted = doc.submitted;
values.entryType = doc.schema.name;
values.entryLabel = doc.schema.label;
// Set Formatted Doc Link Data
await doc.loadLinks();
const links: PrintTemplateData = {};
for (const [linkName, linkDoc] of Object.entries(doc.links ?? {})) {
if (fieldnames && !fieldnames.includes(linkName)) {
continue;
}
links[linkName] = await getPrintTemplateDocValues(linkDoc);
}
if (Object.keys(links).length) {
values.links = links;
}
return values;
}
export async function getPathAndMakePDF(
name: string,
innerHTML: string,
width: number,
height: number
) {
const { filePath: savePath } = await getSavePath(name, 'pdf');
if (!savePath) {
return;
}
const html = constructPrintDocument(innerHTML);
const success = await ipc.makePDF(html, savePath, width, height);
if (success) {
showExportInFolder(t`Save as PDF Successful`, savePath);
} else {
showToast({ message: t`Export Failed`, type: 'error' });
}
}
function constructPrintDocument(innerHTML: string) {
const html = document.createElement('html');
const head = document.createElement('head');
const body = document.createElement('body');
const style = getAllCSSAsStyleElem();
head.innerHTML = [
'<meta charset="UTF-8">',
'<title>Print Window</title>',
].join('\n');
head.append(style);
body.innerHTML = innerHTML;
html.append(head, body);
return html.outerHTML;
}
function getAllCSSAsStyleElem() {
const cssTexts: string[] = [];
for (const sheet of document.styleSheets) {
for (const rule of sheet.cssRules) {
cssTexts.push(rule.cssText);
}
if (sheet.ownerRule) {
cssTexts.push(sheet.ownerRule.cssText);
}
}
const styleElem = document.createElement('style');
styleElem.innerHTML = cssTexts.join('\n');
return styleElem;
}
export async function updatePrintTemplates(fyo: Fyo) {
const templateFiles = await ipc.getTemplates();
const existingTemplates = (await fyo.db.getAll(ModelNameEnum.PrintTemplate, {
fields: ['name', 'modified'],
filters: { isCustom: false },
})) as { name: string; modified: Date }[];
const nameModifiedMap = getValueMapFromList(
existingTemplates,
'name',
'modified'
);
const updateList: TemplateUpdateItem[] = [];
for (const templateFile of templateFiles) {
const updates = getPrintTemplateUpdateList(
templateFile,
nameModifiedMap,
fyo
);
updateList.push(...updates);
}
const isLogging = fyo.store.skipTelemetryLogging;
fyo.store.skipTelemetryLogging = true;
for (const { name, type, template } of updateList) {
const doc = await getDocFromNameIfExistsElseNew(
ModelNameEnum.PrintTemplate,
name
);
await doc.set({ name, type, template, isCustom: false });
await doc.sync();
}
fyo.store.skipTelemetryLogging = isLogging;
}
function getPrintTemplateUpdateList(
{ file, template, modified: modifiedString }: TemplateFile,
nameModifiedMap: Record<string, Date>,
fyo: Fyo
): TemplateUpdateItem[] {
const templateList: TemplateUpdateItem[] = [];
const dbModified = new Date(modifiedString);
for (const { name, type } of getNameAndTypeFromTemplateFile(file, fyo)) {
const fileModified = nameModifiedMap[name];
if (fileModified && dbModified.valueOf() >= fileModified.valueOf()) {
continue;
}
templateList.push({
name,
type,
template,
});
}
return templateList;
}
function getNameAndTypeFromTemplateFile(
file: string,
fyo: Fyo
): { name: string; type: string }[] {
/**
* Template File Name Format:
* TemplateName[.SchemaName].template.html
*
* If the SchemaName is absent then it is assumed
* that the SchemaName is:
* - SalesInvoice
* - SalesQuote
* - PurchaseInvoice
*/
const fileName = file.split('.template.html')[0];
const name = fileName.split('.')[0];
const schemaName = fileName.split('.')[1];
if (schemaName) {
const label = fyo.schemaMap[schemaName]?.label ?? schemaName;
return [{ name: `${name} - ${label}`, type: schemaName }];
}
return [
ModelNameEnum.SalesInvoice,
ModelNameEnum.SalesQuote,
ModelNameEnum.PurchaseInvoice,
].map((schemaName) => {
const label = fyo.schemaMap[schemaName]?.label ?? schemaName;
return { name: `${name} - ${label}`, type: schemaName };
});
}
export const baseTemplate = `<main class="h-full w-full bg-white">
<!-- Edit This Code -->
<header class="p-4 flex justify-between border-b">
<h2
class="font-semibold text-2xl"
:style="{ color: print.color }"
>
{{ print.companyName }}
</h2>
<h2 class="font-semibold text-2xl" >
{{ doc.name }}
</h2>
</header>
<div class="p-4 text-gray-600">
Edit the code in the Template Editor on the right
to create your own personalized custom template.
</div>
</main>
`;
|
2302_79757062/books
|
src/utils/printTemplates.ts
|
TypeScript
|
agpl-3.0
| 10,224
|
import { reactive, ref } from 'vue';
import type { HistoryState } from 'vue-router';
export const showSidebar = ref(true);
export const docsPathRef = ref<string>('');
export const systemLanguageRef = ref<string>('');
export const historyState = reactive({
forward: !!(history.state as HistoryState)?.forward,
back: !!(history.state as HistoryState)?.back,
});
|
2302_79757062/books
|
src/utils/refs.ts
|
TypeScript
|
agpl-3.0
| 365
|
import { Fyo, t } from 'fyo';
import { RawValueMap } from 'fyo/core/types';
import { groupBy } from 'lodash';
import { ModelNameEnum } from 'models/types';
import { reports } from 'reports';
import { OptionField } from 'schemas/types';
import { createFilters, routeFilters } from 'src/utils/filters';
import { GetAllOptions } from 'utils/db/types';
import { safeParseFloat } from 'utils/index';
import { RouteLocationRaw } from 'vue-router';
import { fuzzyMatch } from '.';
import { getFormRoute, routeTo } from './ui';
export const searchGroups = [
'Docs',
'List',
'Create',
'Report',
'Page',
] as const;
export type SearchGroup = typeof searchGroups[number];
interface SearchItem {
label: string;
group: Exclude<SearchGroup, 'Docs'>;
route?: string;
action?: () => void | Promise<void>;
}
interface DocSearchItem extends Omit<SearchItem, 'group'> {
group: 'Docs';
schemaLabel: string;
more: string[];
}
export type SearchItems = (DocSearchItem | SearchItem)[];
interface Searchable {
needsUpdate: boolean;
schemaName: string;
fields: string[];
meta: string[];
isChild: boolean;
isSubmittable: boolean;
}
interface Keyword {
values: string[];
meta: Record<string, string | boolean | undefined>;
priority: number;
}
interface SearchFilters {
groupFilters: Record<SearchGroup, boolean>;
skipTables: boolean;
skipTransactions: boolean;
schemaFilters: Record<string, boolean>;
}
interface SearchIntermediate {
suggestions: SearchItems;
previousInput?: string;
}
export function getGroupLabelMap() {
return {
Create: t`Create`,
List: t`List`,
Report: t`Report`,
Docs: t`Docs`,
Page: t`Page`,
};
}
function getCreateAction(fyo: Fyo, schemaName: string, initData?: RawValueMap) {
return async function action() {
const doc = fyo.doc.getNewDoc(schemaName, initData);
const route = getFormRoute(schemaName, doc.name!);
await routeTo(route);
};
}
function getCreateList(fyo: Fyo): SearchItem[] {
const hasInventory = fyo.doc.singles.AccountingSettings?.enableInventory;
const formEditCreateList = [
ModelNameEnum.SalesInvoice,
ModelNameEnum.PurchaseInvoice,
ModelNameEnum.JournalEntry,
...(hasInventory
? [
ModelNameEnum.Shipment,
ModelNameEnum.PurchaseReceipt,
ModelNameEnum.StockMovement,
]
: []),
].map(
(schemaName) =>
({
label: fyo.schemaMap[schemaName]?.label,
group: 'Create',
action: getCreateAction(fyo, schemaName),
} as SearchItem)
);
const filteredCreateList = [
{
label: t`Sales Payment`,
schemaName: ModelNameEnum.Payment,
create: createFilters.SalesPayments,
},
{
label: t`Purchase Payment`,
schemaName: ModelNameEnum.Payment,
create: createFilters.PurchasePayments,
},
{
label: t`Customer`,
schemaName: ModelNameEnum.Party,
create: createFilters.Customers,
},
{
label: t`Supplier`,
schemaName: ModelNameEnum.Party,
create: createFilters.Suppliers,
},
{
label: t`Party`,
schemaName: ModelNameEnum.Party,
create: createFilters.Party,
},
{
label: t`Sales Item`,
schemaName: ModelNameEnum.Item,
create: createFilters.SalesItems,
},
{
label: t`Purchase Item`,
schemaName: ModelNameEnum.Item,
create: createFilters.PurchaseItems,
},
{
label: t`Item`,
schemaName: ModelNameEnum.Item,
create: createFilters.Items,
},
].map(({ label, create, schemaName }) => {
return {
label,
group: 'Create',
action: getCreateAction(fyo, schemaName, create),
} as SearchItem;
});
return [formEditCreateList, filteredCreateList].flat();
}
function getReportList(fyo: Fyo): SearchItem[] {
const hasGstin = !!fyo.singles?.AccountingSettings?.gstin;
const hasInventory = !!fyo.singles?.AccountingSettings?.enableInventory;
const reportNames = Object.keys(reports) as (keyof typeof reports)[];
return reportNames
.filter((r) => {
const report = reports[r];
if (report.isInventory && !hasInventory) {
return false;
}
if (report.title.startsWith('GST') && !hasGstin) {
return false;
}
return true;
})
.map((r) => {
const report = reports[r];
return {
label: report.title,
route: `/report/${r}`,
group: 'Report',
};
});
}
function getListViewList(fyo: Fyo): SearchItem[] {
let schemaNames = [
ModelNameEnum.Account,
ModelNameEnum.JournalEntry,
ModelNameEnum.PurchaseInvoice,
ModelNameEnum.SalesInvoice,
ModelNameEnum.Tax,
ModelNameEnum.UOM,
ModelNameEnum.Address,
ModelNameEnum.AccountingLedgerEntry,
ModelNameEnum.Currency,
ModelNameEnum.NumberSeries,
ModelNameEnum.PrintTemplate,
];
if (fyo.doc.singles.AccountingSecuttings?.enableInventory) {
schemaNames.push(
ModelNameEnum.StockMovement,
ModelNameEnum.Shipment,
ModelNameEnum.PurchaseReceipt,
ModelNameEnum.Location,
ModelNameEnum.StockLedgerEntry
);
}
if (fyo.doc.singles.AccountingSettings?.enablePriceList) {
schemaNames.push(ModelNameEnum.PriceList);
}
if (fyo.singles.InventorySettings?.enableBatches) {
schemaNames.push(ModelNameEnum.Batch);
}
if (fyo.singles.InventorySettings?.enableSerialNumber) {
schemaNames.push(ModelNameEnum.SerialNumber);
}
if (fyo.doc.singles.AccountingSettings?.enableFormCustomization) {
schemaNames.push(ModelNameEnum.CustomForm);
}
if (fyo.store.isDevelopment) {
schemaNames = Object.keys(fyo.schemaMap) as ModelNameEnum[];
}
const standardLists = schemaNames
.map((s) => fyo.schemaMap[s])
.filter((s) => s && !s.isChild && !s.isSingle)
.map(
(s) =>
({
label: s!.label,
route: `/list/${s!.name}`,
group: 'List',
} as SearchItem)
);
const filteredLists = [
{
label: t`Customers`,
route: `/list/Party/${t`Customers`}`,
filters: routeFilters.Customers,
},
{
label: t`Suppliers`,
route: `/list/Party/${t`Suppliers`}`,
filters: routeFilters.Suppliers,
},
{
label: t`Party`,
route: `/list/Party/${t`Party`}`,
filters: routeFilters.Party,
},
{
label: t`Sales Items`,
route: `/list/Item/${t`Sales Items`}`,
filters: routeFilters.SalesItems,
},
{
label: t`Sales Payments`,
route: `/list/Payment/${t`Sales Payments`}`,
filters: routeFilters.SalesPayments,
},
{
label: t`Purchase Items`,
route: `/list/Item/${t`Purchase Items`}`,
filters: routeFilters.PurchaseItems,
},
{
label: t`Items`,
route: `/list/Item/${t`Items`}`,
filters: routeFilters.Items,
},
{
label: t`Purchase Payments`,
route: `/list/Payment/${t`Purchase Payments`}`,
filters: routeFilters.PurchasePayments,
},
].map((i) => {
const label = i.label;
const route = encodeURI(`${i.route}?filters=${JSON.stringify(i.filters)}`);
return { label, route, group: 'List' } as SearchItem;
});
return [standardLists, filteredLists].flat();
}
function getSetupList(): SearchItem[] {
return [
{
label: t`Dashboard`,
route: '/',
group: 'Page',
},
{
label: t`Chart of Accounts`,
route: '/chart-of-accounts',
group: 'Page',
},
{
label: t`Import Wizard`,
route: '/import-wizard',
group: 'Page',
},
{
label: t`Settings`,
route: '/settings',
group: 'Page',
},
];
}
function getNonDocSearchList(fyo: Fyo) {
return [
getListViewList(fyo),
getCreateList(fyo),
getReportList(fyo),
getSetupList(),
]
.flat()
.map((d) => {
if (d.route && !d.action) {
d.action = async () => {
await routeTo(d.route!);
};
}
return d;
});
}
export class Search {
/**
* A simple fuzzy searcher.
*
* How the Search works:
* - Pulls `keywordFields` (string columns) from the db.
* - `name` or `parent` (parent doc's name) is used as the main
* label.
* - The `name`, `keywordFields` and schema label are used as
* search target terms.
* - Input is split on `' '` (whitespace) and each part has to completely
* or partially match the search target terms.
* - Non matches are ignored.
* - Each letter in the input narrows the search using the `this._intermediate`
* object where the incremental searches are stored.
* - Search index is marked for updation when a doc is entered or deleted.
* - Marked indices are rebuilt when the modal is opened.
*/
_obsSet = false;
numSearches = 0;
searchables: Record<string, Searchable>;
keywords: Record<string, Keyword[]>;
priorityMap: Record<string, number> = {
[ModelNameEnum.SalesInvoice]: 125,
[ModelNameEnum.PurchaseInvoice]: 100,
[ModelNameEnum.Payment]: 75,
[ModelNameEnum.StockMovement]: 75,
[ModelNameEnum.Shipment]: 75,
[ModelNameEnum.PurchaseReceipt]: 75,
[ModelNameEnum.Item]: 50,
[ModelNameEnum.Party]: 50,
[ModelNameEnum.JournalEntry]: 50,
};
filters: SearchFilters = {
groupFilters: {
List: true,
Report: true,
Create: true,
Page: true,
Docs: true,
},
schemaFilters: {},
skipTables: false,
skipTransactions: false,
};
fyo: Fyo;
_intermediate: SearchIntermediate = { suggestions: [] };
_nonDocSearchList: SearchItem[];
_groupLabelMap?: Record<SearchGroup, string>;
constructor(fyo: Fyo) {
this.fyo = fyo;
this.keywords = {};
this.searchables = {};
this._nonDocSearchList = getNonDocSearchList(fyo);
}
/**
* these getters are used for hacky two way binding between the
* `skipT*` filters and the `schemaFilters`.
*/
get skipTables() {
let value = true;
for (const val of Object.values(this.searchables)) {
if (!val.isChild) {
continue;
}
value &&= !this.filters.schemaFilters[val.schemaName];
}
return value;
}
get skipTransactions() {
let value = true;
for (const val of Object.values(this.searchables)) {
if (!val.isSubmittable) {
continue;
}
value &&= !this.filters.schemaFilters[val.schemaName];
}
return value;
}
set(filterName: string, value: boolean) {
/**
* When a filter is set, intermediate is reset
* this way the groups are rebuild with the filters
* applied.
*/
if (filterName in this.filters.groupFilters) {
this.filters.groupFilters[filterName as SearchGroup] = value;
} else if (filterName in this.searchables) {
this.filters.schemaFilters[filterName] = value;
this.filters.skipTables = this.skipTables;
this.filters.skipTransactions = this.skipTransactions;
} else if (filterName === 'skipTables') {
Object.values(this.searchables)
.filter(({ isChild }) => isChild)
.forEach(({ schemaName }) => {
this.filters.schemaFilters[schemaName] = !value;
});
this.filters.skipTables = value;
} else if (filterName === 'skipTransactions') {
Object.values(this.searchables)
.filter(({ isSubmittable }) => isSubmittable)
.forEach(({ schemaName }) => {
this.filters.schemaFilters[schemaName] = !value;
});
this.filters.skipTransactions = value;
}
this._setIntermediate([]);
}
async initializeKeywords() {
this._setSearchables();
await this.updateKeywords();
this._setDocObservers();
this._setSchemaFilters();
this._groupLabelMap = getGroupLabelMap();
this._setFilterDefaults();
}
_setFilterDefaults() {
const totalChildKeywords = Object.values(this.searchables)
.filter((s) => s.isChild)
.map((s) => this.keywords[s.schemaName]?.length ?? 0)
.reduce((a, b) => a + b, 0);
if (totalChildKeywords > 2_000) {
this.set('skipTables', true);
}
}
_setSchemaFilters() {
for (const name in this.searchables) {
this.filters.schemaFilters[name] = true;
}
}
async updateKeywords() {
for (const searchable of Object.values(this.searchables)) {
if (!searchable.needsUpdate) {
continue;
}
const options: GetAllOptions = {
fields: [searchable.fields, searchable.meta].flat(),
order: 'desc',
};
if (!searchable.isChild) {
options.orderBy = 'modified';
}
const maps = await this.fyo.db.getAllRaw(searchable.schemaName, options);
this._setKeywords(maps, searchable);
this.searchables[searchable.schemaName].needsUpdate = false;
}
}
_searchSuggestions(input: string): SearchItems {
const matches: { si: SearchItem | DocSearchItem; distance: number }[] = [];
for (const si of this._intermediate.suggestions) {
const label = si.label;
const groupLabel =
(si as DocSearchItem).schemaLabel || this._groupLabelMap?.[si.group];
const more = (si as DocSearchItem).more ?? [];
const values = [label, more, groupLabel]
.flat()
.filter(Boolean) as string[];
const { isMatch, distance } = this._getMatchAndDistance(input, values);
if (isMatch) {
matches.push({ si, distance });
}
}
matches.sort((a, b) => a.distance - b.distance);
const suggestions = matches.map((m) => m.si);
this._setIntermediate(suggestions, input);
return suggestions;
}
_shouldUseSuggestions(input?: string): boolean {
if (!input) {
return false;
}
const { suggestions, previousInput } = this._intermediate;
if (!suggestions?.length || !previousInput) {
return false;
}
if (!input.startsWith(previousInput)) {
return false;
}
return true;
}
_setIntermediate(suggestions: SearchItems, previousInput?: string) {
this.numSearches = suggestions.length;
this._intermediate.suggestions = suggestions;
this._intermediate.previousInput = previousInput;
}
search(input?: string): SearchItems {
const useSuggestions = this._shouldUseSuggestions(input);
/**
* If the suggestion list is already populated
* and the input is an extention of the previous
* then use the suggestions.
*/
if (useSuggestions) {
return this._searchSuggestions(input!);
} else {
this._setIntermediate([]);
}
/**
* Create the suggestion list.
*/
const groupedKeywords = this._getGroupedKeywords();
const keys = Object.keys(groupedKeywords);
if (!keys.includes('0')) {
keys.push('0');
}
keys.sort((a, b) => safeParseFloat(b) - safeParseFloat(a));
const array: SearchItems = [];
for (const key of keys) {
const keywords = groupedKeywords[key] ?? [];
this._pushDocSearchItems(keywords, array, input);
if (key === '0') {
this._pushNonDocSearchItems(array, input);
}
}
this._setIntermediate(array, input);
return array;
}
_pushDocSearchItems(keywords: Keyword[], array: SearchItems, input?: string) {
if (!input) {
return;
}
if (!this.filters.groupFilters.Docs) {
return;
}
const subArray = this._getSubSortedArray(keywords, input);
array.push(...subArray);
}
_pushNonDocSearchItems(array: SearchItems, input?: string) {
const filtered = this._nonDocSearchList.filter(
(si) => this.filters.groupFilters[si.group]
);
const subArray = this._getSubSortedArray(filtered, input);
array.push(...subArray);
}
_getSubSortedArray(
items: (SearchItem | Keyword)[],
input?: string
): SearchItems {
const subArray: { item: SearchItem | DocSearchItem; distance: number }[] =
[];
for (const item of items) {
const subArrayItem = this._getSubArrayItem(item, input);
if (!subArrayItem) {
continue;
}
subArray.push(subArrayItem);
}
subArray.sort((a, b) => a.distance - b.distance);
return subArray.map(({ item }) => item);
}
_getSubArrayItem(item: SearchItem | Keyword, input?: string) {
if (isSearchItem(item)) {
return this._getSubArrayItemFromSearchItem(item, input);
}
if (!input) {
return null;
}
return this._getSubArrayItemFromKeyword(item, input);
}
_getSubArrayItemFromSearchItem(item: SearchItem, input?: string) {
if (!input) {
return { item, distance: 0 };
}
const values = this._getValueListFromSearchItem(item).filter(Boolean);
const { isMatch, distance } = this._getMatchAndDistance(input, values);
if (!isMatch) {
return null;
}
return { item, distance };
}
_getValueListFromSearchItem({ label, group }: SearchItem): string[] {
return [label, group];
}
_getSubArrayItemFromKeyword(item: Keyword, input: string) {
const values = this._getValueListFromKeyword(item).filter(Boolean);
const { isMatch, distance } = this._getMatchAndDistance(input, values);
if (!isMatch) {
return null;
}
return {
item: this._getDocSearchItemFromKeyword(item),
distance,
};
}
_getValueListFromKeyword({ values, meta }: Keyword): string[] {
const schemaLabel = meta.schemaName as string;
return [values, schemaLabel].flat();
}
_getMatchAndDistance(input: string, values: string[]) {
/**
* All the parts should match with something.
*/
let distance = Number.MAX_SAFE_INTEGER;
for (const part of input.split(' ').filter(Boolean)) {
const match = this._getInternalMatch(part, values);
if (!match.isMatch) {
return { isMatch: false, distance: Number.MAX_SAFE_INTEGER };
}
distance = match.distance < distance ? match.distance : distance;
}
return { isMatch: true, distance };
}
_getInternalMatch(input: string, values: string[]) {
let isMatch = false;
let distance = Number.MAX_SAFE_INTEGER;
for (const k of values) {
const match = fuzzyMatch(input, k);
isMatch ||= match.isMatch;
if (match.distance < distance) {
distance = match.distance;
}
}
return { isMatch, distance };
}
_getDocSearchItemFromKeyword(keyword: Keyword): DocSearchItem {
const schemaName = keyword.meta.schemaName as string;
const schemaLabel = this.fyo.schemaMap[schemaName]?.label ?? schemaName;
const route = this._getRouteFromKeyword(keyword);
return {
label: keyword.values[0],
schemaLabel,
more: keyword.values.slice(1),
group: 'Docs',
action: async () => {
await routeTo(route);
},
};
}
_getRouteFromKeyword(keyword: Keyword): RouteLocationRaw {
const { parent, parentSchemaName, schemaName } = keyword.meta;
if (parent && parentSchemaName) {
return getFormRoute(parentSchemaName as string, parent as string);
}
return getFormRoute(schemaName as string, keyword.values[0]);
}
_getGroupedKeywords() {
/**
* filter out the ignored groups
* group by the keyword priority
*/
const keywords: Keyword[] = [];
const schemaNames = Object.keys(this.keywords);
for (const sn of schemaNames) {
const searchable = this.searchables[sn];
if (!this.filters.schemaFilters[sn] || !this.filters.groupFilters.Docs) {
continue;
}
if (searchable.isChild && this.filters.skipTables) {
continue;
}
if (searchable.isSubmittable && this.filters.skipTransactions) {
continue;
}
keywords.push(...this.keywords[sn]);
}
return groupBy(keywords.flat(), 'priority');
}
_setSearchables() {
for (const schemaName of Object.keys(this.fyo.schemaMap)) {
const schema = this.fyo.schemaMap[schemaName];
if (!schema?.keywordFields?.length || this.searchables[schemaName]) {
continue;
}
const fields = [...schema.keywordFields];
const meta = [];
if (schema.isChild) {
meta.push('parent', 'parentSchemaName');
}
if (schema.isSubmittable) {
meta.push('submitted', 'cancelled');
}
this.searchables[schemaName] = {
schemaName,
fields,
meta,
isChild: !!schema.isChild,
isSubmittable: !!schema.isSubmittable,
needsUpdate: true,
};
}
}
_setDocObservers() {
if (this._obsSet) {
return;
}
for (const { schemaName } of Object.values(this.searchables)) {
this.fyo.doc.observer.on(`sync:${schemaName}`, () => {
this.searchables[schemaName].needsUpdate = true;
});
this.fyo.doc.observer.on(`delete:${schemaName}`, () => {
this.searchables[schemaName].needsUpdate = true;
});
}
this._obsSet = true;
}
_setKeywords(maps: RawValueMap[], searchable: Searchable) {
if (!maps?.length) {
return;
}
this.keywords[searchable.schemaName] = [];
for (const map of maps) {
const keyword: Keyword = { values: [], meta: {}, priority: 0 };
this._setKeywordValues(map, searchable, keyword);
this._setMeta(map, searchable, keyword);
this.keywords[searchable.schemaName]!.push(keyword);
}
this._setPriority(searchable);
}
_setKeywordValues(
map: RawValueMap,
searchable: Searchable,
keyword: Keyword
) {
// Set individual field values
for (const fn of searchable.fields) {
let value = map[fn] as string | undefined;
const field = this.fyo.getField(searchable.schemaName, fn);
const { options } = field as OptionField;
if (options) {
value = options.find((o) => o.value === value)?.label ?? value;
}
keyword.values.push(value ?? '');
}
}
_setMeta(map: RawValueMap, searchable: Searchable, keyword: Keyword) {
// Set the meta map
for (const fn of searchable.meta) {
const meta = map[fn];
if (typeof meta === 'number') {
keyword.meta[fn] = Boolean(meta);
} else if (typeof meta === 'string') {
keyword.meta[fn] = meta;
}
}
keyword.meta.schemaName = searchable.schemaName;
if (keyword.meta.parent) {
keyword.values.unshift(keyword.meta.parent as string);
}
}
_setPriority(searchable: Searchable) {
const keywords = this.keywords[searchable.schemaName] ?? [];
const basePriority = this.priorityMap[searchable.schemaName] ?? 0;
for (const k of keywords) {
k.priority += basePriority;
if (k.meta.submitted) {
k.priority += 25;
}
if (k.meta.cancelled) {
k.priority -= 200;
}
if (searchable.isChild) {
k.priority -= 150;
}
}
}
}
function isSearchItem(item: SearchItem | Keyword): item is SearchItem {
return !!(item as SearchItem).group;
}
|
2302_79757062/books
|
src/utils/search.ts
|
TypeScript
|
agpl-3.0
| 22,934
|
import { Keys } from 'utils/types';
import { watch } from 'vue';
import { getIsMac } from './misc';
interface ModMap {
alt: boolean;
ctrl: boolean;
meta: boolean;
shift: boolean;
repeat: boolean;
}
type Mod = keyof ModMap;
type Context = unknown;
type ShortcutFunction = () => unknown;
type ShortcutConfig = {
callback: ShortcutFunction;
propagate: boolean;
};
type ShortcutMap = Map<Context, Map<string, ShortcutConfig>>;
const mods: Readonly<Mod[]> = ['alt', 'ctrl', 'meta', 'repeat', 'shift'];
/**
* Used to add shortcuts based on **context**.
*
* **Context** is a identifier for where the shortcut belongs. For instance
* a _Form_ component having shortcuts for _Submit Form_.
*
* In the above example an app can have multiple instances of the _Form_
* component active at the same time, so the passed context should be a
* unique identifier such as the component object.
*
* If only one instance of a component is meant to be active at a time
* (for example a _Sidebar_ component) then do not use objects, use some
* primitive datatype (`string`).
*/
export class Shortcuts {
keys: Keys;
isMac: boolean;
shortcuts: ShortcutMap;
modMap: Partial<Record<Mod, boolean>>;
keySet: Set<string>;
constructor(keys: Keys) {
this.modMap = {};
this.keySet = new Set();
this.keys = keys;
this.shortcuts = new Map();
this.isMac = getIsMac();
watch(this.keys, (keys) => {
const key = this.getKey(Array.from(keys.pressed), keys);
if (!key) {
return false;
}
if (!key || !this.keySet.has(key)) {
return;
}
this.#trigger(key);
});
}
#trigger(key: string) {
const configList = Array.from(this.shortcuts.keys())
.map((cxt) => this.shortcuts.get(cxt)?.get(key))
.filter(Boolean)
.reverse() as ShortcutConfig[];
for (const config of configList) {
config.callback();
if (!config.propagate) {
break;
}
}
}
/**
* Check if a context is present or if a shortcut
* is present in a context.
*
* @param context context in which the shortcut is to be checked
* @param shortcut shortcut that is to be checked
* @returns boolean indicating presence
*/
has(context: Context, shortcut?: string[]): boolean {
if (!shortcut) {
return this.shortcuts.has(context);
}
const contextualShortcuts = this.shortcuts.get(context);
if (!contextualShortcuts) {
return false;
}
const key = this.getKey(shortcut);
if (!key) {
return false;
}
return contextualShortcuts.has(key);
}
/**
* Assign a function to a shortcut in a given context.
*
* @param context context object to which the shortcut belongs
* @param shortcut keyboard event codes used as shortcut chord
* @param callback function to be called when the shortcut is pressed
* @param propagate whether to check and execute shortcuts in earlier contexts
* @param removeIfSet whether to delete the set shortcut
*/
set(
context: Context,
shortcut: string[],
callback: ShortcutFunction,
propagate = false,
removeIfSet = true
): void {
const key = this.getKey(shortcut);
if (!key) {
return;
}
let contextualShortcuts = this.shortcuts.get(context);
/**
* Maintain context order.
*/
if (!contextualShortcuts) {
contextualShortcuts = new Map();
} else {
this.shortcuts.delete(contextualShortcuts);
}
if (contextualShortcuts.has(key) && !removeIfSet) {
this.shortcuts.set(context, contextualShortcuts);
throw new Error(`Shortcut ${key} already exists.`);
}
this.keySet.add(key);
contextualShortcuts.set(key, { callback, propagate });
this.shortcuts.set(context, contextualShortcuts);
}
/**
* Either delete a single shortcut or all the shortcuts in
* a given context.
*
* @param context context from which the shortcut is to be removed
* @param shortcut shortcut that is to be deleted
* @returns boolean indicating success
*/
delete(context: Context, shortcut?: string[]): boolean {
if (!shortcut) {
return this.shortcuts.delete(context);
}
const contextualShortcuts = this.shortcuts.get(context);
if (!contextualShortcuts) {
return false;
}
const key = this.getKey(shortcut);
if (!key) {
return false;
}
return contextualShortcuts.delete(key);
}
/**
* Converts shortcuts list and modMap to a string to be
* used as a shortcut key.
*
* @param shortcut array of shortcut keys
* @param modMap boolean map of mod keys to be used
* @returns string to be used as the shortcut Map key
*/
getKey(shortcut: string[], modMap?: Partial<ModMap>): string | null {
const _modMap = modMap || this.modMap;
this.modMap = {};
const shortcutString = shortcut.sort().join('+');
const modString = mods.filter((k) => _modMap[k]).join('+');
if (shortcutString && modString) {
return modString + '+' + shortcutString;
}
if (!modString) {
return shortcutString;
}
if (!shortcutString) {
return modString;
}
return null;
}
/**
* Shortcut Modifiers
*/
get alt() {
this.modMap['alt'] = true;
return this;
}
get ctrl() {
this.modMap['ctrl'] = true;
return this;
}
get meta() {
this.modMap['meta'] = true;
return this;
}
get shift() {
this.modMap['shift'] = true;
return this;
}
get repeat() {
this.modMap['repeat'] = true;
return this;
}
get pmod() {
if (this.isMac) {
return this.meta;
}
return this.ctrl;
}
}
|
2302_79757062/books
|
src/utils/shortcuts.ts
|
TypeScript
|
agpl-3.0
| 5,689
|
import { t } from 'fyo';
import { routeFilters } from 'src/utils/filters';
import { fyo } from '../initFyo';
import { SidebarConfig, SidebarItem, SidebarRoot } from './types';
export function getSidebarConfig(): SidebarConfig {
const sideBar = getCompleteSidebar();
return getFilteredSidebar(sideBar);
}
function getFilteredSidebar(sideBar: SidebarConfig): SidebarConfig {
return sideBar.filter((root) => {
root.items = root.items?.filter((item) => {
if (item.hidden !== undefined) {
return !item.hidden();
}
return true;
});
if (root.hidden !== undefined) {
return !root.hidden();
}
return true;
});
}
function getRegionalSidebar(): SidebarRoot[] {
const hasGstin = !!fyo.singles?.AccountingSettings?.gstin;
if (!hasGstin) {
return [];
}
return [
{
label: t`GST`,
name: 'gst',
icon: 'gst',
route: '/report/GSTR1',
items: [
{
label: t`GSTR1`,
name: 'gstr1',
route: '/report/GSTR1',
},
{
label: t`GSTR2`,
name: 'gstr2',
route: '/report/GSTR2',
},
],
},
];
}
function getInventorySidebar(): SidebarRoot[] {
const hasInventory = !!fyo.singles.AccountingSettings?.enableInventory;
if (!hasInventory) {
return [];
}
return [
{
label: t`Inventory`,
name: 'inventory',
icon: 'inventory',
iconSize: '18',
route: '/list/StockMovement',
items: [
{
label: t`Stock Movement`,
name: 'stock-movement',
route: '/list/StockMovement',
schemaName: 'StockMovement',
},
{
label: t`Shipment`,
name: 'shipment',
route: '/list/Shipment',
schemaName: 'Shipment',
},
{
label: t`Purchase Receipt`,
name: 'purchase-receipt',
route: '/list/PurchaseReceipt',
schemaName: 'PurchaseReceipt',
},
{
label: t`Stock Ledger`,
name: 'stock-ledger',
route: '/report/StockLedger',
},
{
label: t`Stock Balance`,
name: 'stock-balance',
route: '/report/StockBalance',
},
],
},
];
}
function getPOSSidebar() {
const isPOSEnabled = !!fyo.singles.InventorySettings?.enablePointOfSale;
if (!isPOSEnabled) {
return [];
}
return {
label: t`POS`,
name: 'pos',
route: '/pos',
icon: 'pos',
};
}
function getReportSidebar() {
return {
label: t`Reports`,
name: 'reports',
icon: 'reports',
route: '/report/GeneralLedger',
items: [
{
label: t`General Ledger`,
name: 'general-ledger',
route: '/report/GeneralLedger',
},
{
label: t`Profit And Loss`,
name: 'profit-and-loss',
route: '/report/ProfitAndLoss',
},
{
label: t`Balance Sheet`,
name: 'balance-sheet',
route: '/report/BalanceSheet',
},
{
label: t`Trial Balance`,
name: 'trial-balance',
route: '/report/TrialBalance',
},
],
};
}
function getCompleteSidebar(): SidebarConfig {
return [
{
label: t`Get Started`,
name: 'get-started',
route: '/get-started',
icon: 'general',
iconSize: '24',
iconHeight: 5,
hidden: () => !!fyo.singles.SystemSettings?.hideGetStarted,
},
{
label: t`Dashboard`,
name: 'dashboard',
route: '/',
icon: 'dashboard',
},
{
label: t`Sales`,
name: 'sales',
icon: 'sales',
route: '/list/SalesInvoice',
items: [
{
label: t`Sales Quotes`,
name: 'sales-quotes',
route: '/list/SalesQuote',
schemaName: 'SalesQuote',
},
{
label: t`Sales Invoices`,
name: 'sales-invoices',
route: '/list/SalesInvoice',
schemaName: 'SalesInvoice',
},
{
label: t`Sales Payments`,
name: 'payments',
route: `/list/Payment/${t`Sales Payments`}`,
schemaName: 'Payment',
filters: routeFilters.SalesPayments,
},
{
label: t`Customers`,
name: 'customers',
route: `/list/Party/${t`Customers`}`,
schemaName: 'Party',
filters: routeFilters.Customers,
},
{
label: t`Sales Items`,
name: 'sales-items',
route: `/list/Item/${t`Sales Items`}`,
schemaName: 'Item',
filters: routeFilters.SalesItems,
},
{
label: t`Loyalty Program`,
name: 'loyalty-program',
route: '/list/LoyaltyProgram',
schemaName: 'LoyaltyProgram',
hidden: () => !fyo.singles.AccountingSettings?.enableLoyaltyProgram,
},
{
label: t`Lead`,
name: 'lead',
route: '/list/Lead',
schemaName: 'Lead',
hidden: () => !fyo.singles.AccountingSettings?.enableLead,
},
] as SidebarItem[],
},
{
label: t`Purchases`,
name: 'purchases',
icon: 'purchase',
route: '/list/PurchaseInvoice',
items: [
{
label: t`Purchase Invoices`,
name: 'purchase-invoices',
route: '/list/PurchaseInvoice',
schemaName: 'PurchaseInvoice',
},
{
label: t`Purchase Payments`,
name: 'payments',
route: `/list/Payment/${t`Purchase Payments`}`,
schemaName: 'Payment',
filters: routeFilters.PurchasePayments,
},
{
label: t`Suppliers`,
name: 'suppliers',
route: `/list/Party/${t`Suppliers`}`,
schemaName: 'Party',
filters: routeFilters.Suppliers,
},
{
label: t`Purchase Items`,
name: 'purchase-items',
route: `/list/Item/${t`Purchase Items`}`,
schemaName: 'Item',
filters: routeFilters.PurchaseItems,
},
] as SidebarItem[],
},
{
label: t`Common`,
name: 'common-entries',
icon: 'common-entries',
route: '/list/JournalEntry',
items: [
{
label: t`Journal Entry`,
name: 'journal-entry',
route: '/list/JournalEntry',
schemaName: 'JournalEntry',
},
{
label: t`Party`,
name: 'party',
route: '/list/Party',
schemaName: 'Party',
filters: { role: 'Both' },
},
{
label: t`Items`,
name: 'common-items',
route: `/list/Item/${t`Items`}`,
schemaName: 'Item',
filters: { for: 'Both' },
},
{
label: t`Price List`,
name: 'price-list',
route: '/list/PriceList',
schemaName: 'PriceList',
hidden: () => !fyo.singles.AccountingSettings?.enablePriceList,
},
{
label: t`Pricing Rule`,
name: 'pricing-rule',
route: '/list/PricingRule',
schemaName: 'PricingRule',
hidden: () => !fyo.singles.AccountingSettings?.enablePricingRule,
},
] as SidebarItem[],
},
getReportSidebar(),
getInventorySidebar(),
getPOSSidebar(),
getRegionalSidebar(),
{
label: t`Setup`,
name: 'setup',
icon: 'settings',
route: '/chart-of-accounts',
items: [
{
label: t`Chart of Accounts`,
name: 'chart-of-accounts',
route: '/chart-of-accounts',
},
{
label: t`Tax Templates`,
name: 'taxes',
route: '/list/Tax',
schemaName: 'Tax',
},
{
label: t`Import Wizard`,
name: 'import-wizard',
route: '/import-wizard',
},
{
label: t`Print Templates`,
name: 'print-template',
route: `/list/PrintTemplate/${t`Print Templates`}`,
},
{
label: t`Customize Form`,
name: 'customize-form',
// route: `/customize-form`,
route: `/list/CustomForm/${t`Customize Form`}`,
hidden: () =>
!fyo.singles.AccountingSettings?.enableFormCustomization,
},
{
label: t`Settings`,
name: 'settings',
route: '/settings',
},
] as SidebarItem[],
},
].flat();
}
|
2302_79757062/books
|
src/utils/sidebarConfig.ts
|
TypeScript
|
agpl-3.0
| 8,522
|
export function setDarkMode(darkMode: boolean): void {
if (darkMode) {
document.documentElement.classList.add(
'dark',
'custom-scroll',
'custom-scroll-thumb1'
);
return;
}
document.documentElement.classList.remove('dark');
}
|
2302_79757062/books
|
src/utils/theme.ts
|
TypeScript
|
agpl-3.0
| 261
|
import type { Doc } from 'fyo/model/doc';
import type { Action } from 'fyo/model/types';
import type { ModelNameEnum } from 'models/types';
import type { Field, FieldType } from 'schemas/types';
import type { QueryFilter } from 'utils/db/types';
import type { Ref } from 'vue';
import type { toastDurationMap } from './ui';
export type DocRef<D extends Doc = Doc> = Ref<D | null>;
export type ToastType = 'info' | 'warning' | 'error' | 'success';
export type ToastDuration = keyof typeof toastDurationMap;
export interface MessageDialogButton {
label: string;
action: () => Promise<unknown> | unknown;
}
export interface MessageDialogOptions {
message: string;
detail?: string;
buttons?: MessageDialogButton[];
}
export interface ToastOptions {
message: string;
type?: ToastType;
duration?: ToastDuration;
action?: () => void;
actionText?: string;
}
export type WindowAction = 'close' | 'minimize' | 'maximize' | 'unmaximize';
export type SettingsTab =
| ModelNameEnum.AccountingSettings
| ModelNameEnum.Defaults
| ModelNameEnum.PrintSettings
| ModelNameEnum.SystemSettings;
export interface QuickEditOptions {
doc: Doc;
hideFields?: string[];
showFields?: string[];
defaults?: Record<string, unknown>;
}
export type SidebarConfig = SidebarRoot[];
export interface SidebarRoot {
label: string;
name: string;
route: string;
icon: string;
iconSize?: string;
iconHeight?: number;
hidden?: () => boolean;
items?: SidebarItem[];
filters?: QueryFilter;
}
export interface SidebarItem {
label: string;
name: string;
route: string;
schemaName?: string;
hidden?: () => boolean;
filters?: QueryFilter;
}
export interface ExportField {
fieldname: string;
fieldtype: FieldType;
label: string;
export: boolean;
}
export interface ExportTableField {
fieldname: string;
label: string;
target: string;
fields: ExportField[];
}
export type ActionGroup = {
group: string;
label: string;
type: string;
actions: Action[];
};
export type DropdownItem = {
label: string;
value?: string;
action?: () => unknown;
group?: string;
component?: { template: string };
isGroup?: boolean;
};
export type UIGroupedFields = Map<string, Map<string, Field[]>>;
export type ExportFormat = 'csv' | 'json';
export type PeriodKey = 'This Year' | 'This Quarter' | 'This Month' | 'YTD';
export type PrintValues = {
print: Record<string, unknown>;
doc: Record<string, unknown>;
};
export interface DialogOptions {
title: string;
type?: ToastType;
detail?: string | string[];
buttons?: DialogButton[];
}
export type DialogButton = {
label: string;
action: () => unknown;
isPrimary?: boolean;
isEscape?: boolean;
};
export type GetStartedConfigItem = {
label: string;
items: {
key: string;
label: string;
icon: string;
description: string;
fieldname: string;
documentation?: string;
action?: () => void;
}[];
};
|
2302_79757062/books
|
src/utils/types.ts
|
TypeScript
|
agpl-3.0
| 2,942
|
/**
* Utils to do UI stuff such as opening dialogs, toasts, etc.
* Basically anything that may directly or indirectly import a Vue file.
*/
import { t } from 'fyo';
import type { Doc } from 'fyo/model/doc';
import { Action } from 'fyo/model/types';
import { getActions } from 'fyo/utils';
import {
BaseError,
getDbError,
LinkValidationError,
ValueError,
} from 'fyo/utils/errors';
import { Invoice } from 'models/baseModels/Invoice/Invoice';
import { PurchaseInvoice } from 'models/baseModels/PurchaseInvoice/PurchaseInvoice';
import { SalesInvoice } from 'models/baseModels/SalesInvoice/SalesInvoice';
import { getLedgerLink } from 'models/helpers';
import { Transfer } from 'models/inventory/Transfer';
import { Transactional } from 'models/Transactional/Transactional';
import { ModelNameEnum } from 'models/types';
import { Schema } from 'schemas/types';
import { handleErrorWithDialog } from 'src/errorHandling';
import { fyo } from 'src/initFyo';
import router from 'src/router';
import { assertIsType } from 'utils/index';
import { SelectFileOptions } from 'utils/types';
import { RouteLocationRaw } from 'vue-router';
import { evaluateHidden } from './doc';
import { showDialog, showToast } from './interactive';
import { showSidebar } from './refs';
import {
ActionGroup,
QuickEditOptions,
SettingsTab,
ToastOptions,
UIGroupedFields,
} from './types';
export const toastDurationMap = { short: 2_500, long: 5_000 } as const;
export async function openQuickEdit({
doc,
hideFields = [],
showFields = [],
}: QuickEditOptions) {
const { schemaName, name } = doc;
if (!name) {
throw new ValueError(t`Quick edit error: ${schemaName} entry has no name.`);
}
if (router.currentRoute.value.query.name === name) {
return;
}
const query = {
edit: 1,
name,
schemaName,
showFields,
hideFields,
};
await router.push({ query });
}
export async function openSettings(tab: SettingsTab) {
await routeTo({ path: '/settings', query: { tab } });
}
export async function routeTo(route: RouteLocationRaw) {
if (
typeof route === 'string' &&
route === router.currentRoute.value.fullPath
) {
return;
}
return await router.push(route);
}
export async function deleteDocWithPrompt(doc: Doc) {
const schemaLabel = fyo.schemaMap[doc.schemaName]!.label;
let detail = t`This action is permanent.`;
if (doc.isTransactional && doc.isSubmitted) {
detail = t`This action is permanent and will delete associated ledger entries.`;
}
return (await showDialog({
title: t`Delete ${getDocReferenceLabel(doc)}?`,
detail,
type: 'warning',
buttons: [
{
label: t`Yes`,
async action() {
try {
await doc.delete();
} catch (err) {
if (getDbError(err as Error) === LinkValidationError) {
await showDialog({
title: t`Delete Failed`,
detail: t`Cannot delete ${schemaLabel} "${doc.name!}" because of linked entries.`,
type: 'error',
});
} else {
await handleErrorWithDialog(err as Error, doc);
}
return false;
}
return true;
},
isPrimary: true,
},
{
label: t`No`,
action() {
return false;
},
isEscape: true,
},
],
})) as boolean;
}
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(
', '
)}`;
}
}
return (await showDialog({
title: t`Cancel ${getDocReferenceLabel(doc)}?`,
detail,
type: 'warning',
buttons: [
{
label: t`Yes`,
async action() {
try {
await doc.cancel();
} catch (err) {
await handleErrorWithDialog(err as Error, doc);
return false;
}
return true;
},
isPrimary: true,
},
{
label: t`No`,
action() {
return false;
},
isEscape: true,
},
],
})) as boolean;
}
export function getActionsForDoc(doc?: Doc): Action[] {
if (!doc) return [];
const actions: Action[] = [
...getActions(doc),
getDuplicateAction(doc),
getDeleteAction(doc),
getCancelAction(doc),
];
return actions
.filter((d) => d.condition?.(doc) ?? true)
.map((d) => {
return {
group: d.group,
label: d.label,
component: d.component,
action: d.action,
};
});
}
export function getGroupedActionsForDoc(doc?: Doc): ActionGroup[] {
const actions = getActionsForDoc(doc);
const actionsMap = actions.reduce((acc, ac) => {
if (!ac.group) {
ac.group = '';
}
acc[ac.group] ??= {
group: ac.group,
label: ac.label ?? '',
type: ac.type ?? 'secondary',
actions: [],
};
acc[ac.group].actions.push(ac);
return acc;
}, {} as Record<string, ActionGroup>);
const grouped = Object.keys(actionsMap)
.filter(Boolean)
.sort()
.map((k) => actionsMap[k]);
return [grouped, actionsMap['']].flat().filter(Boolean);
}
function getCancelAction(doc: Doc): Action {
return {
label: t`Cancel`,
component: {
template: '<span class="text-red-700">{{ t`Cancel` }}</span>',
},
condition: (doc: Doc) => doc.canCancel,
async action() {
await commonDocCancel(doc);
},
};
}
function getDeleteAction(doc: Doc): Action {
return {
label: t`Delete`,
component: {
template: '<span class="text-red-700">{{ t`Delete` }}</span>',
},
condition: (doc: Doc) => doc.canDelete,
async action() {
await commongDocDelete(doc);
},
};
}
async function openEdit({ name, schemaName }: Doc) {
if (!name) {
return;
}
const route = getFormRoute(schemaName, name);
return await routeTo(route);
}
function getDuplicateAction(doc: Doc): Action {
const isSubmittable = !!doc.schema.isSubmittable;
return {
label: t`Duplicate`,
group: t`Create`,
condition: (doc: Doc) =>
!!(
((isSubmittable && doc.submitted) || !isSubmittable) &&
!doc.notInserted
),
async action() {
try {
const dupe = doc.duplicate();
await openEdit(dupe);
} catch (err) {
await handleErrorWithDialog(err as Error, doc);
}
},
};
}
export function getFieldsGroupedByTabAndSection(
schema: Schema,
doc: Doc
): UIGroupedFields {
const grouped: UIGroupedFields = new Map();
for (const field of schema?.fields ?? []) {
const tab = field.tab ?? 'Main';
const section = field.section ?? 'Default';
if (!grouped.has(tab)) {
grouped.set(tab, new Map());
}
const tabbed = grouped.get(tab)!;
if (!tabbed.has(section)) {
tabbed.set(section, []);
}
if (field.meta) {
continue;
}
if (evaluateHidden(field, doc)) {
continue;
}
tabbed.get(section)!.push(field);
}
// Delete empty tabs and sections
for (const tkey of grouped.keys()) {
const section = grouped.get(tkey);
if (!section) {
grouped.delete(tkey);
continue;
}
for (const skey of section.keys()) {
const fields = section.get(skey);
if (!fields || !fields.length) {
section.delete(skey);
}
}
if (!section?.size) {
grouped.delete(tkey);
}
}
return grouped;
}
export function getFormRoute(
schemaName: string,
name: string
): RouteLocationRaw {
const route = fyo.models[schemaName]
?.getListViewSettings(fyo)
?.formRoute?.(name);
if (typeof route === 'string') {
return route;
}
// Use `encodeURIComponent` if more name issues
return `/edit/${schemaName}/${name.replaceAll('/', '%2F')}`;
}
export async function getDocFromNameIfExistsElseNew(
schemaName: string,
name?: string
) {
if (!name) {
return fyo.doc.getNewDoc(schemaName);
}
try {
return await fyo.doc.getDoc(schemaName, name);
} catch {
return fyo.doc.getNewDoc(schemaName);
}
}
export async function isPrintable(schemaName: string) {
const numTemplates = await fyo.db.count(ModelNameEnum.PrintTemplate, {
filters: { type: schemaName },
});
return numTemplates > 0;
}
export function toggleSidebar(value?: boolean) {
if (typeof value !== 'boolean') {
value = !showSidebar.value;
}
showSidebar.value = value;
}
export function focusOrSelectFormControl(
doc: Doc,
ref: unknown,
shouldClear = true
) {
if (!doc?.fyo) {
return;
}
const naming = doc.fyo.schemaMap[doc.schemaName]?.naming;
if (naming !== 'manual' || doc.inserted) {
return;
}
if (!doc.fyo.doc.isTemporaryName(doc.name ?? '', doc.schema)) {
return;
}
if (Array.isArray(ref) && ref.length > 0) {
ref = ref[0];
}
if (
!ref ||
typeof ref !== 'object' ||
!assertIsType<Record<string, () => void>>(ref)
) {
return;
}
if (!shouldClear && typeof ref?.select === 'function') {
ref.select();
return;
}
if (typeof ref?.clear === 'function') {
ref.clear();
}
if (typeof ref?.focus === 'function') {
ref.focus();
}
doc.name = '';
}
export async function selectTextFile(filters?: SelectFileOptions['filters']) {
const options = {
title: t`Select File`,
filters,
};
const { success, canceled, filePath, data, name } = await ipc.selectFile(
options
);
if (canceled || !success) {
showToast({
type: 'error',
message: t`File selection failed`,
});
return {};
}
const text = new TextDecoder().decode(data);
if (!text) {
showToast({
type: 'error',
message: t`Empty file selected`,
});
return {};
}
return { text, filePath, name };
}
export enum ShortcutKey {
enter = 'enter',
ctrl = 'ctrl',
pmod = 'pmod',
shift = 'shift',
alt = 'alt',
delete = 'delete',
esc = 'esc',
}
export function getShortcutKeyMap(
platform: string
): Record<ShortcutKey, string> {
if (platform === 'Mac') {
return {
[ShortcutKey.alt]: '⌥',
[ShortcutKey.ctrl]: '⌃',
[ShortcutKey.pmod]: '⌘',
[ShortcutKey.shift]: 'shift',
[ShortcutKey.delete]: 'delete',
[ShortcutKey.esc]: 'esc',
[ShortcutKey.enter]: 'return',
};
}
return {
[ShortcutKey.alt]: 'Alt',
[ShortcutKey.ctrl]: 'Ctrl',
[ShortcutKey.pmod]: 'Ctrl',
[ShortcutKey.shift]: '⇧',
[ShortcutKey.delete]: 'Backspace',
[ShortcutKey.esc]: 'Esc',
[ShortcutKey.enter]: 'Enter',
};
}
export async function commongDocDelete(
doc: Doc,
routeBack = true
): Promise<boolean> {
const res = await deleteDocWithPrompt(doc);
if (!res) {
return false;
}
showActionToast(doc, 'delete');
if (routeBack) {
router.back();
}
return true;
}
export async function commonDocCancel(doc: Doc): Promise<boolean> {
const res = await cancelDocWithPrompt(doc);
if (!res) {
return false;
}
showActionToast(doc, 'cancel');
return true;
}
export async function commonDocSync(
doc: Doc,
useDialog = false
): Promise<boolean> {
let success: boolean;
if (useDialog) {
success = !!(await showSubmitOrSyncDialog(doc, 'sync'));
} else {
success = await syncWithoutDialog(doc);
}
if (!success) {
return false;
}
showActionToast(doc, 'sync');
return true;
}
async function syncWithoutDialog(doc: Doc): Promise<boolean> {
try {
await doc.sync();
} catch (error) {
await handleErrorWithDialog(error, doc);
return false;
}
return true;
}
export async function commonDocSubmit(doc: Doc): Promise<boolean> {
let success = true;
if (
doc instanceof SalesInvoice &&
fyo.singles.AccountingSettings?.enableInventory
) {
success = await showInsufficientInventoryDialog(doc);
}
if (!success) {
return false;
}
success = await showSubmitOrSyncDialog(doc, 'submit');
if (!success) {
return false;
}
showSubmitToast(doc);
return true;
}
async function showInsufficientInventoryDialog(doc: SalesInvoice) {
const insufficient: { item: string; quantity: number }[] = [];
for (const { item, quantity, batch } of doc.items ?? []) {
if (!item || typeof quantity !== 'number') {
continue;
}
const isTracked = await fyo.getValue(ModelNameEnum.Item, item, 'trackItem');
if (!isTracked) {
continue;
}
const stockQuantity =
(await fyo.db.getStockQuantity(
item,
undefined,
undefined,
doc.date!.toISOString(),
batch
)) ?? 0;
if (stockQuantity > quantity) {
continue;
}
insufficient.push({ item, quantity: quantity - stockQuantity });
}
if (insufficient.length) {
const buttons = [
{
label: t`Yes`,
action: () => true,
isPrimary: true,
},
{
label: t`No`,
action: () => false,
isEscape: true,
},
];
const list = insufficient
.map(({ item, quantity }) => `${item} (${quantity})`)
.join(', ');
const detail = [
t`The following items have insufficient quantity for Shipment: ${list}`,
t`Continue submitting Sales Invoice?`,
];
return (await showDialog({
title: t`Insufficient Quantity`,
type: 'warning',
detail,
buttons,
})) as boolean;
}
return true;
}
async function showSubmitOrSyncDialog(doc: Doc, type: 'submit' | 'sync') {
const label = getDocReferenceLabel(doc);
let title = t`Save ${label}?`;
if (type === 'submit') {
title = t`Submit ${label}?`;
}
let detail: string;
if (type === 'submit') {
detail = getDocSubmitMessage(doc);
} else {
detail = getDocSyncMessage(doc);
}
const yesAction = async () => {
try {
await doc[type]();
} catch (error) {
await handleErrorWithDialog(error, doc);
return false;
}
return true;
};
const buttons = [
{
label: t`Yes`,
action: yesAction,
isPrimary: true,
},
{
label: t`No`,
action: () => false,
isEscape: true,
},
];
const dialogOptions = {
title,
detail,
buttons,
};
return (await showDialog(dialogOptions)) as boolean;
}
function getDocSyncMessage(doc: Doc): string {
const label = getDocReferenceLabel(doc);
const detail = t`Create new ${doc.schema.label} entry?`;
if (doc.inserted) {
return t`Save changes made to ${label}?`;
}
if (doc instanceof Invoice && doc.grandTotal?.isZero()) {
const gt = doc.fyo.format(doc.grandTotal ?? doc.fyo.pesa(0), 'Currency');
return [
detail,
t`Entry has Grand Total ${gt}. Please verify amounts.`,
].join(' ');
}
return detail;
}
function getDocSubmitMessage(doc: Doc): string {
const details = [t`Mark ${doc.schema.label} as submitted?`];
if (doc instanceof SalesInvoice && doc.makeAutoPayment) {
const toAccount = doc.autoPaymentAccount!;
const fromAccount = doc.account!;
const amount = fyo.format(doc.outstandingAmount, 'Currency');
details.push(
t`Payment of ${amount} will be made from account "${fromAccount}" to account "${toAccount}" on Submit.`
);
} else if (doc instanceof PurchaseInvoice && doc.makeAutoPayment) {
const fromAccount = doc.autoPaymentAccount!;
const toAccount = doc.account!;
const amount = fyo.format(doc.outstandingAmount, 'Currency');
details.push(
t`Payment of ${amount} will be made from account "${fromAccount}" to account "${toAccount}" on Submit.`
);
}
return details.join(' ');
}
function showActionToast(doc: Doc, type: 'sync' | 'cancel' | 'delete') {
const label = getDocReferenceLabel(doc);
const message = {
sync: t`${label} saved`,
cancel: t`${label} cancelled`,
delete: t`${label} deleted`,
}[type];
showToast({ type: 'success', message, duration: 'short' });
}
function showSubmitToast(doc: Doc) {
const label = getDocReferenceLabel(doc);
const message = t`${label} submitted`;
const toastOption: ToastOptions = {
type: 'success',
message,
duration: 'long',
...getSubmitSuccessToastAction(doc),
};
showToast(toastOption);
}
function getSubmitSuccessToastAction(doc: Doc) {
const isStockTransfer = doc instanceof Transfer;
const isTransactional = doc instanceof Transactional;
if (isStockTransfer) {
return {
async action() {
const route = getLedgerLink(doc, 'StockLedger');
await routeTo(route);
},
actionText: t`View Stock Entries`,
};
}
if (isTransactional) {
return {
async action() {
const route = getLedgerLink(doc, 'GeneralLedger');
await routeTo(route);
},
actionText: t`View Accounting Entries`,
};
}
return {};
}
export function showCannotSaveOrSubmitToast(doc: Doc) {
const label = getDocReferenceLabel(doc);
let message = t`${label} already saved`;
if (doc.schema.isSubmittable && doc.isSubmitted) {
message = t`${label} already submitted`;
}
showToast({ type: 'warning', message, duration: 'short' });
}
export function showCannotCancelOrDeleteToast(doc: Doc) {
const label = getDocReferenceLabel(doc);
let message = t`${label} cannot be deleted`;
if (doc.schema.isSubmittable && !doc.isCancelled) {
message = t`${label} cannot be cancelled`;
}
showToast({ type: 'warning', message, duration: 'short' });
}
function getDocReferenceLabel(doc: Doc) {
const label = doc.schema.label || doc.schemaName;
if (doc.schema.naming === 'random') {
return label;
}
return doc.name || label;
}
export const printSizes = [
'A0',
'A1',
'A2',
'A3',
'A4',
'A5',
'A6',
'A7',
'A8',
'A9',
'B0',
'B1',
'B2',
'B3',
'B4',
'B5',
'B6',
'B7',
'B8',
'B9',
'Letter',
'Legal',
'Executive',
'C5E',
'Comm10',
'DLE',
'Folio',
'Ledger',
'Tabloid',
'Custom',
] as const;
export const paperSizeMap: Record<
typeof printSizes[number],
{ width: number; height: number }
> = {
A0: {
width: 84.1,
height: 118.9,
},
A1: {
width: 59.4,
height: 84.1,
},
A2: {
width: 42,
height: 59.4,
},
A3: {
width: 29.7,
height: 42,
},
A4: {
width: 21,
height: 29.7,
},
A5: {
width: 14.8,
height: 21,
},
A6: {
width: 10.5,
height: 14.8,
},
A7: {
width: 7.4,
height: 10.5,
},
A8: {
width: 5.2,
height: 7.4,
},
A9: {
width: 3.7,
height: 5.2,
},
B0: {
width: 100,
height: 141.4,
},
B1: {
width: 70.7,
height: 100,
},
B2: {
width: 50,
height: 70.7,
},
B3: {
width: 35.3,
height: 50,
},
B4: {
width: 25,
height: 35.3,
},
B5: {
width: 17.6,
height: 25,
},
B6: {
width: 12.5,
height: 17.6,
},
B7: {
width: 8.8,
height: 12.5,
},
B8: {
width: 6.2,
height: 8.8,
},
B9: {
width: 4.4,
height: 6.2,
},
Letter: {
width: 21.59,
height: 27.94,
},
Legal: {
width: 21.59,
height: 35.56,
},
Executive: {
width: 19.05,
height: 25.4,
},
C5E: {
width: 16.3,
height: 22.9,
},
Comm10: {
width: 10.5,
height: 24.1,
},
DLE: {
width: 11,
height: 22,
},
Folio: {
width: 21,
height: 33,
},
Ledger: {
width: 43.2,
height: 27.9,
},
Tabloid: {
width: 27.9,
height: 43.2,
},
Custom: {
width: -1,
height: -1,
},
};
export function showExportInFolder(message: string, filePath: string) {
showToast({
message,
actionText: t`Open Folder`,
type: 'success',
action: () => {
ipc.showItemInFolder(filePath);
},
});
}
export async function deleteDb(filePath: string) {
const { error } = await ipc.deleteFile(filePath);
if (error?.code === 'EBUSY') {
await showDialog({
title: t`Delete Failed`,
detail: t`Please restart and try again.`,
type: 'error',
});
} else if (error?.code === 'ENOENT') {
await showDialog({
title: t`Delete Failed`,
detail: t`File ${filePath} does not exist.`,
type: 'error',
});
} else if (error?.code === 'EPERM') {
await showDialog({
title: t`Cannot Delete`,
detail: t`Close Frappe Books and try manually.`,
type: 'error',
});
} else if (error) {
const err = new BaseError(500, error.message);
err.name = error.name;
err.stack = error.stack;
throw err;
}
}
export async function getSelectedFilePath() {
return ipc.getOpenFilePath({
title: t`Select file`,
properties: ['openFile'],
filters: [{ name: 'SQLite DB File', extensions: ['db'] }],
});
}
export async function getSavePath(name: string, extention: string) {
const response = await ipc.getSaveFilePath({
title: t`Select folder`,
defaultPath: `${name}.${extention}`,
});
const canceled = response.canceled;
let filePath = response.filePath;
if (filePath && !filePath.endsWith(extention) && filePath !== ':memory:') {
filePath = `${filePath}.${extention}`;
}
return { canceled, filePath };
}
|
2302_79757062/books
|
src/utils/ui.ts
|
TypeScript
|
agpl-3.0
| 21,966
|
import { Keys } from 'utils/types';
import {
onActivated,
onDeactivated,
onMounted,
onUnmounted,
reactive,
ref,
} from 'vue';
import { getIsMac } from './misc';
import { Shortcuts } from './shortcuts';
import { DocRef } from './types';
import {
commonDocCancel,
commonDocSubmit,
commonDocSync,
commongDocDelete,
showCannotCancelOrDeleteToast,
showCannotSaveOrSubmitToast,
} from './ui';
export function useKeys() {
const isMac = getIsMac();
const keys: Keys = reactive({
pressed: new Set<string>(),
alt: false,
ctrl: false,
meta: false,
shift: false,
repeat: false,
});
const keydownListener = (e: KeyboardEvent) => {
const notMods = !(e.altKey || e.metaKey || e.ctrlKey);
if (e.target instanceof HTMLInputElement && notMods) {
return;
}
if (
e.target instanceof HTMLElement &&
e.target.contentEditable === 'true' &&
notMods
) {
return;
}
keys.alt = e.altKey;
keys.ctrl = e.ctrlKey;
keys.meta = e.metaKey;
keys.shift = e.shiftKey;
keys.repeat = e.repeat;
const { code } = e;
if (
code.startsWith('Alt') ||
code.startsWith('Control') ||
code.startsWith('Meta') ||
code.startsWith('Shift')
) {
return;
}
keys.pressed.add(code);
};
const keyupListener = (e: KeyboardEvent) => {
const { code } = e;
if (code.startsWith('Meta') && isMac) {
keys.alt = false;
keys.ctrl = false;
keys.meta = false;
keys.shift = false;
keys.repeat = false;
keys.pressed.clear();
return;
}
keys.pressed.delete(code);
};
onMounted(() => {
window.addEventListener('keydown', keydownListener);
window.addEventListener('keyup', keyupListener);
});
onUnmounted(() => {
window.removeEventListener('keydown', keydownListener);
window.removeEventListener('keyup', keyupListener);
});
return keys;
}
export function useMouseLocation() {
const loc = ref({ clientX: 0, clientY: 0 });
const mousemoveListener = (e: MouseEvent) => {
loc.value.clientX = e.clientX;
loc.value.clientY = e.clientY;
};
onMounted(() => {
window.addEventListener('mousemove', mousemoveListener);
});
onUnmounted(() => {
window.removeEventListener('mousemove', mousemoveListener);
});
return loc;
}
export function useDocShortcuts(
shortcuts: Shortcuts,
docRef: DocRef,
name: string,
isMultiple = true
) {
let context = name;
if (isMultiple) {
context = name + '-' + Math.random().toString(36).slice(2, 6);
}
const syncOrSubmitCallback = async () => {
const doc = docRef.value;
if (!doc) {
return;
}
if (doc.canSave) {
return await commonDocSync(doc, true);
}
if (doc.canSubmit) {
return await commonDocSubmit(doc);
}
showCannotSaveOrSubmitToast(doc);
};
const cancelOrDeleteCallback = async () => {
const doc = docRef.value;
if (!doc) {
return;
}
if (doc.canCancel) {
return await commonDocCancel(doc);
}
if (doc.canDelete) {
return await commongDocDelete(doc);
}
showCannotCancelOrDeleteToast(doc);
};
onMounted(() => {
if (isMultiple && shortcuts.has(context)) {
return;
}
shortcuts.pmod.set(context, ['KeyS'], syncOrSubmitCallback, false);
shortcuts.pmod.set(context, ['Backspace'], cancelOrDeleteCallback, false);
});
onActivated(() => {
if (isMultiple && shortcuts.has(context)) {
return;
}
shortcuts.pmod.set(context, ['KeyS'], syncOrSubmitCallback, false);
shortcuts.pmod.set(context, ['Backspace'], cancelOrDeleteCallback, false);
});
onDeactivated(() => {
if (!shortcuts.has(context)) {
return;
}
shortcuts.delete(context);
});
onUnmounted(() => {
if (!shortcuts.has(context)) {
return;
}
shortcuts.delete(context);
});
return context;
}
|
2302_79757062/books
|
src/utils/vueUtils.ts
|
TypeScript
|
agpl-3.0
| 3,944
|
const fs = require('fs');
const colors = JSON.parse(
fs.readFileSync('colors.json', { encoding: 'utf-8' })
);
module.exports = {
darkMode: 'class',
purge: false,
theme: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
},
screens: {
sm: '640px',
md: '768px',
lg: '1024px',
xl: '1280px',
},
fontSize: {
xs: '11px',
sm: '12px',
base: '13px',
lg: '14px',
xl: '18px',
'2xl': '20px',
'3xl': '24px',
'4xl': '28px',
},
extend: {
maxHeight: {
64: '16rem',
},
minWidth: {
40: '10rem',
56: '14rem',
},
maxWidth: {
32: '8rem',
56: '14rem',
},
spacing: {
7: '1.75rem',
14: '3.5rem',
18: '4.5rem',
28: '7rem',
72: '18rem',
80: '20rem',
},
boxShadow: {
'outline-px': '0 0 0 1px rgba(66, 153, 225, 0.5)',
DEFAULT: '0 2px 4px 0 rgba(0, 0, 0, 0.05)',
md: '0 0 2px 0 rgba(0, 0, 0, 0.10), 0 2px 4px 0 rgba(0, 0, 0, 0.08)',
button: '0 0.5px 0 0 rgba(0, 0, 0, 0.08)',
},
borderRadius: {
sm: '0.25rem', // 4px
DEFAULT: '0.313rem', // 5px
md: '0.375rem', // 6px
lg: '0.5rem', // 8px
xl: '0.75rem', // 12px
},
gridColumn: {
'span-full': '1 / -1',
},
colors,
},
},
variants: {
margin: ['responsive', 'first', 'last', 'hover', 'focus'],
backgroundColor: [
'responsive',
'first',
'hover',
'focus',
'focus-within',
'dark',
],
display: ['group-hover'],
borderWidth: ['last'],
fontWeight: ['dark'],
},
plugins: [require('tailwindcss-rtl')],
};
/*
* 208, 100, 50
* 209, 62, 50
*/
|
2302_79757062/books
|
tailwind.config.js
|
JavaScript
|
agpl-3.0
| 1,796
|
<main class="bg-white h-full px-6" :style="{ 'font-family': print.font }">
<!-- Invoice Header -->
<header class="py-6 flex text-sm text-gray-900 border-b">
<!-- Company Logo & Name -->
<section class="w-1/3">
<img
v-if="print.displayLogo"
class="h-12 max-w-32 object-contain"
:src="print.logo"
/>
<div class="text-xl text-gray-700 font-semibold" v-else>
{{ print.companyName }}
</div>
</section>
<!-- Company Contacts -->
<section class="w-1/3">
<div>{{ print.email }}</div>
<div class="mt-1">{{ print.phone }}</div>
</section>
<!-- Company Address & GSTIN -->
<section class="w-1/3">
<div v-if="print.address">{{ print.links.address.addressDisplay }}</div>
<div v-if="print.gstin">GSTIN: {{ print.gstin }}</div>
</section>
</header>
<!-- Sub Heading Section -->
<section class="mt-8 flex justify-between">
<!-- Invoice Details -->
<section class="w-1/3">
<h2 class="text-2xl font-semibold">{{ doc.name }}</h2>
<p class="py-2 text-base">{{ doc.date }}</p>
</section>
<!-- Party Details -->
<section class="w-1/3" v-if="doc.party">
<h2 class="py-1 text-right text-lg font-semibold">{{ doc.party }}</h2>
<p
v-if="doc.links.party.address"
class="mt-1 text-xs text-gray-600 text-right"
>
{{ doc.links.party.links.address.addressDisplay }}
</p>
<p
v-if="doc.links.party.gstin"
class="mt-1 text-xs text-gray-600 text-right"
>
GSTIN: {{ doc.partyGSTIN }}
</p>
</section>
</section>
<!-- Items Table -->
<section class="mt-8 text-base">
<!-- Heading Row -->
<section class="text-gray-600 w-full flex border-b">
<div class="py-4 w-5/12">{{ t`Item` }}</div>
<div class="py-4 text-right w-2/12" v-if="doc.showHSN">
{{ t`HSN/SAC` }}
</div>
<div class="py-4 text-right w-1/12">{{ t`Quantity` }}</div>
<div class="py-4 text-right w-3/12">{{ t`Rate` }}</div>
<div class="py-4 text-right w-3/12">{{ t`Amount` }}</div>
</section>
<!-- Body Rows -->
<section
class="flex py-1 text-gray-900 w-full border-b"
v-for="row in doc.items"
:key="row.name"
>
<div class="w-5/12 py-4">{{ row.item }}</div>
<div class="w-2/12 text-right py-4" v-if="doc.showHSN">
{{ row.hsnCode }}
</div>
<div class="w-1/12 text-right py-4">{{ row.quantity }}</div>
<div class="w-3/12 text-right py-4">{{ row.rate }}</div>
<div class="w-3/12 text-right py-4">{{ row.amount }}</div>
</section>
</section>
<!-- Invoice Footer -->
<footer class="mt-8 flex justify-end text-base">
<!-- Invoice Terms -->
<section class="w-1/2">
<h3 class="text-sm tracking-widest text-gray-600 mt-2" v-if="doc.terms">
{{ t`Notes` }}
</h3>
<p class="my-4 text-lg whitespace-pre-line">{{ doc.terms }}</p>
</section>
<!-- Totaled Amounts -->
<section class="w-1/2">
<!-- Subtotal -->
<div class="flex pl-2 justify-between py-3 border-b">
<h3>{{ t`Subtotal` }}</h3>
<p>{{ doc.netTotal }}</p>
</div>
<!-- Discount (if applied before tax) -->
<div
class="flex pl-2 justify-between py-3 border-b"
v-if="doc.totalDiscount && !doc.discountAfterTax"
>
<h3>{{ t`Discount` }}</h3>
<p>{{ doc.totalDiscount }}</p>
</div>
<!-- Tax Breakdown -->
<div
class="flex pl-2 justify-between py-3"
v-for="tax in doc.taxes"
:key="tax.name"
>
<h3>{{ tax.account }}</h3>
<p>{{ tax.amount }}</p>
</div>
<!-- Discount (if applied after tax) -->
<div
class="flex pl-2 justify-between py-3 border-t"
v-if="doc.totalDiscount && doc.discountAfterTax"
>
<h3>{{ t`Discount` }}</h3>
<p>{{ doc.totalDiscount }}</p>
</div>
<!-- Grand Total -->
<div
class="
flex
pl-2
justify-between
py-3
border-t
text-green-600
font-semibold
text-base
"
>
<h3>{{ t`Grand Total` }}</h3>
<p>{{ doc.grandTotal }}</p>
</div>
</section>
</footer>
</main>
|
2302_79757062/books
|
templates/Basic.template.html
|
HTML
|
agpl-3.0
| 4,338
|
<main class="bg-white h-full" :style="{ 'font-family': print.font }">
<!-- Invoice Header -->
<header class="bg-gray-100 px-12 py-10">
<!-- Company Details -->
<section class="flex items-center">
<img
v-if="print.displayLogo"
class="h-12 max-w-32 object-contain mr-4"
:src="print.logo"
/>
<div>
<p class="font-semibold text-xl" :style="{ color: print.color }">
{{ print.companyName }}
</p>
<p class="text-sm text-gray-800" v-if="print.address">
{{ print.links.address.addressDisplay }}
</p>
<p class="text-sm text-gray-800" v-if="print.gstin">
GSTIN: {{ print.gstin }}
</p>
</div>
</section>
<!-- Sub Heading Section -->
<div class="mt-8 text-lg">
<!-- Doc Details -->
<section class="flex">
<h3 class="w-1/3 font-semibold">
{{ doc.entryType === 'SalesInvoice' ? 'Invoice' : 'Bill' }}
</h3>
<div class="w-2/3 text-gray-800">
<p class="font-semibold">{{ doc.name }}</p>
<p>{{ doc.date }}</p>
</div>
</section>
<!-- Party Details -->
<section class="mt-4 flex">
<h3 class="w-1/3 font-semibold">
{{ doc.entryType === 'SalesInvoice' ? 'Customer' : 'Supplier' }}
</h3>
<div class="w-2/3 text-gray-800" v-if="doc.party">
<p class="font-semibold">{{ doc.party }}</p>
<p v-if="doc.links.party.address">
{{ doc.links.party.links.address.addressDisplay }}
</p>
<p v-if="doc.links.party.gstin">GSTIN: {{ doc.links.party.gstin }}</p>
</div>
</section>
</div>
</header>
<!-- Items Table -->
<section class="px-12 pt-12 text-lg">
<!-- Heading Row -->
<section class="mb-4 flex font-semibold">
<div class="w-4/12">{{ t`Item` }}</div>
<div class="w-2/12 text-right" v-if="doc.showHSN">{{ t`HSN/SAC` }}</div>
<div class="w-2/12 text-right">{{ t`Quantity` }}</div>
<div class="w-3/12 text-right">{{ t`Rate` }}</div>
<div class="w-3/12 text-right">{{ t`Amount` }}</div>
</section>
<!-- Body Rows -->
<section
class="flex py-1 text-gray-800"
v-for="row in doc.items"
:key="row.name"
>
<div class="w-4/12">{{ row.item }}</div>
<div class="w-2/12 text-right" v-if="doc.showHSN">{{ row.hsnCode }}</div>
<div class="w-2/12 text-right">{{ row.quantity }}</div>
<div class="w-3/12 text-right">{{ row.rate }}</div>
<div class="w-3/12 text-right">{{ row.amount }}</div>
</section>
</section>
<!-- Invoice Footer -->
<footer class="px-12 py-12 text-lg">
<!-- Totaled Amounts -->
<section class="flex -mx-3 justify-end flex-1 bg-gray-100 gap-8">
<!-- Subtotal -->
<div class="text-right py-3">
<h3 class="text-gray-800">{{ t`Subtotal` }}</h3>
<p class="text-xl mt-2">{{ doc.netTotal }}</p>
</div>
<!-- Discount (if applied before tax) -->
<div
class="text-right py-3"
v-if="doc.totalDiscount && !doc.discountAfterTax"
>
<h3 class="text-gray-800">{{ t`Discount` }}</h3>
<p class="text-xl mt-2">{{ doc.totalDiscount }}</p>
</div>
<!-- Tax Breakdown -->
<div class="text-right py-3" v-for="tax in doc.taxes" :key="tax.name">
<h3 class="text-gray-800">{{ tax.account }}</h3>
<p class="text-xl mt-2">{{ tax.amount }}</p>
</div>
<!-- Discount (if applied after tax) -->
<div
class="text-right py-3"
v-if="doc.totalDiscount && doc.discountAfterTax"
>
<h3 class="text-gray-800">{{ t`Discount` }}</h3>
<p class="text-xl mt-2">{{ doc.totalDiscount }}</p>
</div>
<!-- Grand Total -->
<div
class="py-3 px-4 text-right text-white"
:style="{ backgroundColor: print.color }"
>
<h3>{{ t`Grand Total` }}</h3>
<p class="text-2xl mt-2 font-semibold">{{ doc.grandTotal }}</p>
</div>
</section>
<!-- Invoice Terms -->
<section class="mt-12" v-if="doc.terms">
<h3 class="text-lg font-semibold">Notes</h3>
<p class="mt-4 text-lg whitespace-pre-line">{{ doc.terms }}</p>
</section>
</footer>
</main>
|
2302_79757062/books
|
templates/Business.template.html
|
HTML
|
agpl-3.0
| 4,296
|
<main class="h-full" :style="{ 'font-family': print.font }">
<!-- Invoice Header -->
<header class="flex items-center justify-between w-full border-b px-12 py-10">
<!-- Left Section -->
<section class="flex items-center">
<img
v-if="print.displayLogo"
class="h-12 max-w-32 object-contain mr-4"
:src="print.logo"
/>
<div>
<p class="font-semibold text-xl" :style="{ color: print.color }">
{{ print.companyName }}
</p>
<p>{{ doc.date }}</p>
</div>
</section>
<!-- Right Section -->
<section class="text-right">
<p class="font-semibold text-xl" :style="{ color: print.color }">
{{ doc.entryLabel }}
</p>
<p>{{ doc.name }}</p>
</section>
</header>
<!-- Party && Company Details -->
<section class="flex px-12 py-10 border-b">
<!-- Party Details -->
<section class="w-1/2">
<h3 class="uppercase text-sm font-semibold tracking-widest text-gray-800">
{{ doc.entryType === 'SalesInvoice' ? 'To' : 'From' }}
</h3>
<p class="mt-4 text-black leading-relaxed text-lg">{{ doc.party }}</p>
<p
v-if="doc.links.party.address"
class="mt-2 text-black leading-relaxed text-lg"
>
{{ doc.links.party.links.address.addressDisplay ?? '' }}
</p>
<p
v-if="doc.links.party.gstin"
class="mt-2 text-black leading-relaxed text-lg"
>
GSTIN: {{ doc.links.party.gstin }}
</p>
</section>
<!-- Company Details -->
<section class="w-1/2">
<h3
class="
uppercase
text-sm
font-semibold
tracking-widest
text-gray-800
ml-8
"
>
{{ doc.entryType === 'SalesInvoice' ? 'From' : 'To' }}
</h3>
<p class="mt-4 ml-8 text-black leading-relaxed text-lg">
{{ print.companyName }}
</p>
<p
v-if="print.address"
class="mt-2 ml-8 text-black leading-relaxed text-lg"
>
{{ print.links.address.addressDisplay }}
</p>
<p
v-if="print.gstin"
class="mt-2 ml-8 text-black leading-relaxed text-lg"
>
GSTIN: {{ print.gstin }}
</p>
</section>
</section>
<!-- Items Table -->
<section class="px-12 py-10 border-b">
<!-- Heading Row -->
<section
class="
mb-4
flex
uppercase
text-sm
tracking-widest
font-semibold
text-gray-800
"
>
<div class="w-4/12 text-left">{{ t`Item` }}</div>
<div class="w-2/12 text-right" v-if="doc.showHSN">{{ t`HSN/SAC` }}</div>
<div class="w-2/12 text-right">{{ t`Quantity` }}</div>
<div class="w-3/12 text-right">{{ t`Rate` }}</div>
<div class="w-3/12 text-right">{{ t`Amount`}}</div>
</section>
<!-- Body Rows -->
<section class="flex py-1 text-lg" v-for="row in doc.items" :key="row.name">
<div class="w-4/12 text-left">{{ row.item }}</div>
<div class="w-2/12 text-right" v-if="doc.showHSN">{{ row.hsnCode }}</div>
<div class="w-2/12 text-right">{{ row.quantity }}</div>
<div class="w-3/12 text-right">{{ row.rate }}</div>
<div class="w-3/12 text-right">{{ row.amount }}</div>
</section>
</section>
<!-- Invoice Footer -->
<footer class="flex px-12 py-10">
<!-- Invoice Terms -->
<section class="w-1/2" v-if="doc.terms">
<h3 class="uppercase text-sm tracking-widest font-semibold text-gray-800">
{{ t`Notes` }}
</h3>
<p class="mt-4 text-lg whitespace-pre-line">{{ doc.terms }}</p>
</section>
<!-- Totaled Amounts -->
<section class="w-1/2 text-lg ml-auto">
<!-- Subtotal -->
<div class="flex pl-2 justify-between py-1">
<h3>{{ t`Subtotal` }}</h3>
<p>{{ doc.netTotal }}</p>
</div>
<!-- Discount (if applied before tax) -->
<div
class="flex pl-2 justify-between py-1"
v-if="doc.totalDiscount && !doc.discountAfterTax"
>
<h3>{{ t`Discount` }}</h3>
<p>{{ doc.totalDiscount }}</p>
</div>
<!-- Tax Breakdown -->
<div
class="flex pl-2 justify-between py-1"
v-for="tax in doc.taxes"
:key="tax.name"
>
<h3>{{ tax.account }}</h3>
<p>{{ tax.amount }}</p>
</div>
<!-- Discount (if applied after tax) -->
<div
class="flex pl-2 justify-between py-1"
v-if="doc.totalDiscount && doc.discountAfterTax"
>
<h3>{{ t`Discount` }}</h3>
<p>{{ doc.totalDiscount }}</p>
</div>
<!-- Grand Total -->
<div
class="flex pl-2 justify-between py-1 font-semibold"
:style="{ color: print.color }"
>
<h3>{{ t`Grand Total` }}</h3>
<p>{{ doc.grandTotal }}</p>
</div>
</section>
</footer>
</main>
|
2302_79757062/books
|
templates/Minimal.template.html
|
HTML
|
agpl-3.0
| 4,898
|
import { DatabaseManager } from 'backend/database/manager';
import { config } from 'dotenv';
import { Fyo } from 'fyo';
import { DummyAuthDemux } from 'fyo/tests/helpers';
import { DateTime } from 'luxon';
import path from 'path';
import setupInstance from 'src/setup/setupInstance';
import { SetupWizardOptions } from 'src/setup/types';
import test from 'tape';
import { getFiscalYear } from 'utils/misc';
export function getTestSetupWizardOptions(): SetupWizardOptions {
return {
logo: null,
companyName: 'Test Company',
country: 'India',
fullname: 'Test Person',
email: 'test@testmyfantasy.com',
bankName: 'Test Bank of Scriptia',
currency: 'INR',
fiscalYearStart: DateTime.fromJSDate(
getFiscalYear('04-01', true)!
).toISODate(),
fiscalYearEnd: DateTime.fromJSDate(
getFiscalYear('04-01', false)!
).toISODate(),
chartOfAccounts: 'India - Chart of Accounts',
};
}
export function getTestDbPath(dbPath?: string) {
config();
return dbPath ?? process.env.TEST_DB_PATH ?? ':memory:';
}
/**
* Test Boilerplate
*
* The bottom three functions are test boilerplate for when
* an initialized fyo object is to be used.
*
* They are required because top level await is not supported.
*
* Therefore setup and cleanup of the fyo object is wrapped
* in tests which are executed serially (and awaited in order)
* by tape.
*
* If `closeTestFyo` is not called the test process won't exit.
*/
export function getTestFyo(): Fyo {
return new Fyo({
DatabaseDemux: DatabaseManager,
AuthDemux: DummyAuthDemux,
isTest: true,
isElectron: false,
});
}
const ext = '.spec.ts';
/* eslint-disable @typescript-eslint/no-misused-promises */
export function setupTestFyo(fyo: Fyo, filename: string) {
const testName = path.basename(filename, ext);
return test(`setup: ${testName}`, async () => {
const options = getTestSetupWizardOptions();
const dbPath = getTestDbPath();
await setupInstance(dbPath, options, fyo);
});
}
export function closeTestFyo(fyo: Fyo, filename: string) {
const testName = path.basename(filename, ext);
return test(`cleanup: ${testName}`, async () => {
await fyo.close();
});
}
|
2302_79757062/books
|
tests/helpers.ts
|
TypeScript
|
agpl-3.0
| 2,213
|
import path from 'path';
import { _electron } from 'playwright';
import { fileURLToPath } from 'url';
import test from 'tape';
const dirname = path.dirname(fileURLToPath(import.meta.url));
const root = path.join(dirname, '..');
const appSourcePath = path.join(root, 'dist_electron', 'build', 'main.js');
(async function run() {
const electronApp = await _electron.launch({ args: [appSourcePath] });
const window = await electronApp.firstWindow();
window.setDefaultTimeout(60_000);
test('load app', async (t) => {
t.equal(await window.title(), 'Frappe Books', 'title matches');
await new Promise((r) => window.once('load', () => r()));
t.ok(true, 'window has loaded');
});
test('navigate to database selector', async (t) => {
/**
* When running on local, Frappe Books will open
* the last selected database.
*/
const changeDb = window.getByTestId('change-db');
const createNew = window.getByTestId('create-new-file');
const changeDbPromise = changeDb
.waitFor({ state: 'visible' })
.then(() => 'change-db');
const createNewPromise = createNew
.waitFor({ state: 'visible' })
.then(() => 'create-new-file');
const el = await Promise.race([changeDbPromise, createNewPromise]);
if (el === 'change-db') {
await changeDb.click();
await createNewPromise;
}
t.ok(await createNew.isVisible(), 'create new is visible');
});
test('fill setup form', async (t) => {
await window.getByTestId('create-new-file').click();
await window.getByTestId('submit-button').waitFor();
t.equal(
await window.getByTestId('submit-button').isDisabled(),
true,
'submit button is disabled before form fill'
);
await window.getByPlaceholder('Company Name').fill('Test Company');
await window.getByPlaceholder('John Doe').fill('Test Owner');
await window.getByPlaceholder('john@doe.com').fill('test@example.com');
await window.getByPlaceholder('Select Country').fill('India');
await window.getByPlaceholder('Select Country').blur();
await window.getByPlaceholder('Prime Bank').fill('Test Bank');
await window.getByPlaceholder('Prime Bank').blur();
t.equal(
await window.getByTestId('submit-button').isDisabled(),
false,
'submit button enabled after form fill'
);
});
test('create new instance', async (t) => {
await window.getByTestId('submit-button').click();
t.equal(
await window.getByTestId('company-name').innerText(),
'Test Company',
'new instance created, company name found in sidebar'
);
});
test('close app', async (t) => {
await electronApp.close();
t.ok(true, 'app closed without errors');
});
})();
|
2302_79757062/books
|
uitest/index.mjs
|
JavaScript
|
agpl-3.0
| 2,742
|
import { Creds } from 'utils/types';
export abstract class AuthDemuxBase {
abstract getCreds(): Promise<Creds>;
}
|
2302_79757062/books
|
utils/auth/types.ts
|
TypeScript
|
agpl-3.0
| 117
|
import Store from 'electron-store';
import type { ConfigMap } from 'fyo/core/types';
const config = new Store<ConfigMap>();
export default config;
|
2302_79757062/books
|
utils/config.ts
|
TypeScript
|
agpl-3.0
| 148
|
export function parseCSV(text: string): string[][] {
// Works on RFC 4180 csv
let rows = splitCsvBlock(text);
if (rows.length === 1) {
rows = splitCsvBlock(text, '\n');
}
return rows.map(splitCsvLine);
}
export function generateCSV(matrix: unknown[][]): string {
// Generates RFC 4180 csv
const formattedRows = getFormattedRows(matrix);
return formattedRows.join('\r\n');
}
function splitCsvBlock(text: string, splitter = '\r\n'): string[] {
if (!text.endsWith(splitter)) {
text += splitter;
}
const lines = [];
let line = '';
let inDq = false;
for (let i = 0; i <= text.length; i++) {
const c = text[i];
if (
c === '"' &&
((c[i + 1] === '"' && c[i + 2] === '"') || c[i + 1] !== '"')
) {
inDq = !inDq;
}
const isEnd = [...splitter]
.slice(1)
.map((s, j) => text[i + j + 1] === s)
.every(Boolean);
if (!inDq && c === splitter[0] && isEnd) {
lines.push(line);
line = '';
i = i + splitter.length - 1;
continue;
}
line += c;
}
return lines;
}
export function splitCsvLine(line: string): string[] {
line += ',';
const items = [];
let item = '';
let inDq = false;
for (let i = 0; i < line.length; i++) {
const c = line[i];
if (
c === '"' &&
((c[i + 1] === '"' && c[i + 2] === '"') || c[i + 1] !== '"')
) {
inDq = !inDq;
}
if (!inDq && c === ',') {
item = unwrapDq(item);
item = item.replaceAll('""', '"');
items.push(item);
item = '';
continue;
}
item += c;
}
return items;
}
function unwrapDq(item: string): string {
const s = item.at(0);
const e = item.at(-1);
if (s === '"' && e === '"') {
return item.slice(1, -1);
}
return item;
}
function getFormattedRows(matrix: unknown[][]): string[] {
const formattedMatrix: string[] = [];
for (const row of matrix) {
const formattedRow: string[] = [];
for (const item of row) {
const formattedItem = getFormattedItem(item);
formattedRow.push(formattedItem);
}
formattedMatrix.push(formattedRow.join(','));
}
return formattedMatrix;
}
function getFormattedItem(item: unknown): string {
if (typeof item === 'string') {
return formatStringToCSV(item);
}
if (item === null || item === undefined) {
return '';
}
if (typeof item === 'object') {
return item.toString();
}
return String(item);
}
function formatStringToCSV(item: string): string {
let shouldDq = false;
if (item.match(/^".*"$/)) {
shouldDq = true;
item = item.slice(1, -1);
}
if (item.match(/"/)) {
shouldDq = true;
item = item.replaceAll('"', '""');
}
if (item.match(/,|\s/)) {
shouldDq = true;
}
if (shouldDq) {
return '"' + item + '"';
}
return item;
}
|
2302_79757062/books
|
utils/csvParser.ts
|
TypeScript
|
agpl-3.0
| 2,823
|
/**
* The types in this file will be used by the main db class (core.ts) in the
* backend process and the the frontend db class (dbHandler.ts).
*
* DatabaseBase is an abstract class so that the function signatures
* match on both ends i.e. DatabaseCore and DatabaseHandler.
*/
import { SchemaMap } from 'schemas/types';
type UnknownMap = Record<string, unknown>;
export abstract class DatabaseBase {
// Create
abstract insert(
schemaName: string,
fieldValueMap: UnknownMap
): Promise<UnknownMap>;
// Read
abstract get(
schemaName: string,
name: string,
fields?: string | string[]
): Promise<UnknownMap>;
abstract getAll(
schemaName: string,
options: GetAllOptions
): Promise<UnknownMap[]>;
abstract getSingleValues(
...fieldnames: ({ fieldname: string; parent?: string } | string)[]
): Promise<{ fieldname: string; parent: string; value: unknown }[]>;
// Update
abstract rename(
schemaName: string,
oldName: string,
newName: string
): Promise<void>;
abstract update(schemaName: string, fieldValueMap: UnknownMap): Promise<void>;
// Delete
abstract delete(schemaName: string, name: string): Promise<void>;
abstract deleteAll(schemaName:string, filters:QueryFilter): Promise<number>;
// Other
abstract close(): Promise<void>;
abstract exists(schemaName: string, name?: string): Promise<boolean>;
}
export type DatabaseMethod = keyof DatabaseBase;
export interface GetAllOptions {
fields?: string[];
filters?: QueryFilter;
offset?: number;
limit?: number;
groupBy?: string | string[];
orderBy?: string | string[];
order?: 'asc' | 'desc';
}
export type QueryFilter = Record<
string,
boolean | string | null | (string | number | (string | number | null)[])[]
>;
/**
* DatabaseDemuxBase is an abstract class that ensures that the function signatures
* match between the DatabaseManager and the DatabaseDemux.
*
* This allows testing the frontend code while directly plugging in the DatabaseManager
* and bypassing all the API and IPC calls.
*/
export abstract class DatabaseDemuxBase {
abstract getSchemaMap(): Promise<SchemaMap> | SchemaMap;
abstract createNewDatabase(
dbPath: string,
countryCode: string
): Promise<string>;
abstract connectToDatabase(
dbPath: string,
countryCode?: string
): Promise<string>;
abstract call(method: DatabaseMethod, ...args: unknown[]): Promise<unknown>;
abstract callBespoke(method: string, ...args: unknown[]): Promise<unknown>;
}
// Return types of Bespoke Queries
export type TopExpenses = { account: string; total: number }[];
export type TotalOutstanding = { total: number; outstanding: number };
export type Cashflow = { inflow: number; outflow: number; yearmonth: string }[];
export type Balance = { balance: number; yearmonth: string }[];
export type IncomeExpense = { income: Balance; expense: Balance };
export type TotalCreditAndDebit = {
account: string;
totalCredit: number;
totalDebit: number;
};
|
2302_79757062/books
|
utils/db/types.ts
|
TypeScript
|
agpl-3.0
| 3,011
|
import { Fyo } from 'fyo';
export function getDefaultUOMs(fyo: Fyo) {
return [
{
name: fyo.t`Unit`,
isWhole: true,
},
{
name: fyo.t`Kg`,
isWhole: false,
},
{
name: fyo.t`Gram`,
isWhole: false,
},
{
name: fyo.t`Meter`,
isWhole: false,
},
{
name: fyo.t`Hour`,
isWhole: false,
},
{
name: fyo.t`Day`,
isWhole: false,
},
];
}
export function getDefaultLocations(fyo: Fyo) {
return [{ name: fyo.t`Stores` }];
}
|
2302_79757062/books
|
utils/defaults.ts
|
TypeScript
|
agpl-3.0
| 533
|
import type { Fyo } from 'fyo';
import { Money } from 'pesa';
/**
* And so should not contain and platforma specific imports.
*/
export function getValueMapFromList<T, K extends keyof T, V extends keyof T>(
list: T[],
key: K,
valueKey: V,
filterUndefined = true
): Record<string, T[V]> {
if (filterUndefined) {
list = list.filter(
(f) =>
(f[valueKey] as unknown) !== undefined &&
(f[key] as unknown) !== undefined
);
}
return list.reduce((acc, f) => {
const keyValue = String(f[key]);
const value = f[valueKey];
acc[keyValue] = value;
return acc;
}, {} as Record<string, T[V]>);
}
export function getRandomString(): string {
const randomNumber = Math.random().toString(36).slice(2, 8);
const currentTime = Date.now().toString(36);
return `${randomNumber}-${currentTime}`;
}
export async function sleep(durationMilliseconds = 1000) {
return new Promise((r) => setTimeout(() => r(null), durationMilliseconds));
}
export function getMapFromList<T, K extends keyof T>(
list: T[],
name: K
): Record<string, T> {
/**
* Do not convert function to use copies of T
* instead of references.
*/
const acc: Record<string, T> = {};
for (const t of list) {
const key = t[name];
if (key === undefined) {
continue;
}
acc[String(key)] = t;
}
return acc;
}
export function getDefaultMapFromList<T, K extends keyof T, D>(
list: T[] | string[],
defaultValue: D,
name?: K
): Record<string, D> {
const acc: Record<string, D> = {};
if (typeof list[0] === 'string') {
for (const l of list as string[]) {
acc[l] = defaultValue;
}
return acc;
}
if (!name) {
return {};
}
for (const l of list as T[]) {
const key = String(l[name]);
acc[key] = defaultValue;
}
return acc;
}
export function getListFromMap<T>(map: Record<string, T>): T[] {
return Object.keys(map).map((n) => map[n]);
}
export function getIsNullOrUndef(value: unknown): value is null | undefined {
return value === null || value === undefined;
}
export function titleCase(phrase: string): string {
return phrase
.split(' ')
.map((word) => {
const wordLower = word.toLowerCase();
if (['and', 'an', 'a', 'from', 'by', 'on'].includes(wordLower)) {
return wordLower;
}
return wordLower[0].toUpperCase() + wordLower.slice(1);
})
.join(' ');
}
export function invertMap(map: Record<string, string>): Record<string, string> {
const keys = Object.keys(map);
const inverted: Record<string, string> = {};
for (const key of keys) {
const val = map[key];
inverted[val] = key;
}
return inverted;
}
export function time<K, T>(func: (...args: K[]) => T, ...args: K[]): T {
/* eslint-disable no-console */
const name = func.name;
console.time(name);
const stuff = func(...args);
console.timeEnd(name);
return stuff;
}
export async function timeAsync<K, T>(
func: (...args: K[]) => Promise<T>,
...args: K[]
): Promise<T> {
/* eslint-disable no-console */
const name = func.name;
console.time(name);
const stuff = await func(...args);
console.timeEnd(name);
return stuff;
}
export function changeKeys<T>(
source: Record<string, T>,
keyMap: Record<string, string | undefined>
) {
const dest: Record<string, T> = {};
for (const key of Object.keys(source)) {
const newKey = keyMap[key] ?? key;
dest[newKey] = source[key];
}
return dest;
}
export function deleteKeys<T>(
source: Record<string, T>,
keysToDelete: string[]
) {
const dest: Record<string, T> = {};
for (const key of Object.keys(source)) {
if (keysToDelete.includes(key)) {
continue;
}
dest[key] = source[key];
}
return dest;
}
function safeParseNumber(value: unknown, parser: (v: string) => number) {
let parsed: number;
switch (typeof value) {
case 'string':
parsed = parser(value);
break;
case 'number':
parsed = value;
break;
default:
parsed = Number(value);
break;
}
if (Number.isNaN(parsed)) {
return 0;
}
return parsed;
}
export function safeParseFloat(value: unknown): number {
return safeParseNumber(value, Number);
}
export function safeParseInt(value: unknown): number {
return safeParseNumber(value, (v: string) => Math.trunc(Number(v)));
}
export function safeParsePesa(value: unknown, fyo: Fyo): Money {
if (value instanceof Money) {
return value;
}
if (typeof value === 'number') {
return fyo.pesa(value);
}
if (typeof value === 'bigint') {
return fyo.pesa(value);
}
if (typeof value !== 'string') {
return fyo.pesa(0);
}
try {
return fyo.pesa(value);
} catch {
return fyo.pesa(0);
}
}
export function joinMapLists<A, B>(
listA: A[],
listB: B[],
keyA: keyof A,
keyB: keyof B
): (A & B)[] {
const mapA = getMapFromList(listA, keyA);
const mapB = getMapFromList(listB, keyB);
const keyListA = listA
.map((i) => i[keyA])
.filter((k) => (k as unknown as string) in mapB);
const keyListB = listB
.map((i) => i[keyB])
.filter((k) => (k as unknown as string) in mapA);
const keys = new Set([keyListA, keyListB].flat().sort());
const joint: (A & B)[] = [];
for (const k of keys) {
const a = mapA[k as unknown as string];
const b = mapB[k as unknown as string];
const c = { ...a, ...b };
joint.push(c);
}
return joint;
}
export function removeAtIndex<T>(array: T[], index: number): T[] {
if (index < 0 || index >= array.length) {
return array;
}
return [...array.slice(0, index), ...array.slice(index + 1)];
}
/**
* Asserts that `value` is of type T. Use with care.
*/
export const assertIsType = <T>(value: unknown): value is T => true;
|
2302_79757062/books
|
utils/index.ts
|
TypeScript
|
agpl-3.0
| 5,766
|
export interface BackendResponse {
data?: unknown;
error?: { message: string; name: string; stack?: string; code?: string };
}
|
2302_79757062/books
|
utils/ipc/types.ts
|
TypeScript
|
agpl-3.0
| 131
|
// ipcRenderer.send(...)
export enum IPC_MESSAGES {
OPEN_MENU = 'open-menu',
OPEN_SETTINGS = 'open-settings',
OPEN_EXTERNAL = 'open-external',
SHOW_ITEM_IN_FOLDER = 'show-item-in-folder',
RELOAD_MAIN_WINDOW = 'reload-main-window',
MINIMIZE_MAIN_WINDOW = 'minimize-main-window',
MAXIMIZE_MAIN_WINDOW = 'maximize-main-window',
ISMAXIMIZED_MAIN_WINDOW = 'ismaximized-main-window',
ISMAXIMIZED_RESULT = 'ismaximized-result',
ISFULLSCREEN_MAIN_WINDOW = 'isfullscreen-main-window',
ISFULLSCREEN_RESULT = 'isfullscreen-result',
CLOSE_MAIN_WINDOW = 'close-main-window',
}
// ipcRenderer.invoke(...)
export enum IPC_ACTIONS {
GET_OPEN_FILEPATH = 'open-dialog',
GET_SAVE_FILEPATH = 'save-dialog',
GET_DIALOG_RESPONSE = 'show-message-box',
GET_ENV = 'get-env',
SAVE_HTML_AS_PDF = 'save-html-as-pdf',
SAVE_DATA = 'save-data',
SHOW_ERROR = 'show-error',
SEND_ERROR = 'send-error',
GET_LANGUAGE_MAP = 'get-language-map',
CHECK_FOR_UPDATES = 'check-for-updates',
CHECK_DB_ACCESS = 'check-db-access',
SELECT_FILE = 'select-file',
GET_CREDS = 'get-creds',
GET_DB_LIST = 'get-db-list',
GET_TEMPLATES = 'get-templates',
DELETE_FILE = 'delete-file',
GET_DB_DEFAULT_PATH = 'get-db-default-path',
// Database messages
DB_CREATE = 'db-create',
DB_CONNECT = 'db-connect',
DB_CALL = 'db-call',
DB_BESPOKE = 'db-bespoke',
DB_SCHEMA = 'db-schema',
}
// ipcMain.send(...)
export enum IPC_CHANNELS {
LOG_MAIN_PROCESS_ERROR = 'main-process-error',
CONSOLE_LOG = 'console-log',
}
export enum DB_CONN_FAILURE {
INVALID_FILE = 'invalid-file',
CANT_OPEN = 'cant-open',
CANT_CONNECT = 'cant-connect',
}
// events
export enum CUSTOM_EVENTS {
MAIN_PROCESS_ERROR = 'main-process-error',
LOG_UNEXPECTED = 'log-unexpected',
}
|
2302_79757062/books
|
utils/messages.ts
|
TypeScript
|
agpl-3.0
| 1,774
|
import { DateTime } from 'luxon';
import countryInfo from '../fixtures/countryInfo.json';
import { CUSTOM_EVENTS } from './messages';
import { CountryInfoMap, UnexpectedLogObject } from './types';
export function getCountryInfo(): CountryInfoMap {
// @ts-ignore
return countryInfo as CountryInfoMap;
}
export function getCountryCodeFromCountry(countryName: string): string {
const countryInfoMap = getCountryInfo();
const countryInfo = countryInfoMap[countryName];
if (countryInfo === undefined) {
return '';
}
return countryInfo.code;
}
export function getFiscalYear(
date: string,
isStart: boolean
): undefined | Date {
if (!date) {
return undefined;
}
const today = DateTime.local();
const dateTime = DateTime.fromFormat(date, 'MM-dd');
if (isStart) {
return dateTime
.plus({ year: [1, 2, 3].includes(today.month) ? -1 : 0 })
.toJSDate();
}
return dateTime
.plus({ year: [1, 2, 3].includes(today.month) ? 0 : 1 })
.toJSDate();
}
export function logUnexpected(detail: Partial<UnexpectedLogObject>) {
/**
* Raises a custom event, it's lsitener is in renderer.ts
* used to log unexpected occurances as errors.
*/
if (!window?.CustomEvent) {
return;
}
detail.name ??= 'LogUnexpected';
detail.message ??= 'Logging an unexpected occurance';
detail.stack ??= new Error().stack;
detail.more ??= {};
const event = new window.CustomEvent(CUSTOM_EVENTS.LOG_UNEXPECTED, {
detail,
});
window.dispatchEvent(event);
}
|
2302_79757062/books
|
utils/misc.ts
|
TypeScript
|
agpl-3.0
| 1,516
|
/**
* Properties of a schema which are to be translated,
* irrespective of nesting.
*/
export const schemaTranslateables = [
'label',
'description',
'placeholder',
'section',
'tab',
];
export function getIndexFormat(inp: string | string[] | unknown) {
/**
* converts:
* ['This is an ', ,' interpolated ',' string.'] and
* 'This is an ${variableA} interpolated ${variableB} string.'
* to 'This is an ${0} interpolated ${1} string.'
*/
let string: string | undefined = undefined;
let snippets: string[] | undefined = undefined;
if (typeof inp === 'string') {
string = inp;
} else if (inp instanceof Array) {
snippets = inp;
} else {
throw new Error(`invalid input ${String(inp)} of type ${typeof inp}`);
}
if (snippets === undefined) {
snippets = getSnippets(string as string);
}
if (snippets.length === 1) {
return snippets[0];
}
let str = '';
snippets.forEach((s, i) => {
if (i === snippets!.length - 1) {
str += s;
return;
}
str += s + '${' + String(i) + '}';
});
return str;
}
export function getSnippets(str: string) {
let start = 0;
const snippets = [...str.matchAll(/\${[^}]+}/g)].map((m) => {
const end = m.index;
if (end === undefined) {
return '';
}
const snip = str.slice(start, end);
start = end + m[0].length;
return snip;
});
snippets.push(str.slice(start));
return snippets;
}
export function getWhitespaceSanitized(str: string) {
return str.replace(/\s+/g, ' ').trim();
}
export function getIndexList(str: string) {
return [...str.matchAll(/\${([^}]+)}/g)].map(([, i]) => parseInt(i));
}
|
2302_79757062/books
|
utils/translationHelpers.ts
|
TypeScript
|
agpl-3.0
| 1,659
|
import type { ConfigFile } from 'fyo/core/types';
export type UnknownMap = Record<string, unknown>;
export type Translation = { translation: string; context?: string };
export type LanguageMap = Record<string, Translation>;
export type CountryInfoMap = Record<string, CountryInfo | undefined>;
export interface CountryInfo {
code: string;
currency: string;
currency_fraction?: string;
currency_fraction_units?: number;
smallest_currency_fraction_value?: number;
currency_symbol?: string;
timezones?: string[];
fiscal_year_start: string;
fiscal_year_end: string;
locale: string;
}
export interface VersionParts {
major: number;
minor: number;
patch: number;
beta?: number;
}
export type Creds = {
errorLogUrl: string;
telemetryUrl: string;
tokenString: string;
};
export type UnexpectedLogObject = {
name: string;
message: string;
stack: string;
more: Record<string, unknown>;
};
export interface SelectFileOptions {
title: string;
filters?: { name: string; extensions: string[] }[];
}
export interface SelectFileReturn {
name: string;
filePath: string;
success: boolean;
data: Buffer;
canceled: boolean;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type PropertyEnum<T extends Record<string, any>> = {
[key in keyof Required<T>]: key;
};
export type TemplateFile = { file: string; template: string; modified: string };
export interface Keys extends ModMap {
pressed: Set<string>;
}
interface ModMap {
alt: boolean;
ctrl: boolean;
meta: boolean;
shift: boolean;
repeat: boolean;
}
export interface ConfigFilesWithModified extends ConfigFile {
modified: string;
}
|
2302_79757062/books
|
utils/types.ts
|
TypeScript
|
agpl-3.0
| 1,673
|
import { VersionParts } from './types';
export class Version {
/**
* comparators for version strings of the form
* x.x.x[-beta.x]
*/
static gte(a: string, b: string) {
let valid = false;
return compare(a, b, (c) => {
if (c === 0) {
return false;
}
valid ||= c > 0;
return !valid;
});
}
static lte(a: string, b: string) {
return !Version.gt(a, b);
}
static eq(a: string, b: string) {
return compare(a, b, (c) => c !== 0);
}
static gt(a: string, b: string) {
return Version.gte(a, b) && !Version.eq(a, b);
}
static lt(a: string, b: string) {
return Version.lte(a, b) && !Version.eq(a, b);
}
}
const seq = ['major', 'minor', 'patch', 'beta'] as (keyof VersionParts)[];
function compare(a: string, b: string, isInvalid: (x: number) => boolean) {
const partsA = parseVersionString(a);
const partsB = parseVersionString(b);
for (const p of seq) {
const c = compareSingle(partsA, partsB, p);
if (isInvalid(c)) {
return false;
}
}
return true;
}
function parseVersionString(a: string): VersionParts {
const parts = a.split('-');
const nonbeta = parts[0].split('.').map((n) => parseFloat(n));
const versionParts: VersionParts = {
major: nonbeta[0],
minor: nonbeta[1],
patch: nonbeta[2],
};
const beta = parseFloat(parts[1]?.split('.')?.[1]);
if (!Number.isNaN(beta)) {
versionParts.beta = beta;
}
if (Number.isNaN(beta) && parts[1]?.includes('beta')) {
versionParts.beta = 0;
}
return versionParts;
}
function compareSingle(
partsA: VersionParts,
partsB: VersionParts,
key: keyof VersionParts
): number {
if (key !== 'beta') {
return partsA[key] - partsB[key];
}
if (typeof partsA.beta === 'number' && typeof partsB.beta === 'number') {
return partsA.beta - partsB.beta;
}
// A is not in beta
if (partsA.beta === undefined && typeof partsB.beta === 'number') {
return 1;
}
// B is not in beta
if (typeof partsA.beta === 'number' && partsB.beta === undefined) {
return -1;
}
// Both A and B are not in Beta
return 0;
}
|
2302_79757062/books
|
utils/version.ts
|
TypeScript
|
agpl-3.0
| 2,135
|
import vue from '@vitejs/plugin-vue';
import path from 'path';
import { defineConfig } from 'vite';
/**
* This vite config file is used only for dev mode, i.e.
* to create a serve build modules of the source code
* which will be rendered by electron.
*
* For building the project, vite is used programmatically
* see build/scripts/build.mjs for this.
*/
export default () => {
let port = 6969;
let host = '0.0.0.0';
if (process.env.VITE_PORT && process.env.VITE_HOST) {
port = Number(process.env.VITE_PORT);
host = process.env.VITE_HOST;
}
return defineConfig({
server: { host, port, strictPort: true },
root: path.resolve(__dirname, './src'),
plugins: [vue()],
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
fyo: path.resolve(__dirname, './fyo'),
src: path.resolve(__dirname, './src'),
schemas: path.resolve(__dirname, './schemas'),
backend: path.resolve(__dirname, './backend'),
models: path.resolve(__dirname, './models'),
utils: path.resolve(__dirname, './utils'),
regional: path.resolve(__dirname, './regional'),
reports: path.resolve(__dirname, './reports'),
dummy: path.resolve(__dirname, './dummy'),
fixtures: path.resolve(__dirname, './fixtures'),
},
},
});
};
|
2302_79757062/books
|
vite.config.ts
|
TypeScript
|
agpl-3.0
| 1,328
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
//写一个函数用于找三个数中的最大值;并实际调用函数,比较23,124,-8764中的最大值;
//同时要判断传进来的参数是否都是数字型,只要其中一个参数不是数字型,就提前返回NaN。
function getMax(a,b,c){
if(typeof a!== 'number'||typeof b!== 'number'||typeof c!== 'number'){
return NaN;
}
return Math.max(a,b,c);
}
let num1=23;
let num2=124;
let num3=-8764;
let max=(getMax(num1,num2,num3));
console.log(max);
</script>
</html>
|
2302_79957586/JavaScript
|
1.html
|
HTML
|
unknown
| 795
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
//编写一个getArrMax函数,利用该函数求数组[13,68,79, 92, 83]中的最大值。
function getArrMax(){
let max=arguments[0];
for(let i=1;i<arguments.length;i++){
if(arguments[i]> max){
max = arguments[i];
}
}return max;
}
console.log(getArrMax(13,68,79,92,83));
</script>
</html>
|
2302_79957586/JavaScript
|
2.html
|
HTML
|
unknown
| 606
|