Compare commits

..

13 Commits

Author SHA1 Message Date
bcade32ed1 CE-1107: style updates to icon 2024-04-15 21:37:46 -05:00
8071c54ccd CE-1107: updates to date picker styles 2024-04-15 09:01:31 -05:00
334871988b CE-1107: added alert widget, fixed axios problems 2024-04-12 14:47:37 -05:00
ddb055bc81 Merge pull request #53 from Kingsrook/feature/CE-1072-update-how-we-display-imported
CE-1072 return displayValue for DATE_TIME fields (if they're differen…
2024-04-05 11:30:07 -05:00
66ddf4cb57 CE-1072 return displayValue for DATE_TIME fields (if they're different from the raw value) 2024-04-04 20:06:00 -05:00
7e15f4601d Merged feature/quartz-scheduler into main 2024-03-29 18:35:41 -05:00
cdb61695d1 Merge pull request #50 from Kingsrook/feature/CE-1120-bug-order-statuses-not
CE-1120: updated to handle errors on join tables (specifically was ha…
2024-03-28 15:20:10 -05:00
c08696b3a1 Remove todo no longer needed 2024-03-20 10:34:37 -05:00
84e627467f CE-936 - Update to receive warnings within the response QRecord and display them (this fixes inserts that warn) 2024-03-19 11:13:58 -05:00
6c524c4eca CE-936 - Fix editing child records; fix warning icon on view screen 2024-03-19 10:41:03 -05:00
5c442b2024 qqq-frontend-core 1.0.89 2024-03-18 15:06:17 -05:00
b8c36bccd2 Add abiltiy to edit child records as an association on insert/edit screens. 2024-03-18 15:06:17 -05:00
67feb95c60 Add abiltiy to edit child records as an association on insert/edit screens. 2024-03-18 12:48:16 -05:00
23 changed files with 2075 additions and 1251 deletions

2200
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,13 +6,14 @@
"@auth0/auth0-react": "1.10.2", "@auth0/auth0-react": "1.10.2",
"@emotion/react": "11.7.1", "@emotion/react": "11.7.1",
"@emotion/styled": "11.6.0", "@emotion/styled": "11.6.0",
"@kingsrook/qqq-frontend-core": "1.0.88", "@kingsrook/qqq-frontend-core": "1.0.94",
"@mui/icons-material": "5.4.1", "@mui/icons-material": "5.4.1",
"@mui/material": "5.11.1", "@mui/material": "5.11.1",
"@mui/styles": "5.11.1", "@mui/styles": "5.11.1",
"@mui/system": "5.11.1", "@mui/system": "5.11.1",
"@mui/x-data-grid": "5.17.23", "@mui/x-data-grid": "5.17.23",
"@mui/x-data-grid-pro": "5.17.23", "@mui/x-data-grid-pro": "5.17.23",
"@mui/x-date-pickers": "7.1.1",
"@mui/x-license-pro": "5.12.3", "@mui/x-license-pro": "5.12.3",
"@react-jvectormap/core": "1.0.1", "@react-jvectormap/core": "1.0.1",
"@react-jvectormap/unitedstates": "1.0.1", "@react-jvectormap/unitedstates": "1.0.1",
@ -26,6 +27,7 @@
"chroma-js": "2.4.2", "chroma-js": "2.4.2",
"cmdk": "0.2.0", "cmdk": "0.2.0",
"datejs": "1.0.0-rc3", "datejs": "1.0.0-rc3",
"dayjs": "1.11.10",
"downshift": "3.2.10", "downshift": "3.2.10",
"faker": "5.5.3", "faker": "5.5.3",
"form-data": "4.0.0", "form-data": "4.0.0",

View File

@ -79,7 +79,7 @@ export default function App()
Client.setUnauthorizedCallback(() => Client.setUnauthorizedCallback(() =>
{ {
logout(); logout();
}) });
const shouldStoreNewToken = (newToken: string, oldToken: string): boolean => const shouldStoreNewToken = (newToken: string, oldToken: string): boolean =>
{ {
@ -104,7 +104,7 @@ export default function App()
// if the old (local storage) token is expired, then we need to store the new one // // if the old (local storage) token is expired, then we need to store the new one //
//////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////
const oldExp = oldJSON["exp"]; const oldExp = oldJSON["exp"];
if(oldExp * 1000 < (new Date().getTime())) if (oldExp * 1000 < (new Date().getTime()))
{ {
console.log("Access token in local storage was expired - so we should store a new one."); console.log("Access token in local storage was expired - so we should store a new one.");
return (true); return (true);
@ -114,21 +114,21 @@ export default function App()
// remove the exp & iat values from what we compare - as they are always different from auth0 // // remove the exp & iat values from what we compare - as they are always different from auth0 //
// note, this is only deleting them from what we compare, not from what we'd store. // // note, this is only deleting them from what we compare, not from what we'd store. //
//////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////
delete newJSON["exp"] delete newJSON["exp"];
delete newJSON["iat"] delete newJSON["iat"];
delete oldJSON["exp"] delete oldJSON["exp"];
delete oldJSON["iat"] delete oldJSON["iat"];
const different = JSON.stringify(newJSON) !== JSON.stringify(oldJSON); const different = JSON.stringify(newJSON) !== JSON.stringify(oldJSON);
if(different) if (different)
{ {
console.log("Latest access token from auth0 has changed vs localStorage - so we should store a new one."); console.log("Latest access token from auth0 has changed vs localStorage - so we should store a new one.");
} }
return (different); return (different);
} }
catch(e) catch (e)
{ {
console.log("Caught in shouldStoreNewToken: " + e) console.log("Caught in shouldStoreNewToken: " + e);
} }
return (true); return (true);
@ -185,7 +185,7 @@ export default function App()
{ {
console.log(`Error loading token: ${JSON.stringify(e)}`); console.log(`Error loading token: ${JSON.stringify(e)}`);
qController.clearAuthenticationMetaDataLocalStorage(); qController.clearAuthenticationMetaDataLocalStorage();
localStorage.removeItem("accessToken") localStorage.removeItem("accessToken");
removeCookie(SESSION_UUID_COOKIE_NAME, {path: "/"}); removeCookie(SESSION_UUID_COOKIE_NAME, {path: "/"});
logout(); logout();
return; return;
@ -550,7 +550,7 @@ export default function App()
}); });
} }
const pathToLabelMap: {[path: string]: string} = {} const pathToLabelMap: { [path: string]: string } = {};
for (let i = 0; i < appRoutesList.length; i++) for (let i = 0; i < appRoutesList.length; i++)
{ {
const route = appRoutesList[i]; const route = appRoutesList[i];
@ -575,11 +575,11 @@ export default function App()
console.error(e); console.error(e);
if (e instanceof QException) if (e instanceof QException)
{ {
if ((e as QException).status === "401") if ((e as QException).status === 401)
{ {
console.log("Exception is a QException with status = 401. Clearing some of localStorage & cookies"); console.log("Exception is a QException with status = 401. Clearing some of localStorage & cookies");
qController.clearAuthenticationMetaDataLocalStorage(); qController.clearAuthenticationMetaDataLocalStorage();
localStorage.removeItem("accessToken") localStorage.removeItem("accessToken");
removeCookie(SESSION_UUID_COOKIE_NAME, {path: "/"}); removeCookie(SESSION_UUID_COOKIE_NAME, {path: "/"});
////////////////////////////////////////////////////// //////////////////////////////////////////////////////
@ -656,7 +656,7 @@ export default function App()
const [pageHeader, setPageHeader] = useState("" as string | JSX.Element); const [pageHeader, setPageHeader] = useState("" as string | JSX.Element);
const [accentColor, setAccentColor] = useState("#0062FF"); const [accentColor, setAccentColor] = useState("#0062FF");
const [accentColorLight, setAccentColorLight] = useState("#C0D6F7") const [accentColorLight, setAccentColorLight] = useState("#C0D6F7");
const [tableMetaData, setTableMetaData] = useState(null); const [tableMetaData, setTableMetaData] = useState(null);
const [tableProcesses, setTableProcesses] = useState(null); const [tableProcesses, setTableProcesses] = useState(null);
const [dotMenuOpen, setDotMenuOpen] = useState(false); const [dotMenuOpen, setDotMenuOpen] = useState(false);
@ -707,4 +707,4 @@ export default function App()
</QContext.Provider> </QContext.Provider>
) )
); );
} }

View File

@ -34,10 +34,10 @@ import ToggleButton from "@mui/material/ToggleButton";
import ToggleButtonGroup from "@mui/material/ToggleButtonGroup"; import ToggleButtonGroup from "@mui/material/ToggleButtonGroup";
import Tooltip from "@mui/material/Tooltip"; import Tooltip from "@mui/material/Tooltip";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import React, {useContext, useEffect, useState} from "react";
import QContext from "QContext"; import QContext from "QContext";
import Client from "qqq/utils/qqq/Client"; import Client from "qqq/utils/qqq/Client";
import ValueUtils from "qqq/utils/qqq/ValueUtils"; import ValueUtils from "qqq/utils/qqq/ValueUtils";
import React, {useContext, useEffect, useState} from "react";
interface Props interface Props
{ {
@ -217,7 +217,7 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
{ {
if (e instanceof QException) if (e instanceof QException)
{ {
if ((e as QException).status === "403") if ((e as QException).status === 403)
{ {
setStatusString("You do not have permission to view audits"); setStatusString("You do not have permission to view audits");
return; return;

View File

@ -24,27 +24,38 @@ import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QF
import {QFieldType} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldType"; import {QFieldType} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldType";
import * as Yup from "yup"; import * as Yup from "yup";
type DisabledFields = { [fieldName: string]: boolean } | string[];
/******************************************************************************* /*******************************************************************************
** Meta-data to represent a single field in a table. ** Meta-data to represent a single field in a table.
** **
*******************************************************************************/ *******************************************************************************/
class DynamicFormUtils class DynamicFormUtils
{ {
public static getFormData(qqqFormFields: QFieldMetaData[])
/*******************************************************************************
**
*******************************************************************************/
public static getFormData(qqqFormFields: QFieldMetaData[], disabledFields?: DisabledFields)
{ {
const dynamicFormFields: any = {}; const dynamicFormFields: any = {};
const formValidations: any = {}; const formValidations: any = {};
qqqFormFields.forEach((field) => qqqFormFields.forEach((field) =>
{ {
dynamicFormFields[field.name] = this.getDynamicField(field); dynamicFormFields[field.name] = this.getDynamicField(field, disabledFields);
formValidations[field.name] = this.getValidationForField(field); formValidations[field.name] = this.getValidationForField(field, disabledFields);
}); });
return {dynamicFormFields, formValidations}; return {dynamicFormFields, formValidations};
} }
public static getDynamicField(field: QFieldMetaData)
/*******************************************************************************
**
*******************************************************************************/
public static getDynamicField(field: QFieldMetaData, disabledFields?: DisabledFields)
{ {
let fieldType: string; let fieldType: string;
switch (field.type.toString()) switch (field.type.toString())
@ -85,15 +96,21 @@ class DynamicFormUtils
} }
} }
////////////////////////////////////////////////////////////
// this feels right, but... might be cases where it isn't //
////////////////////////////////////////////////////////////
const effectiveIsEditable = field.isEditable && !this.isFieldDynamicallyDisabled(field.name, disabledFields);
const effectivelyIsRequired = field.isRequired && effectiveIsEditable;
let label = field.label ? field.label : field.name; let label = field.label ? field.label : field.name;
label += field.isRequired ? " *" : ""; label += effectivelyIsRequired ? " *" : "";
return ({ return ({
fieldMetaData: field, fieldMetaData: field,
name: field.name, name: field.name,
label: label, label: label,
isRequired: field.isRequired, isRequired: effectivelyIsRequired,
isEditable: field.isEditable, isEditable: effectiveIsEditable,
type: fieldType, type: fieldType,
displayFormat: field.displayFormat, displayFormat: field.displayFormat,
// todo invalidMsg: "Zipcode is not valid (e.g. 70000).", // todo invalidMsg: "Zipcode is not valid (e.g. 70000).",
@ -101,11 +118,18 @@ class DynamicFormUtils
}); });
} }
public static getValidationForField(field: QFieldMetaData)
/*******************************************************************************
**
*******************************************************************************/
public static getValidationForField(field: QFieldMetaData, disabledFields?: DisabledFields)
{ {
if (field.isRequired) const effectiveIsEditable = field.isEditable && !this.isFieldDynamicallyDisabled(field.name, disabledFields);
const effectivelyIsRequired = field.isRequired && effectiveIsEditable;
if (effectivelyIsRequired)
{ {
if(field.possibleValueSourceName) if (field.possibleValueSourceName)
{ {
//////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////
// the "nullable(true)" here doesn't mean that you're allowed to set the field to null... // // the "nullable(true)" here doesn't mean that you're allowed to set the field to null... //
@ -121,6 +145,10 @@ class DynamicFormUtils
return (null); return (null);
} }
/*******************************************************************************
**
*******************************************************************************/
public static addPossibleValueProps(dynamicFormFields: any, qFields: QFieldMetaData[], tableName: string, processName: string, displayValues: Map<string, string>) public static addPossibleValueProps(dynamicFormFields: any, qFields: QFieldMetaData[], tableName: string, processName: string, displayValues: Map<string, string>)
{ {
for (let i = 0; i < qFields.length; i++) for (let i = 0; i < qFields.length; i++)
@ -159,6 +187,29 @@ class DynamicFormUtils
} }
} }
} }
/*******************************************************************************
** private helper - check the disabled fields object (array or map), and return
** true iff fieldName is in it.
*******************************************************************************/
private static isFieldDynamicallyDisabled(fieldName: string, disabledFields?: DisabledFields): boolean
{
if (!disabledFields)
{
return (false);
}
if (Array.isArray(disabledFields))
{
return (disabledFields.indexOf(fieldName) > -1)
}
else
{
return (disabledFields[fieldName]);
}
}
} }
export default DynamicFormUtils; export default DynamicFormUtils;

View File

@ -22,8 +22,10 @@
import {Capability} from "@kingsrook/qqq-frontend-core/lib/model/metaData/Capability"; import {Capability} from "@kingsrook/qqq-frontend-core/lib/model/metaData/Capability";
import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData"; import {QFieldMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldMetaData";
import {QFieldType} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldType"; import {QFieldType} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QFieldType";
import {QInstance} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QInstance";
import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData"; import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableMetaData";
import {QTableSection} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableSection"; import {QTableSection} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QTableSection";
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
import {QPossibleValue} from "@kingsrook/qqq-frontend-core/lib/model/QPossibleValue"; import {QPossibleValue} from "@kingsrook/qqq-frontend-core/lib/model/QPossibleValue";
import {QRecord} from "@kingsrook/qqq-frontend-core/lib/model/QRecord"; import {QRecord} from "@kingsrook/qqq-frontend-core/lib/model/QRecord";
import {Alert} from "@mui/material"; import {Alert} from "@mui/material";
@ -32,22 +34,24 @@ import Box from "@mui/material/Box";
import Card from "@mui/material/Card"; import Card from "@mui/material/Card";
import Grid from "@mui/material/Grid"; import Grid from "@mui/material/Grid";
import Icon from "@mui/material/Icon"; import Icon from "@mui/material/Icon";
import {Form, Formik, useFormikContext} from "formik"; import Modal from "@mui/material/Modal";
import React, {useContext, useEffect, useReducer, useState} from "react"; import {Form, Formik, FormikErrors, FormikTouched, FormikValues, useFormikContext} from "formik";
import {useLocation, useNavigate, useParams} from "react-router-dom";
import * as Yup from "yup";
import QContext from "QContext"; import QContext from "QContext";
import colors from "qqq/assets/theme/base/colors";
import {QCancelButton, QSaveButton} from "qqq/components/buttons/DefaultButtons"; import {QCancelButton, QSaveButton} from "qqq/components/buttons/DefaultButtons";
import QDynamicForm from "qqq/components/forms/DynamicForm"; import QDynamicForm from "qqq/components/forms/DynamicForm";
import DynamicFormUtils from "qqq/components/forms/DynamicFormUtils"; import DynamicFormUtils from "qqq/components/forms/DynamicFormUtils";
import MDTypography from "qqq/components/legacy/MDTypography"; import MDTypography from "qqq/components/legacy/MDTypography";
import HelpContent from "qqq/components/misc/HelpContent"; import HelpContent from "qqq/components/misc/HelpContent";
import QRecordSidebar from "qqq/components/misc/RecordSidebar"; import QRecordSidebar from "qqq/components/misc/RecordSidebar";
import RecordGridWidget, {ChildRecordListData} from "qqq/components/widgets/misc/RecordGridWidget";
import HtmlUtils from "qqq/utils/HtmlUtils"; import HtmlUtils from "qqq/utils/HtmlUtils";
import Client from "qqq/utils/qqq/Client"; import Client from "qqq/utils/qqq/Client";
import TableUtils from "qqq/utils/qqq/TableUtils"; import TableUtils from "qqq/utils/qqq/TableUtils";
import ValueUtils from "qqq/utils/qqq/ValueUtils"; import ValueUtils from "qqq/utils/qqq/ValueUtils";
import React, {useContext, useEffect, useReducer, useState} from "react";
import {useLocation, useNavigate, useParams} from "react-router-dom";
import {Value} from "sass";
import * as Yup from "yup";
interface Props interface Props
{ {
@ -58,6 +62,8 @@ interface Props
defaultValues: { [key: string]: string }; defaultValues: { [key: string]: string };
disabledFields: { [key: string]: boolean } | string[]; disabledFields: { [key: string]: boolean } | string[];
isCopy?: boolean; isCopy?: boolean;
onSubmitCallback?: (values: any) => void;
overrideHeading?: string
} }
EntityForm.defaultProps = { EntityForm.defaultProps = {
@ -67,7 +73,8 @@ EntityForm.defaultProps = {
closeModalHandler: null, closeModalHandler: null,
defaultValues: {}, defaultValues: {},
disabledFields: {}, disabledFields: {},
isCopy: false isCopy: false,
onSubmitCallback: null,
}; };
function EntityForm(props: Props): JSX.Element function EntityForm(props: Props): JSX.Element
@ -90,10 +97,15 @@ function EntityForm(props: Props): JSX.Element
const [asyncLoadInited, setAsyncLoadInited] = useState(false); const [asyncLoadInited, setAsyncLoadInited] = useState(false);
const [tableMetaData, setTableMetaData] = useState(null as QTableMetaData); const [tableMetaData, setTableMetaData] = useState(null as QTableMetaData);
const [metaData, setMetaData] = useState(null as QInstance);
const [record, setRecord] = useState(null as QRecord); const [record, setRecord] = useState(null as QRecord);
const [tableSections, setTableSections] = useState(null as QTableSection[]); const [tableSections, setTableSections] = useState(null as QTableSection[]);
const [renderedWidgetSections, setRenderedWidgetSections] = useState({} as {[name: string]: JSX.Element});
const [childListWidgetData, setChildListWidgetData] = useState({} as {[name: string]: ChildRecordListData});
const [, forceUpdate] = useReducer((x) => x + 1, 0); const [, forceUpdate] = useReducer((x) => x + 1, 0);
const [showEditChildForm, setShowEditChildForm] = useState(null as any);
const [notAllowedError, setNotAllowedError] = useState(null as string); const [notAllowedError, setNotAllowedError] = useState(null as string);
const {pageHeader, setPageHeader} = useContext(QContext); const {pageHeader, setPageHeader} = useContext(QContext);
@ -101,6 +113,8 @@ function EntityForm(props: Props): JSX.Element
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
const cardElevation = props.isModal ? 3 : 0;
//////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////
// first take defaultValues and disabledFields from props // // first take defaultValues and disabledFields from props //
// but, also allow them to be sent in the hash, in the format of: // // but, also allow them to be sent in the hash, in the format of: //
@ -129,7 +143,131 @@ function EntityForm(props: Props): JSX.Element
{} {}
} }
function getFormSection(values: any, touched: any, formFields: any, errors: any): JSX.Element
/*******************************************************************************
**
*******************************************************************************/
function openAddChildRecord(name: string, widgetData: any)
{
let defaultValues = widgetData.defaultValuesForNewChildRecords;
let disabledFields = widgetData.disabledFieldsForNewChildRecords;
if(!disabledFields)
{
disabledFields = widgetData.defaultValuesForNewChildRecords;
}
doOpenEditChildForm(name, widgetData.childTableMetaData, null, defaultValues, disabledFields);
}
/*******************************************************************************
**
*******************************************************************************/
function openEditChildRecord(name: string, widgetData: any, rowIndex: number)
{
let defaultValues = widgetData.queryOutput.records[rowIndex].values;
let disabledFields = widgetData.disabledFieldsForNewChildRecords;
if(!disabledFields)
{
disabledFields = widgetData.defaultValuesForNewChildRecords;
}
doOpenEditChildForm(name, widgetData.childTableMetaData, rowIndex, defaultValues, disabledFields);
}
/*******************************************************************************
**
*******************************************************************************/
const deleteChildRecord = (name: string, widgetData: any, rowIndex: number) =>
{
updateChildRecordList(name, "delete", rowIndex);
};
/*******************************************************************************
**
*******************************************************************************/
function doOpenEditChildForm(widgetName: string, table: QTableMetaData, rowIndex: number, defaultValues: any, disabledFields: any)
{
const showEditChildForm: any = {};
showEditChildForm.widgetName = widgetName;
showEditChildForm.table = table;
showEditChildForm.rowIndex = rowIndex;
showEditChildForm.defaultValues = defaultValues;
showEditChildForm.disabledFields = disabledFields;
setShowEditChildForm(showEditChildForm);
}
/*******************************************************************************
**
*******************************************************************************/
const closeEditChildForm = (event: object, reason: string) =>
{
if (reason === "backdropClick" || reason === "escapeKeyDown")
{
return;
}
setShowEditChildForm(null);
};
/*******************************************************************************
**
*******************************************************************************/
function submitEditChildForm(values: any)
{
updateChildRecordList(showEditChildForm.widgetName, showEditChildForm.rowIndex == null ? "insert" : "edit", showEditChildForm.rowIndex, values);
}
/*******************************************************************************
**
*******************************************************************************/
async function updateChildRecordList(widgetName: string, action: "insert" | "edit" | "delete", rowIndex?: number, values?: any)
{
const metaData = await qController.loadMetaData();
const widgetMetaData = metaData.widgets.get(widgetName);
const newChildListWidgetData: {[name: string]: ChildRecordListData} = Object.assign({}, childListWidgetData)
if(!newChildListWidgetData[widgetName].queryOutput.records)
{
newChildListWidgetData[widgetName].queryOutput.records = [];
}
switch(action)
{
case "insert":
newChildListWidgetData[widgetName].queryOutput.records.push({values: values})
break;
case "edit":
newChildListWidgetData[widgetName].queryOutput.records[rowIndex] = {values: values};
break;
case "delete":
newChildListWidgetData[widgetName].queryOutput.records.splice(rowIndex, 1);
break;
}
newChildListWidgetData[widgetName].totalRows = newChildListWidgetData[widgetName].queryOutput.records.length;
setChildListWidgetData(newChildListWidgetData);
const newRenderedWidgetSections = Object.assign({}, renderedWidgetSections)
newRenderedWidgetSections[widgetName] = getWidgetSection(widgetMetaData, newChildListWidgetData[widgetName]);
setRenderedWidgetSections(newRenderedWidgetSections);
forceUpdate();
setShowEditChildForm(null);
}
/*******************************************************************************
** render a section (full of fields) as a form
*******************************************************************************/
function getFormSection(section: QTableSection, values: any, touched: any, formFields: any, errors: any, omitWrapper = false): JSX.Element
{ {
const formData: any = {}; const formData: any = {};
formData.values = values; formData.values = values;
@ -152,13 +290,68 @@ function EntityForm(props: Props): JSX.Element
if (!Object.keys(formFields).length) if (!Object.keys(formFields).length)
{ {
return <div>Loading...</div>; return <div>Error: No form fields in section {section.name}</div>;
} }
const helpRoles = [props.id ? "EDIT_SCREEN" : "INSERT_SCREEN", "WRITE_SCREENS", "ALL_SCREENS"] const helpRoles = [props.id ? "EDIT_SCREEN" : "INSERT_SCREEN", "WRITE_SCREENS", "ALL_SCREENS"]
return <QDynamicForm formData={formData} record={record} helpRoles={helpRoles} helpContentKeyPrefix={`table:${tableName};`} />;
if(omitWrapper)
{
return <QDynamicForm formData={formData} record={record} helpRoles={helpRoles} helpContentKeyPrefix={`table:${tableName};`} />
}
return <Card id={section.name} sx={{overflow: "visible", scrollMarginTop: "100px"}} elevation={cardElevation}>
<MDTypography variant="h6" p={3} pb={1}>
{section.label}
</MDTypography>
{getSectionHelp(section)}
<Box pb={1} px={3}>
<Box pb={"0.75rem"} width="100%">
<QDynamicForm formData={formData} record={record} helpRoles={helpRoles} helpContentKeyPrefix={`table:${tableName};`} />
</Box>
</Box>
</Card>
} }
/*******************************************************************************
** render a section as a widget
*******************************************************************************/
function getWidgetSection(widgetMetaData: QWidgetMetaData, widgetData: any): JSX.Element
{
widgetData.viewAllLink = null;
widgetMetaData.showExportButton = false;
return <RecordGridWidget
key={new Date().getTime()} // added so that editing values actually re-renders...
widgetMetaData={widgetMetaData}
data={widgetData}
disableRowClick
allowRecordEdit
allowRecordDelete
addNewRecordCallback={() => openAddChildRecord(widgetMetaData.name, widgetData)}
editRecordCallback={(rowIndex) => openEditChildRecord(widgetMetaData.name, widgetData, rowIndex)}
deleteRecordCallback={(rowIndex) => deleteChildRecord(widgetMetaData.name, widgetData, rowIndex)}
/>
}
/*******************************************************************************
** render a form section
*******************************************************************************/
function renderSection(section: QTableSection, values: FormikValues | Value, touched: FormikTouched<FormikValues> | Value, formFields: Map<string, any>, errors: FormikErrors<FormikValues> | Value)
{
if(section.fieldNames && section.fieldNames.length > 0)
{
return getFormSection(section, values, touched, formFields.get(section.name), errors);
}
else
{
return renderedWidgetSections[section.widgetName] ?? <Box>Loading {section.label}...</Box>
}
}
if (!asyncLoadInited) if (!asyncLoadInited)
{ {
setAsyncLoadInited(true); setAsyncLoadInited(true);
@ -167,10 +360,16 @@ function EntityForm(props: Props): JSX.Element
const tableMetaData = await qController.loadTableMetaData(tableName); const tableMetaData = await qController.loadTableMetaData(tableName);
setTableMetaData(tableMetaData); setTableMetaData(tableMetaData);
const metaData = await qController.loadMetaData();
setMetaData(metaData);
///////////////////////////////////////////////// /////////////////////////////////////////////////
// define the sections, e.g., for the left-bar // // define the sections, e.g., for the left-bar //
///////////////////////////////////////////////// /////////////////////////////////////////////////
const tableSections = TableUtils.getSectionsForRecordSidebar(tableMetaData, [...tableMetaData.fields.keys()]); const tableSections = TableUtils.getSectionsForRecordSidebar(tableMetaData, [...tableMetaData.fields.keys()], (section: QTableSection) =>
{
return section.widgetName && metaData.widgets.get(section.widgetName)?.type == "childRecordList" && metaData.widgets.get(section.widgetName)?.defaultValues?.has("manageAssociationName")
});
setTableSections(tableSections); setTableSections(tableSections);
const fieldArray = [] as QFieldMetaData[]; const fieldArray = [] as QFieldMetaData[];
@ -263,6 +462,18 @@ function EntityForm(props: Props): JSX.Element
} }
} }
///////////////////////////////////////////////////
// if an override heading was passed in, use it. //
///////////////////////////////////////////////////
if(props.overrideHeading)
{
setFormTitle(props.overrideHeading);
if (!props.isModal)
{
setPageHeader(props.overrideHeading);
}
}
////////////////////////////////////// //////////////////////////////////////
// check capabilities & permissions // // check capabilities & permissions //
////////////////////////////////////// //////////////////////////////////////
@ -309,27 +520,9 @@ function EntityForm(props: Props): JSX.Element
const { const {
dynamicFormFields, dynamicFormFields,
formValidations, formValidations,
} = DynamicFormUtils.getFormData(fieldArray); } = DynamicFormUtils.getFormData(fieldArray, disabledFields);
DynamicFormUtils.addPossibleValueProps(dynamicFormFields, fieldArray, tableName, null, record ? record.displayValues : defaultDisplayValues); DynamicFormUtils.addPossibleValueProps(dynamicFormFields, fieldArray, tableName, null, record ? record.displayValues : defaultDisplayValues);
if(disabledFields)
{
if(Array.isArray(disabledFields))
{
for (let i = 0; i < disabledFields.length; i++)
{
dynamicFormFields[disabledFields[i]].isEditable = false;
}
}
else
{
for (let fieldName in disabledFields)
{
dynamicFormFields[fieldName].isEditable = false;
}
}
}
///////////////////////////////////// /////////////////////////////////////
// group the formFields by section // // group the formFields by section //
///////////////////////////////////// /////////////////////////////////////
@ -337,51 +530,70 @@ function EntityForm(props: Props): JSX.Element
let t1sectionName; let t1sectionName;
let t1section; let t1section;
const nonT1Sections: QTableSection[] = []; const nonT1Sections: QTableSection[] = [];
const newRenderedWidgetSections: {[name: string]: JSX.Element} = {};
const newChildListWidgetData: {[name: string]: ChildRecordListData} = {};
for (let i = 0; i < tableSections.length; i++) for (let i = 0; i < tableSections.length; i++)
{ {
const section = tableSections[i]; const section = tableSections[i];
const sectionDynamicFormFields: any[] = []; const sectionDynamicFormFields: any[] = [];
if (section.isHidden || !section.fieldNames) if (section.isHidden)
{ {
continue; continue;
} }
for (let j = 0; j < section.fieldNames.length; j++) const hasFields = section.fieldNames && section.fieldNames.length > 0;
const hasChildRecordListWidget = section.widgetName && metaData.widgets.get(section.widgetName)?.type == "childRecordList"
if(!hasFields && !hasChildRecordListWidget)
{ {
const fieldName = section.fieldNames[j]; continue;
const field = tableMetaData.fields.get(fieldName); }
if(!field) if(hasFields)
{
for (let j = 0; j < section.fieldNames.length; j++)
{ {
console.log(`Omitting un-found field ${fieldName} from form`); const fieldName = section.fieldNames[j];
const field = tableMetaData.fields.get(fieldName);
if (!field)
{
console.log(`Omitting un-found field ${fieldName} from form`);
continue;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// if id !== null (and we're not copying) - means we're on the edit screen -- show all fields on the edit screen. //
// || (or) we're on the insert screen in which case, only show editable fields. //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if ((props.id !== null && !props.isCopy) || field.isEditable)
{
sectionDynamicFormFields.push(dynamicFormFields[fieldName]);
}
}
if (sectionDynamicFormFields.length === 0)
{
////////////////////////////////////////////////////////////////////////////////////////////////
// in case there are no active fields in this section, remove it from the tableSections array //
////////////////////////////////////////////////////////////////////////////////////////////////
tableSections.splice(i, 1);
i--;
continue; continue;
} }
else
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// if id !== null (and we're not copying) - means we're on the edit screen -- show all fields on the edit screen. //
// || (or) we're on the insert screen in which case, only show editable fields. //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if ((props.id !== null && !props.isCopy) || field.isEditable)
{ {
sectionDynamicFormFields.push(dynamicFormFields[fieldName]); dynamicFormFieldsBySection.set(section.name, sectionDynamicFormFields);
} }
} }
if (sectionDynamicFormFields.length === 0)
{
////////////////////////////////////////////////////////////////////////////////////////////////
// in case there are no active fields in this section, remove it from the tableSections array //
////////////////////////////////////////////////////////////////////////////////////////////////
tableSections.splice(i, 1);
i--;
continue;
}
else else
{ {
dynamicFormFieldsBySection.set(section.name, sectionDynamicFormFields); const widgetMetaData = metaData.widgets.get(section.widgetName);
const widgetData = await qController.widget(widgetMetaData.name, props.id ? `${tableMetaData.primaryKeyField}=${props.id}` : "");
newRenderedWidgetSections[section.widgetName] = getWidgetSection(widgetMetaData, widgetData);
newChildListWidgetData[section.widgetName] = widgetData;
} }
////////////////////////////////////// //////////////////////////////////////
// capture the tier1 section's name // // capture the tier1 section's name //
////////////////////////////////////// //////////////////////////////////////
@ -395,16 +607,38 @@ function EntityForm(props: Props): JSX.Element
nonT1Sections.push(section); nonT1Sections.push(section);
} }
} }
setT1SectionName(t1sectionName); setT1SectionName(t1sectionName);
setT1Section(t1section); setT1Section(t1section);
setNonT1Sections(nonT1Sections); setNonT1Sections(nonT1Sections);
setFormFields(dynamicFormFieldsBySection); setFormFields(dynamicFormFieldsBySection);
setValidations(Yup.object().shape(formValidations)); setValidations(Yup.object().shape(formValidations));
setRenderedWidgetSections(newRenderedWidgetSections);
setChildListWidgetData(newChildListWidgetData);
forceUpdate(); forceUpdate();
})(); })();
} }
//////////////////////////////////////////////////////////////////
// watch widget data - if they change, re-render those sections //
//////////////////////////////////////////////////////////////////
useEffect(() =>
{
if(childListWidgetData)
{
const newRenderedWidgetSections: {[name: string]: JSX.Element} = {};
for(let name in childListWidgetData)
{
const widgetMetaData = metaData.widgets.get(name);
newRenderedWidgetSections[name] = getWidgetSection(widgetMetaData, childListWidgetData[name]);
}
setRenderedWidgetSections(newRenderedWidgetSections);
}
}, [childListWidgetData]);
const handleCancelClicked = () => const handleCancelClicked = () =>
{ {
/////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////
@ -429,9 +663,23 @@ function EntityForm(props: Props): JSX.Element
} }
}; };
/*******************************************************************************
** event handler for the (Formik) Form.
*******************************************************************************/
const handleSubmit = async (values: any, actions: any) => const handleSubmit = async (values: any, actions: any) =>
{ {
actions.setSubmitting(true); actions.setSubmitting(true);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// if there's a callback (e.g., for a modal nested on another create/edit screen), then just pass our data back there anre return. //
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(props.onSubmitCallback)
{
props.onSubmitCallback(values);
return;
}
await (async () => await (async () =>
{ {
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@ -486,9 +734,32 @@ function EntityForm(props: Props): JSX.Element
} }
} }
const associationsToPost: any = {}
let haveAssociationsToPost = false;
for (let name of Object.keys(childListWidgetData))
{
const manageAssociationName = metaData.widgets.get(name)?.defaultValues?.get("manageAssociationName")
if(!manageAssociationName)
{
console.log(`Cannot send association data to backend - missing a manageAssociationName defaultValue in widget meta data for widget name ${name}`);
}
associationsToPost[manageAssociationName] = [];
haveAssociationsToPost = true;
for(let i=0; i<childListWidgetData[name].queryOutput?.records?.length; i++)
{
associationsToPost[manageAssociationName].push(childListWidgetData[name].queryOutput.records[i].values);
}
}
if(haveAssociationsToPost)
{
valuesToPost["associations"] = JSON.stringify(associationsToPost);
}
if (props.id !== null && !props.isCopy) if (props.id !== null && !props.isCopy)
{ {
// todo - audit that it's a dupe ///////////////////////
// perform an update //
///////////////////////
await qController await qController
.update(tableName, props.id, valuesToPost) .update(tableName, props.id, valuesToPost)
.then((record) => .then((record) =>
@ -499,8 +770,14 @@ function EntityForm(props: Props): JSX.Element
} }
else else
{ {
let warningMessage = null;
if(record.warnings && record.warnings.length && record.warnings.length > 0)
{
warningMessage = record.warnings[0];
}
const path = location.pathname.replace(/\/edit$/, ""); const path = location.pathname.replace(/\/edit$/, "");
navigate(path, {state: {updateSuccess: true}}); navigate(path, {state: {updateSuccess: true, warning: warningMessage}});
} }
}) })
.catch((error) => .catch((error) =>
@ -522,6 +799,10 @@ function EntityForm(props: Props): JSX.Element
} }
else else
{ {
/////////////////////////////////
// perform an insert //
// todo - audit if it's a dupe //
/////////////////////////////////
await qController await qController
.create(tableName, valuesToPost) .create(tableName, valuesToPost)
.then((record) => .then((record) =>
@ -532,10 +813,16 @@ function EntityForm(props: Props): JSX.Element
} }
else else
{ {
let warningMessage = null;
if(record.warnings && record.warnings.length && record.warnings.length > 0)
{
warningMessage = record.warnings[0];
}
const path = props.isCopy ? const path = props.isCopy ?
location.pathname.replace(new RegExp(`/${props.id}/copy$`), "/" + record.values.get(tableMetaData.primaryKeyField)) location.pathname.replace(new RegExp(`/${props.id}/copy$`), "/" + record.values.get(tableMetaData.primaryKeyField))
: location.pathname.replace(/create$/, record.values.get(tableMetaData.primaryKeyField)); : location.pathname.replace(/create$/, record.values.get(tableMetaData.primaryKeyField));
navigate(path, {state: {createSuccess: true}}); navigate(path, {state: {createSuccess: true, warning: warningMessage}});
} }
}) })
.catch((error) => .catch((error) =>
@ -594,7 +881,6 @@ function EntityForm(props: Props): JSX.Element
} }
else else
{ {
const cardElevation = props.isModal ? 3 : 0;
body = ( body = (
<Box mb={3}> <Box mb={3}>
{ {
@ -656,7 +942,7 @@ function EntityForm(props: Props): JSX.Element
t1sectionName && formFields ? ( t1sectionName && formFields ? (
<Box px={3}> <Box px={3}>
<Box pb={"0.25rem"} width="100%"> <Box pb={"0.25rem"} width="100%">
{getFormSection(values, touched, formFields.get(t1sectionName), errors)} {getFormSection(t1section, values, touched, formFields.get(t1sectionName), errors, true)}
</Box> </Box>
</Box> </Box>
) : null ) : null
@ -665,17 +951,7 @@ function EntityForm(props: Props): JSX.Element
</Box> </Box>
{formFields && nonT1Sections.length ? nonT1Sections.map((section: QTableSection) => ( {formFields && nonT1Sections.length ? nonT1Sections.map((section: QTableSection) => (
<Box key={`edit-card-${section.name}`} pb={3}> <Box key={`edit-card-${section.name}`} pb={3}>
<Card id={section.name} sx={{overflow: "visible", scrollMarginTop: "100px"}} elevation={cardElevation}> {renderSection(section, values, touched, formFields, errors)}
<MDTypography variant="h6" p={3} pb={1}>
{section.label}
</MDTypography>
{getSectionHelp(section)}
<Box pb={1} px={3}>
<Box pb={"0.75rem"} width="100%">
{getFormSection(values, touched, formFields.get(section.name), errors)}
</Box>
</Box>
</Card>
</Box> </Box>
)) : null} )) : null}
@ -690,6 +966,23 @@ function EntityForm(props: Props): JSX.Element
)} )}
</Formik> </Formik>
{
showEditChildForm &&
<Modal open={showEditChildForm as boolean} onClose={(event, reason) => closeEditChildForm(event, reason)}>
<div className="modalEditForm">
<EntityForm
isModal={true}
closeModalHandler={closeEditChildForm}
table={showEditChildForm.table}
defaultValues={showEditChildForm.defaultValues}
disabledFields={showEditChildForm.disabledFields}
onSubmitCallback={submitEditChildForm}
overrideHeading={`${showEditChildForm.rowIndex != null ? "Editing" : "Creating New"} ${showEditChildForm.table.label}`}
/>
</div>
</Modal>
}
</Grid> </Grid>
</Grid> </Grid>
</Box> </Box>

View File

@ -19,13 +19,12 @@
*/ */
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData"; import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
import {Skeleton} from "@mui/material"; import {Alert, Skeleton} from "@mui/material";
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import Grid from "@mui/material/Grid"; import Grid from "@mui/material/Grid";
import Tab from "@mui/material/Tab"; import Tab from "@mui/material/Tab";
import Tabs from "@mui/material/Tabs"; import Tabs from "@mui/material/Tabs";
import parse from "html-react-parser"; import parse from "html-react-parser";
import React, {useContext, useEffect, useReducer, useState} from "react";
import QContext from "QContext"; import QContext from "QContext";
import MDTypography from "qqq/components/legacy/MDTypography"; import MDTypography from "qqq/components/legacy/MDTypography";
import TabPanel from "qqq/components/misc/TabPanel"; import TabPanel from "qqq/components/misc/TabPanel";
@ -47,10 +46,11 @@ import USMapWidget from "qqq/components/widgets/misc/USMapWidget";
import ParentWidget from "qqq/components/widgets/ParentWidget"; import ParentWidget from "qqq/components/widgets/ParentWidget";
import MultiStatisticsCard from "qqq/components/widgets/statistics/MultiStatisticsCard"; import MultiStatisticsCard from "qqq/components/widgets/statistics/MultiStatisticsCard";
import StatisticsCard from "qqq/components/widgets/statistics/StatisticsCard"; import StatisticsCard from "qqq/components/widgets/statistics/StatisticsCard";
import Widget, {HeaderIcon, WIDGET_DROPDOWN_SELECTION_LOCAL_STORAGE_KEY_ROOT, LabelComponent} from "qqq/components/widgets/Widget"; import Widget, {HeaderIcon, LabelComponent, WIDGET_DROPDOWN_SELECTION_LOCAL_STORAGE_KEY_ROOT} from "qqq/components/widgets/Widget";
import WidgetBlock from "qqq/components/widgets/WidgetBlock"; import WidgetBlock from "qqq/components/widgets/WidgetBlock";
import ProcessRun from "qqq/pages/processes/ProcessRun"; import ProcessRun from "qqq/pages/processes/ProcessRun";
import Client from "qqq/utils/qqq/Client"; import Client from "qqq/utils/qqq/Client";
import React, {useContext, useEffect, useReducer, useState} from "react";
import TableWidget from "./tables/TableWidget"; import TableWidget from "./tables/TableWidget";
@ -91,9 +91,9 @@ function DashboardWidgets({widgetMetaDataList, tableName, entityPrimaryKey, omit
let initialSelectedTab = 0; let initialSelectedTab = 0;
let selectedTabKey: string = null; let selectedTabKey: string = null;
if(parentWidgetMetaData && wrapWidgetsInTabPanels) if (parentWidgetMetaData && wrapWidgetsInTabPanels)
{ {
selectedTabKey = `qqq.widgets.selectedTabs.${parentWidgetMetaData.name}` selectedTabKey = `qqq.widgets.selectedTabs.${parentWidgetMetaData.name}`;
if (localStorage.getItem(selectedTabKey)) if (localStorage.getItem(selectedTabKey))
{ {
initialSelectedTab = Number(localStorage.getItem(selectedTabKey)); initialSelectedTab = Number(localStorage.getItem(selectedTabKey));
@ -191,7 +191,7 @@ function DashboardWidgets({widgetMetaDataList, tableName, entityPrimaryKey, omit
const metaDataToUse = (thisWidgetHasDropdowns) ? widgetMetaData : parentWidgetMetaData; const metaDataToUse = (thisWidgetHasDropdowns) ? widgetMetaData : parentWidgetMetaData;
for (let i = 0; i < metaDataToUse.dropdowns.length; i++) for (let i = 0; i < metaDataToUse.dropdowns.length; i++)
{ {
const dropdownName = metaDataToUse.dropdowns[i].possibleValueSourceName; const dropdownName = metaDataToUse.dropdowns[i].possibleValueSourceName ?? metaDataToUse.dropdowns[i].name;
const localStorageKey = `${WIDGET_DROPDOWN_SELECTION_LOCAL_STORAGE_KEY_ROOT}.${metaDataToUse.name}.${dropdownName}`; const localStorageKey = `${WIDGET_DROPDOWN_SELECTION_LOCAL_STORAGE_KEY_ROOT}.${metaDataToUse.name}.${dropdownName}`;
const json = JSON.parse(localStorage.getItem(localStorageKey)); const json = JSON.parse(localStorage.getItem(localStorageKey));
if (json) if (json)
@ -286,6 +286,21 @@ function DashboardWidgets({widgetMetaDataList, tableName, entityPrimaryKey, omit
/> />
) )
} }
{
widgetMetaData.type === "alert" && widgetData[i]?.html && (
<Widget
omitPadding={true}
widgetMetaData={widgetMetaData}
widgetData={widgetData[i]}
reloadWidgetCallback={(data) => reloadWidget(i, data)}
isChild={areChildren}
labelAdditionalComponentsRight={labelAdditionalComponentsRight}
labelAdditionalComponentsLeft={labelAdditionalComponentsLeft}
>
<Alert severity={widgetData[i]?.alertType?.toLowerCase()}>{parse(widgetData[i]?.html)}</Alert>
</Widget>
)
}
{ {
widgetMetaData.type === "usaMap" && ( widgetMetaData.type === "usaMap" && (
<USMapWidget <USMapWidget
@ -550,7 +565,7 @@ function DashboardWidgets({widgetMetaDataList, tableName, entityPrimaryKey, omit
); );
}; };
if(wrapWidgetsInTabPanels) if (wrapWidgetsInTabPanels)
{ {
omitWrappingGridContainer = true; omitWrappingGridContainer = true;
} }
@ -582,7 +597,7 @@ function DashboardWidgets({widgetMetaDataList, tableName, entityPrimaryKey, omit
</TabPanel>); </TabPanel>);
} }
return (<React.Fragment key={`${widgetMetaData.name}-${i}`}>{renderedWidget}</React.Fragment>) return (<React.Fragment key={`${widgetMetaData.name}-${i}`}>{renderedWidget}</React.Fragment>);
}) })
} }
</> </>
@ -590,7 +605,8 @@ function DashboardWidgets({widgetMetaDataList, tableName, entityPrimaryKey, omit
const tabs = widgetMetaDataList && wrapWidgetsInTabPanels ? const tabs = widgetMetaDataList && wrapWidgetsInTabPanels ?
<Tabs <Tabs
sx={{m: 0, mb: 1.5, ml: -2, mr: -2, mt: -3, sx={{
m: 0, mb: 1.5, ml: -2, mr: -2, mt: -3,
"& .MuiTabs-scroller": { "& .MuiTabs-scroller": {
ml: 0 ml: 0
} }
@ -603,7 +619,7 @@ function DashboardWidgets({widgetMetaDataList, tableName, entityPrimaryKey, omit
<Tab key={widgetMetaData.name} label={widgetMetaData.label} /> <Tab key={widgetMetaData.name} label={widgetMetaData.label} />
))} ))}
</Tabs> </Tabs>
: <></> : <></>;
return ( return (
widgetCount > 0 ? ( widgetCount > 0 ? (

View File

@ -28,14 +28,14 @@ import Icon from "@mui/material/Icon";
import Tooltip from "@mui/material/Tooltip/Tooltip"; import Tooltip from "@mui/material/Tooltip/Tooltip";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import parse from "html-react-parser"; import parse from "html-react-parser";
import React, {useContext, useEffect, useState} from "react";
import {NavigateFunction, useNavigate} from "react-router-dom";
import QContext from "QContext"; import QContext from "QContext";
import colors from "qqq/assets/theme/base/colors"; import colors from "qqq/assets/theme/base/colors";
import HelpContent, {hasHelpContent} from "qqq/components/misc/HelpContent"; import HelpContent, {hasHelpContent} from "qqq/components/misc/HelpContent";
import WidgetDropdownMenu, {DropdownOption} from "qqq/components/widgets/components/WidgetDropdownMenu"; import WidgetDropdownMenu, {DropdownOption} from "qqq/components/widgets/components/WidgetDropdownMenu";
import {WidgetUtils} from "qqq/components/widgets/WidgetUtils"; import {WidgetUtils} from "qqq/components/widgets/WidgetUtils";
import HtmlUtils from "qqq/utils/HtmlUtils"; import HtmlUtils from "qqq/utils/HtmlUtils";
import React, {useContext, useEffect, useState} from "react";
import {NavigateFunction, useNavigate} from "react-router-dom";
export interface WidgetData export interface WidgetData
{ {
@ -169,15 +169,17 @@ export class AddNewRecordButton extends LabelComponent
label: string; label: string;
defaultValues: any; defaultValues: any;
disabledFields: any; disabledFields: any;
addNewRecordCallback?: () => void;
constructor(table: QTableMetaData, defaultValues: any, label: string = "Add new", disabledFields: any = defaultValues) constructor(table: QTableMetaData, defaultValues: any, label: string = "Add new", disabledFields: any = defaultValues, addNewRecordCallback?: () => void)
{ {
super(); super();
this.table = table; this.table = table;
this.label = label; this.label = label;
this.defaultValues = defaultValues; this.defaultValues = defaultValues;
this.disabledFields = disabledFields; this.disabledFields = disabledFields;
this.addNewRecordCallback = addNewRecordCallback;
} }
openEditForm = (navigate: any, table: QTableMetaData, id: any = null, defaultValues: any, disabledFields: any) => openEditForm = (navigate: any, table: QTableMetaData, id: any = null, defaultValues: any, disabledFields: any) =>
@ -189,7 +191,7 @@ export class AddNewRecordButton extends LabelComponent
{ {
return ( return (
<Typography variant="body2" p={2} pr={0} display="inline" position="relative" top="-0.5rem"> <Typography variant="body2" p={2} pr={0} display="inline" position="relative" top="-0.5rem">
<Button sx={{mt: 0.75}} onClick={() => this.openEditForm(args.navigate, this.table, null, this.defaultValues, this.disabledFields)}>{this.label}</Button> <Button sx={{mt: 0.75}} onClick={() => this.addNewRecordCallback ? this.addNewRecordCallback() : this.openEditForm(args.navigate, this.table, null, this.defaultValues, this.disabledFields)}>{this.label}</Button>
</Typography> </Typography>
); );
}; };
@ -238,12 +240,20 @@ export class Dropdown extends LabelComponent
if (localStorageOption) if (localStorageOption)
{ {
const id = localStorageOption.id; const id = localStorageOption.id;
for (let i = 0; i < this.options.length; i++)
if (this.dropdownMetaData.type == "DATE_PICKER")
{ {
if (this.options[i].id == id) defaultValue = id;
}
else
{
for (let i = 0; i < this.options.length; i++)
{ {
defaultValue = this.options[i]; if (this.options[i].id == id)
args.dropdownData[args.componentIndex] = defaultValue?.id; {
defaultValue = this.options[i];
args.dropdownData[args.componentIndex] = defaultValue?.id;
}
} }
} }
} }
@ -297,6 +307,7 @@ export class Dropdown extends LabelComponent
<Box mb={2} sx={{float: "right"}}> <Box mb={2} sx={{float: "right"}}>
<WidgetDropdownMenu <WidgetDropdownMenu
name={this.dropdownName} name={this.dropdownName}
type={this.dropdownMetaData.type}
defaultValue={defaultValue} defaultValue={defaultValue}
sx={{marginLeft: "1rem"}} sx={{marginLeft: "1rem"}}
label={label} label={label}
@ -620,11 +631,11 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
setUsingLabelAsTitle(props.widgetData.isLabelPageTitle); setUsingLabelAsTitle(props.widgetData.isLabelPageTitle);
} }
const helpRoles = ["ALL_SCREENS"] const helpRoles = ["ALL_SCREENS"];
const slotName = "label"; const slotName = "label";
const showHelp = helpHelpActive || hasHelpContent(props.widgetMetaData?.helpContent?.get(slotName), helpRoles); const showHelp = helpHelpActive || hasHelpContent(props.widgetMetaData?.helpContent?.get(slotName), helpRoles);
if(showHelp) if (showHelp)
{ {
const formattedHelpContent = <HelpContent helpContents={props.widgetMetaData?.helpContent?.get(slotName)} roles={helpRoles} helpContentKey={`widget:${props.widgetMetaData?.name};slot:${slotName}`} />; const formattedHelpContent = <HelpContent helpContents={props.widgetMetaData?.helpContent?.get(slotName)} roles={helpRoles} helpContentKey={`widget:${props.widgetMetaData?.name};slot:${slotName}`} />;
labelElement = <Tooltip title={formattedHelpContent} arrow={true} placement="bottom-start">{labelElement}</Tooltip>; labelElement = <Tooltip title={formattedHelpContent} arrow={true} placement="bottom-start">{labelElement}</Tooltip>;

View File

@ -31,7 +31,7 @@ export default function TextBlock({widgetMetaData, data}: StandardBlockComponent
{ {
return ( return (
<BlockElementWrapper metaData={widgetMetaData} data={data} slot=""> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="">
<span>{data.values.text}</span> <span style={{fontSize: "1.000rem"}}>{data.values.text}</span>
</BlockElementWrapper> </BlockElementWrapper>
); );
} }

View File

@ -19,18 +19,23 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import {Collapse, Theme, InputAdornment} from "@mui/material"; import {CalendarTodayOutlined} from "@mui/icons-material";
import {Collapse, InputAdornment, Theme} from "@mui/material";
import Autocomplete from "@mui/material/Autocomplete"; import Autocomplete from "@mui/material/Autocomplete";
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import Icon from "@mui/material/Icon"; import Icon from "@mui/material/Icon";
import IconButton from "@mui/material/IconButton"; import IconButton from "@mui/material/IconButton";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
import {SxProps} from "@mui/system"; import {SxProps} from "@mui/system";
import {DatePicker, DateValidationError, LocalizationProvider, PickerChangeHandlerContext, PickerValidDate} from "@mui/x-date-pickers";
import {AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs";
import dayjs from "dayjs";
import {Field, Form, Formik} from "formik"; import {Field, Form, Formik} from "formik";
import React, {useState} from "react"; import QContext from "QContext";
import colors from "qqq/assets/theme/base/colors"; import colors from "qqq/assets/theme/base/colors";
import MDInput from "qqq/components/legacy/MDInput"; import MDInput from "qqq/components/legacy/MDInput";
import ValueUtils from "qqq/utils/qqq/ValueUtils"; import ValueUtils from "qqq/utils/qqq/ValueUtils";
import React, {useContext, useEffect, useState} from "react";
export interface DropdownOption export interface DropdownOption
@ -45,6 +50,7 @@ export interface DropdownOption
interface Props interface Props
{ {
name: string; name: string;
type?: string;
defaultValue?: any; defaultValue?: any;
label?: string; label?: string;
startIcon?: string; startIcon?: string;
@ -96,7 +102,7 @@ function makeBackendValuesFromFrontendValues(frontendDefaultValues: StartAndEndD
return (backendTimeValues); return (backendTimeValues);
} }
function WidgetDropdownMenu({name, defaultValue, label, startIcon, width, disableClearable, allowBackAndForth, backAndForthInverted, dropdownOptions, onChangeCallback, sx}: Props): JSX.Element function WidgetDropdownMenu({name, type, defaultValue, label, startIcon, width, disableClearable, allowBackAndForth, backAndForthInverted, dropdownOptions, onChangeCallback, sx}: Props): JSX.Element
{ {
const [customTimesVisible, setCustomTimesVisible] = useState(defaultValue && defaultValue.id && defaultValue.id.startsWith("custom,")); const [customTimesVisible, setCustomTimesVisible] = useState(defaultValue && defaultValue.id && defaultValue.id.startsWith("custom,"));
const [customTimeValuesFrontend, setCustomTimeValuesFrontend] = useState(parseCustomTimeValuesFromDefaultValue(defaultValue) as StartAndEndDate); const [customTimeValuesFrontend, setCustomTimeValuesFrontend] = useState(parseCustomTimeValuesFromDefaultValue(defaultValue) as StartAndEndDate);
@ -105,16 +111,27 @@ function WidgetDropdownMenu({name, defaultValue, label, startIcon, width, disabl
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [value, setValue] = useState(defaultValue); const [value, setValue] = useState(defaultValue);
const [dateValue, setDateValue] = useState(defaultValue);
const [inputValue, setInputValue] = useState(""); const [inputValue, setInputValue] = useState("");
const [backDisabled, setBackDisabled] = useState(false); const [backDisabled, setBackDisabled] = useState(false);
const [forthDisabled, setForthDisabled] = useState(false); const [forthDisabled, setForthDisabled] = useState(false);
const {accentColor} = useContext(QContext);
const doForceOpen = (event: React.MouseEvent<HTMLDivElement>) => const doForceOpen = (event: React.MouseEvent<HTMLDivElement>) =>
{ {
setIsOpen(true); setIsOpen(true);
}; };
useEffect(() =>
{
if (type == "DATE_PICKER")
{
handleOnChange(null, defaultValue, null);
}
}, [defaultValue]);
function getSelectedIndex(value: DropdownOption) function getSelectedIndex(value: DropdownOption)
{ {
let currentIndex = null; let currentIndex = null;
@ -129,9 +146,19 @@ function WidgetDropdownMenu({name, defaultValue, label, startIcon, width, disabl
return currentIndex; return currentIndex;
} }
const navigateBackAndForth = (event: React.MouseEvent, direction: -1 | 1) =>
const navigateBackAndForth = (event: React.MouseEvent, direction: -1 | 1, type: string) =>
{ {
event.stopPropagation(); event.stopPropagation();
if (type == "DATE_PICKER")
{
let currentDate = new Date(dateValue);
currentDate.setDate(currentDate.getDate() + direction);
handleOnChange(null, currentDate, null);
return;
}
let currentIndex = getSelectedIndex(value); let currentIndex = getSelectedIndex(value);
if (currentIndex == null) if (currentIndex == null)
@ -156,9 +183,26 @@ function WidgetDropdownMenu({name, defaultValue, label, startIcon, width, disabl
}; };
const handleDatePickerOnChange = (value: PickerValidDate, context: PickerChangeHandlerContext<DateValidationError>) =>
{
if (value.isValid())
{
handleOnChange(null, value.toDate(), null);
}
};
const handleOnChange = (event: any, newValue: any, reason: string) => const handleOnChange = (event: any, newValue: any, reason: string) =>
{ {
setValue(newValue); if (type == "DATE_PICKER")
{
setDateValue(newValue);
newValue = {"id": new Date(newValue).toLocaleDateString()};
}
else
{
setValue(newValue);
}
const isTimeframeCustom = name == "timeframe" && newValue && newValue.id == "custom"; const isTimeframeCustom = name == "timeframe" && newValue && newValue.id == "custom";
setCustomTimesVisible(isTimeframeCustom); setCustomTimesVisible(isTimeframeCustom);
@ -250,86 +294,123 @@ function WidgetDropdownMenu({name, defaultValue, label, startIcon, width, disabl
const fontSize = "1rem"; const fontSize = "1rem";
let optionPaddingLeftRems = 0.75; let optionPaddingLeftRems = 0.75;
if(startIcon) if (startIcon)
{ {
optionPaddingLeftRems += allowBackAndForth ? 1.5 : 1.75 optionPaddingLeftRems += allowBackAndForth ? 1.5 : 1.75;
} }
if(allowBackAndForth) if (allowBackAndForth)
{ {
optionPaddingLeftRems += 2.5; optionPaddingLeftRems += 2.5;
} }
return ( if (type == "DATE_PICKER")
dropdownOptions ? ( {
<Box sx={{whiteSpace: "nowrap", display: "flex", return (
"& .MuiPopperUnstyled-root": { <Box sx={{
border: `1px solid ${colors.grayLines.main}`, ...sx,
borderTop: "none", background: "white",
borderRadius: "0 0 0.75rem 0.75rem", width: "250px",
padding: 0, borderRadius: "0.75rem !important",
}, "& .MuiPaper-rounded": { border: `1px solid ${colors.grayLines.main}`,
borderRadius: "0 0 0.75rem 0.75rem", "& *": {cursor: "pointer"}
} }} display="flex" alignItems="center" onClick={(event) => doForceOpen(event)}>
}} className="dashboardDropdownMenu"> {allowBackAndForth && <IconButton sx={{padding: 0, margin: "8px"}} onClick={(event) => navigateBackAndForth(event, backAndForthInverted ? 1 : -1, type)} disabled={backDisabled}><Icon>navigate_before</Icon></IconButton>}
<Autocomplete <LocalizationProvider dateAdapter={AdapterDayjs}>
id={`${label}-combo-box`} <DatePicker
sx={{paddingRight: "8px"}}
defaultValue={defaultValue} defaultValue={dayjs(defaultValue)}
value={value} name={name}
onChange={handleOnChange} value={dayjs(dateValue)}
inputValue={inputValue} onChange={handleDatePickerOnChange}
onInputChange={handleOnInputChange} slots={{
openPickerIcon: CalendarTodayOutlined
isOptionEqualToValue={(option, value) => option.id === value.id} }}
slotProps={{
open={isOpen} openPickerIcon: {sx: {fontSize: "1.25rem !important", color: "#757575"}},
onOpen={() => setIsOpen(true)} actionBar: {actions: ["today"]},
onClose={() => setIsOpen(false)} textField: {variant: "standard", InputProps: {sx: {fontSize: "16px", color: "#495057"}, disableUnderline: true}}
}}
size="small" />
disablePortal </LocalizationProvider>
disableClearable={disableClearable} {allowBackAndForth && <IconButton onClick={(event) => navigateBackAndForth(event, backAndForthInverted ? -1 : 1, type)} disabled={forthDisabled}><Icon>navigate_next</Icon></IconButton>}
options={dropdownOptions}
sx={{
...sx,
cursor: "pointer",
display: "inline-block",
"& .MuiOutlinedInput-notchedOutline": {
border: "none"
},
}}
renderInput={(params: any) =>
<>
<Box sx={{width: `${width}px`, background: "white", borderRadius: isOpen ? "0.75rem 0.75rem 0 0" : "0.75rem", border: `1px solid ${colors.grayLines.main}`, "& *": {cursor: "pointer"}}} display="flex" alignItems="center" onClick={(event) => doForceOpen(event)}>
{allowBackAndForth && <IconButton onClick={(event) => navigateBackAndForth(event, backAndForthInverted ? 1 : -1)} disabled={backDisabled}><Icon>navigate_before</Icon></IconButton>}
<TextField {...params} placeholder={label} sx={{
"& .MuiInputBase-input": {
fontSize: fontSize
}
}} InputProps={{...params.InputProps, startAdornment: startAdornment/*, endAdornment: endAdornment*/}}
/>
{allowBackAndForth && <IconButton onClick={(event) => navigateBackAndForth(event, backAndForthInverted ? -1 : 1)} disabled={forthDisabled}><Icon>navigate_next</Icon></IconButton>}
</Box>
</>
}
renderOption={(props, option: DropdownOption) => (
<li {...props} style={{whiteSpace: "normal", fontSize: fontSize, paddingLeft: `${optionPaddingLeftRems}rem`}}>{option.label}</li>
)}
noOptionsText={<Box fontSize={fontSize}>No options found</Box>}
slotProps={{
popper: {
sx: {
width: `${width}px!important`
}
}
}}
/>
{customTimes}
</Box> </Box>
) : null );
); }
else
{
return (
dropdownOptions ? (
<Box sx={{
whiteSpace: "nowrap", display: "flex",
"& .MuiPopperUnstyled-root": {
border: `1px solid ${colors.grayLines.main}`,
borderTop: "none",
borderRadius: "0 0 0.75rem 0.75rem",
padding: 0,
}, "& .MuiPaper-rounded": {
borderRadius: "0 0 0.75rem 0.75rem",
}
}} className="dashboardDropdownMenu">
<Autocomplete
id={`${label}-combo-box`}
defaultValue={defaultValue}
value={value}
onChange={handleOnChange}
inputValue={inputValue}
onInputChange={handleOnInputChange}
isOptionEqualToValue={(option, value) => option.id === value.id}
open={isOpen}
onOpen={() => setIsOpen(true)}
onClose={() => setIsOpen(false)}
size="small"
disablePortal
disableClearable={disableClearable}
options={dropdownOptions}
sx={{
...sx,
cursor: "pointer",
display: "inline-block",
"& .MuiOutlinedInput-notchedOutline": {
border: "none"
},
}}
renderInput={(params: any) =>
<>
<Box sx={{width: `${width}px`, background: "white", borderRadius: isOpen ? "0.75rem 0.75rem 0 0" : "0.75rem", border: `1px solid ${colors.grayLines.main}`, "& *": {cursor: "pointer"}}} display="flex" alignItems="center" onClick={(event) => doForceOpen(event)}>
{allowBackAndForth && <IconButton onClick={(event) => navigateBackAndForth(event, backAndForthInverted ? 1 : -1, type)} disabled={backDisabled}><Icon>navigate_before</Icon></IconButton>}
<TextField {...params} placeholder={label} sx={{
"& .MuiInputBase-input": {
fontSize: fontSize
}
}} InputProps={{...params.InputProps, startAdornment: startAdornment/*, endAdornment: endAdornment*/}}
/>
{allowBackAndForth && <IconButton onClick={(event) => navigateBackAndForth(event, backAndForthInverted ? -1 : 1, type)} disabled={forthDisabled}><Icon>navigate_next</Icon></IconButton>}
</Box>
</>
}
renderOption={(props, option: DropdownOption) => (
<li {...props} style={{whiteSpace: "normal", fontSize: fontSize, paddingLeft: `${optionPaddingLeftRems}rem`}}>{option.label}</li>
)}
noOptionsText={<Box fontSize={fontSize}>No options found</Box>}
slotProps={{
popper: {
sx: {
width: `${width}px!important`
}
}
}}
/>
{customTimes}
</Box>
) : null
);
}
} }
export default WidgetDropdownMenu; export default WidgetDropdownMenu;

View File

@ -119,7 +119,7 @@ export default function DataBagViewer({dataBagId}: Props): JSX.Element
{ {
if (e instanceof QException) if (e instanceof QException)
{ {
if ((e as QException).status === "404") if ((e as QException).status === 404)
{ {
setNotFoundMessage("Data bag data could not be found."); setNotFoundMessage("Data bag data could not be found.");
return; return;

View File

@ -25,28 +25,53 @@ import {QRecord} from "@kingsrook/qqq-frontend-core/lib/model/QRecord";
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
import Icon from "@mui/material/Icon"; import Icon from "@mui/material/Icon";
import IconButton from "@mui/material/IconButton";
import Tooltip from "@mui/material/Tooltip/Tooltip"; import Tooltip from "@mui/material/Tooltip/Tooltip";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import {DataGridPro, GridCallbackDetails, GridEventListener, GridFilterModel, gridPreferencePanelStateSelector, GridRowParams, GridSelectionModel, GridToolbarColumnsButton, GridToolbarContainer, GridToolbarDensitySelector, GridToolbarExportContainer, GridToolbarFilterButton, MuiEvent, useGridApiContext, useGridApiEventHandler, useGridSelector} from "@mui/x-data-grid-pro"; import {DataGridPro, GridCallbackDetails, GridEventListener, GridRenderCellParams, GridRowParams, GridToolbarContainer, MuiEvent, useGridApiContext, useGridApiEventHandler} from "@mui/x-data-grid-pro";
import React, {useEffect, useRef, useState} from "react"; import Widget, {AddNewRecordButton, LabelComponent, WidgetData} from "qqq/components/widgets/Widget";
import {useNavigate, Link} from "react-router-dom";
import Widget, {AddNewRecordButton, LabelComponent} from "qqq/components/widgets/Widget";
import DataGridUtils from "qqq/utils/DataGridUtils"; import DataGridUtils from "qqq/utils/DataGridUtils";
import HtmlUtils from "qqq/utils/HtmlUtils"; import HtmlUtils from "qqq/utils/HtmlUtils";
import Client from "qqq/utils/qqq/Client"; import Client from "qqq/utils/qqq/Client";
import ValueUtils from "qqq/utils/qqq/ValueUtils"; import ValueUtils from "qqq/utils/qqq/ValueUtils";
import React, {useEffect, useRef, useState} from "react";
import {Link, useNavigate} from "react-router-dom";
export interface ChildRecordListData extends WidgetData
{
title: string;
queryOutput: {records: {values: any}[]}
childTableMetaData: QTableMetaData;
tablePath: string;
viewAllLink: string;
totalRows: number;
canAddChildRecord: boolean;
defaultValuesForNewChildRecords: {[fieldName: string]: any};
disabledFieldsForNewChildRecords: {[fieldName: string]: any};
}
interface Props interface Props
{ {
widgetMetaData: QWidgetMetaData; widgetMetaData: QWidgetMetaData;
data: any; data: ChildRecordListData;
addNewRecordCallback?: () => void;
disableRowClick: boolean;
allowRecordEdit: boolean;
editRecordCallback?: (rowIndex: number) => void;
allowRecordDelete: boolean;
deleteRecordCallback?: (rowIndex: number) => void;
} }
RecordGridWidget.defaultProps = {}; RecordGridWidget.defaultProps =
{
disableRowClick: false,
allowRecordEdit: false,
allowRecordDelete: false
};
const qController = Client.getInstance(); const qController = Client.getInstance();
function RecordGridWidget({widgetMetaData, data}: Props): JSX.Element function RecordGridWidget({widgetMetaData, data, addNewRecordCallback, disableRowClick, allowRecordEdit, editRecordCallback, allowRecordDelete, deleteRecordCallback}: Props): JSX.Element
{ {
const instance = useRef({timer: null}); const instance = useRef({timer: null});
const [rows, setRows] = useState([]); const [rows, setRows] = useState([]);
@ -74,7 +99,7 @@ function RecordGridWidget({widgetMetaData, data}: Props): JSX.Element
} }
const tableMetaData = new QTableMetaData(data.childTableMetaData); const tableMetaData = new QTableMetaData(data.childTableMetaData);
const rows = DataGridUtils.makeRows(records, tableMetaData); const rows = DataGridUtils.makeRows(records, tableMetaData, true);
///////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////
// note - tablePath may be null, if the user doesn't have access to the table. // // note - tablePath may be null, if the user doesn't have access to the table. //
@ -103,6 +128,28 @@ function RecordGridWidget({widgetMetaData, data}: Props): JSX.Element
} }
} }
////////////////////////////////////
// add actions cell, if available //
////////////////////////////////////
if(allowRecordEdit || allowRecordDelete)
{
columns.unshift({
field: "_actions",
type: "string",
headerName: "Actions",
sortable: false,
filterable: false,
width: allowRecordEdit && allowRecordDelete ? 80 : 50,
renderCell: ((params: GridRenderCellParams) =>
{
return <Box>
{allowRecordEdit && <IconButton onClick={() => editRecordCallback(params.row.__rowIndex)}><Icon>edit</Icon></IconButton>}
{allowRecordDelete && <IconButton onClick={() => deleteRecordCallback(params.row.__rowIndex)}><Icon>delete</Icon></IconButton>}
</Box>
})
})
}
setRows(rows); setRows(rows);
setRecords(records) setRecords(records)
setColumns(columns); setColumns(columns);
@ -195,7 +242,7 @@ function RecordGridWidget({widgetMetaData, data}: Props): JSX.Element
{ {
disabledFields = data.defaultValuesForNewChildRecords; disabledFields = data.defaultValuesForNewChildRecords;
} }
labelAdditionalComponentsRight.push(new AddNewRecordButton(data.childTableMetaData, data.defaultValuesForNewChildRecords, "Add new", disabledFields)) labelAdditionalComponentsRight.push(new AddNewRecordButton(data.childTableMetaData, data.defaultValuesForNewChildRecords, "Add new", disabledFields, addNewRecordCallback))
} }
@ -204,13 +251,18 @@ function RecordGridWidget({widgetMetaData, data}: Props): JSX.Element
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
const handleRowClick = (params: GridRowParams, event: MuiEvent<React.MouseEvent>, details: GridCallbackDetails) => const handleRowClick = (params: GridRowParams, event: MuiEvent<React.MouseEvent>, details: GridCallbackDetails) =>
{ {
if(disableRowClick)
{
return;
}
(async () => (async () =>
{ {
const qInstance = await qController.loadMetaData() const qInstance = await qController.loadMetaData()
let tablePath = qInstance.getTablePathByName(data.childTableMetaData.name) let tablePath = qInstance.getTablePathByName(data.childTableMetaData.name)
if(tablePath) if(tablePath)
{ {
tablePath = `${tablePath}/${params.id}`; tablePath = `${tablePath}/${params.row[data.childTableMetaData.primaryKeyField]}`;
DataGridUtils.handleRowClick(tablePath, event, gridMouseDownX, gridMouseDownY, navigate, instance); DataGridUtils.handleRowClick(tablePath, event, gridMouseDownX, gridMouseDownY, navigate, instance);
} }
})(); })();
@ -266,6 +318,7 @@ function RecordGridWidget({widgetMetaData, data}: Props): JSX.Element
rowBuffer={10} rowBuffer={10}
getRowClassName={(params) => (params.indexRelativeToCurrentPage % 2 === 0 ? "even" : "odd")} getRowClassName={(params) => (params.indexRelativeToCurrentPage % 2 === 0 ? "even" : "odd")}
onRowClick={handleRowClick} onRowClick={handleRowClick}
getRowId={(row) => row.__rowIndex}
// getRowHeight={() => "auto"} // maybe nice? wraps values in cells... // getRowHeight={() => "auto"} // maybe nice? wraps values in cells...
components={{ components={{
Toolbar: CustomToolbar Toolbar: CustomToolbar

View File

@ -169,7 +169,7 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
{ {
if (e instanceof QException) if (e instanceof QException)
{ {
if ((e as QException).status === "404") if ((e as QException).status === 404)
{ {
setNotFoundMessage("Script code could not be found."); setNotFoundMessage("Script code could not be found.");
return; return;

View File

@ -21,8 +21,8 @@
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import {Theme} from "@mui/material/styles"; import {Theme} from "@mui/material/styles";
import {ReactNode} from "react";
import colors from "qqq/assets/theme/base/colors"; import colors from "qqq/assets/theme/base/colors";
import {ReactNode} from "react";
// Declaring prop types for DataTableBodyCell // Declaring prop types for DataTableBodyCell
interface Props interface Props
@ -49,7 +49,7 @@ function DataTableBodyCell({noBorder, align, children}: Props): JSX.Element
"@media (max-width: 1440px)": { "@media (max-width: 1440px)": {
fontSize: "0.875rem" fontSize: "0.875rem"
}, },
"&:nth-child(1)": { "&:nth-of-type(1)": {
paddingLeft: "1rem" paddingLeft: "1rem"
}, },
"&:last-child": { "&:last-child": {

View File

@ -23,9 +23,9 @@ import Box from "@mui/material/Box";
import Icon from "@mui/material/Icon"; import Icon from "@mui/material/Icon";
import {Theme} from "@mui/material/styles"; import {Theme} from "@mui/material/styles";
import Tooltip from "@mui/material/Tooltip"; import Tooltip from "@mui/material/Tooltip";
import {ReactNode} from "react";
import colors from "qqq/assets/theme/base/colors"; import colors from "qqq/assets/theme/base/colors";
import {useMaterialUIController} from "qqq/context"; import {useMaterialUIController} from "qqq/context";
import {ReactNode} from "react";
// Declaring props types for DataTableHeadCell // Declaring props types for DataTableHeadCell
interface Props interface Props
@ -50,7 +50,7 @@ function DataTableHeadCell({width, children, sorted, align, tooltip, ...rest}: P
px={1.5} px={1.5}
sx={({palette: {light}, borders: {borderWidth}}: Theme) => ({ sx={({palette: {light}, borders: {borderWidth}}: Theme) => ({
borderBottom: `${borderWidth[1]} solid ${colors.grayLines.main}`, borderBottom: `${borderWidth[1]} solid ${colors.grayLines.main}`,
"&:nth-child(1)": { "&:nth-of-type(1)": {
paddingLeft: "1rem" paddingLeft: "1rem"
}, },
"&:last-child": { "&:last-child": {

View File

@ -47,9 +47,6 @@ import {DataGridPro, GridColDef} from "@mui/x-data-grid-pro";
import FormData from "form-data"; import FormData from "form-data";
import {Form, Formik} from "formik"; import {Form, Formik} from "formik";
import parse from "html-react-parser"; import parse from "html-react-parser";
import React, {useContext, useEffect, useState} from "react";
import {useLocation, useNavigate, useParams} from "react-router-dom";
import * as Yup from "yup";
import QContext from "QContext"; import QContext from "QContext";
import {QCancelButton, QSubmitButton} from "qqq/components/buttons/DefaultButtons"; import {QCancelButton, QSubmitButton} from "qqq/components/buttons/DefaultButtons";
import QDynamicForm from "qqq/components/forms/DynamicForm"; import QDynamicForm from "qqq/components/forms/DynamicForm";
@ -66,6 +63,9 @@ import {TABLE_VARIANT_LOCAL_STORAGE_KEY_ROOT} from "qqq/pages/records/query/Reco
import Client from "qqq/utils/qqq/Client"; import Client from "qqq/utils/qqq/Client";
import TableUtils from "qqq/utils/qqq/TableUtils"; import TableUtils from "qqq/utils/qqq/TableUtils";
import ValueUtils from "qqq/utils/qqq/ValueUtils"; import ValueUtils from "qqq/utils/qqq/ValueUtils";
import React, {useContext, useEffect, useState} from "react";
import {useLocation, useNavigate, useParams} from "react-router-dom";
import * as Yup from "yup";
interface Props interface Props
@ -91,7 +91,7 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
const processNameParam = useParams().processName; const processNameParam = useParams().processName;
const processName = process === null ? processNameParam : process.name; const processName = process === null ? processNameParam : process.name;
let tableVariantLocalStorageKey: string | null = null; let tableVariantLocalStorageKey: string | null = null;
if(table) if (table)
{ {
tableVariantLocalStorageKey = `${TABLE_VARIANT_LOCAL_STORAGE_KEY_ROOT}.${table.name}`; tableVariantLocalStorageKey = `${TABLE_VARIANT_LOCAL_STORAGE_KEY_ROOT}.${table.name}`;
} }
@ -416,10 +416,10 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
////////////////////////////////////////////////// //////////////////////////////////////////////////
step.components && (step.components.map((component: QFrontendComponent, index: number) => step.components && (step.components.map((component: QFrontendComponent, index: number) =>
{ {
let helpRoles = ["PROCESS_SCREEN", "ALL_SCREENS"] let helpRoles = ["PROCESS_SCREEN", "ALL_SCREENS"];
if(component.type == QComponentType.BULK_EDIT_FORM) if (component.type == QComponentType.BULK_EDIT_FORM)
{ {
helpRoles = ["EDIT_SCREEN", "WRITE_SCREENS", "ALL_SCREENS"] helpRoles = ["EDIT_SCREEN", "WRITE_SCREENS", "ALL_SCREENS"];
} }
return ( return (
@ -1068,7 +1068,7 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
const handlePermissionDenied = (e: any): boolean => const handlePermissionDenied = (e: any): boolean =>
{ {
if ((e as QException).status === "403") if ((e as QException).status === 403)
{ {
setProcessError(`You do not have permission to run this ${isReport ? "report" : "process"}.`, true); setProcessError(`You do not have permission to run this ${isReport ? "report" : "process"}.`, true);
return (true); return (true);

View File

@ -28,9 +28,6 @@ import Button from "@mui/material/Button";
import Card from "@mui/material/Card"; import Card from "@mui/material/Card";
import Grid from "@mui/material/Grid"; import Grid from "@mui/material/Grid";
import Snackbar from "@mui/material/Snackbar"; import Snackbar from "@mui/material/Snackbar";
import React, {useContext, useReducer, useState} from "react";
import AceEditor from "react-ace";
import {useParams} from "react-router-dom";
import QContext from "QContext"; import QContext from "QContext";
import ScriptViewer from "qqq/components/widgets/misc/ScriptViewer"; import ScriptViewer from "qqq/components/widgets/misc/ScriptViewer";
import BaseLayout from "qqq/layouts/BaseLayout"; import BaseLayout from "qqq/layouts/BaseLayout";
@ -41,6 +38,9 @@ import "ace-builds/src-noconflict/mode-java";
import "ace-builds/src-noconflict/mode-javascript"; import "ace-builds/src-noconflict/mode-javascript";
import "ace-builds/src-noconflict/mode-json"; import "ace-builds/src-noconflict/mode-json";
import "ace-builds/src-noconflict/theme-github"; import "ace-builds/src-noconflict/theme-github";
import React, {useContext, useReducer, useState} from "react";
import AceEditor from "react-ace";
import {useParams} from "react-router-dom";
import "ace-builds/src-noconflict/ext-language_tools"; import "ace-builds/src-noconflict/ext-language_tools";
const qController = Client.getInstance(); const qController = Client.getInstance();
@ -121,7 +121,7 @@ function RecordDeveloperView({table}: Props): JSX.Element
{ {
if (e instanceof QException) if (e instanceof QException)
{ {
if ((e as QException).status === "404") if ((e as QException).status === 404)
{ {
setNotFoundMessage(`${tableMetaData.label} ${id} could not be found.`); setNotFoundMessage(`${tableMetaData.label} ${id} could not be found.`);
return; return;

View File

@ -447,13 +447,13 @@ function RecordView({table, launchProcess}: Props): JSX.Element
if (e instanceof QException) if (e instanceof QException)
{ {
if ((e as QException).status === "404") if ((e as QException).status === 404)
{ {
setNotFoundMessage(`${tableMetaData.label} ${id} could not be found.`); setNotFoundMessage(`${tableMetaData.label} ${id} could not be found.`);
historyPurge(location.pathname); historyPurge(location.pathname);
return; return;
} }
else if ((e as QException).status === "403") else if ((e as QException).status === 403)
{ {
setNotFoundMessage(`You do not have permission to view ${tableMetaData.label} records`); setNotFoundMessage(`You do not have permission to view ${tableMetaData.label} records`);
historyPurge(location.pathname); historyPurge(location.pathname);
@ -867,7 +867,7 @@ function RecordView({table, launchProcess}: Props): JSX.Element
} }
{ {
warningMessage ? warningMessage ?
<Alert color="warning" sx={{mb: 3}} onClose={() => <Alert color="warning" sx={{mb: 3}} icon={<Icon>warning</Icon>} onClose={() =>
{ {
setWarningMessage(null); setWarningMessage(null);
}}> }}>

View File

@ -158,6 +158,7 @@ but we've turned off the click-to-sort function, so remove hand cursor */
white-space: normal; white-space: normal;
height: auto; height: auto;
} }
.MuiDataGrid-filterForm .MuiDataGrid-filterForm
{ {
align-items: flex-end; align-items: flex-end;
@ -173,10 +174,12 @@ but we've turned off the click-to-sort function, so remove hand cursor */
{ {
width: 200px; width: 200px;
} }
.MuiDataGrid-filterForm .MuiDataGrid-filterFormValueInput .MuiDataGrid-filterForm .MuiDataGrid-filterFormValueInput
{ {
width: 300px; width: 300px;
} }
.MuiDataGrid-filterForm .MuiDataGrid-filterFormOperatorInput .MuiDataGrid-filterForm .MuiDataGrid-filterFormOperatorInput
{ {
width: 150px; width: 150px;
@ -187,13 +190,14 @@ but we've turned off the click-to-sort function, so remove hand cursor */
{ {
padding-top: 4px; padding-top: 4px;
} }
.MuiDataGrid-filterForm .MuiDataGrid-filterFormValueInput .MuiAutocomplete-root .MuiAutocomplete-endAdornment svg .MuiDataGrid-filterForm .MuiDataGrid-filterFormValueInput .MuiAutocomplete-root .MuiAutocomplete-endAdornment svg
{ {
height: 0.625em; height: 0.625em;
} }
/* fix strange size bug on filter autocompletes */ /* fix strange size bug on filter autocompletes */
.MuiDataGrid-filterForm .MuiDataGrid-filterFormValueInput>.MuiBox-root>.MuiBox-root:has(>.MuiAutocomplete-root) .MuiDataGrid-filterForm .MuiDataGrid-filterFormValueInput > .MuiBox-root > .MuiBox-root:has(>.MuiAutocomplete-root)
{ {
margin-bottom: 0; margin-bottom: 0;
width: 100%; width: 100%;
@ -208,16 +212,31 @@ but we've turned off the click-to-sort function, so remove hand cursor */
} }
/* clears the X from Internet Explorer */ /* clears the X from Internet Explorer */
input[type=search]::-ms-clear { display: none; width : 0; height: 0; } input[type=search]::-ms-clear
input[type=search]::-ms-reveal { display: none; width : 0; height: 0; } {
display: none;
width: 0;
height: 0;
}
input[type=search]::-ms-reveal
{
display: none;
width: 0;
height: 0;
}
/* clears the X from Chrome */ /* clears the X from Chrome */
input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-decoration,
input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-results-button, input[type="search"]::-webkit-search-results-button,
input[type="search"]::-webkit-search-results-decoration { display: none; } input[type="search"]::-webkit-search-results-decoration
{
display: none;
}
/* Shrink the big margin-bottom on modal processes */ /* Shrink the big margin-bottom on modal processes */
.modalProcess>.MuiBox-root>.MuiBox-root .modalProcess > .MuiBox-root > .MuiBox-root
{ {
margin-bottom: 24px; margin-bottom: 24px;
} }
@ -270,6 +289,7 @@ input[type="search"]::-webkit-search-results-decoration { display: none; }
color: initial !important; color: initial !important;
border: 1px solid rgb(206, 212, 218); border: 1px solid rgb(206, 212, 218);
} }
.MuiDataGrid-filterForm .MuiAutocomplete-tag .MuiSvgIcon-root .MuiDataGrid-filterForm .MuiAutocomplete-tag .MuiSvgIcon-root
{ {
color: initial !important; color: initial !important;
@ -287,7 +307,7 @@ input[type="search"]::-webkit-search-results-decoration { display: none; }
right: 0.125rem; right: 0.125rem;
} }
.devDocumentation ul>li .devDocumentation ul > li
{ {
margin-left: 30px; margin-left: 30px;
} }
@ -640,6 +660,7 @@ input[type="search"]::-webkit-search-results-decoration { display: none; }
border: 1px solid #BDBDBD; border: 1px solid #BDBDBD;
border-radius: 0.5rem !important; border-radius: 0.5rem !important;
} }
.MuiToggleButtonGroup-root .MuiButtonBase-root .MuiToggleButtonGroup-root .MuiButtonBase-root
{ {
text-transform: none; text-transform: none;
@ -650,11 +671,19 @@ input[type="search"]::-webkit-search-results-decoration { display: none; }
border: none; border: none;
flex: 1 1 0px; flex: 1 1 0px;
} }
.MuiToggleButtonGroup-root .MuiButtonBase-root.Mui-selected .MuiToggleButtonGroup-root .MuiButtonBase-root.Mui-selected
{ {
background: rgba(117, 117, 117, 0.20); background: rgba(117, 117, 117, 0.20);
} }
.MuiToggleButtonGroup-root .MuiButtonBase-root.Mui-disabled .MuiToggleButtonGroup-root .MuiButtonBase-root.Mui-disabled
{ {
border: none; border: none;
} }
.MuiPickersDay-root.Mui-selected, .MuiPickersDay-root.MuiPickersDay-dayWithMargin:hover
{
color: white;
background-color: #0062FF !important;
}

View File

@ -29,11 +29,11 @@ import Tooltip from "@mui/material/Tooltip/Tooltip";
import {GridColDef, GridFilterItem, GridRowsProp, MuiEvent} from "@mui/x-data-grid-pro"; import {GridColDef, GridFilterItem, GridRowsProp, MuiEvent} from "@mui/x-data-grid-pro";
import {GridFilterOperator} from "@mui/x-data-grid/models/gridFilterOperator"; import {GridFilterOperator} from "@mui/x-data-grid/models/gridFilterOperator";
import {GridColumnHeaderParams} from "@mui/x-data-grid/models/params/gridColumnHeaderParams"; import {GridColumnHeaderParams} from "@mui/x-data-grid/models/params/gridColumnHeaderParams";
import React from "react";
import {Link, NavigateFunction} from "react-router-dom";
import HelpContent, {hasHelpContent} from "qqq/components/misc/HelpContent"; import HelpContent, {hasHelpContent} from "qqq/components/misc/HelpContent";
import {buildQGridPvsOperators, QGridBlobOperators, QGridBooleanOperators, QGridNumericOperators, QGridStringOperators} from "qqq/pages/records/query/GridFilterOperators"; import {buildQGridPvsOperators, QGridBlobOperators, QGridBooleanOperators, QGridNumericOperators, QGridStringOperators} from "qqq/pages/records/query/GridFilterOperators";
import ValueUtils from "qqq/utils/qqq/ValueUtils"; import ValueUtils from "qqq/utils/qqq/ValueUtils";
import React from "react";
import {Link, NavigateFunction} from "react-router-dom";
const emptyApplyFilterFn = (filterItem: GridFilterItem, column: GridColDef): null => null; const emptyApplyFilterFn = (filterItem: GridFilterItem, column: GridColDef): null => null;
@ -118,7 +118,7 @@ export default class DataGridUtils
/******************************************************************************* /*******************************************************************************
** **
*******************************************************************************/ *******************************************************************************/
public static makeRows = (results: QRecord[], tableMetaData: QTableMetaData): GridRowsProp[] => public static makeRows = (results: QRecord[], tableMetaData: QTableMetaData, allowEmptyId = false): GridRowsProp[] =>
{ {
const fields = [...tableMetaData.fields.values()]; const fields = [...tableMetaData.fields.values()];
const rows = [] as any[]; const rows = [] as any[];
@ -159,7 +159,10 @@ export default class DataGridUtils
///////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////
// DataGrid gets very upset about a null or undefined here, so, try to make it happier // // DataGrid gets very upset about a null or undefined here, so, try to make it happier //
///////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////
row["id"] = "--"; if(!allowEmptyId)
{
row["id"] = "--";
}
} }
} }
@ -279,7 +282,7 @@ export default class DataGridUtils
if (key === tableMetaData.primaryKeyField && linkBase) if (key === tableMetaData.primaryKeyField && linkBase)
{ {
column.renderCell = (cellValues: any) => ( column.renderCell = (cellValues: any) => (
<Link to={`${linkBase}${encodeURIComponent(cellValues.value)}`} onClick={(e) => e.stopPropagation()}>{cellValues.value}</Link> cellValues.value ? <Link to={`${linkBase}${encodeURIComponent(cellValues.value)}`} onClick={(e) => e.stopPropagation()}>{cellValues.value}</Link> : ""
); );
} }
}); });

View File

@ -35,7 +35,7 @@ class Client
{ {
console.log(`Caught Exception: ${JSON.stringify(exception)}`); console.log(`Caught Exception: ${JSON.stringify(exception)}`);
if(exception && exception.status == "401" && Client.unauthorizedCallback) if (exception && exception.status == 401 && Client.unauthorizedCallback)
{ {
console.log("This is a 401 - calling the unauthorized callback."); console.log("This is a 401 - calling the unauthorized callback.");
Client.unauthorizedCallback(); Client.unauthorizedCallback();

View File

@ -30,61 +30,101 @@ import {QueryJoin} from "@kingsrook/qqq-frontend-core/lib/model/query/QueryJoin"
*******************************************************************************/ *******************************************************************************/
class TableUtils class TableUtils
{ {
/******************************************************************************* /*******************************************************************************
** For a table, return a sub-set of sections (originally meant for display in
** the record-screen sidebars)
** **
** If the table has no sections, one big "all fields" section is created.
**
** a list of "allowed field names" may be given, in which case, a section is only
** included if it has a field in that list. e.g., an edit-screen, where disabled
** fields aren't to be shown - if a section only has disabled fields, don't include it.
**
** By default sections w/ widget names are excluded -- but -- to include them,
** provide the metaData plus list of allowedWidgetTypes.
*******************************************************************************/ *******************************************************************************/
public static getSectionsForRecordSidebar(tableMetaData: QTableMetaData, allowedKeys: any = null): QTableSection[] public static getSectionsForRecordSidebar(tableMetaData: QTableMetaData, allowedFieldNames: any = null, additionalInclusionPredicate?: (section: QTableSection) => boolean): QTableSection[]
{ {
/////////////////////////////////////////////////////////////////
// if the table has sections, then filter them and return some //
/////////////////////////////////////////////////////////////////
if (tableMetaData.sections) if (tableMetaData.sections)
{ {
if (allowedKeys) //////////////////////////////////////////////////////////////////////////////////////////////
// if there are filters (a list of allowed field names, or an additionalInclusionPredicate, //
// then only return a subset of sections matching the filters //
//////////////////////////////////////////////////////////////////////////////////////////////
if (allowedFieldNames || additionalInclusionPredicate)
{ {
const allowedKeySet = new Set<string>(); ////////////////////////////////////////////////////////////////
allowedKeys.forEach((k: string) => allowedKeySet.add(k)); // put the field names in a set, for better inclusion testing //
////////////////////////////////////////////////////////////////
const allowedFieldNameSet = new Set<string>();
if(allowedFieldNames)
{
allowedFieldNames.forEach((k: string) => allowedFieldNameSet.add(k));
}
///////////////////////////////////////////////////////////////////////////////
// loop over the sections, deciding which ones to include in the return list //
///////////////////////////////////////////////////////////////////////////////
const allowedSections: QTableSection[] = []; const allowedSections: QTableSection[] = [];
for (let i = 0; i < tableMetaData.sections.length; i++) for (let i = 0; i < tableMetaData.sections.length; i++)
{ {
const section = tableMetaData.sections[i]; const section = tableMetaData.sections[i];
if (section.fieldNames) let includeSection = false;
for (let j = 0; j < section.fieldNames?.length; j++)
{ {
for (let j = 0; j < section.fieldNames.length; j++) if (allowedFieldNameSet.has(section.fieldNames[j]))
{ {
if (allowedKeySet.has(section.fieldNames[j])) includeSection = true;
{ break;
allowedSections.push(section);
break;
}
} }
} }
if (additionalInclusionPredicate && additionalInclusionPredicate(section))
{
includeSection = true;
}
if(includeSection)
{
allowedSections.push(section);
}
} }
console.log("allowedSections length: " + allowedSections.length);
return (allowedSections); return (allowedSections);
} }
else
{ ////////////////////////////////////////////////////////////////
return (tableMetaData.sections); // if there are no filters to apply, then return all sections //
} ////////////////////////////////////////////////////////////////
return (tableMetaData.sections);
} }
else
///////////////////////////////////////////////////////////////////////////////////////////////
// else, if the table had no sections, then make a pseudo-one with either all of the fields, //
// or a subset based on the allowedFieldNames //
///////////////////////////////////////////////////////////////////////////////////////////////
let fieldNames = [...tableMetaData.fields.keys()];
if (allowedFieldNames)
{ {
let fieldNames = [...tableMetaData.fields.keys()]; fieldNames = [];
if (allowedKeys) for (const fieldName in tableMetaData.fields.keys())
{ {
fieldNames = []; if (allowedFieldNames[fieldName])
for (const fieldName in tableMetaData.fields.keys())
{ {
if (allowedKeys[fieldName]) fieldNames.push(fieldName);
{
fieldNames.push(fieldName);
}
} }
} }
return ([new QTableSection({
iconName: "description", label: "All Fields", name: "allFields", fieldNames: [...fieldNames],
})]);
} }
return ([new QTableSection({
iconName: "description", label: "All Fields", name: "allFields", fieldNames: [...fieldNames],
})]);
} }

View File

@ -219,6 +219,16 @@ class ValueUtils
if (field.type === QFieldType.DATE_TIME) if (field.type === QFieldType.DATE_TIME)
{ {
if(displayValue && displayValue != rawValue)
{
//////////////////////////////////////////////////////////////////////////////
// if the date-time actually has a displayValue set, and it isn't just the //
// raw-value being copied into the display value by whoever called us, then //
// return the display value. //
//////////////////////////////////////////////////////////////////////////////
return displayValue;
}
if (!rawValue) if (!rawValue)
{ {
return (""); return ("");
@ -270,6 +280,7 @@ class ValueUtils
{ {
date = new Date(date); date = new Date(date);
} }
// @ts-ignore // @ts-ignore
return (`${date.toString("yyyy-MM-dd hh:mm:ss")} ${date.getHours() < 12 ? "AM" : "PM"} ${date.getTimezone()}`); return (`${date.toString("yyyy-MM-dd hh:mm:ss")} ${date.getHours() < 12 ? "AM" : "PM"} ${date.getTimezone()}`);
} }