QQQ-28 Updates for bulk processes

This commit is contained in:
2022-07-22 19:29:48 -05:00
parent 4412a274f4
commit 33bcffd4c3
8 changed files with 744 additions and 321 deletions

View File

@ -62,6 +62,8 @@
"no-shadow": "off", "no-shadow": "off",
"no-unused-vars": "off", "no-unused-vars": "off",
"no-plusplus": "off", "no-plusplus": "off",
"no-underscore-dangle": "off",
"no-else-return": "off",
"spaced-comment": "off", "spaced-comment": "off",
"object-curly-spacing": [ "object-curly-spacing": [
"error", "error",

View File

@ -74,7 +74,10 @@ function EntityForm({id}: Props): JSX.Element
sortedKeys.forEach((key) => sortedKeys.forEach((key) =>
{ {
const fieldMetaData = tableMetaData.fields.get(key); const fieldMetaData = tableMetaData.fields.get(key);
if (fieldMetaData.isEditable)
{
fieldArray.push(fieldMetaData); fieldArray.push(fieldMetaData);
}
}); });
if (id !== null) if (id !== null)

View File

@ -1,16 +1,22 @@
/** /*
========================================================= * QQQ - Low-code Application Framework for Engineers.
* Material Dashboard 2 PRO React TS - v1.0.0 * Copyright (C) 2021-2022. Kingsrook, LLC
========================================================= * 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* Product Page: https://www.creative-tim.com/product/material-dashboard-2-pro-react-ts * https://github.com/Kingsrook/
* Copyright 2022 Creative Tim (https://www.creative-tim.com) *
* This program is free software: you can redistribute it and/or modify
Coded by www.creative-tim.com * it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
========================================================= * License, or (at your option) any later version.
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
// @mui material components // @mui material components
@ -21,32 +27,38 @@ import MDBox from "components/MDBox";
import MDTypography from "components/MDTypography"; import MDTypography from "components/MDTypography";
// NewUser page components // NewUser page components
import FormField from "layouts/pages/users/new-user/components/FormField"; import {useFormikContext} from "formik";
import {QFrontendStepMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFrontendStepMetaData"; import React from "react";
import QDynamicFormField from "qqq/components/QDynamicFormField";
interface Props { interface Props {
formLabel?: string; formLabel?: string;
formData: any; formData: any;
primaryKeyId?: string; primaryKeyId?: string;
bulkEditMode?: boolean;
bulkEditSwitchChangeHandler?: any
} }
function QDynamicForm(props: Props): JSX.Element function QDynamicForm(props: Props): JSX.Element
{ {
const {formData, formLabel, primaryKeyId} = props; const {
formData, formLabel, primaryKeyId, bulkEditMode, bulkEditSwitchChangeHandler,
} = props;
const { const {
formFields, values, errors, touched, formFields, values, errors, touched,
} = formData; } = formData;
/* const formikProps = useFormikContext();
const {
firstName: firstNameV, const fileChanged = (event: React.FormEvent<HTMLInputElement>, field: any) =>
lastName: lastNameV, {
company: companyV, formikProps.setFieldValue(field.name, event.currentTarget.files[0]);
email: emailV, };
password: passwordV,
repeatPassword: repeatPasswordV, const bulkEditSwitchChanged = (name: string, value: boolean) =>
} = values; {
*/ bulkEditSwitchChangeHandler(name, value);
};
return ( return (
<MDBox> <MDBox>
@ -73,93 +85,46 @@ function QDynamicForm(props: Props): JSX.Element
{ {
values[fieldName] = ""; values[fieldName] = "";
} }
if (field.type === "file")
{
return ( return (
<Grid item xs={12} sm={6} key={fieldName}> <Grid item xs={12} sm={6} key={fieldName}>
<FormField <MDBox mb={1.5}>
<input
id={fieldName}
name={fieldName}
type="file"
onChange={(event: React.FormEvent<HTMLInputElement>) => fileChanged(event, field)}
/>
<MDBox mt={0.75}>
<MDTypography component="div" variant="caption" color="error" fontWeight="regular">
{errors[fieldName] && <span>You must select a file to proceed</span>}
</MDTypography>
</MDBox>
</MDBox>
</Grid>
);
}
// todo? inputProps={{ autoComplete: "" }}
// todo? placeholder={password.placeholder}
// todo? success={!errors[fieldName] && touched[fieldName]}
return (
<Grid item xs={12} sm={6} key={fieldName}>
<QDynamicFormField
type={field.type} type={field.type}
label={field.label} label={field.label}
name={fieldName} name={fieldName}
value={values[fieldName]} value={values[fieldName]}
error={errors[fieldName] && touched[fieldName]} error={errors[fieldName] && touched[fieldName]}
bulkEditMode={bulkEditMode}
bulkEditSwitchChangeHandler={bulkEditSwitchChanged}
/> />
</Grid> </Grid>
); );
})} })}
</Grid> </Grid>
{/*
<Grid container spacing={3}>
<Grid item xs={12} sm={6}>
<FormField
type={firstName.type}
label={firstName.label}
name={firstName.name}
value={firstNameV}
placeholder={firstName.placeholder}
error={errors.firstName && touched.firstName}
success={firstNameV.length > 0 && !errors.firstName}
/>
</Grid>
<Grid item xs={12} sm={6}>
<FormField
type={lastName.type}
label={lastName.label}
name={lastName.name}
value={lastNameV}
placeholder={lastName.placeholder}
error={errors.lastName && touched.lastName}
success={lastNameV.length > 0 && !errors.lastName}
/>
</Grid>
</Grid>
<Grid container spacing={3}>
<Grid item xs={12} sm={6}>
<FormField
type={company.type}
label={company.label}
name={company.name}
value={companyV}
placeholder={company.placeholder}
/>
</Grid>
<Grid item xs={12} sm={6}>
<FormField
type={email.type}
label={email.label}
name={email.name}
value={emailV}
placeholder={email.placeholder}
error={errors.email && touched.email}
success={emailV.length > 0 && !errors.email}
/>
</Grid>
</Grid>
<Grid container spacing={3}>
<Grid item xs={12} sm={6}>
<FormField
type={password.type}
label={password.label}
name={password.name}
value={passwordV}
placeholder={password.placeholder}
error={errors.password && touched.password}
success={passwordV.length > 0 && !errors.password}
inputProps={{ autoComplete: "" }}
/>
</Grid>
<Grid item xs={12} sm={6}>
<FormField
type={repeatPassword.type}
label={repeatPassword.label}
name={repeatPassword.name}
value={repeatPasswordV}
placeholder={repeatPassword.placeholder}
error={errors.repeatPassword && touched.repeatPassword}
success={repeatPasswordV.length > 0 && !errors.repeatPassword}
inputProps={{ autoComplete: "" }}
/>
</Grid>
</Grid>
*/}
</MDBox> </MDBox>
</MDBox> </MDBox>
); );
@ -168,6 +133,9 @@ function QDynamicForm(props: Props): JSX.Element
QDynamicForm.defaultProps = { QDynamicForm.defaultProps = {
formLabel: undefined, formLabel: undefined,
primaryKeyId: undefined, primaryKeyId: undefined,
bulkEditMode: false,
bulkEditSwitchChangeHandler: () =>
{},
}; };
export default QDynamicForm; export default QDynamicForm;

View File

@ -38,6 +38,15 @@ class DynamicFormUtils
const formValidations: any = {}; const formValidations: any = {};
qqqFormFields.forEach((field) => qqqFormFields.forEach((field) =>
{
dynamicFormFields[field.name] = this.getDynamicField(field);
formValidations[field.name] = this.getValidationForField(field);
});
return {dynamicFormFields, formValidations};
}
public static getDynamicField(field: QFieldMetaData)
{ {
let fieldType: string; let fieldType: string;
switch (field.type.toString()) switch (field.type.toString())
@ -64,19 +73,41 @@ class DynamicFormUtils
let label = field.label ? field.label : field.name; let label = field.label ? field.label : field.name;
label += field.isRequired ? " *" : ""; label += field.isRequired ? " *" : "";
dynamicFormFields[field.name] = { return ({
name: field.name, name: field.name,
label: label, label: label,
isRequired: field.isRequired, isRequired: field.isRequired,
type: fieldType, type: fieldType,
// todo invalidMsg: "Zipcode is not valid (e.g. 70000).", // todo invalidMsg: "Zipcode is not valid (e.g. 70000).",
}; });
}
public static getValidationForField(field: QFieldMetaData)
{
if (field.isRequired) if (field.isRequired)
{ {
formValidations[field.name] = Yup.string().required(`${field.label} is required.`); return (Yup.string().required(`${field.label} is required.`));
}
return (null);
}
public static getFormDataForUploadForm(fieldName: string, fieldLabel: string, isRequired: boolean = true)
{
const dynamicFormFields: any = {};
const formValidations: any = {};
dynamicFormFields[fieldName] = {
name: fieldName,
label: fieldLabel,
isRequired: isRequired,
type: "file",
// todo invalidMsg: "Zipcode is not valid (e.g. 70000).",
};
if (isRequired)
{
formValidations[fieldName] = Yup.string().required(`${fieldLabel} is required.`);
} }
});
return {dynamicFormFields, formValidations}; return {dynamicFormFields, formValidations};
} }

View File

@ -0,0 +1,107 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2022. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// formik components
import {ErrorMessage, Field} from "formik";
// Material Dashboard 2 PRO React TS components
import MDBox from "components/MDBox";
import MDTypography from "components/MDTypography";
import MDInput from "components/MDInput";
import QDynamicForm from "qqq/components/QDynamicForm";
import React, {useState} from "react";
import Grid from "@mui/material/Grid";
import Switch from "@mui/material/Switch";
// Declaring props types for FormField
interface Props
{
label: string;
name: string;
[key: string]: any;
bulkEditMode?: boolean;
bulkEditSwitchChangeHandler?: any
}
function QDynamicFormField({
label, name, bulkEditMode, bulkEditSwitchChangeHandler, ...rest
}: Props): JSX.Element
{
const [switchChecked, setSwitchChecked] = useState(false);
const [isDisabled, setIsDisabled] = useState(bulkEditMode);
const field = () => (
<>
<Field {...rest} name={name} as={MDInput} variant="standard" label={label} fullWidth disabled={isDisabled} />
<MDBox mt={0.75}>
<MDTypography component="div" variant="caption" color="error" fontWeight="regular">
{!isDisabled && <ErrorMessage name={name} />}
</MDTypography>
</MDBox>
</>
);
const bulkEditSwitchChanged = () =>
{
const newSwitchValue = !switchChecked;
setSwitchChecked(newSwitchValue);
setIsDisabled(!newSwitchValue);
bulkEditSwitchChangeHandler(name, newSwitchValue);
};
if (bulkEditMode)
{
return (
<MDBox mb={1.5}>
<Grid container>
<Grid item xs={1} alignItems="baseline" pt={1}>
<Switch
id={`bulkEditSwitch-${name}`}
checked={switchChecked}
onClick={bulkEditSwitchChanged}
/>
</Grid>
<Grid item xs={11}>
<label htmlFor={`bulkEditSwitch-${name}`}>
{field()}
</label>
</Grid>
</Grid>
</MDBox>
);
}
else
{
return (
<MDBox mb={1.5}>
{field()}
</MDBox>
);
}
}
QDynamicFormField.defaultProps = {
bulkEditMode: false,
bulkEditSwitchChangeHandler: () =>
{},
};
export default QDynamicFormField;

View File

@ -57,6 +57,7 @@ import {QFilterCriteria} from "@kingsrook/qqq-frontend-core/lib/model/query/QFil
import {QCriteriaOperator} from "@kingsrook/qqq-frontend-core/lib/model/query/QCriteriaOperator"; import {QCriteriaOperator} from "@kingsrook/qqq-frontend-core/lib/model/query/QCriteriaOperator";
import {QFieldType} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldType"; import {QFieldType} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldType";
import QClient from "qqq/utils/QClient"; import QClient from "qqq/utils/QClient";
import Button from "@mui/material/Button";
import Footer from "../../components/Footer"; import Footer from "../../components/Footer";
import QProcessUtils from "../../utils/QProcessUtils"; import QProcessUtils from "../../utils/QProcessUtils";
@ -366,14 +367,109 @@ function EntityList({table}: Props): JSX.Element
})(); })();
} }
function getNoOfSelectedRecords()
{
if (selectFullFilterState === "filter")
{
return (totalRecords);
}
return (selectedIds.length);
}
function getRecordsQueryString()
{
if (selectFullFilterState === "filter")
{
return `?recordsParam=filterJSON&filterJSON=${JSON.stringify(buildQFilter())}`;
}
if (selectedIds.length > 0)
{
return `?recordsParam=recordIds&recordIds=${selectedIds.join(",")}`;
}
return "";
}
const bulkLoadClicked = () =>
{
document.location.href = `/processes/${tableName}.bulkInsert${getRecordsQueryString()}`;
};
const bulkEditClicked = () =>
{
if (getNoOfSelectedRecords() === 0)
{
setAlertContent("No records were selected to Bulk Edit.");
return;
}
document.location.href = `/processes/${tableName}.bulkEdit${getRecordsQueryString()}`;
};
const bulkDeleteClicked = () =>
{
if (getNoOfSelectedRecords() === 0)
{
setAlertContent("No records were selected to Bulk Delete.");
return;
}
document.location.href = `/processes/${tableName}.bulkDelete${getRecordsQueryString()}`;
};
function CustomToolbar() function CustomToolbar()
{ {
const [bulkActionsMenuAnchor, setBulkActionsMenuAnchor] = useState(null as HTMLElement);
const bulkActionsMenuOpen = Boolean(bulkActionsMenuAnchor);
const openBulkActionsMenu = (event: React.MouseEvent<HTMLElement>) =>
{
setBulkActionsMenuAnchor(event.currentTarget);
};
const closeBulkActionsMenu = () =>
{
setBulkActionsMenuAnchor(null);
};
return ( return (
<GridToolbarContainer> <GridToolbarContainer>
<div>
<Button
id="refresh-button"
onClick={updateTable}
>
<Icon>refresh</Icon>
Refresh
</Button>
</div>
<GridToolbarColumnsButton /> <GridToolbarColumnsButton />
<GridToolbarFilterButton /> <GridToolbarFilterButton />
<GridToolbarDensitySelector /> <GridToolbarDensitySelector />
<GridToolbarExport /> <GridToolbarExport />
<div>
<Button
id="bulk-actions-button"
onClick={openBulkActionsMenu}
aria-controls={bulkActionsMenuOpen ? "basic-menu" : undefined}
aria-haspopup="true"
aria-expanded={bulkActionsMenuOpen ? "true" : undefined}
>
<Icon>fact_check</Icon>
Bulk Actions
</Button>
<Menu
id="bulk-actions-menu"
open={bulkActionsMenuOpen}
anchorEl={bulkActionsMenuAnchor}
onClose={closeBulkActionsMenu}
MenuListProps={{"aria-labelledby": "bulk-actions-button"}}
>
<MenuItem onClick={bulkLoadClicked}>Bulk Load</MenuItem>
<MenuItem onClick={bulkEditClicked}>Bulk Edit</MenuItem>
<MenuItem onClick={bulkDeleteClicked}>Bulk Delete</MenuItem>
</Menu>
</div>
<div> <div>
{ {
selectFullFilterState === "checked" && ( selectFullFilterState === "checked" && (
@ -416,21 +512,6 @@ function EntityList({table}: Props): JSX.Element
); );
} }
function getRecordsQueryString()
{
if (selectFullFilterState === "filter")
{
return `?recordsParam=filterJSON&filterJSON=${JSON.stringify(buildQFilter())}`;
}
if (selectedIds.length > 0)
{
return `?recordsParam=recordIds&recordIds=${selectedIds.join(",")}`;
}
return "";
}
const renderActionsMenu = ( const renderActionsMenu = (
<Menu <Menu
anchorEl={actionsMenu} anchorEl={actionsMenu}

View File

@ -13,10 +13,10 @@
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/ */
import {useEffect, useState} from "react"; import React, {useEffect, useState, Fragment} from "react";
// formik components // formik components
import {Formik, Form} from "formik"; import {Form, Formik, useFormikContext} from "formik";
// @mui material components // @mui material components
import Grid from "@mui/material/Grid"; import Grid from "@mui/material/Grid";
@ -36,7 +36,6 @@ import Footer from "examples/Footer";
// ProcessRun layout schemas for form and form fields // ProcessRun layout schemas for form and form fields
import * as Yup from "yup"; import * as Yup from "yup";
import {QController} from "@kingsrook/qqq-frontend-core/lib/controllers/QController";
import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData"; import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData";
import {QFrontendStepMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFrontendStepMetaData"; import {QFrontendStepMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFrontendStepMetaData";
import {useLocation, useParams} from "react-router-dom"; import {useLocation, useParams} from "react-router-dom";
@ -45,34 +44,170 @@ import {QJobStarted} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJob
import {QJobComplete} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJobComplete"; import {QJobComplete} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJobComplete";
import {QJobError} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJobError"; import {QJobError} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJobError";
import {QJobRunning} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJobRunning"; import {QJobRunning} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJobRunning";
import { import {DataGridPro, GridColDef} from "@mui/x-data-grid-pro";
DataGridPro, GridColDef, GridRowParams, GridRowsProp, import {QFrontendComponent} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFrontendComponent";
} from "@mui/x-data-grid-pro"; import {QComponentType} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QComponentType";
import FormData from "form-data";
import QClient from "qqq/utils/QClient";
import {CircularProgress} from "@mui/material";
import QDynamicForm from "../../components/QDynamicForm"; import QDynamicForm from "../../components/QDynamicForm";
import MDTypography from "../../../components/MDTypography"; import MDTypography from "../../../components/MDTypography";
function getDynamicStepContent( function logFormValidations(prefix: string, formValidations: any)
{
console.log(`${prefix}: ${JSON.stringify(formValidations)} `);
}
function ProcessRun(): JSX.Element
{
const {processName} = useParams();
///////////////////
// process state //
///////////////////
const [processUUID, setProcessUUID] = useState(null as string);
const [jobUUID, setJobUUID] = useState(null as string);
const [qJobRunning, setQJobRunning] = useState(null as QJobRunning);
const [qJobRunningDate, setQJobRunningDate] = useState(null as Date);
const [activeStepIndex, setActiveStepIndex] = useState(0);
const [activeStep, setActiveStep] = useState(null as QFrontendStepMetaData);
const [newStep, setNewStep] = useState(null);
const [steps, setSteps] = useState([] as QFrontendStepMetaData[]);
const [needInitialLoad, setNeedInitialLoad] = useState(true);
const [processMetaData, setProcessMetaData] = useState(null);
const [processValues, setProcessValues] = useState({} as any);
const [processError, setProcessError] = useState(null as string);
const [needToCheckJobStatus, setNeedToCheckJobStatus] = useState(false);
const [lastProcessResponse, setLastProcessResponse] = useState(
null as QJobStarted | QJobComplete | QJobError | QJobRunning,
);
const onLastStep = activeStepIndex === steps.length - 2;
const noMoreSteps = activeStepIndex === steps.length - 1;
////////////////
// form state //
////////////////
const [formId, setFormId] = useState("");
const [formFields, setFormFields] = useState({});
const [initialValues, setInitialValues] = useState({});
const [validationScheme, setValidationScheme] = useState(null);
const [validationFunction, setValidationFunction] = useState(null);
const [formError, setFormError] = useState(null as string);
///////////////////////
// record list state //
///////////////////////
const [needRecords, setNeedRecords] = useState(false);
const [recordConfig, setRecordConfig] = useState({} as any);
const [pageNumber, setPageNumber] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
//////////////////////////////
// state for bulk edit form //
//////////////////////////////
const [disabledBulkEditFields, setDisabledBulkEditFields] = useState({} as any);
const doesStepHaveComponent = (step: QFrontendStepMetaData, type: QComponentType): boolean =>
{
if (step.components)
{
for (let i = 0; i < step.components.length; i++)
{
if (step.components[i].type === type)
{
return (true);
}
}
}
return (false);
};
//////////////////////////////////////////////////////////////
// event handler for the bulk-edit field-enabled checkboxes //
//////////////////////////////////////////////////////////////
const bulkEditSwitchChanged = (name: string, switchValue: boolean) =>
{
const newDisabledBulkEditFields = JSON.parse(JSON.stringify(disabledBulkEditFields));
newDisabledBulkEditFields[name] = !switchValue;
setDisabledBulkEditFields(newDisabledBulkEditFields);
};
const formatViewValue = (value: any): JSX.Element =>
{
if (value === null || value === undefined)
{
return <span>--</span>;
}
if (typeof value === "string")
{
return (
<>
{value.split(/\n/).map((value: string, index: number) => (
// eslint-disable-next-line react/no-array-index-key
<Fragment key={index}>
<span>{value}</span>
<br />
</Fragment>
))}
</>
);
}
return (<span>{value}</span>);
};
////////////////////////////////////////////////////
// generate the main form body content for a step //
////////////////////////////////////////////////////
const getDynamicStepContent = (
stepIndex: number, stepIndex: number,
step: any, step: any,
formData: any, formData: any,
processError: string, processError: string,
processValues: any, processValues: any,
recordConfig: any, recordConfig: any,
): JSX.Element ): JSX.Element =>
{ {
const {
formFields, values, errors, touched,
} = formData;
// console.log(`in getDynamicStepContent: step label ${step?.label}`);
if (processError) if (processError)
{ {
return ( return (
<> <>
<MDTypography color="error" variant="h3"> <MDTypography color="error" variant="h5">
Error Error
</MDTypography> </MDTypography>
<div>{processError}</div> <MDTypography color="body" variant="button">
{processError}
</MDTypography>
</>
);
}
if (qJobRunning)
{
return (
<>
<MDTypography variant="h5">
{" "}
Working
</MDTypography>
<Grid container>
<Grid item padding={1}>
<CircularProgress color="info" />
</Grid>
<Grid item>
<MDTypography color="body" variant="button">
{qJobRunning?.message}
<br />
{qJobRunning.current && qJobRunning.total && (
<div>{`${qJobRunning.current.toLocaleString()} of ${qJobRunning.total.toLocaleString()}`}</div>
)}
<i>
{`Updated at ${qJobRunningDate.toLocaleTimeString()}`}
</i>
</MDTypography>
</Grid>
</Grid>
</> </>
); );
} }
@ -83,28 +218,47 @@ function getDynamicStepContent(
return <div>Loading...</div>; return <div>Loading...</div>;
} }
console.log(`in getDynamicStepContent. the step looks like: ${JSON.stringify(step)}`);
return ( return (
<> <>
{step.formFields && <QDynamicForm formData={formData} formLabel={step.label} />} <MDTypography variation="h5" fontWeight="bold">{step?.label}</MDTypography>
{step.components && (
step.components.map((component: QFrontendComponent, index: number) => (
// eslint-disable-next-line react/no-array-index-key
<div key={index}>
{
component.type === QComponentType.HELP_TEXT && (
<MDTypography variant="button" color="info">
{component.values.text}
</MDTypography>
)
}
</div>
)))}
{(step.formFields || doesStepHaveComponent(step, QComponentType.FILE_UPLOAD)) && (
<QDynamicForm
formData={formData}
bulkEditMode={doesStepHaveComponent(activeStep, QComponentType.BULK_EDIT_FORM)}
bulkEditSwitchChangeHandler={bulkEditSwitchChanged}
/>
)}
{step.viewFields && ( {step.viewFields && (
<div> <div>
{step.viewFields.map((field: QFieldMetaData) => ( {step.viewFields.map((field: QFieldMetaData) => (
<div key={field.name}> <MDBox key={field.name} display="flex" py={1} pr={2}>
<b> <MDTypography variant="button" fontWeight="bold">
{field.label} {field.label}
: : &nbsp;
</b> </MDTypography>
{" "} <MDTypography variant="button" fontWeight="regular" color="text">
{processValues[field.name]} {formatViewValue(processValues[field.name])}
</div> </MDTypography>
</MDBox>
))} ))}
</div> </div>
)} )}
{step.recordListFields && ( {(step.recordListFields && recordConfig.columns) && (
<div> <div>
<b>Records</b> <MDTypography variant="button" fontWeight="bold">Records</MDTypography>
{" "} {" "}
<br /> <br />
<MDBox height="100%"> <MDBox height="100%">
@ -121,71 +275,40 @@ function getDynamicStepContent(
onPageSizeChange={recordConfig.handleRowsPerPageChange} onPageSizeChange={recordConfig.handleRowsPerPageChange}
onPageChange={recordConfig.handlePageChange} onPageChange={recordConfig.handlePageChange}
onRowClick={recordConfig.handleRowClick} onRowClick={recordConfig.handleRowClick}
getRowId={(row) => row.__idForDataGridPro__}
paginationMode="server" paginationMode="server"
pagination pagination
density="compact" density="compact"
loading={recordConfig.loading} loading={recordConfig.loading}
disableColumnFilter
/> />
</MDBox> </MDBox>
</div> </div>
)} )}
</> </>
); );
} };
function trace(name: string, isComponent: boolean = false) const handlePageChange = (page: number) =>
{
if (isComponent)
{ {
console.log(`COMPONENT: ${name}`); setPageNumber(page);
} };
else
const handleRowsPerPageChange = (size: number) =>
{ {
console.log(` function: ${name}`); setRowsPerPage(size);
} };
}
const qController = new QController("");
function ProcessRun(): JSX.Element
{
const {processName} = useParams();
const [processUUID, setProcessUUID] = useState(null as string);
const [jobUUID, setJobUUID] = useState(null as string);
const [activeStepIndex, setActiveStepIndex] = useState(0);
const [activeStep, setActiveStep] = useState(null as QFrontendStepMetaData);
const [newStep, setNewStep] = useState(null);
const [steps, setSteps] = useState([] as QFrontendStepMetaData[]);
const [needInitialLoad, setNeedInitialLoad] = useState(true);
const [processMetaData, setProcessMetaData] = useState(null);
const [processValues, setProcessValues] = useState({} as any);
const [lastProcessResponse, setLastProcessResponse] = useState(
null as QJobStarted | QJobComplete | QJobError | QJobRunning,
);
const [formId, setFormId] = useState("");
const [formFields, setFormFields] = useState({});
const [initialValues, setInitialValues] = useState({});
const [validationScheme, setValidationScheme] = useState(null);
const [validationFunction, setValidationFunction] = useState(null);
const [needToCheckJobStatus, setNeedToCheckJobStatus] = useState(false);
const [needRecords, setNeedRecords] = useState(false);
const [processError, setProcessError] = useState(null as string);
const [recordConfig, setRecordConfig] = useState({} as any);
const onLastStep = activeStepIndex === steps.length - 2;
const noMoreSteps = activeStepIndex === steps.length - 1;
trace("ProcessRun", true);
function buildNewRecordConfig() function buildNewRecordConfig()
{ {
const newRecordConfig = {} as any; const newRecordConfig = {} as any;
newRecordConfig.pageNo = 1; newRecordConfig.pageNo = pageNumber;
newRecordConfig.rowsPerPage = 20; newRecordConfig.rowsPerPage = rowsPerPage;
newRecordConfig.columns = [] as GridColDef[]; newRecordConfig.columns = [] as GridColDef[];
newRecordConfig.rows = []; newRecordConfig.rows = [];
newRecordConfig.totalRecords = 0; newRecordConfig.totalRecords = 0;
newRecordConfig.handleRowsPerPageChange = null; newRecordConfig.handleRowsPerPageChange = handleRowsPerPageChange;
newRecordConfig.handlePageChange = null; newRecordConfig.handlePageChange = handlePageChange;
newRecordConfig.handleRowClick = null; newRecordConfig.handleRowClick = null;
newRecordConfig.loading = true; newRecordConfig.loading = true;
return (newRecordConfig); return (newRecordConfig);
@ -196,8 +319,6 @@ function ProcessRun(): JSX.Element
////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
useEffect(() => useEffect(() =>
{ {
trace("updateActiveStep");
if (!processMetaData) if (!processMetaData)
{ {
console.log("No process meta data yet, so returning early"); console.log("No process meta data yet, so returning early");
@ -249,10 +370,39 @@ function ProcessRun(): JSX.Element
initialValues[field.name] = processValues[field.name]; initialValues[field.name] = processValues[field.name];
}); });
////////////////////////////////////////////////////
// disable all fields if this is a bulk edit form //
////////////////////////////////////////////////////
if (doesStepHaveComponent(activeStep, QComponentType.BULK_EDIT_FORM))
{
const newDisabledBulkEditFields: any = {};
activeStep.formFields.forEach((field) =>
{
newDisabledBulkEditFields[field.name] = true;
dynamicFormFields[field.name].isRequired = false;
formValidations[field.name] = null;
});
setDisabledBulkEditFields(newDisabledBulkEditFields);
}
setFormFields(dynamicFormFields); setFormFields(dynamicFormFields);
setInitialValues(initialValues); setInitialValues(initialValues);
setValidationScheme(Yup.object().shape(formValidations)); setValidationScheme(Yup.object().shape(formValidations));
setValidationFunction(null); setValidationFunction(null);
logFormValidations("Post-disable thingie", formValidations);
}
else if (doesStepHaveComponent(activeStep, QComponentType.FILE_UPLOAD))
{
//////////////////////////////////////////////////////////////////////////
// if this step has an upload component, then set up the form for that. //
//////////////////////////////////////////////////////////////////////////
const {dynamicFormFields, formValidations} = DynamicFormUtils.getFormDataForUploadForm("fileUpload", "File");
setFormFields(dynamicFormFields);
setInitialValues(initialValues);
setValidationScheme(Yup.object().shape(formValidations));
setValidationFunction(null);
} }
else else
{ {
@ -263,24 +413,65 @@ function ProcessRun(): JSX.Element
setValidationScheme(null); setValidationScheme(null);
setValidationFunction(() => true); setValidationFunction(() => true);
} }
}
}, [newStep, rowsPerPage, pageNumber]);
//////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////
// if there are fields to load, build a record config, and set the needRecords state flag // // if there are records to load: build a record config, and set the needRecords state flag //
//////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////
if (activeStep.recordListFields) useEffect(() =>
{
if (activeStep && activeStep.recordListFields)
{ {
const newRecordConfig = buildNewRecordConfig(); const newRecordConfig = buildNewRecordConfig();
activeStep.recordListFields.forEach((field) => activeStep.recordListFields.forEach((field) =>
{ {
newRecordConfig.columns.push({field: field.name, headerName: field.label, width: 200}); newRecordConfig.columns.push({
field: field.name, headerName: field.label, width: 200, sortable: false,
});
}); });
setRecordConfig(newRecordConfig); setRecordConfig(newRecordConfig);
setNeedRecords(true); setNeedRecords(true);
} }
} }, [activeStep, rowsPerPage, pageNumber]);
}, [newStep]);
// when we need to load records, do so, async /////////////////////////////////////////////////////
// handle a bulk-edit enabled-switch being checked //
/////////////////////////////////////////////////////
useEffect(() =>
{
if (activeStep && activeStep.formFields)
{
console.log("In useEffect for disabledBulkEditFields");
console.log(disabledBulkEditFields);
const newDynamicFormFields: any = {};
const newFormValidations: any = {};
activeStep.formFields.forEach((field) =>
{
const fieldName = field.name;
const isDisabled = disabledBulkEditFields[fieldName];
newDynamicFormFields[field.name] = DynamicFormUtils.getDynamicField(field);
newFormValidations[field.name] = DynamicFormUtils.getValidationForField(field);
if (isDisabled)
{
newDynamicFormFields[field.name].isRequired = false;
newFormValidations[field.name] = null;
}
logFormValidations("Upon update", newFormValidations);
setFormFields(newDynamicFormFields);
setValidationScheme(Yup.object().shape(newFormValidations));
});
}
}, [disabledBulkEditFields]);
////////////////////////////////////////////////
// when we need to load records, do so, async //
////////////////////////////////////////////////
useEffect(() => useEffect(() =>
{ {
if (needRecords) if (needRecords)
@ -288,13 +479,15 @@ function ProcessRun(): JSX.Element
setNeedRecords(false); setNeedRecords(false);
(async () => (async () =>
{ {
const records = await qController.processRecords( const response = await QClient.getInstance().processRecords(
processName, processName,
processUUID, processUUID,
recordConfig.rowsPerPage * (recordConfig.pageNo - 1), recordConfig.rowsPerPage * recordConfig.pageNo,
recordConfig.rowsPerPage, recordConfig.rowsPerPage,
); );
const {records} = response;
///////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////
// re-construct the recordConfig object, so the setState call triggers a new rendering // // re-construct the recordConfig object, so the setState call triggers a new rendering //
///////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////
@ -306,14 +499,11 @@ function ProcessRun(): JSX.Element
records.forEach((record) => records.forEach((record) =>
{ {
const row = Object.fromEntries(record.values.entries()); const row = Object.fromEntries(record.values.entries());
if (!row.id) row.__idForDataGridPro__ = ++rowId;
{
row.id = ++rowId;
}
newRecordConfig.rows.push(row); newRecordConfig.rows.push(row);
}); });
// todo count?
newRecordConfig.totalRecords = records.length; newRecordConfig.totalRecords = response.totalRecords;
setRecordConfig(newRecordConfig); setRecordConfig(newRecordConfig);
})(); })();
} }
@ -326,8 +516,9 @@ function ProcessRun(): JSX.Element
{ {
if (lastProcessResponse) if (lastProcessResponse)
{ {
trace("handleProcessResponse");
setLastProcessResponse(null); setLastProcessResponse(null);
setQJobRunning(null);
if (lastProcessResponse instanceof QJobComplete) if (lastProcessResponse instanceof QJobComplete)
{ {
const qJobComplete = lastProcessResponse as QJobComplete; const qJobComplete = lastProcessResponse as QJobComplete;
@ -345,6 +536,8 @@ function ProcessRun(): JSX.Element
else if (lastProcessResponse instanceof QJobRunning) else if (lastProcessResponse instanceof QJobRunning)
{ {
const qJobRunning = lastProcessResponse as QJobRunning; const qJobRunning = lastProcessResponse as QJobRunning;
setQJobRunning(qJobRunning);
setQJobRunningDate(new Date());
setNeedToCheckJobStatus(true); setNeedToCheckJobStatus(true);
} }
else if (lastProcessResponse instanceof QJobError) else if (lastProcessResponse instanceof QJobError)
@ -363,13 +556,12 @@ function ProcessRun(): JSX.Element
{ {
if (needToCheckJobStatus) if (needToCheckJobStatus)
{ {
trace("checkJobStatus");
setNeedToCheckJobStatus(false); setNeedToCheckJobStatus(false);
(async () => (async () =>
{ {
setTimeout(async () => setTimeout(async () =>
{ {
const processResponse = await qController.processJobStatus( const processResponse = await QClient.getInstance().processJobStatus(
processName, processName,
processUUID, processUUID,
jobUUID, jobUUID,
@ -385,7 +577,6 @@ function ProcessRun(): JSX.Element
////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////
if (needInitialLoad) if (needInitialLoad)
{ {
trace("initialLoad");
setNeedInitialLoad(false); setNeedInitialLoad(false);
(async () => (async () =>
{ {
@ -411,15 +602,28 @@ function ProcessRun(): JSX.Element
console.log(`@dk: Query String for init: ${queryStringForInit}`); console.log(`@dk: Query String for init: ${queryStringForInit}`);
const processMetaData = await qController.loadProcessMetaData(processName); try
// console.log(processMetaData); {
const processMetaData = await QClient.getInstance().loadProcessMetaData(processName);
setProcessMetaData(processMetaData); setProcessMetaData(processMetaData);
setSteps(processMetaData.frontendSteps); setSteps(processMetaData.frontendSteps);
}
catch (e)
{
setProcessError("Error loading process definition.");
return;
}
const processResponse = await qController.processInit(processName, queryStringForInit); try
{
const processResponse = await QClient.getInstance().processInit(processName, queryStringForInit);
setProcessUUID(processResponse.processUUID); setProcessUUID(processResponse.processUUID);
setLastProcessResponse(processResponse); setLastProcessResponse(processResponse);
// console.log(processResponse); }
catch (e)
{
setProcessError("Error initializing process.");
}
})(); })();
} }
@ -429,7 +633,6 @@ function ProcessRun(): JSX.Element
////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////
const handleBack = () => const handleBack = () =>
{ {
trace("handleBack");
setNewStep(activeStepIndex - 1); setNewStep(activeStepIndex - 1);
}; };
@ -438,23 +641,44 @@ function ProcessRun(): JSX.Element
////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////
const handleSubmit = async (values: any, actions: any) => const handleSubmit = async (values: any, actions: any) =>
{ {
trace("handleSubmit"); setFormError(null);
// todo - post? const formData = new FormData();
let queryString = "";
Object.keys(values).forEach((key) => Object.keys(values).forEach((key) =>
{ {
queryString += `${key}=${encodeURIComponent(values[key])}&`; formData.append(key, values[key]);
}); });
actions.setSubmitting(false); if (doesStepHaveComponent(activeStep, QComponentType.BULK_EDIT_FORM))
actions.resetForm(); {
const bulkEditEnabledFields: string[] = [];
activeStep.formFields.forEach((field) =>
{
if (!disabledBulkEditFields[field.name])
{
bulkEditEnabledFields.push(field.name);
}
});
const processResponse = await qController.processStep( if (bulkEditEnabledFields.length === 0)
{
setFormError("You must edit at least one field to continue.");
return;
}
formData.append("bulkEditEnabledFields", bulkEditEnabledFields.join(","));
}
const formDataHeaders = {
"content-type": "multipart/form-data; boundary=--------------------------320289315924586491558366",
};
console.log("Calling processStep...");
const processResponse = await QClient.getInstance().processStep(
processName, processName,
processUUID, processUUID,
activeStep.name, activeStep.name,
queryString, formData,
formDataHeaders,
); );
setLastProcessResponse(processResponse); setLastProcessResponse(processResponse);
}; };
@ -529,9 +753,15 @@ function ProcessRun(): JSX.Element
back back
</MDButton> </MDButton>
)} )}
{noMoreSteps || processError ? ( {noMoreSteps || processError || qJobRunning ? (
<MDBox /> <MDBox />
) : ( ) : (
<>
{formError && (
<MDTypography component="div" variant="caption" color="error" fontWeight="regular" align="right" fullWidth>
{formError}
</MDTypography>
)}
<MDButton <MDButton
disabled={isSubmitting} disabled={isSubmitting}
type="submit" type="submit"
@ -540,6 +770,7 @@ function ProcessRun(): JSX.Element
> >
{onLastStep ? "submit" : "next"} {onLastStep ? "submit" : "next"}
</MDButton> </MDButton>
</>
)} )}
</MDBox> </MDBox>
</MDBox> </MDBox>

View File

@ -31,7 +31,7 @@ class QClient
{ {
private static qController: QController; private static qController: QController;
private static getInstance() public static getInstance()
{ {
if (this.qController == null) if (this.qController == null)
{ {