Compare commits

...

31 Commits

Author SHA1 Message Date
30991cb34e CE-881 - Fix parsing hash (e.g., for defaultValues) in case it has a # in it 2024-04-02 15:46:23 -05:00
2fd6272ea3 CE-881 - Update download component to understand storageTableName & storageReference, as alternative to serverFilePath 2024-04-01 16:05:16 -05:00
b63d74f785 Merged main into feature/CE-881-create-basic-saved-reports 2024-03-29 18:36:51 -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
5e3991d9ae CE-1120: updated to handle errors on join tables (specifically was happening with deposco customer orders) 2024-03-28 15:09:56 -05:00
ff946df461 CE-881 - Add views menu option to punch into create-saved-view screen w/ pre-populated form 2024-03-27 20:16:06 -05:00
f1826c81a9 Merge pull request #48 from Kingsrook/bugfix/null-field-names-in-criteria
Strip away null field names in criteria (e.g., from incomplete advanc…
2024-03-27 20:14:01 -05:00
230aaeef8c Strip away null field names in criteria (e.g., from incomplete advanced filters) when storing in local storage, in saved views, and any time we load a view. 2024-03-21 16:41:09 -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
edab918763 CE-969: fixed flex wrapping on advanced queries, recursive calls to 'clean values' and 'prep subquery for backend' 2024-03-18 19:39:19 -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
e34811354f CE-969: reverted change when no criteria on query 2024-03-15 18:10:25 -05:00
ef85f5cd40 CE-969: cleanups from review feedback 2024-03-15 17:27:30 -05:00
c36dfb5683 CE-969: added basic support for 'too complex' subfilters 2024-03-12 17:40:56 -05:00
626ada3507 Update to qqq-backend-core 0.20.0-20240308.165846-65 2024-03-08 12:42:31 -06:00
6cf1c2a0e4 Merge pull request #45 from Kingsrook/feature/CE-989-bug-performance-issue
CE-989 add option to (not) includeTableCountsOn(app)HomeScreen
2024-03-08 10:56:11 -06:00
39a7aadd3f CE-989 add option to (not) includeTableCountsOn(app)HomeScreen 2024-03-07 20:30:14 -06:00
167af989d5 Add tooltips from metaData/helpContent to widget blocks. 2024-03-05 14:36:54 -06:00
ad7ea994a8 CE-889 - try to fix NPE's on localeCompares 2024-03-04 15:09:22 -06:00
e925310173 Merge pull request #44 from Kingsrook/feature/CE-878-make-the-operations-dashboard
CE-878: updated to allow sublabel to be displayed under label
2024-03-04 14:47:52 -06:00
8ebc2415fe Merged feature/CE-878-make-the-operations-dashboard into main 2024-02-29 09:39:08 -06:00
88a4c17bbc CE-798 follow-up - in cleanupValuesInFilerFromQueryString, don't try to translate [null] to a list of possible values (which fetches all of them)... 2024-02-27 13:57:04 -06:00
2900cd8593 CE-798 follow-up - Prevent tab in date/date-time filter value input boxes from closing a quick-filter menu (via an onKeyDown handler) 2024-02-27 13:35:37 -06:00
8ab0f5f549 CE-798 follow-up - increase width of date-time boxes (was too small to see all the fields!) 2024-02-27 11:56:54 -06:00
8cffbbcac4 Update to cimg/openjdk:17.0.9 2024-02-22 20:30:51 -06:00
37eb280d79 Revert to previous check for disabling export-menu items - that is - totalRecords === 0, instead of !totalRecords. makes tables w/o count allowed to do exports again. 2024-02-22 12:16:27 -06:00
36 changed files with 5173 additions and 3714 deletions

View File

@ -7,7 +7,7 @@ orbs:
executors: executors:
java17: java17:
docker: docker:
- image: 'cimg/openjdk:17.0' - image: 'cimg/openjdk:17.0.9'
commands: commands:
install_java17: install_java17:

View File

@ -28,8 +28,7 @@
}, },
"plugins": [ "plugins": [
"react", "react",
"@typescript-eslint", "@typescript-eslint"
"import"
], ],
"rules": { "rules": {
"brace-style": [ "brace-style": [
@ -43,41 +42,6 @@
"SwitchCase": 1 "SwitchCase": 1
} }
], ],
"import/extensions": [
"error",
"ignorePackages",
{
"ts": "never",
"tsx": "never",
"js": "never"
}
],
"import/no-extraneous-dependencies": [
"error",
{
"devDependencies": true
}
],
"import/order": [
"error",
{
"groups": [
"builtin", // Built-in imports (come from NodeJS native) go first
"external", // <- External imports
"internal", // <- Absolute imports
["sibling", "parent"], // <- Relative imports, the sibling and parent types they can be mingled together
"index", // <- index imports
"unknown"
],
"newlines-between": "never",
"alphabetize": {
/* sort in ascending order. Options: ["ignore", "asc", "desc"] */
"order": "asc",
/* ignore case. Options: [true, false] */
"caseInsensitive": true
}
}
],
"jsx-one-expression-per-line": "off", "jsx-one-expression-per-line": "off",
"max-len": "off", "max-len": "off",
"no-console": "off", "no-console": "off",
@ -114,15 +78,6 @@
"quotes": [ "quotes": [
"error", "error",
"double" "double"
],
"sort-imports": [
"error",
{
"ignoreCase": false,
"ignoreDeclarationSort": true,
"ignoreMemberSort": true,
"allowSeparatedGroups": false
}
] ]
}, },
"settings": { "settings": {

6820
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@
"@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.87", "@kingsrook/qqq-frontend-core": "1.0.90",
"@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",

View File

@ -66,7 +66,7 @@
<dependency> <dependency>
<groupId>com.kingsrook.qqq</groupId> <groupId>com.kingsrook.qqq</groupId>
<artifactId>qqq-backend-core</artifactId> <artifactId>qqq-backend-core</artifactId>
<version>feature-CE-876-develop-missing-widget-types-20240221.002945-1</version> <version>0.20.0-20240308.165846-65</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>

View File

@ -36,7 +36,7 @@ import Icon from "@mui/material/Icon";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import {makeStyles} from "@mui/styles"; import {makeStyles} from "@mui/styles";
import {Command} from "cmdk"; import {Command} from "cmdk";
import React, {useContext, useEffect, useRef, useState} from "react"; import React, {useContext, useEffect, useRef} from "react";
import {useNavigate} from "react-router-dom"; import {useNavigate} from "react-router-dom";
import QContext from "QContext"; import QContext from "QContext";
import HistoryUtils, {QHistoryEntry} from "qqq/utils/HistoryUtils"; import HistoryUtils, {QHistoryEntry} from "qqq/utils/HistoryUtils";
@ -174,7 +174,9 @@ const CommandMenu = ({metaData}: Props) =>
}) })
tableNames = tableNames.sort((a: string, b:string) => tableNames = tableNames.sort((a: string, b:string) =>
{ {
return (metaData.tables.get(a).label.localeCompare(metaData.tables.get(b).label)); const labelA = metaData.tables.get(a).label ?? "";
const labelB = metaData.tables.get(b).label ?? "";
return (labelA.localeCompare(labelB));
}) })
const path = location.pathname; const path = location.pathname;
@ -222,7 +224,9 @@ const CommandMenu = ({metaData}: Props) =>
}) })
tableNames = tableNames.sort((a: string, b:string) => tableNames = tableNames.sort((a: string, b:string) =>
{ {
return (metaData.tables.get(a).label.localeCompare(metaData.tables.get(b).label)); const labelA = metaData.tables.get(a).label ?? "";
const labelB = metaData.tables.get(b).label ?? "";
return (labelA.localeCompare(labelB));
}) })
return( return(
<Command.Group heading="Tables"> <Command.Group heading="Tables">
@ -252,7 +256,9 @@ const CommandMenu = ({metaData}: Props) =>
appNames = appNames.sort((a: string, b:string) => appNames = appNames.sort((a: string, b:string) =>
{ {
return (getFullAppLabel(metaData.appTree, a, 1, "").localeCompare(getFullAppLabel(metaData.appTree, b, 1, ""))); const labelA = getFullAppLabel(metaData.appTree, a, 1, "") ?? "";
const labelB = getFullAppLabel(metaData.appTree, b, 1, "") ?? "";
return (labelA.localeCompare(labelB));
}) })
return( return(
@ -286,7 +292,9 @@ const CommandMenu = ({metaData}: Props) =>
appNames = appNames.sort((a: string, b:string) => appNames = appNames.sort((a: string, b:string) =>
{ {
return (metaData.apps.get(a).label.localeCompare(metaData.apps.get(b).label)); const labelA = metaData.apps.get(a).label ?? "";
const labelB = metaData.apps.get(b).label ?? "";
return (labelA.localeCompare(labelB));
}) })
const entryMap = new Map<string, boolean>(); const entryMap = new Map<string, boolean>();

View File

@ -22,7 +22,9 @@
package com.kingsrook.qqq.frontend.materialdashboard.model.metadata; package com.kingsrook.qqq.frontend.materialdashboard.model.metadata;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QSupplementalAppMetaData; import com.kingsrook.qqq.backend.core.model.metadata.layout.QSupplementalAppMetaData;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
/******************************************************************************* /*******************************************************************************
@ -30,7 +32,39 @@ import com.kingsrook.qqq.backend.core.model.metadata.layout.QSupplementalAppMeta
*******************************************************************************/ *******************************************************************************/
public class MaterialDashboardAppMetaData extends QSupplementalAppMetaData public class MaterialDashboardAppMetaData extends QSupplementalAppMetaData
{ {
public static final String TYPE_NAME = "materialDashboard";
private Boolean showAppLabelOnHomeScreen = true; private Boolean showAppLabelOnHomeScreen = true;
private Boolean includeTableCountsOnHomeScreen = true;
/*******************************************************************************
**
*******************************************************************************/
public static MaterialDashboardAppMetaData of(QAppMetaData app)
{
return ((MaterialDashboardAppMetaData) CollectionUtils.nonNullMap(app.getSupplementalMetaData()).get(TYPE_NAME));
}
/*******************************************************************************
** either get the supplemental meta dat attached to an app - or create a new one
** and attach it to the app, and return that.
*******************************************************************************/
public static MaterialDashboardAppMetaData ofOrWithNew(QAppMetaData app)
{
MaterialDashboardAppMetaData materialDashboardAppMetaData = of(app);
if(materialDashboardAppMetaData == null)
{
materialDashboardAppMetaData = new MaterialDashboardAppMetaData();
app.withSupplementalMetaData(materialDashboardAppMetaData);
}
return (materialDashboardAppMetaData);
}
@ -51,7 +85,7 @@ public class MaterialDashboardAppMetaData extends QSupplementalAppMetaData
@Override @Override
public String getType() public String getType()
{ {
return ("materialDashboard"); return TYPE_NAME;
} }
@ -85,4 +119,35 @@ public class MaterialDashboardAppMetaData extends QSupplementalAppMetaData
return (this); return (this);
} }
/*******************************************************************************
** Getter for includeTableCountsOnHomeScreen
*******************************************************************************/
public Boolean getIncludeTableCountsOnHomeScreen()
{
return (this.includeTableCountsOnHomeScreen);
}
/*******************************************************************************
** Setter for includeTableCountsOnHomeScreen
*******************************************************************************/
public void setIncludeTableCountsOnHomeScreen(Boolean includeTableCountsOnHomeScreen)
{
this.includeTableCountsOnHomeScreen = includeTableCountsOnHomeScreen;
}
/*******************************************************************************
** Fluent setter for includeTableCountsOnHomeScreen
*******************************************************************************/
public MaterialDashboardAppMetaData withIncludeTableCountsOnHomeScreen(Boolean includeTableCountsOnHomeScreen)
{
this.includeTableCountsOnHomeScreen = includeTableCountsOnHomeScreen;
return (this);
}
} }

View File

@ -34,7 +34,7 @@ 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, {JSXElementConstructor, useContext, useEffect, useState} from "react"; 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";
@ -58,19 +58,19 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
const [limit, setLimit] = useState(1000); const [limit, setLimit] = useState(1000);
const [statusString, setStatusString] = useState("Loading audits..."); const [statusString, setStatusString] = useState("Loading audits...");
const [auditsByDate, setAuditsByDate] = useState([] as QRecord[][]); const [auditsByDate, setAuditsByDate] = useState([] as QRecord[][]);
const [auditDetailMap, setAuditDetailMap] = useState(null as Map<number, JSX.Element[]>) const [auditDetailMap, setAuditDetailMap] = useState(null as Map<number, JSX.Element[]>);
const [fieldChangeMap, setFieldChangeMap] = useState(null as Map<number, JSX.Element>) const [fieldChangeMap, setFieldChangeMap] = useState(null as Map<number, JSX.Element>);
const [sortDirection, setSortDirection] = useState(localStorage.getItem("audit.sortDirection") === "true"); const [sortDirection, setSortDirection] = useState(localStorage.getItem("audit.sortDirection") === "true");
const {accentColor} = useContext(QContext); const {accentColor} = useContext(QContext);
function wrapValue(value: any): JSX.Element function wrapValue(value: any): JSX.Element
{ {
return <span style={{fontWeight: "500", color: " rgb(123, 128, 154)"}}>{value}</span> return <span style={{fontWeight: "500", color: " rgb(123, 128, 154)"}}>{value}</span>;
} }
function wasValue(value: any): JSX.Element function wasValue(value: any): JSX.Element
{ {
return <span style={{fontWeight: "100", color: " rgb(123, 128, 154)"}}>{value}</span> return <span style={{fontWeight: "100", color: " rgb(123, 128, 154)"}}>{value}</span>;
} }
function getAuditDetailFieldChangeRow(qRecord: QRecord): JSX.Element | null function getAuditDetailFieldChangeRow(qRecord: QRecord): JSX.Element | null
@ -81,8 +81,12 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
const newValue = qRecord.values.get("auditDetail.newValue"); const newValue = qRecord.values.get("auditDetail.newValue");
if (fieldName && (oldValue !== null || newValue !== null)) if (fieldName && (oldValue !== null || newValue !== null))
{ {
const fieldLabel = tableMetaData?.fields?.get(fieldName)?.label ?? fieldName const fieldLabel = tableMetaData?.fields?.get(fieldName)?.label ?? fieldName;
return (<tr><td>{fieldLabel}</td><td>{oldValue}</td><td>{newValue}</td></tr>) return (<tr>
<td>{fieldLabel}</td>
<td>{oldValue}</td>
<td>{newValue}</td>
</tr>);
} }
return (null); return (null);
} }
@ -198,12 +202,12 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
new QFilterOrderBy("timestamp", sortDirection), new QFilterOrderBy("timestamp", sortDirection),
new QFilterOrderBy("id", sortDirection), new QFilterOrderBy("id", sortDirection),
new QFilterOrderBy("auditDetail.id", true) new QFilterOrderBy("auditDetail.id", true)
], "AND", 0, limit); ], null, "AND", 0, limit);
/////////////////////////////// ///////////////////////////////
// fetch audits in try-catch // // fetch audits in try-catch //
/////////////////////////////// ///////////////////////////////
let audits = [] as QRecord[] let audits = [] as QRecord[];
try try
{ {
audits = await qController.query("audit", filter, [new QueryJoin("auditDetail", true, "LEFT")]); audits = await qController.query("audit", filter, [new QueryJoin("auditDetail", true, "LEFT")]);
@ -233,7 +237,7 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////
// group the audits by auditId (e.g., this is a list that joined audit & auditDetail, so un-flatten it) // // group the audits by auditId (e.g., this is a list that joined audit & auditDetail, so un-flatten it) //
////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////
const unflattenedAudits: QRecord[] = [] const unflattenedAudits: QRecord[] = [];
const detailMap: Map<number, JSX.Element[]> = new Map(); const detailMap: Map<number, JSX.Element[]> = new Map();
const fieldChangeRowsMap: Map<number, JSX.Element[]> = new Map(); const fieldChangeRowsMap: Map<number, JSX.Element[]> = new Map();
for (let i = 0; i < audits.length; i++) for (let i = 0; i < audits.length; i++)
@ -252,7 +256,7 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
detailMap.set(id, []); detailMap.set(id, []);
} }
detailMap.get(id).push(auditDetail) detailMap.get(id).push(auditDetail);
} }
// table version, probably not to commit // table version, probably not to commit
@ -288,11 +292,11 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
{fieldChangeRowsMap.get(id).map((row, key) => <React.Fragment key={key}>{row}</React.Fragment>)} {fieldChangeRowsMap.get(id).map((row, key) => <React.Fragment key={key}>{row}</React.Fragment>)}
</tbody> </tbody>
</table> </table>
) );
fieldChangeMap.set(id, fieldChangeTable); fieldChangeMap.set(id, fieldChangeTable);
} }
} }
setFieldChangeMap(fieldChangeMap) setFieldChangeMap(fieldChangeMap);
////////////////////////////// //////////////////////////////
// group the audits by date // // group the audits by date //
@ -350,7 +354,7 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
const changeSortDirection = () => const changeSortDirection = () =>
{ {
setAudits([]); setAudits([]);
const newSortDirection = !sortDirection const newSortDirection = !sortDirection;
setSortDirection(newSortDirection); setSortDirection(newSortDirection);
localStorage.setItem("audit.sortDirection", String(newSortDirection)); localStorage.setItem("audit.sortDirection", String(newSortDirection));
}; };

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,9 +118,16 @@ 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)
{ {
@ -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: //
@ -114,22 +128,151 @@ function EntityForm(props: Props): JSX.Element
{ {
try try
{ {
const parts = hashParts[i].split("=") const parts = hashParts[i].split("=");
if (parts.length > 1 && parts[0] == "defaultValues") if (parts.length > 1)
{ {
defaultValues = JSON.parse(decodeURIComponent(parts[1])) as { [key: string]: any }; const name = parts[0].replace(/^#/, "");
const value = parts[1];
if (name == "defaultValues")
{
defaultValues = JSON.parse(decodeURIComponent(value)) as { [key: string]: any };
} }
if (parts.length > 1 && parts[0] == "disabledFields") if (name == "disabledFields")
{ {
disabledFields = JSON.parse(decodeURIComponent(parts[1])) as { [key: string]: any }; disabledFields = JSON.parse(decodeURIComponent(value)) as { [key: string]: any };
}
} }
} }
catch (e) catch (e)
{} {
}
} }
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 +295,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"];
if (omitWrapper)
{
return <QDynamicForm formData={formData} record={record} helpRoles={helpRoles} helpContentKeyPrefix={`table:${tableName};`} />; 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 +365,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 +467,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 +525,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,16 +535,28 @@ 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;
} }
const hasFields = section.fieldNames && section.fieldNames.length > 0;
const hasChildRecordListWidget = section.widgetName && metaData.widgets.get(section.widgetName)?.type == "childRecordList";
if (!hasFields && !hasChildRecordListWidget)
{
continue;
}
if (hasFields)
{
for (let j = 0; j < section.fieldNames.length; j++) for (let j = 0; j < section.fieldNames.length; j++)
{ {
const fieldName = section.fieldNames[j]; const fieldName = section.fieldNames[j];
@ -381,7 +591,14 @@ function EntityForm(props: Props): JSX.Element
{ {
dynamicFormFieldsBySection.set(section.name, sectionDynamicFormFields); dynamicFormFieldsBySection.set(section.name, sectionDynamicFormFields);
} }
}
else
{
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 +612,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 +668,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 () =>
{ {
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@ -453,7 +706,7 @@ function EntityForm(props: Props): JSX.Element
////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (fieldMetaData.type === QFieldType.DATE_TIME && valuesToPost[fieldName]) if (fieldMetaData.type === QFieldType.DATE_TIME && valuesToPost[fieldName])
{ {
console.log(`DateTime ${fieldName}: Initial value: [${initialValues[fieldName]}] -> [${valuesToPost[fieldName]}]`) console.log(`DateTime ${fieldName}: Initial value: [${initialValues[fieldName]}] -> [${valuesToPost[fieldName]}]`);
if (initialValues[fieldName] == valuesToPost[fieldName]) if (initialValues[fieldName] == valuesToPost[fieldName])
{ {
console.log(" - Is the same, so, deleting from the post"); console.log(" - Is the same, so, deleting from the post");
@ -486,9 +739,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 +775,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 +804,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 +818,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) =>
@ -563,15 +855,15 @@ function EntityForm(props: Props): JSX.Element
const getSectionHelp = (section: QTableSection) => const getSectionHelp = (section: QTableSection) =>
{ {
const helpRoles = [props.id ? "EDIT_SCREEN" : "INSERT_SCREEN", "WRITE_SCREENS", "ALL_SCREENS"] const helpRoles = [props.id ? "EDIT_SCREEN" : "INSERT_SCREEN", "WRITE_SCREENS", "ALL_SCREENS"];
const formattedHelpContent = <HelpContent helpContents={section.helpContents} roles={helpRoles} helpContentKey={`table:${tableMetaData.name};section:${section.name}`} />; const formattedHelpContent = <HelpContent helpContents={section.helpContents} roles={helpRoles} helpContentKey={`table:${tableMetaData.name};section:${section.name}`} />;
return formattedHelpContent && ( return formattedHelpContent && (
<Box px={"1.5rem"} fontSize={"0.875rem"}> <Box px={"1.5rem"} fontSize={"0.875rem"}>
{formattedHelpContent} {formattedHelpContent}
</Box> </Box>
) );
} };
if (notAllowedError) if (notAllowedError)
{ {
@ -594,7 +886,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 +947,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 +956,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 +971,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>
@ -714,7 +1012,7 @@ function EntityForm(props: Props): JSX.Element
function ScrollToFirstError(): JSX.Element function ScrollToFirstError(): JSX.Element
{ {
const {submitCount, isValid} = useFormikContext() const {submitCount, isValid} = useFormikContext();
useEffect(() => useEffect(() =>
{ {
@ -744,8 +1042,8 @@ function ScrollToFirstError(): JSX.Element
} }
firstErrorMessage.scrollIntoView({block: "center"}); firstErrorMessage.scrollIntoView({block: "center"});
}, 100) }, 100);
}, [submitCount, isValid]) }, [submitCount, isValid]);
return null; return null;
} }

View File

@ -71,7 +71,7 @@ function hasGotoFieldNames(tableMetaData: QTableMetaData): boolean
function GotoRecordDialog(props: Props): JSX.Element function GotoRecordDialog(props: Props): JSX.Element
{ {
const fields: QFieldMetaData[] = [] const fields: QFieldMetaData[] = [];
let pkey = props?.tableMetaData?.fields.get(props?.tableMetaData?.primaryKeyField); let pkey = props?.tableMetaData?.fields.get(props?.tableMetaData?.primaryKeyField);
let addedPkey = false; let addedPkey = false;
@ -108,7 +108,7 @@ function GotoRecordDialog(props: Props): JSX.Element
const rs = {} as { [field: string]: string }; const rs = {} as { [field: string]: string };
fields.forEach((field) => rs[field.name] = ""); fields.forEach((field) => rs[field.name] = "");
return (rs); return (rs);
} };
const [error, setError] = useState(""); const [error, setError] = useState("");
const [values, setValues] = useState(makeInitialValues()); const [values, setValues] = useState(makeInitialValues());
@ -118,14 +118,14 @@ function GotoRecordDialog(props: Props): JSX.Element
{ {
values[fieldName] = newValue; values[fieldName] = newValue;
setValues(JSON.parse(JSON.stringify(values))); setValues(JSON.parse(JSON.stringify(values)));
} };
const close = () => const close = () =>
{ {
setError(""); setError("");
setValues(makeInitialValues()); setValues(makeInitialValues());
props.closeHandler(); props.closeHandler();
} };
const keyPressed = (e: React.KeyboardEvent<HTMLDivElement>) => const keyPressed = (e: React.KeyboardEvent<HTMLDivElement>) =>
{ {
@ -144,7 +144,7 @@ function GotoRecordDialog(props: Props): JSX.Element
const index = targetId?.replaceAll("gotoInput-", ""); const index = targetId?.replaceAll("gotoInput-", "");
document.getElementById("gotoButton-" + index).click(); document.getElementById("gotoButton-" + index).click();
} }
} };
const closeRequested = () => const closeRequested = () =>
{ {
@ -152,15 +152,15 @@ function GotoRecordDialog(props: Props): JSX.Element
{ {
close(); close();
} }
} };
const goClicked = async (fieldName: string) => const goClicked = async (fieldName: string) =>
{ {
setError(""); setError("");
const filter = new QQueryFilter([new QFilterCriteria(fieldName, QCriteriaOperator.EQUALS, [values[fieldName]])], null, "AND", null, 10); const filter = new QQueryFilter([new QFilterCriteria(fieldName, QCriteriaOperator.EQUALS, [values[fieldName]])], null, null, "AND", null, 10);
try try
{ {
const queryResult = await qController.query(props.tableMetaData.name, filter, null, props.tableVariant) const queryResult = await qController.query(props.tableMetaData.name, filter, null, props.tableVariant);
if (queryResult.length == 0) if (queryResult.length == 0)
{ {
setError("Record not found."); setError("Record not found.");
@ -183,13 +183,13 @@ function GotoRecordDialog(props: Props): JSX.Element
setError(`Error: ${(e && e.message) ? e.message : e}`); setError(`Error: ${(e && e.message) ? e.message : e}`);
setTimeout(() => setError(""), 6000); setTimeout(() => setError(""), 6000);
} }
} };
if (props.tableMetaData) if (props.tableMetaData)
{ {
if (fields.length == 0 && !error) if (fields.length == 0 && !error)
{ {
setError("This table is not configured for this feature.") setError("This table is not configured for this feature.");
} }
} }
@ -244,7 +244,7 @@ function GotoRecordDialog(props: Props): JSX.Element
: <Box>&nbsp;</Box> : <Box>&nbsp;</Box>
} }
</Dialog> </Dialog>
) );
} }
interface GotoRecordButtonProps interface GotoRecordButtonProps
@ -266,7 +266,7 @@ GotoRecordButton.defaultProps = {
export function GotoRecordButton(props: GotoRecordButtonProps): JSX.Element export function GotoRecordButton(props: GotoRecordButtonProps): JSX.Element
{ {
const [gotoIsOpen, setGotoIsOpen] = useState(props.autoOpen) const [gotoIsOpen, setGotoIsOpen] = useState(props.autoOpen);
function openGoto() function openGoto()
{ {

View File

@ -25,7 +25,7 @@ import {QTableMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QT
import {QJobComplete} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJobComplete"; import {QJobComplete} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJobComplete";
import {QJobError} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJobError"; import {QJobError} from "@kingsrook/qqq-frontend-core/lib/model/processes/QJobError";
import {QRecord} from "@kingsrook/qqq-frontend-core/lib/model/QRecord"; import {QRecord} from "@kingsrook/qqq-frontend-core/lib/model/QRecord";
import {Alert, Button, Link} from "@mui/material"; import {Alert, Button} from "@mui/material";
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import Dialog from "@mui/material/Dialog"; import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions"; import DialogActions from "@mui/material/DialogActions";
@ -40,14 +40,14 @@ import TextField from "@mui/material/TextField";
import Tooltip from "@mui/material/Tooltip"; import Tooltip from "@mui/material/Tooltip";
import {TooltipProps} from "@mui/material/Tooltip/Tooltip"; import {TooltipProps} from "@mui/material/Tooltip/Tooltip";
import FormData from "form-data"; import FormData from "form-data";
import React, {useContext, useEffect, useRef, useState} from "react";
import {useLocation, 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 {QCancelButton, QDeleteButton, QSaveButton} from "qqq/components/buttons/DefaultButtons"; import {QCancelButton, QDeleteButton, QSaveButton} from "qqq/components/buttons/DefaultButtons";
import RecordQueryView from "qqq/models/query/RecordQueryView"; import RecordQueryView from "qqq/models/query/RecordQueryView";
import FilterUtils from "qqq/utils/qqq/FilterUtils"; import FilterUtils from "qqq/utils/qqq/FilterUtils";
import {SavedViewUtils} from "qqq/utils/qqq/SavedViewUtils"; import {SavedViewUtils} from "qqq/utils/qqq/SavedViewUtils";
import React, {useContext, useEffect, useRef, useState} from "react";
import {useLocation, useNavigate} from "react-router-dom";
interface Props interface Props
{ {
@ -87,7 +87,7 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
const RENAME_OPTION = "Rename..."; const RENAME_OPTION = "Rename...";
const DELETE_OPTION = "Delete..."; const DELETE_OPTION = "Delete...";
const CLEAR_OPTION = "New View"; const CLEAR_OPTION = "New View";
const dropdownOptions = [DUPLICATE_OPTION, RENAME_OPTION, DELETE_OPTION, CLEAR_OPTION]; const NEW_REPORT_OPTION = "Create Report from Current View";
const {accentColor, accentColorLight} = useContext(QContext); const {accentColor, accentColorLight} = useContext(QContext);
@ -187,10 +187,26 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
case DELETE_OPTION: case DELETE_OPTION:
setIsDeleteFilter(true) setIsDeleteFilter(true)
break; break;
case NEW_REPORT_OPTION:
createNewReport();
break;
} }
} }
/*******************************************************************************
**
*******************************************************************************/
function createNewReport()
{
const defaultValues: {[key: string]: any} = {};
defaultValues.tableName = tableMetaData.name;
defaultValues.queryFilterJson = JSON.stringify(view.queryFilter, null, 3);
defaultValues.columnsJson = JSON.stringify(view.queryColumns, null, 3);
navigate(`${metaData.getTablePathByName("savedReport")}/create#defaultValues=${encodeURIComponent(JSON.stringify(defaultValues))}`);
}
/******************************************************************************* /*******************************************************************************
** fired when save or delete button saved on confirmation dialogs ** fired when save or delete button saved on confirmation dialogs
@ -227,6 +243,12 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
///////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////
const viewObject = JSON.parse(JSON.stringify(view)); const viewObject = JSON.parse(JSON.stringify(view));
viewObject.queryFilter = JSON.parse(JSON.stringify(FilterUtils.convertFilterPossibleValuesToIds(viewObject.queryFilter))); viewObject.queryFilter = JSON.parse(JSON.stringify(FilterUtils.convertFilterPossibleValuesToIds(viewObject.queryFilter)));
////////////////////////////////////////////////////////////////////////////
// strip away incomplete filters too, just for cleaner saved view filters //
////////////////////////////////////////////////////////////////////////////
FilterUtils.stripAwayIncompleteCriteria(viewObject.queryFilter)
formData.append("viewJson", JSON.stringify(viewObject)); formData.append("viewJson", JSON.stringify(viewObject));
if (isSaveFilterAs || isRenameFilter || currentSavedView == null) if (isSaveFilterAs || isRenameFilter || currentSavedView == null)
@ -370,6 +392,7 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
const hasStorePermission = metaData?.processes.has("storeSavedView"); const hasStorePermission = metaData?.processes.has("storeSavedView");
const hasDeletePermission = metaData?.processes.has("deleteSavedView"); const hasDeletePermission = metaData?.processes.has("deleteSavedView");
const hasQueryPermission = metaData?.processes.has("querySavedView"); const hasQueryPermission = metaData?.processes.has("querySavedView");
const hasSavedReportsPermission = metaData?.tables.has("savedReport");
const tooltipMaxWidth = (maxWidth: string) => const tooltipMaxWidth = (maxWidth: string) =>
{ {
@ -423,7 +446,7 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
</Tooltip> </Tooltip>
} }
{ {
hasStorePermission && currentSavedView != null && hasDeletePermission && currentSavedView != null &&
<Tooltip {...menuTooltipAttribs} title="Delete this saved view."> <Tooltip {...menuTooltipAttribs} title="Delete this saved view.">
<MenuItem disabled={currentSavedView === null} onClick={() => handleDropdownOptionClick(DELETE_OPTION)}> <MenuItem disabled={currentSavedView === null} onClick={() => handleDropdownOptionClick(DELETE_OPTION)}>
<ListItemIcon><Icon>delete</Icon></ListItemIcon> <ListItemIcon><Icon>delete</Icon></ListItemIcon>
@ -439,6 +462,15 @@ function SavedViews({qController, metaData, tableMetaData, currentSavedView, tab
</MenuItem> </MenuItem>
</Tooltip> </Tooltip>
} }
{
hasSavedReportsPermission &&
<Tooltip {...menuTooltipAttribs} title="Create a new Saved Report using your current view of this table as a starting point.">
<MenuItem onClick={() => handleDropdownOptionClick(NEW_REPORT_OPTION)}>
<ListItemIcon><Icon>article</Icon></ListItemIcon>
Create Report from Current View
</MenuItem>
</Tooltip>
}
<Divider/> <Divider/>
<MenuItem disabled style={{"opacity": "initial"}}><b>Your Saved Views</b></MenuItem> <MenuItem disabled style={{"opacity": "initial"}}><b>Your Saved Views</b></MenuItem>
{ {

View File

@ -29,7 +29,6 @@ import {QCriteriaOperator} from "@kingsrook/qqq-frontend-core/lib/model/query/QC
import {QFilterCriteria} from "@kingsrook/qqq-frontend-core/lib/model/query/QFilterCriteria"; import {QFilterCriteria} from "@kingsrook/qqq-frontend-core/lib/model/query/QFilterCriteria";
import {QFilterOrderBy} from "@kingsrook/qqq-frontend-core/lib/model/query/QFilterOrderBy"; import {QFilterOrderBy} from "@kingsrook/qqq-frontend-core/lib/model/query/QFilterOrderBy";
import {QQueryFilter} from "@kingsrook/qqq-frontend-core/lib/model/query/QQueryFilter"; import {QQueryFilter} from "@kingsrook/qqq-frontend-core/lib/model/query/QQueryFilter";
import {Badge, ToggleButton, ToggleButtonGroup} from "@mui/material";
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 Dialog from "@mui/material/Dialog"; import Dialog from "@mui/material/Dialog";
@ -38,9 +37,10 @@ import DialogContent from "@mui/material/DialogContent";
import DialogContentText from "@mui/material/DialogContentText"; import DialogContentText from "@mui/material/DialogContentText";
import DialogTitle from "@mui/material/DialogTitle"; import DialogTitle from "@mui/material/DialogTitle";
import Icon from "@mui/material/Icon"; import Icon from "@mui/material/Icon";
import ToggleButton from "@mui/material/ToggleButton";
import ToggleButtonGroup from "@mui/material/ToggleButtonGroup";
import Tooltip from "@mui/material/Tooltip"; import Tooltip from "@mui/material/Tooltip";
import {GridApiPro} from "@mui/x-data-grid-pro/models/gridApiPro"; import {GridApiPro} from "@mui/x-data-grid-pro/models/gridApiPro";
import React, {forwardRef, useContext, useImperativeHandle, useReducer, useState} from "react";
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 {QCancelButton, QSaveButton} from "qqq/components/buttons/DefaultButtons"; import {QCancelButton, QSaveButton} from "qqq/components/buttons/DefaultButtons";
@ -51,6 +51,7 @@ import QuickFilter, {quickFilterButtonStyles} from "qqq/components/query/QuickFi
import XIcon from "qqq/components/query/XIcon"; import XIcon from "qqq/components/query/XIcon";
import FilterUtils from "qqq/utils/qqq/FilterUtils"; import FilterUtils from "qqq/utils/qqq/FilterUtils";
import TableUtils from "qqq/utils/qqq/TableUtils"; import TableUtils from "qqq/utils/qqq/TableUtils";
import React, {forwardRef, useContext, useImperativeHandle, useReducer, useState} from "react";
interface BasicAndAdvancedQueryControlsProps interface BasicAndAdvancedQueryControlsProps
{ {
@ -89,14 +90,14 @@ let debounceTimeout: string | number | NodeJS.Timeout;
*******************************************************************************/ *******************************************************************************/
const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryControlsProps, ref) => const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryControlsProps, ref) =>
{ {
const {metaData, tableMetaData, savedViewsComponent, columnMenuComponent, quickFilterFieldNames, setQuickFilterFieldNames, setQueryFilter, queryFilter, gridApiRef, queryFilterJSON, mode, setMode} = props const {metaData, tableMetaData, savedViewsComponent, columnMenuComponent, quickFilterFieldNames, setQuickFilterFieldNames, setQueryFilter, queryFilter, gridApiRef, queryFilterJSON, mode, setMode} = props;
///////////////////// /////////////////////
// state variables // // state variables //
///////////////////// /////////////////////
const [defaultQuickFilterFieldNames, setDefaultQuickFilterFieldNames] = useState(getDefaultQuickFilterFieldNames(tableMetaData)); const [defaultQuickFilterFieldNames, setDefaultQuickFilterFieldNames] = useState(getDefaultQuickFilterFieldNames(tableMetaData));
const [defaultQuickFilterFieldNameMap, setDefaultQuickFilterFieldNameMap] = useState(Object.fromEntries(defaultQuickFilterFieldNames.map(k => [k, true]))); const [defaultQuickFilterFieldNameMap, setDefaultQuickFilterFieldNameMap] = useState(Object.fromEntries(defaultQuickFilterFieldNames.map(k => [k, true])));
const [addQuickFilterMenu, setAddQuickFilterMenu] = useState(null) const [addQuickFilterMenu, setAddQuickFilterMenu] = useState(null);
const [addQuickFilterOpenCounter, setAddQuickFilterOpenCounter] = useState(0); const [addQuickFilterOpenCounter, setAddQuickFilterOpenCounter] = useState(0);
const [showClearFiltersWarning, setShowClearFiltersWarning] = useState(false); const [showClearFiltersWarning, setShowClearFiltersWarning] = useState(false);
const [mouseOverElement, setMouseOverElement] = useState(null as string); const [mouseOverElement, setMouseOverElement] = useState(null as string);
@ -104,6 +105,11 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
const {accentColor} = useContext(QContext); const {accentColor} = useContext(QContext);
/////////////////////////////////////////////////
// temporary, until we implement sub-filtering //
/////////////////////////////////////////////////
const [isQueryTooComplex, setIsQueryTooComplex] = useState(false);
////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////
// make some functions available to our parent - so it can tell us to do things // // make some functions available to our parent - so it can tell us to do things //
////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////
@ -122,7 +128,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
{ {
return (mode); return (mode);
} }
} };
}); });
@ -207,7 +213,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
if (found) if (found)
{ {
clearTimeout(debounceTimeout) clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(() => debounceTimeout = setTimeout(() =>
{ {
setQueryFilter(queryFilter); setQueryFilter(queryFilter);
@ -254,7 +260,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
*******************************************************************************/ *******************************************************************************/
const handleRemoveQuickFilterField = (fieldName: string): void => const handleRemoveQuickFilterField = (fieldName: string): void =>
{ {
const index = quickFilterFieldNames.indexOf(fieldName) const index = quickFilterFieldNames.indexOf(fieldName);
if (index >= 0) if (index >= 0)
{ {
////////////////////////////////////// //////////////////////////////////////
@ -276,7 +282,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
{ {
setAddQuickFilterMenu(event.currentTarget); setAddQuickFilterMenu(event.currentTarget);
setAddQuickFilterOpenCounter(addQuickFilterOpenCounter + 1); setAddQuickFilterOpenCounter(addQuickFilterOpenCounter + 1);
} };
/******************************************************************************* /*******************************************************************************
@ -285,7 +291,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
const closeAddQuickFilterMenu = () => const closeAddQuickFilterMenu = () =>
{ {
setAddQuickFilterMenu(null); setAddQuickFilterMenu(null);
} };
/******************************************************************************* /*******************************************************************************
@ -352,7 +358,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
} }
addQuickFilterField({fieldName: fullFieldName}, "selectedFromAddFilterMenu"); addQuickFilterField({fieldName: fullFieldName}, "selectedFromAddFilterMenu");
} };
/******************************************************************************* /*******************************************************************************
@ -360,8 +366,11 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
** filter panel ** filter panel
*******************************************************************************/ *******************************************************************************/
const openFilterBuilder = (e: React.MouseEvent<HTMLAnchorElement> | React.MouseEvent<HTMLButtonElement>) => const openFilterBuilder = (e: React.MouseEvent<HTMLAnchorElement> | React.MouseEvent<HTMLButtonElement>) =>
{
if (!isQueryTooComplex)
{ {
gridApiRef.current.showFilterPanel(); gridApiRef.current.showFilterPanel();
}
}; };
@ -385,13 +394,13 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
{ {
queryFilter.criteria.splice(index, 1); queryFilter.criteria.splice(index, 1);
setQueryFilter(queryFilter); setQueryFilter(queryFilter);
} };
/******************************************************************************* /*******************************************************************************
** format the current query as a string for showing on-screen as a preview. ** format the current query as a string for showing on-screen as a preview.
*******************************************************************************/ *******************************************************************************/
const queryToAdvancedString = () => const queryToAdvancedString = (thisQueryFilter: QQueryFilter) =>
{ {
if (queryFilter == null || !queryFilter.criteria) if (queryFilter == null || !queryFilter.criteria)
{ {
@ -401,19 +410,22 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
let counter = 0; let counter = 0;
return ( return (
<Box display="flex" flexWrap="wrap" fontSize="0.875rem"> <React.Fragment>
{queryFilter.criteria.map((criteria, i) => {thisQueryFilter.criteria?.map((criteria, i) =>
{ {
const {criteriaIsValid} = validateCriteria(criteria, null); const {criteriaIsValid} = validateCriteria(criteria, null);
if (criteriaIsValid) if (criteriaIsValid)
{ {
counter++; counter++;
return ( return (
<span key={i} style={{marginBottom: "0.125rem"}} onMouseOver={() => handleMouseOverElement(`queryPreview-${i}`)} onMouseOut={() => handleMouseOutElement()}> <span key={i} style={{marginBottom: "0.125rem"}} onMouseOver={() => handleMouseOverElement(`queryPreview-${i}`)} onMouseOut={() => handleMouseOutElement()}>
{counter > 1 ? <span style={{marginLeft: "0.25rem", marginRight: "0.25rem"}}>{queryFilter.booleanOperator}&nbsp;</span> : <span/>} {counter > 1 ? <span style={{marginLeft: "0.25rem", marginRight: "0.25rem"}}>{thisQueryFilter.booleanOperator}&nbsp;</span> : <span />}
{FilterUtils.criteriaToHumanString(tableMetaData, criteria, true)} {FilterUtils.criteriaToHumanString(tableMetaData, criteria, true)}
{mouseOverElement == `queryPreview-${i}` && <span className={`advancedQueryPreviewX-${counter - 1}`}><XIcon position="forAdvancedQueryPreview" onClick={() => removeCriteriaByIndex(i)} /></span>} {!isQueryTooComplex && (
mouseOverElement == `queryPreview-${i}` && <span className={`advancedQueryPreviewX-${counter - 1}`}>
<XIcon position="forAdvancedQueryPreview" onClick={() => removeCriteriaByIndex(i)} /></span>
)}
{counter > 1 && i == thisQueryFilter.criteria?.length - 1 && thisQueryFilter.subFilters?.length > 0 ? <span style={{marginLeft: "0.25rem", marginRight: "0.25rem"}}>{thisQueryFilter.booleanOperator}&nbsp;</span> : <span />}
</span> </span>
); );
} }
@ -422,7 +434,19 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
return (<span />); return (<span />);
} }
})} })}
</Box>
{thisQueryFilter.subFilters?.length > 0 && (thisQueryFilter.subFilters.map((filter: QQueryFilter, j) =>
{
return (
<React.Fragment key={j}>
{j > 0 ? <span style={{marginLeft: "0.25rem", marginRight: "0.25rem"}}>{thisQueryFilter.booleanOperator}&nbsp;</span> : <span></span>}
<span style={{display: "flex", marginRight: "0.20rem"}}>(</span>
{queryToAdvancedString(filter)}
<span style={{display: "flex", marginRight: "0.20rem"}}>)</span>
</React.Fragment>
);
}))}
</React.Fragment>
); );
}; };
@ -443,7 +467,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
const {canFilterWorkAsBasic} = FilterUtils.canFilterWorkAsBasic(tableMetaData, queryFilter); const {canFilterWorkAsBasic} = FilterUtils.canFilterWorkAsBasic(tableMetaData, queryFilter);
if (!canFilterWorkAsBasic) if (!canFilterWorkAsBasic)
{ {
console.log("Query cannot work as basic - so - not allowing toggle to basic.") console.log("Query cannot work as basic - so - not allowing toggle to basic.");
return; return;
} }
@ -475,6 +499,11 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
return; return;
} }
//////////////////////////////////////////////
// set a flag if the query is 'too complex' //
//////////////////////////////////////////////
setIsQueryTooComplex(queryFilter.subFilters?.length > 0);
const {canFilterWorkAsBasic} = FilterUtils.canFilterWorkAsBasic(tableMetaData, queryFilter); const {canFilterWorkAsBasic} = FilterUtils.canFilterWorkAsBasic(tableMetaData, queryFilter);
if (!canFilterWorkAsBasic) if (!canFilterWorkAsBasic)
{ {
@ -496,7 +525,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
} }
} }
} }
} };
/******************************************************************************* /*******************************************************************************
@ -513,9 +542,18 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
count++; count++;
} }
} }
return count;
/////////////////////////////////////////////////////////////
// recursively add any children filters to the total count //
/////////////////////////////////////////////////////////////
for (let i = 0; i < queryFilter.subFilters?.length; i++)
{
count += countValidCriteria(queryFilter.subFilters[i]);
} }
return count;
};
/******************************************************************************* /*******************************************************************************
** Event handler for setting the sort from that menu ** Event handler for setting the sort from that menu
@ -523,11 +561,11 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
const handleSetSort = (field: QFieldMetaData, table: QTableMetaData, isAscending: boolean = true): void => const handleSetSort = (field: QFieldMetaData, table: QTableMetaData, isAscending: boolean = true): void =>
{ {
const fullFieldName = table && table.name != tableMetaData.name ? `${table.name}.${field.name}` : field.name; const fullFieldName = table && table.name != tableMetaData.name ? `${table.name}.${field.name}` : field.name;
queryFilter.orderBys = [new QFilterOrderBy(fullFieldName, isAscending)] queryFilter.orderBys = [new QFilterOrderBy(fullFieldName, isAscending)];
setQueryFilter(queryFilter); setQueryFilter(queryFilter);
forceUpdate(); forceUpdate();
} };
/******************************************************************************* /*******************************************************************************
@ -546,7 +584,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
{ {
handleSetSort(field, table, isAscending); handleSetSort(field, table, isAscending);
} }
} };
/******************************************************************************* /*******************************************************************************
@ -563,21 +601,21 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
} }
catch (e) catch (e)
{ {
console.log(`Error toggling sort: ${e}`) console.log(`Error toggling sort: ${e}`);
} }
} }
///////////////////////////////// /////////////////////////////////
// set up the sort menu button // // set up the sort menu button //
///////////////////////////////// /////////////////////////////////
let sortButtonContents = <>Sort...</> let sortButtonContents = <>Sort...</>;
if (queryFilter && queryFilter.orderBys && queryFilter.orderBys.length > 0) if (queryFilter && queryFilter.orderBys && queryFilter.orderBys.length > 0)
{ {
const orderBy = queryFilter.orderBys[0]; const orderBy = queryFilter.orderBys[0];
const orderByFieldName = orderBy.fieldName; const orderByFieldName = orderBy.fieldName;
const [field, fieldTable] = TableUtils.getFieldAndTable(tableMetaData, orderByFieldName); const [field, fieldTable] = TableUtils.getFieldAndTable(tableMetaData, orderByFieldName);
const fieldLabel = fieldTable.name == tableMetaData.name ? field.label : `${fieldTable.label}: ${field.label}`; const fieldLabel = fieldTable.name == tableMetaData.name ? field.label : `${fieldTable.label}: ${field.label}`;
sortButtonContents = <>Sort: {fieldLabel} <Icon onClick={toggleSortDirection} sx={{ml: "0.5rem"}}>{orderBy.isAscending ? "arrow_upward" : "arrow_downward"}</Icon></> sortButtonContents = <>Sort: {fieldLabel} <Icon onClick={toggleSortDirection} sx={{ml: "0.5rem"}}>{orderBy.isAscending ? "arrow_upward" : "arrow_downward"}</Icon></>;
} }
//////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////
@ -594,16 +632,22 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
// set some status flags based on current filter // // set some status flags based on current filter //
/////////////////////////////////////////////////// ///////////////////////////////////////////////////
const hasValidFilters = queryFilter && countValidCriteria(queryFilter) > 0; const hasValidFilters = queryFilter && countValidCriteria(queryFilter) > 0;
const {canFilterWorkAsBasic, reasonsWhyItCannot} = FilterUtils.canFilterWorkAsBasic(tableMetaData, queryFilter); const {canFilterWorkAsBasic, canFilterWorkAsAdvanced, reasonsWhyItCannot} = FilterUtils.canFilterWorkAsBasic(tableMetaData, queryFilter);
let reasonWhyBasicIsDisabled = null; let reasonWhyBasicIsDisabled = null;
if(reasonsWhyItCannot && reasonsWhyItCannot.length > 0) if (canFilterWorkAsAdvanced && reasonsWhyItCannot && reasonsWhyItCannot.length > 0)
{ {
reasonWhyBasicIsDisabled = <> reasonWhyBasicIsDisabled = <>
Your current Filter cannot be managed using Basic mode because: Your current Filter cannot be managed using Basic mode because:
<ul style={{marginLeft: "1rem"}}> <ul style={{marginLeft: "1rem"}}>
{reasonsWhyItCannot.map((reason, i) => <li key={i}>{reason}</li>)} {reasonsWhyItCannot.map((reason, i) => <li key={i}>{reason}</li>)}
</ul> </ul>
</> </>;
}
if (isQueryTooComplex)
{
reasonWhyBasicIsDisabled = <>
Your current Filter is too complex to modify because it contains Sub-filters.
</>;
} }
const borderGray = colors.grayLines.main; const borderGray = colors.grayLines.main;
@ -777,7 +821,9 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
pb={"0.125rem"} pb={"0.125rem"}
boxShadow={"inset 0px 0px 4px 2px #EFEFED"} boxShadow={"inset 0px 0px 4px 2px #EFEFED"}
> >
{queryToAdvancedString()} <Box display="flex" flexWrap="wrap" fontSize="0.875rem">
{queryToAdvancedString(queryFilter)}
</Box>
</Box> </Box>
} }
</Box> </Box>

View File

@ -45,7 +45,7 @@ export default function ExportMenuItem(props: QExportMenuItemProps)
return ( return (
<MenuItem <MenuItem
disabled={!totalRecords} disabled={totalRecords === 0}
onClick={() => onClick={() =>
{ {
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////

View File

@ -94,6 +94,24 @@ export const makeTextField = (field: QFieldMetaData, criteria: QFilterCriteriaWi
document.getElementById(`${idPrefix}${criteria.id}`).focus(); document.getElementById(`${idPrefix}${criteria.id}`).focus();
}; };
/*******************************************************************************
** Event handler for key-down events - specifically added here, to stop pressing
** 'tab' in a date or date-time from closing the quick-filter...
*******************************************************************************/
const handleKeyDown = (e: any) =>
{
if (field.type == QFieldType.DATE || field.type == QFieldType.DATE_TIME)
{
if(e.code == "Tab")
{
console.log("Tab on date or date-time - don't close me, just move to the next sub-field!...");
e.stopPropagation();
}
}
};
const inputProps: any = {}; const inputProps: any = {};
inputProps.endAdornment = ( inputProps.endAdornment = (
<InputAdornment position="end"> <InputAdornment position="end">
@ -110,6 +128,7 @@ export const makeTextField = (field: QFieldMetaData, criteria: QFilterCriteriaWi
autoComplete="off" autoComplete="off"
type={type} type={type}
onChange={(event) => valueChangeHandler(event, valueIndex)} onChange={(event) => valueChangeHandler(event, valueIndex)}
onKeyDown={handleKeyDown}
value={value} value={value}
InputLabelProps={inputLabelProps} InputLabelProps={inputLabelProps}
InputProps={inputProps} InputProps={inputProps}

View File

@ -504,7 +504,7 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
////////////////////////////// //////////////////////////////
// return the button & menu // // return the button & menu //
////////////////////////////// //////////////////////////////
const widthAndMaxWidth = 250 const widthAndMaxWidth = fieldMetaData?.type == QFieldType.DATE_TIME ? 275 : 250
return ( return (
<> <>
{button} {button}

View File

@ -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>
); );
}; };

View File

@ -21,8 +21,6 @@
import BlockElementWrapper from "qqq/components/widgets/blocks/BlockElementWrapper"; import BlockElementWrapper from "qqq/components/widgets/blocks/BlockElementWrapper";
import {StandardBlockComponentProps} from "qqq/components/widgets/blocks/BlockModels"; import {StandardBlockComponentProps} from "qqq/components/widgets/blocks/BlockModels";
import UpOrDownNumberBlock from "qqq/components/widgets/blocks/UpOrDownNumberBlock";
/******************************************************************************* /*******************************************************************************
@ -40,7 +38,7 @@ export default function BigNumberBlock({widgetMetaData, data}: StandardBlockComp
<div style={{width: data.styles.width ?? "auto"}}> <div style={{width: data.styles.width ?? "auto"}}>
<div style={{fontWeight: "700", fontSize: "0.875rem", color: "#3D3D3D", marginBottom: "-0.5rem"}}> <div style={{fontWeight: "700", fontSize: "0.875rem", color: "#3D3D3D", marginBottom: "-0.5rem"}}>
<BlockElementWrapper data={data} slot="heading"> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="heading">
<span>{data.values.heading}</span> <span>{data.values.heading}</span>
</BlockElementWrapper> </BlockElementWrapper>
</div> </div>
@ -49,14 +47,14 @@ export default function BigNumberBlock({widgetMetaData, data}: StandardBlockComp
<div style={{display: "flex", alignItems: "baseline"}}> <div style={{display: "flex", alignItems: "baseline"}}>
<div style={{fontWeight: "700", fontSize: "2rem", marginRight: "0.25rem"}}> <div style={{fontWeight: "700", fontSize: "2rem", marginRight: "0.25rem"}}>
<BlockElementWrapper data={data} slot="number"> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="number">
<span style={{color: data.styles.numberColor}}>{data.values.number}</span> <span style={{color: data.styles.numberColor}}>{data.values.number}</span>
</BlockElementWrapper> </BlockElementWrapper>
</div> </div>
{ {
data.values.context && data.values.context &&
<div style={{fontWeight: "500", fontSize: "0.875rem", color: "#7b809a"}}> <div style={{fontWeight: "500", fontSize: "0.875rem", color: "#7b809a"}}>
<BlockElementWrapper data={data} slot="context"> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="context">
<span>{data.values.context}</span> <span>{data.values.context}</span>
</BlockElementWrapper> </BlockElementWrapper>
</div> </div>

View File

@ -20,14 +20,18 @@
*/ */
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
import {Tooltip} from "@mui/material"; import {Tooltip} from "@mui/material";
import React, {ReactElement} from "react"; import React, {ReactElement, useContext} from "react";
import {Link} from "react-router-dom"; import {Link} from "react-router-dom";
import QContext from "QContext";
import HelpContent, {hasHelpContent} from "qqq/components/misc/HelpContent";
import {BlockData, BlockLink, BlockTooltip} from "qqq/components/widgets/blocks/BlockModels"; import {BlockData, BlockLink, BlockTooltip} from "qqq/components/widgets/blocks/BlockModels";
interface BlockElementWrapperProps interface BlockElementWrapperProps
{ {
data: BlockData; data: BlockData;
metaData: QWidgetMetaData;
slot: string slot: string
linkProps?: any; linkProps?: any;
children: ReactElement; children: ReactElement;
@ -36,8 +40,10 @@ interface BlockElementWrapperProps
/******************************************************************************* /*******************************************************************************
** For Blocks - wrap their "slot" elements with an optional tooltip and/or link ** For Blocks - wrap their "slot" elements with an optional tooltip and/or link
*******************************************************************************/ *******************************************************************************/
export default function BlockElementWrapper({data, slot, linkProps, children}: BlockElementWrapperProps): JSX.Element export default function BlockElementWrapper({data, metaData, slot, linkProps, children}: BlockElementWrapperProps): JSX.Element
{ {
const {helpHelpActive} = useContext(QContext);
let link: BlockLink; let link: BlockLink;
let tooltip: BlockTooltip; let tooltip: BlockTooltip;
@ -61,6 +67,26 @@ export default function BlockElementWrapper({data, slot, linkProps, children}: B
tooltip = data.tooltip; tooltip = data.tooltip;
} }
if(!tooltip)
{
const helpRoles = ["ALL_SCREENS"]
///////////////////////////////////////////////////////////////////////////////////////////////
// the full keys in the helpContent table will look like: //
// widget:MyCoolWidget;slot=myBlockId,label (if the block has a blockId in data) //
// widget:MyCoolWidget;slot=label (no blockId; note, label is slot name here) //
// in the widget metaData, the map of helpContent will just have the "slot" portion as a key //
///////////////////////////////////////////////////////////////////////////////////////////////
const key = data.blockId ? `${data.blockId},${slot}` : slot;
const showHelp = helpHelpActive || hasHelpContent(metaData?.helpContent?.get(key), helpRoles);
if(showHelp)
{
const formattedHelpContent = <HelpContent helpContents={metaData?.helpContent?.get(key)} roles={helpRoles} helpContentKey={`widget:${metaData?.name};slot:${key}`} />;
tooltip = {title: formattedHelpContent, placement: "bottom"}
}
}
let rs = children; let rs = children;
if(link) if(link)

View File

@ -24,6 +24,7 @@ import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/Q
export interface BlockData export interface BlockData
{ {
blockId?: string;
blockTypeName: string; blockTypeName: string;
tooltip?: BlockTooltip; tooltip?: BlockTooltip;
@ -38,7 +39,7 @@ export interface BlockData
export interface BlockTooltip export interface BlockTooltip
{ {
title: string; title: string | JSX.Element;
placement: string; placement: string;
} }

View File

@ -28,19 +28,19 @@ import {StandardBlockComponentProps} from "qqq/components/widgets/blocks/BlockMo
** **
** ${number} ${icon} ** ${number} ${icon}
*******************************************************************************/ *******************************************************************************/
export default function NumberIconBadgeBlock({data}: StandardBlockComponentProps): JSX.Element export default function NumberIconBadgeBlock({widgetMetaData, data}: StandardBlockComponentProps): JSX.Element
{ {
return ( return (
<div style={{display: "inline-block", whiteSpace: "nowrap", color: data.styles.color}}> <div style={{display: "inline-block", whiteSpace: "nowrap", color: data.styles.color}}>
{ {
data.values.number && data.values.number &&
<BlockElementWrapper data={data} slot="number"> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="number">
<span style={{color: data.styles.color, fontSize: "0.875rem"}}>{data.values.number}</span> <span style={{color: data.styles.color, fontSize: "0.875rem"}}>{data.values.number}</span>
</BlockElementWrapper> </BlockElementWrapper>
} }
{ {
data.values.iconName && data.values.iconName &&
<BlockElementWrapper data={data} slot="icon"> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="icon">
<Icon style={{color: data.styles.color, fontSize: "1rem", position: "relative", top: "3px"}}>{data.values.iconName}</Icon> <Icon style={{color: data.styles.color, fontSize: "1rem", position: "relative", top: "3px"}}>{data.values.iconName}</Icon>
</BlockElementWrapper> </BlockElementWrapper>
} }

View File

@ -35,14 +35,14 @@ import {StandardBlockComponentProps} from "qqq/components/widgets/blocks/BlockMo
** ${heading} ** ${heading}
** ${bar} ${value} ** ${bar} ${value}
*******************************************************************************/ *******************************************************************************/
export default function ProgressBarBlock({data}: StandardBlockComponentProps): JSX.Element export default function ProgressBarBlock({widgetMetaData, data}: StandardBlockComponentProps): JSX.Element
{ {
return ( return (
<Typography component="div" variant="button" color="text" fontWeight="light" sx={{textTransform: "none"}}> <Typography component="div" variant="button" color="text" fontWeight="light" sx={{textTransform: "none"}}>
{ {
data.values.heading && data.values.heading &&
<div style={{marginBottom: "0.25rem", fontWeight: 500, color: "#3D3D3D"}}> <div style={{marginBottom: "0.25rem", fontWeight: 500, color: "#3D3D3D"}}>
<BlockElementWrapper data={data} slot="heading"> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="heading">
<span>{data.values.heading}</span> <span>{data.values.heading}</span>
</BlockElementWrapper> </BlockElementWrapper>
</div> </div>
@ -50,7 +50,7 @@ export default function ProgressBarBlock({data}: StandardBlockComponentProps): J
<div style={{display: "flex", alignItems: "center", marginBottom: "0.75rem"}}> <div style={{display: "flex", alignItems: "center", marginBottom: "0.75rem"}}>
<BlockElementWrapper data={data} slot="bar" linkProps={{style: {width: "100%"}}}> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="bar" linkProps={{style: {width: "100%"}}}>
<div style={{background: "#E0E0E0", width: "100%", borderRadius: "0.5rem", height: "1rem"}}> <div style={{background: "#E0E0E0", width: "100%", borderRadius: "0.5rem", height: "1rem"}}>
{ {
data.values.percent > 0 ? <div style={{background: data.styles.barColor ?? "#0062ff", minWidth: "1rem", width: `${data.values.percent}%`, borderRadius: "0.5rem", height: "1rem"}}></div> : <></> data.values.percent > 0 ? <div style={{background: data.styles.barColor ?? "#0062ff", minWidth: "1rem", width: `${data.values.percent}%`, borderRadius: "0.5rem", height: "1rem"}}></div> : <></>
@ -59,7 +59,7 @@ export default function ProgressBarBlock({data}: StandardBlockComponentProps): J
</BlockElementWrapper> </BlockElementWrapper>
<div style={{width: "60px", textAlign: "right", fontWeight: 600, color: "#3D3D3D"}}> <div style={{width: "60px", textAlign: "right", fontWeight: 600, color: "#3D3D3D"}}>
<BlockElementWrapper data={data} slot="value"> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="value">
<span>{data.values.value ?? `${(data.values.percent as number).toFixed(1)}%`}</span> <span>{data.values.value ?? `${(data.values.percent as number).toFixed(1)}%`}</span>
</BlockElementWrapper> </BlockElementWrapper>
</div> </div>

View File

@ -29,7 +29,7 @@ import {StandardBlockComponentProps} from "qqq/components/widgets/blocks/BlockMo
** **
** ${label} ${value} ** ${label} ${value}
*******************************************************************************/ *******************************************************************************/
export default function TableSubRowDetailRowBlock({data}: StandardBlockComponentProps): JSX.Element export default function TableSubRowDetailRowBlock({widgetMetaData, data}: StandardBlockComponentProps): JSX.Element
{ {
return ( return (
<div style={{display: "flex", maxWidth: "calc(100% - 24px)", justifyContent: "space-between"}}> <div style={{display: "flex", maxWidth: "calc(100% - 24px)", justifyContent: "space-between"}}>
@ -37,7 +37,7 @@ export default function TableSubRowDetailRowBlock({data}: StandardBlockComponent
{ {
data.values.label && data.values.label &&
<div style={{overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis"}}> <div style={{overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis"}}>
<BlockElementWrapper data={data} slot="label"> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="label">
<span style={{color: data.styles.labelColor}}>{data.values.label}</span> <span style={{color: data.styles.labelColor}}>{data.values.label}</span>
</BlockElementWrapper> </BlockElementWrapper>
</div> </div>
@ -45,7 +45,7 @@ export default function TableSubRowDetailRowBlock({data}: StandardBlockComponent
{ {
data.values.value && data.values.value &&
<BlockElementWrapper data={data} slot="value"> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="value">
<span style={{color: data.styles.valueColor}}>{data.values.value}</span> <span style={{color: data.styles.valueColor}}>{data.values.value}</span>
</BlockElementWrapper> </BlockElementWrapper>
} }

View File

@ -27,10 +27,10 @@ import {StandardBlockComponentProps} from "qqq/components/widgets/blocks/BlockMo
** **
** ${text} ** ${text}
*******************************************************************************/ *******************************************************************************/
export default function TextBlock({data}: StandardBlockComponentProps): JSX.Element export default function TextBlock({widgetMetaData, data}: StandardBlockComponentProps): JSX.Element
{ {
return ( return (
<BlockElementWrapper data={data} slot=""> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="">
<span>{data.values.text}</span> <span>{data.values.text}</span>
</BlockElementWrapper> </BlockElementWrapper>
); );

View File

@ -35,7 +35,7 @@ import {StandardBlockComponentProps} from "qqq/components/widgets/blocks/BlockMo
** ${icon} ${number} ** ${icon} ${number}
** ${context} ** ${context}
*******************************************************************************/ *******************************************************************************/
export default function UpOrDownNumberBlock({data}: StandardBlockComponentProps): JSX.Element export default function UpOrDownNumberBlock({widgetMetaData, data}: StandardBlockComponentProps): JSX.Element
{ {
if (!data.styles) if (!data.styles)
{ {
@ -61,7 +61,7 @@ export default function UpOrDownNumberBlock({data}: StandardBlockComponentProps)
<div style={{display: "flex", flexDirection: data.styles.isStacked ? "column" : "row", alignItems: data.styles.isStacked ? "flex-end" : "baseline"}}> <div style={{display: "flex", flexDirection: data.styles.isStacked ? "column" : "row", alignItems: data.styles.isStacked ? "flex-end" : "baseline"}}>
<div style={{display: "flex", alignItems: "baseline", fontWeight: 700, fontSize: ".875rem"}}> <div style={{display: "flex", alignItems: "baseline", fontWeight: 700, fontSize: ".875rem"}}>
<BlockElementWrapper data={data} slot="number"> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="number">
<> <>
<Icon sx={{color: goodOrBadColor, alignSelf: "flex-end", fontSize: "2.25rem !important", lineHeight: "0.875rem", height: "1rem", width: "2rem",}}>{iconName}</Icon> <Icon sx={{color: goodOrBadColor, alignSelf: "flex-end", fontSize: "2.25rem !important", lineHeight: "0.875rem", height: "1rem", width: "2rem",}}>{iconName}</Icon>
<span style={{color: goodOrBadColor}}>{data.values.number}</span> <span style={{color: goodOrBadColor}}>{data.values.number}</span>
@ -70,7 +70,7 @@ export default function UpOrDownNumberBlock({data}: StandardBlockComponentProps)
</div> </div>
<div style={{fontWeight: 500, fontSize: "0.875rem", color: "#7b809a", marginLeft: "0.25rem"}}> <div style={{fontWeight: 500, fontSize: "0.875rem", color: "#7b809a", marginLeft: "0.25rem"}}>
<BlockElementWrapper data={data} slot="context"> <BlockElementWrapper metaData={widgetMetaData} data={data} slot="context">
<span>{data.values.context}</span> <span>{data.values.context}</span>
</BlockElementWrapper> </BlockElementWrapper>
</div> </div>

View File

@ -25,14 +25,13 @@ import {QCriteriaOperator} from "@kingsrook/qqq-frontend-core/lib/model/query/QC
import {QFilterCriteria} from "@kingsrook/qqq-frontend-core/lib/model/query/QFilterCriteria"; import {QFilterCriteria} from "@kingsrook/qqq-frontend-core/lib/model/query/QFilterCriteria";
import {QFilterOrderBy} from "@kingsrook/qqq-frontend-core/lib/model/query/QFilterOrderBy"; import {QFilterOrderBy} from "@kingsrook/qqq-frontend-core/lib/model/query/QFilterOrderBy";
import {QQueryFilter} from "@kingsrook/qqq-frontend-core/lib/model/query/QQueryFilter"; import {QQueryFilter} from "@kingsrook/qqq-frontend-core/lib/model/query/QQueryFilter";
import {Chip} from "@mui/material";
import Alert from "@mui/material/Alert"; import Alert from "@mui/material/Alert";
import Avatar from "@mui/material/Avatar"; import Avatar from "@mui/material/Avatar";
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 Chip from "@mui/material/Chip";
import Divider from "@mui/material/Divider"; import Divider from "@mui/material/Divider";
import Grid from "@mui/material/Grid"; import Grid from "@mui/material/Grid";
import Icon from "@mui/material/Icon";
import List from "@mui/material/List"; import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem"; import ListItem from "@mui/material/ListItem";
import ListItemAvatar from "@mui/material/ListItemAvatar"; import ListItemAvatar from "@mui/material/ListItemAvatar";
@ -42,8 +41,6 @@ import Snackbar from "@mui/material/Snackbar";
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 Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import React, {useReducer, useState} from "react";
import AceEditor from "react-ace";
import DataBagDataEditor, {DataBagDataEditorProps} from "qqq/components/databags/DataBagDataEditor"; import DataBagDataEditor, {DataBagDataEditorProps} from "qqq/components/databags/DataBagDataEditor";
import DataBagPreview from "qqq/components/databags/DataBagPreview"; import DataBagPreview from "qqq/components/databags/DataBagPreview";
import TabPanel from "qqq/components/misc/TabPanel"; import TabPanel from "qqq/components/misc/TabPanel";
@ -57,6 +54,8 @@ 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, {useReducer, useState} from "react";
import AceEditor from "react-ace";
import "ace-builds/src-noconflict/ext-language_tools"; import "ace-builds/src-noconflict/ext-language_tools";
const qController = Client.getInstance(); const qController = Client.getInstance();
@ -64,12 +63,11 @@ const qController = Client.getInstance();
// Declaring props types for ViewForm // Declaring props types for ViewForm
interface Props interface Props
{ {
dataBagId: number dataBagId: number;
} }
DataBagViewer.defaultProps = DataBagViewer.defaultProps =
{ {};
};
export default function DataBagViewer({dataBagId}: Props): JSX.Element export default function DataBagViewer({dataBagId}: Props): JSX.Element
{ {
@ -82,7 +80,7 @@ export default function DataBagViewer({dataBagId}: Props): JSX.Element
const [selectedTab, setSelectedTab] = useState(0); const [selectedTab, setSelectedTab] = useState(0);
const [editorProps, setEditorProps] = useState(null as DataBagDataEditorProps); const [editorProps, setEditorProps] = useState(null as DataBagDataEditorProps);
const [successText, setSuccessText] = useState(null as string); const [successText, setSuccessText] = useState(null as string);
const [failText, setFailText] = useState(null as string) const [failText, setFailText] = useState(null as string);
const [, forceUpdate] = useReducer((x) => x + 1, 0); const [, forceUpdate] = useReducer((x) => x + 1, 0);
const [loadingSelectedVersion, _] = useState(new LoadingState(forceUpdate, "loading")); const [loadingSelectedVersion, _] = useState(new LoadingState(forceUpdate, "loading"));
@ -100,7 +98,7 @@ export default function DataBagViewer({dataBagId}: Props): JSX.Element
const criteria = [new QFilterCriteria("dataBagId", QCriteriaOperator.EQUALS, [dataBagId])]; const criteria = [new QFilterCriteria("dataBagId", QCriteriaOperator.EQUALS, [dataBagId])];
const orderBys = [new QFilterOrderBy("sequenceNo", false)]; const orderBys = [new QFilterOrderBy("sequenceNo", false)];
const filter = new QQueryFilter(criteria, orderBys, "AND", 0, 25); const filter = new QQueryFilter(criteria, orderBys, null, "AND", 0, 25);
const versions = await qController.query("dataBagVersion", filter); const versions = await qController.query("dataBagVersion", filter);
console.log("Fetched versions:"); console.log("Fetched versions:");
console.log(versions); console.log(versions);

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

@ -46,9 +46,6 @@ import Snackbar from "@mui/material/Snackbar";
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 Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import React, {useReducer, useState} from "react";
import AceEditor from "react-ace";
import {Link} from "react-router-dom";
import TabPanel from "qqq/components/misc/TabPanel"; import TabPanel from "qqq/components/misc/TabPanel";
import ScriptDocsForm from "qqq/components/scripts/ScriptDocsForm"; import ScriptDocsForm from "qqq/components/scripts/ScriptDocsForm";
import ScriptEditor, {ScriptEditorProps} from "qqq/components/scripts/ScriptEditor"; import ScriptEditor, {ScriptEditorProps} from "qqq/components/scripts/ScriptEditor";
@ -65,6 +62,9 @@ import "ace-builds/src-noconflict/mode-javascript";
import "ace-builds/src-noconflict/mode-velocity"; import "ace-builds/src-noconflict/mode-velocity";
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, {useReducer, useState} from "react";
import AceEditor from "react-ace";
import {Link} 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();
@ -97,8 +97,8 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
const [versionRecordList, setVersionRecordList] = useState(null as QRecord[]); const [versionRecordList, setVersionRecordList] = useState(null as QRecord[]);
const [selectedVersionRecord, setSelectedVersionRecord] = useState(null as QRecord); const [selectedVersionRecord, setSelectedVersionRecord] = useState(null as QRecord);
const [scriptLogs, setScriptLogs] = useState({} as any); const [scriptLogs, setScriptLogs] = useState({} as any);
const [scriptTypeRecord, setScriptTypeRecord] = useState(null as QRecord) const [scriptTypeRecord, setScriptTypeRecord] = useState(null as QRecord);
const [scriptTypeFileSchemaList, setScriptTypeFileSchemaList] = useState(null as QRecord[]) const [scriptTypeFileSchemaList, setScriptTypeFileSchemaList] = useState(null as QRecord[]);
const [availableFileNames, setAvailableFileNames] = useState([] as string[]); const [availableFileNames, setAvailableFileNames] = useState([] as string[]);
const [selectedFileName, setSelectedFileName] = useState(""); const [selectedFileName, setSelectedFileName] = useState("");
const [currentVersionId, setCurrentVersionId] = useState(null as number); const [currentVersionId, setCurrentVersionId] = useState(null as number);
@ -106,7 +106,7 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
const [selectedTab, setSelectedTab] = useState(0); const [selectedTab, setSelectedTab] = useState(0);
const [editorProps, setEditorProps] = useState(null as ScriptEditorProps); const [editorProps, setEditorProps] = useState(null as ScriptEditorProps);
const [successText, setSuccessText] = useState(null as string); const [successText, setSuccessText] = useState(null as string);
const [failText, setFailText] = useState(null as string) const [failText, setFailText] = useState(null as string);
const [, forceUpdate] = useReducer((x) => x + 1, 0); const [, forceUpdate] = useReducer((x) => x + 1, 0);
const [loadingSelectedVersion, _] = useState(new LoadingState(forceUpdate, "loading")); const [loadingSelectedVersion, _] = useState(new LoadingState(forceUpdate, "loading"));
@ -135,7 +135,7 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
} }
else if (fileMode == 2) // MULTI_PRE_DEFINED else if (fileMode == 2) // MULTI_PRE_DEFINED
{ {
const filter = new QQueryFilter([new QFilterCriteria("scriptTypeId", QCriteriaOperator.EQUALS, [scriptRecord.values.get("scriptTypeId")])], [new QFilterOrderBy("id")]) const filter = new QQueryFilter([new QFilterCriteria("scriptTypeId", QCriteriaOperator.EQUALS, [scriptRecord.values.get("scriptTypeId")])], [new QFilterOrderBy("id")]);
scriptTypeFileSchemaList = await qController.query("scriptTypeFileSchema", filter); scriptTypeFileSchemaList = await qController.query("scriptTypeFileSchema", filter);
} }
else // MULTI AD_HOC else // MULTI AD_HOC
@ -147,14 +147,14 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
setScriptTypeFileSchemaList(scriptTypeFileSchemaList); setScriptTypeFileSchemaList(scriptTypeFileSchemaList);
if (scriptTypeFileSchemaList) if (scriptTypeFileSchemaList)
{ {
const availableFileNames = scriptTypeFileSchemaList.map((fileSchemaRecord) => fileSchemaRecord.values.get("name")) const availableFileNames = scriptTypeFileSchemaList.map((fileSchemaRecord) => fileSchemaRecord.values.get("name"));
setAvailableFileNames(availableFileNames); setAvailableFileNames(availableFileNames);
setSelectedFileName(availableFileNames[0]) setSelectedFileName(availableFileNames[0]);
} }
const criteria = [new QFilterCriteria("scriptId", QCriteriaOperator.EQUALS, [scriptId])]; const criteria = [new QFilterCriteria("scriptId", QCriteriaOperator.EQUALS, [scriptId])];
const orderBys = [new QFilterOrderBy("sequenceNo", false)]; const orderBys = [new QFilterOrderBy("sequenceNo", false)];
const filter = new QQueryFilter(criteria, orderBys, "AND", 0, 25); const filter = new QQueryFilter(criteria, orderBys, null, "AND", 0, 25);
const versions = await qController.query("scriptRevision", filter); const versions = await qController.query("scriptRevision", filter);
console.log("Fetched versions:"); console.log("Fetched versions:");
console.log(versions); console.log(versions);
@ -253,12 +253,12 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
const handleSelectFile = (event: SelectChangeEvent) => const handleSelectFile = (event: SelectChangeEvent) =>
{ {
setSelectedFileName(event.target.value); setSelectedFileName(event.target.value);
} };
const getSelectedFileCode = (): string => const getSelectedFileCode = (): string =>
{ {
return (getSelectedVersionCode()[selectedFileName] ?? ""); return (getSelectedVersionCode()[selectedFileName] ?? "");
} };
const getSelectedFileType = (): string => const getSelectedFileType = (): string =>
{ {
@ -272,12 +272,12 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
} }
return ("javascript"); // have some default... return ("javascript"); // have some default...
} };
const getSelectedVersionCode = (): { [name: string]: string } => const getSelectedVersionCode = (): { [name: string]: string } =>
{ {
let rs: {[name: string]: string} = {} let rs: { [name: string]: string } = {};
let files = selectedVersionRecord?.associatedRecords?.get("files") let files = selectedVersionRecord?.associatedRecords?.get("files");
for (let j = 0; j < files?.length; j++) for (let j = 0; j < files?.length; j++)
{ {
@ -286,7 +286,7 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
} }
return (rs); return (rs);
} };
function getVersionsList(versionRecordList: QRecord[], selectedVersionRecord: QRecord) function getVersionsList(versionRecordList: QRecord[], selectedVersionRecord: QRecord)
{ {
@ -348,7 +348,7 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
{ {
(async () => (async () =>
{ {
let filter = new QQueryFilter([new QFilterCriteria("scriptRevisionId", QCriteriaOperator.EQUALS, [scriptRevisionId])], [new QFilterOrderBy("id", false)], "AND", 0, 100); let filter = new QQueryFilter([new QFilterCriteria("scriptRevisionId", QCriteriaOperator.EQUALS, [scriptRevisionId])], [new QFilterOrderBy("id", false)], null, "AND", 0, 100);
scriptLogs[scriptRevisionId] = await qController.query("scriptLog", filter); scriptLogs[scriptRevisionId] = await qController.query("scriptLog", filter);
setScriptLogs(scriptLogs); setScriptLogs(scriptLogs);
forceUpdate(); forceUpdate();
@ -368,7 +368,7 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
} }
return (<ScriptLogsView logs={logs} />); return (<ScriptLogsView logs={logs} />);
} };
let editButtonTooltip = ""; let editButtonTooltip = "";
let editButtonText = "Create New Version"; let editButtonText = "Create New Version";

View File

@ -63,6 +63,8 @@ export default class RecordQueryView
view.queryFilter = json.queryFilter as QQueryFilter; view.queryFilter = json.queryFilter as QQueryFilter;
FilterUtils.stripAwayIncompleteCriteria(view.queryFilter)
////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////
// it's important that some criteria values exist as expression objects - so - do that. // // it's important that some criteria values exist as expression objects - so - do that. //
////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////

View File

@ -77,9 +77,11 @@ function AppHome({app}: Props): JSX.Element
const mdbMetaData = app?.supplementalAppMetaData?.get("materialDashboard"); const mdbMetaData = app?.supplementalAppMetaData?.get("materialDashboard");
let showAppLabelOnHomeScreen = true; let showAppLabelOnHomeScreen = true;
let includeTableCountsOnHomeScreen = true;
if(mdbMetaData) if(mdbMetaData)
{ {
showAppLabelOnHomeScreen = mdbMetaData.showAppLabelOnHomeScreen; showAppLabelOnHomeScreen = mdbMetaData.showAppLabelOnHomeScreen;
includeTableCountsOnHomeScreen = mdbMetaData.includeTableCountsOnHomeScreen;
} }
useEffect(() => useEffect(() =>
@ -128,9 +130,10 @@ function AppHome({app}: Props): JSX.Element
const tableCountNumbers = new Map<string, string>(); const tableCountNumbers = new Map<string, string>();
const tableCountTexts = new Map<string, string>(); const tableCountTexts = new Map<string, string>();
newTables.forEach((table) => newTables.forEach((table) =>
{
if(includeTableCountsOnHomeScreen)
{ {
tableCounts.set(table.name, {isLoading: true, value: null}); tableCounts.set(table.name, {isLoading: true, value: null});
setTimeout(async () => setTimeout(async () =>
{ {
const tableMetaData = await qController.loadTableMetaData(table.name); const tableMetaData = await qController.loadTableMetaData(table.name);
@ -171,6 +174,17 @@ function AppHome({app}: Props): JSX.Element
setTableCountTexts(tableCountTexts); setTableCountTexts(tableCountTexts);
setUpdatedTableCounts(new Date()); setUpdatedTableCounts(new Date());
}, 1); }, 1);
}
else
{
tableCounts.set(table.name, {isLoading: false, value: null});
tableCountNumbers.set(table.name, " ");
tableCountTexts.set(table.name, " ");
setTableCounts(tableCounts);
setTableCountNumbers(tableCountNumbers);
setTableCountTexts(tableCountTexts);
}
}); });
setTableCounts(tableCounts); setTableCounts(tableCounts);
@ -299,7 +313,7 @@ function AppHome({app}: Props): JSX.Element
</Box> </Box>
{ {
section.processes ? ( section.processes ? (
<Box p={3} pl={5} pt={0} pb={1}> <Box p={3} pl={3} pt={0} pb={1}>
<MDTypography variant="h6">Actions</MDTypography> <MDTypography variant="h6">Actions</MDTypography>
</Box> </Box>
) : null ) : null
@ -340,7 +354,7 @@ function AppHome({app}: Props): JSX.Element
} }
{ {
section.reports ? ( section.reports ? (
<Box p={3} pl={5} pt={0} pb={1}> <Box p={3} pl={3} pt={0} pb={1}>
<MDTypography variant="h6">Reports</MDTypography> <MDTypography variant="h6">Reports</MDTypography>
</Box> </Box>
) : null ) : null
@ -383,7 +397,7 @@ function AppHome({app}: Props): JSX.Element
} }
{ {
section.tables ? ( section.tables ? (
<Box p={3} pl={5} pb={1} pt={0}> <Box p={3} pl={3} pb={1} pt={0}>
<MDTypography variant="h6">Data</MDTypography> <MDTypography variant="h6">Data</MDTypography>
</Box> </Box>
) : null ) : null
@ -395,6 +409,13 @@ function AppHome({app}: Props): JSX.Element
section.tables.map((tableName) => section.tables.map((tableName) =>
{ {
let table = app.childMap.get(tableName); let table = app.childMap.get(tableName);
let count = "";
let percentage = "";
if(includeTableCountsOnHomeScreen)
{
count = !tableCounts.has(table.name) || tableCounts.get(table.name).isLoading ? "..." : (tableCountNumbers.get(table.name));
percentage = !tableCounts.has(table.name) || tableCounts.get(table.name).isLoading ? "" : (tableCountTexts.get(table.name));
}
return ( return (
<Grid key={table.name} item xs={12} md={12} lg={tileSizeLg}> <Grid key={table.name} item xs={12} md={12} lg={tileSizeLg}>
{hasTablePermission(tableName) ? {hasTablePermission(tableName) ?
@ -402,8 +423,8 @@ function AppHome({app}: Props): JSX.Element
<Box className="big-icon" mb={3}> <Box className="big-icon" mb={3}>
<MiniStatisticsCard <MiniStatisticsCard
title={{fontWeight: "bold", text: table.label}} title={{fontWeight: "bold", text: table.label}}
count={!tableCounts.has(table.name) || tableCounts.get(table.name).isLoading ? "..." : (tableCountNumbers.get(table.name))} count={count}
percentage={{color: "info", text: (!tableCounts.has(table.name) || tableCounts.get(table.name).isLoading ? "" : (tableCountTexts.get(table.name)))}} percentage={{color: "info", text: percentage}}
icon={{color: "info", component: <Icon>{table.iconName || app.iconName}</Icon>}} icon={{color: "info", component: <Icon>{table.iconName || app.iconName}</Icon>}}
/> />
</Box> </Box>
@ -411,8 +432,8 @@ function AppHome({app}: Props): JSX.Element
<Box mb={3} title="You do not have permission to access this table"> <Box mb={3} title="You do not have permission to access this table">
<MiniStatisticsCard <MiniStatisticsCard
title={{fontWeight: "bold", text: table.label}} title={{fontWeight: "bold", text: table.label}}
count={!tableCounts.has(table.name) || tableCounts.get(table.name).isLoading ? "..." : (tableCountNumbers.get(table.name))} count={count}
percentage={{color: "info", text: (!tableCounts.has(table.name) || tableCounts.get(table.name).isLoading ? "" : (tableCountTexts.get(table.name)))}} percentage={{color: "info", text: percentage}}
icon={{color: "info", component: <Icon>{table.iconName || app.iconName}</Icon>}} icon={{color: "info", component: <Icon>{table.iconName || app.iconName}</Icon>}}
isDisabled={true} isDisabled={true}
/> />

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
@ -226,8 +226,19 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
setShowFullHelpText(!showFullHelpText); setShowFullHelpText(!showFullHelpText);
}; };
const download = (url: string, fileName: string) => const download = (processValues: {[key: string]: string}) =>
{ {
let url;
let fileName = processValues.downloadFileName;
if(processValues.serverFilePath)
{
url = `/download/${encodeURIComponent(processValues.downloadFileName)}?filePath=${encodeURIComponent(processValues.serverFilePath)}`;
}
else if(processValues.storageTableName && processValues.storageReference)
{
url = `/download/${encodeURIComponent(processValues.downloadFileName)}?storageTableName=${encodeURIComponent(processValues.storageTableName)}&storageReference=${encodeURIComponent(processValues.storageReference)}`;
}
///////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////
// todo - this could be simplified, i think? // // todo - this could be simplified, i think? //
// it was originally built like this when we had to submit full access token to backend... // // it was originally built like this when we had to submit full access token to backend... //
@ -556,7 +567,7 @@ function ProcessRun({process, table, defaultProcessValues, isModal, isWidget, is
Download Download
</Box> </Box>
<Box display="flex" py={1} pr={2}> <Box display="flex" py={1} pr={2}>
<MDTypography variant="button" fontWeight="bold" onClick={() => download(`/download/${processValues.downloadFileName}?filePath=${processValues.serverFilePath}`, processValues.downloadFileName)} sx={{cursor: "pointer"}}> <MDTypography variant="button" fontWeight="bold" onClick={() => download(processValues)} sx={{cursor: "pointer"}}>
<Box display="flex" alignItems="center" gap={1} py={1} pr={2}> <Box display="flex" alignItems="center" gap={1} py={1} pr={2}>
<Icon fontSize="large">download_for_offline</Icon> <Icon fontSize="large">download_for_offline</Icon>
{processValues.downloadFileName} {processValues.downloadFileName}

View File

@ -44,11 +44,9 @@ import LinearProgress from "@mui/material/LinearProgress";
import MenuItem from "@mui/material/MenuItem"; import MenuItem from "@mui/material/MenuItem";
import Modal from "@mui/material/Modal"; import Modal from "@mui/material/Modal";
import Tooltip from "@mui/material/Tooltip"; import Tooltip from "@mui/material/Tooltip";
import {ColumnHeaderFilterIconButtonProps, DataGridPro, GridCallbackDetails, GridColDef, GridColumnHeaderParams, GridColumnMenuContainer, GridColumnMenuProps, GridColumnOrderChangeParams, GridColumnPinningMenuItems, GridColumnResizeParams, GridColumnsMenuItem, GridColumnVisibilityModel, GridDensity, GridEventListener, GridFilterMenuItem, GridPinnedColumns, gridPreferencePanelStateSelector, GridPreferencePanelsValue, GridRowId, GridRowParams, GridRowsProp, GridSelectionModel, GridSortItem, GridSortModel, GridState, GridToolbarColumnsButton, GridToolbarContainer, GridToolbarDensitySelector, GridToolbarExportContainer, HideGridColMenuItem, MuiEvent, SortGridMenuItems, useGridApiContext, useGridApiEventHandler, useGridApiRef, useGridSelector} from "@mui/x-data-grid-pro"; import {ColumnHeaderFilterIconButtonProps, DataGridPro, GridCallbackDetails, GridColDef, GridColumnHeaderParams, GridColumnMenuContainer, GridColumnMenuProps, GridColumnOrderChangeParams, GridColumnPinningMenuItems, GridColumnResizeParams, GridColumnVisibilityModel, GridDensity, GridEventListener, GridPinnedColumns, gridPreferencePanelStateSelector, GridPreferencePanelsValue, GridRowId, GridRowParams, GridRowsProp, GridSelectionModel, GridSortItem, GridSortModel, GridState, GridToolbarContainer, GridToolbarDensitySelector, HideGridColMenuItem, MuiEvent, SortGridMenuItems, useGridApiContext, useGridApiEventHandler, useGridApiRef, useGridSelector} from "@mui/x-data-grid-pro";
import {GridRowModel} from "@mui/x-data-grid/models/gridRows"; import {GridRowModel} from "@mui/x-data-grid/models/gridRows";
import FormData from "form-data"; import FormData from "form-data";
import React, {forwardRef, useContext, useEffect, useReducer, useRef, useState} from "react";
import {useLocation, useNavigate, useSearchParams} 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 {QCancelButton, QCreateNewButton} from "qqq/components/buttons/DefaultButtons"; import {QCancelButton, QCreateNewButton} from "qqq/components/buttons/DefaultButtons";
@ -78,6 +76,8 @@ import ProcessUtils from "qqq/utils/qqq/ProcessUtils";
import {SavedViewUtils} from "qqq/utils/qqq/SavedViewUtils"; import {SavedViewUtils} from "qqq/utils/qqq/SavedViewUtils";
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, {forwardRef, useContext, useEffect, useReducer, useRef, useState} from "react";
import {useLocation, useNavigate, useSearchParams} from "react-router-dom";
const CURRENT_SAVED_VIEW_ID_LOCAL_STORAGE_KEY_ROOT = "qqq.currentSavedViewId"; const CURRENT_SAVED_VIEW_ID_LOCAL_STORAGE_KEY_ROOT = "qqq.currentSavedViewId";
const DENSITY_LOCAL_STORAGE_KEY_ROOT = "qqq.density"; const DENSITY_LOCAL_STORAGE_KEY_ROOT = "qqq.density";
@ -112,7 +112,7 @@ const getLoadingScreen = () =>
return (<BaseLayout> return (<BaseLayout>
&nbsp; &nbsp;
</BaseLayout>); </BaseLayout>);
} };
/******************************************************************************* /*******************************************************************************
@ -246,7 +246,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// state of the page - e.g., have we loaded meta data? what about the initial view? or are we ready to render records. // // state of the page - e.g., have we loaded meta data? what about the initial view? or are we ready to render records. //
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const [pageState, setPageState] = useState("initial" as PageState) const [pageState, setPageState] = useState("initial" as PageState);
///////////////////////////////// /////////////////////////////////
// meta-data and derived state // // meta-data and derived state //
@ -260,8 +260,8 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////////////////////// ///////////////////////////////////////////
// state of the view of the query screen // // state of the view of the query screen //
/////////////////////////////////////////// ///////////////////////////////////////////
const [view, setView] = useState(defaultView) const [view, setView] = useState(defaultView);
const [viewAsJson, setViewAsJson] = useState(JSON.stringify(defaultView)) const [viewAsJson, setViewAsJson] = useState(JSON.stringify(defaultView));
const [queryFilter, setQueryFilter] = useState(defaultView.queryFilter); const [queryFilter, setQueryFilter] = useState(defaultView.queryFilter);
const [queryColumns, setQueryColumns] = useState(defaultView.queryColumns); const [queryColumns, setQueryColumns] = useState(defaultView.queryColumns);
const [lastFetchedQFilterJSON, setLastFetchedQFilterJSON] = useState(""); const [lastFetchedQFilterJSON, setLastFetchedQFilterJSON] = useState("");
@ -309,7 +309,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////////////////////////// /////////////////////////////////////////
const [columnStatsFieldName, setColumnStatsFieldName] = useState(null as string); const [columnStatsFieldName, setColumnStatsFieldName] = useState(null as string);
const [columnStatsField, setColumnStatsField] = useState(null as QFieldMetaData); const [columnStatsField, setColumnStatsField] = useState(null as QFieldMetaData);
const [columnStatsFieldTableName, setColumnStatsFieldTableName] = useState(null as string) const [columnStatsFieldTableName, setColumnStatsFieldTableName] = useState(null as string);
const [filterForColumnStats, setFilterForColumnStats] = useState(null as QQueryFilter); const [filterForColumnStats, setFilterForColumnStats] = useState(null as QQueryFilter);
/////////////////////////////////////////////////// ///////////////////////////////////////////////////
@ -353,14 +353,14 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
// add a LoadingState object, in case the initial loads (of meta data and view) are slow // // add a LoadingState object, in case the initial loads (of meta data and view) are slow //
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
const [pageLoadingState, _] = useState(new LoadingState(forceUpdate)) const [pageLoadingState, _] = useState(new LoadingState(forceUpdate));
if (isFirstRenderAfterChangingTables) if (isFirstRenderAfterChangingTables)
{ {
setIsFirstRenderAfterChangingTables(false); setIsFirstRenderAfterChangingTables(false);
console.log("This is the first render after changing tables - so - setting state based on 'defaults' from localStorage"); console.log("This is the first render after changing tables - so - setting state based on 'defaults' from localStorage");
setView(defaultView) setView(defaultView);
} }
/******************************************************************************* /*******************************************************************************
@ -415,7 +415,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
} }
} }
return (false); return (false);
} };
/******************************************************************************* /*******************************************************************************
@ -423,7 +423,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
*******************************************************************************/ *******************************************************************************/
const prepQueryFilterForBackend = (sourceFilter: QQueryFilter) => const prepQueryFilterForBackend = (sourceFilter: QQueryFilter) =>
{ {
const filterForBackend = new QQueryFilter([], sourceFilter.orderBys, sourceFilter.booleanOperator); const filterForBackend = new QQueryFilter([], sourceFilter.orderBys, sourceFilter.subFilters, sourceFilter.booleanOperator);
for (let i = 0; i < sourceFilter?.criteria?.length; i++) for (let i = 0; i < sourceFilter?.criteria?.length; i++)
{ {
const criteria = sourceFilter.criteria[i]; const criteria = sourceFilter.criteria[i];
@ -442,16 +442,26 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// else push a clone of the criteria - since it may get manipulated below (convertFilterPossibleValuesToIds) // // else push a clone of the criteria - since it may get manipulated below (convertFilterPossibleValuesToIds) //
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
const [field] = FilterUtils.getField(tableMetaData, criteria.fieldName) const [field] = FilterUtils.getField(tableMetaData, criteria.fieldName);
filterForBackend.criteria.push(new QFilterCriteria(criteria.fieldName, criteria.operator, FilterUtils.cleanseCriteriaValueForQQQ(criteria.values, field))); filterForBackend.criteria.push(new QFilterCriteria(criteria.fieldName, criteria.operator, FilterUtils.cleanseCriteriaValueForQQQ(criteria.values, field)));
} }
} }
} }
/////////////////////////////////////////
// recursively prep subfilters as well //
/////////////////////////////////////////
let subFilters = [] as QQueryFilter[];
for (let j = 0; j < sourceFilter?.subFilters?.length; j++)
{
subFilters.push(prepQueryFilterForBackend(sourceFilter.subFilters[j]));
}
filterForBackend.subFilters = subFilters;
filterForBackend.skip = pageNumber * rowsPerPage; filterForBackend.skip = pageNumber * rowsPerPage;
filterForBackend.limit = rowsPerPage; filterForBackend.limit = rowsPerPage;
return filterForBackend; return filterForBackend;
} };
/******************************************************************************* /*******************************************************************************
@ -475,7 +485,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////////////////////// ///////////////////////////////////////////
// build the export menu, for the header // // build the export menu, for the header //
/////////////////////////////////////////// ///////////////////////////////////////////
let exportMenu = <></> let exportMenu = <></>;
try try
{ {
const exportMenuItemRestProps = const exportMenuItemRestProps =
@ -485,7 +495,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
columnsModel: columnsModel, columnsModel: columnsModel,
columnVisibilityModel: columnVisibilityModel, columnVisibilityModel: columnVisibilityModel,
queryFilter: prepQueryFilterForBackend(queryFilter) queryFilter: prepQueryFilterForBackend(queryFilter)
} };
exportMenu = (<> exportMenu = (<>
<IconButton sx={{p: 0, fontSize: "0.75rem", mb: 1, color: colors.secondary.main, fontVariationSettings: "'wght' 100"}} onClick={openExportMenu}><Icon fontSize="small">save_alt</Icon></IconButton> <IconButton sx={{p: 0, fontSize: "0.75rem", mb: 1, color: colors.secondary.main, fontVariationSettings: "'wght' 100"}} onClick={openExportMenu}><Icon fontSize="small">save_alt</Icon></IconButton>
@ -552,7 +562,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
<ul style={{marginLeft: "1rem"}}> <ul style={{marginLeft: "1rem"}}>
{joinLabels.map((name) => <li key={name}>{name}</li>)} {joinLabels.map((name) => <li key={name}>{name}</li>)}
</ul> </ul>
</div> </div>;
return ( return (
<div> <div>
@ -586,7 +596,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
</Tooltip> </Tooltip>
</Typography> </Typography>
); );
} };
/////////////////////// ///////////////////////
// Keyboard handling // // Keyboard handling //
@ -602,12 +612,12 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
{ {
if (!e.metaKey && e.key === "n" && table.capabilities.has(Capability.TABLE_INSERT) && table.insertPermission) if (!e.metaKey && e.key === "n" && table.capabilities.has(Capability.TABLE_INSERT) && table.insertPermission)
{ {
e.preventDefault() e.preventDefault();
navigate(`${metaData?.getTablePathByName(tableName)}/create`); navigate(`${metaData?.getTablePathByName(tableName)}/create`);
} }
else if (!e.metaKey && e.key === "r") else if (!e.metaKey && e.key === "r")
{ {
e.preventDefault() e.preventDefault();
updateTable("'r' keyboard event"); updateTable("'r' keyboard event");
} }
/* /*
@ -620,23 +630,23 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
*/ */
else if (!e.metaKey && e.key === "f") else if (!e.metaKey && e.key === "f")
{ {
e.preventDefault() e.preventDefault();
// @ts-ignore // @ts-ignore
if (basicAndAdvancedQueryControlsRef?.current?.getCurrentMode() == "advanced") if (basicAndAdvancedQueryControlsRef?.current?.getCurrentMode() == "advanced")
{ {
gridApiRef.current.showFilterPanel() gridApiRef.current.showFilterPanel();
}
} }
} }
} }
};
document.addEventListener("keydown", down) document.addEventListener("keydown", down);
return () => return () =>
{ {
document.removeEventListener("keydown", down) document.removeEventListener("keydown", down);
} };
}, [dotMenuOpen, keyboardHelpOpen, metaData, activeModalProcess]) }, [dotMenuOpen, keyboardHelpOpen, metaData, activeModalProcess]);
/******************************************************************************* /*******************************************************************************
@ -645,7 +655,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const urlLooksLikeProcess = (): boolean => const urlLooksLikeProcess = (): boolean =>
{ {
return (pathParts[pathParts.length - 2] === tableName); return (pathParts[pathParts.length - 2] === tableName);
} };
////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////
// monitor location changes - if our url looks like a savedView, then load that view, kinda // // monitor location changes - if our url looks like a savedView, then load that view, kinda //
@ -701,9 +711,28 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const doSetView = (view: RecordQueryView): void => const doSetView = (view: RecordQueryView): void =>
{ {
setView(view); setView(view);
setViewAsJson(JSON.stringify(view)); const viewAsJSON = JSON.stringify(view);
localStorage.setItem(viewLocalStorageKey, JSON.stringify(view)); setViewAsJson(viewAsJSON);
try
{
////////////////////////////////////////////////////////////////////////////////////
// in case there's an incomplete criteria in the view (e.g., w/o a fieldName), //
// don't store that in local storage - we don't want that, it's messy, and it //
// has caused fails in the past. So, clone the view, and strip away such things. //
////////////////////////////////////////////////////////////////////////////////////
const viewForLocalStorage: RecordQueryView = JSON.parse(viewAsJSON);
if (viewForLocalStorage?.queryFilter?.criteria?.length > 0)
{
FilterUtils.stripAwayIncompleteCriteria(viewForLocalStorage.queryFilter)
} }
localStorage.setItem(viewLocalStorageKey, JSON.stringify(viewForLocalStorage));
}
catch(e)
{
console.log("Error storing view in local storage: " + e)
}
};
/******************************************************************************* /*******************************************************************************
@ -712,10 +741,10 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const handleColumnVisibilityChange = (columnVisibilityModel: GridColumnVisibilityModel) => const handleColumnVisibilityChange = (columnVisibilityModel: GridColumnVisibilityModel) =>
{ {
setColumnVisibilityModel(columnVisibilityModel); setColumnVisibilityModel(columnVisibilityModel);
queryColumns.updateVisibility(columnVisibilityModel) queryColumns.updateVisibility(columnVisibilityModel);
view.queryColumns = queryColumns; view.queryColumns = queryColumns;
doSetView(view) doSetView(view);
forceUpdate(); forceUpdate();
}; };
@ -735,7 +764,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
fieldName = `${table.name}.${field.name}`; fieldName = `${table.name}.${field.name}`;
} }
view.queryColumns.setIsVisible(fieldName, newValue) view.queryColumns.setIsVisible(fieldName, newValue);
///////////////////// /////////////////////
// update the grid // // update the grid //
@ -745,13 +774,13 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////////////////////////////////// /////////////////////////////////////////////////
// update the view (e.g., write local storage) // // update the view (e.g., write local storage) //
///////////////////////////////////////////////// /////////////////////////////////////////////////
doSetView(view) doSetView(view);
/////////////////// ///////////////////
// ole' faithful // // ole' faithful //
/////////////////// ///////////////////
forceUpdate(); forceUpdate();
} };
/******************************************************************************* /*******************************************************************************
@ -790,7 +819,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setPinnedColumns(queryColumns.toGridPinnedColumns()); setPinnedColumns(queryColumns.toGridPinnedColumns());
setColumnVisibilityModel(queryColumns.toColumnVisibilityModel()); setColumnVisibilityModel(queryColumns.toColumnVisibilityModel());
setColumnsModel(columns); setColumnsModel(columns);
} };
/******************************************************************************* /*******************************************************************************
@ -799,7 +828,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const promptForTableVariantSelection = () => const promptForTableVariantSelection = () =>
{ {
setTableVariantPromptOpen(true); setTableVariantPromptOpen(true);
} };
/******************************************************************************* /*******************************************************************************
@ -826,7 +855,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
} }
return (rs); return (rs);
} };
/******************************************************************************* /*******************************************************************************
@ -1055,7 +1084,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setRowsPerPage(size); setRowsPerPage(size);
view.rowsPerPage = size; view.rowsPerPage = size;
doSetView(view) doSetView(view);
}; };
/******************************************************************************* /*******************************************************************************
@ -1064,11 +1093,11 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const handlePinnedColumnsChange = (pinnedColumns: GridPinnedColumns) => const handlePinnedColumnsChange = (pinnedColumns: GridPinnedColumns) =>
{ {
setPinnedColumns(pinnedColumns); setPinnedColumns(pinnedColumns);
queryColumns.setPinnedLeftColumns(pinnedColumns.left) queryColumns.setPinnedLeftColumns(pinnedColumns.left);
queryColumns.setPinnedRightColumns(pinnedColumns.right) queryColumns.setPinnedRightColumns(pinnedColumns.right);
view.queryColumns = queryColumns; view.queryColumns = queryColumns;
doSetView(view) doSetView(view);
}; };
/******************************************************************************* /*******************************************************************************
@ -1121,7 +1150,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
let selectedPrimaryKeys = new Set<string>(); let selectedPrimaryKeys = new Set<string>();
selectionModel.forEach((value: GridRowId, index: number) => selectionModel.forEach((value: GridRowId, index: number) =>
{ {
checkboxesChecked++ checkboxesChecked++;
const valueToPush = latestQueryResults[value as number].values.get(tableMetaData.primaryKeyField); const valueToPush = latestQueryResults[value as number].values.get(tableMetaData.primaryKeyField);
selectedPrimaryKeys.add(valueToPush as string); selectedPrimaryKeys.add(valueToPush as string);
}); });
@ -1150,7 +1179,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
queryColumns.updateColumnOrder(columnOrdering); queryColumns.updateColumnOrder(columnOrdering);
view.queryColumns = queryColumns; view.queryColumns = queryColumns;
doSetView(view) doSetView(view);
}; };
@ -1162,7 +1191,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
queryColumns.updateColumnWidth(params.colDef.field, params.width); queryColumns.updateColumnWidth(params.colDef.field, params.width);
view.queryColumns = queryColumns; view.queryColumns = queryColumns;
doSetView(view) doSetView(view);
}; };
@ -1185,7 +1214,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
{ {
const fieldName = gridSort[i].field; const fieldName = gridSort[i].field;
const isAscending = gridSort[i].sort == "asc"; const isAscending = gridSort[i].sort == "asc";
queryFilter.orderBys.push(new QFilterOrderBy(fieldName, isAscending)) queryFilter.orderBys.push(new QFilterOrderBy(fieldName, isAscending));
} }
////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////
@ -1209,7 +1238,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const handleColumnHeaderClick = (params: GridColumnHeaderParams, event: MuiEvent, details: GridCallbackDetails): void => const handleColumnHeaderClick = (params: GridColumnHeaderParams, event: MuiEvent, details: GridCallbackDetails): void =>
{ {
event.defaultMuiPrevented = true; event.defaultMuiPrevented = true;
} };
/******************************************************************************* /*******************************************************************************
@ -1227,7 +1256,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setRowsPerPage(view.rowsPerPage ?? defaultRowsPerPage); setRowsPerPage(view.rowsPerPage ?? defaultRowsPerPage);
setMode(view.mode ?? defaultMode); setMode(view.mode ?? defaultMode);
setQuickFilterFieldNames(view.quickFilterFieldNames ?? []) // todo not i think ?? getDefaultQuickFilterFieldNames(tableMetaData)); setQuickFilterFieldNames(view.quickFilterFieldNames ?? []); // todo not i think ?? getDefaultQuickFilterFieldNames(tableMetaData));
////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////
// do this last - in case anything in the view got modified in any of those other doSet methods // // do this last - in case anything in the view got modified in any of those other doSet methods //
@ -1240,7 +1269,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////
// @ts-ignore // @ts-ignore
setTimeout(() => basicAndAdvancedQueryControlsRef?.current?.ensureAllFilterCriteriaAreActiveQuickFilters(view.queryFilter, "activatedView")); setTimeout(() => basicAndAdvancedQueryControlsRef?.current?.ensureAllFilterCriteriaAreActiveQuickFilters(view.queryFilter, "activatedView"));
} };
/******************************************************************************* /*******************************************************************************
@ -1287,14 +1316,14 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
if (!isFromActivateView) if (!isFromActivateView)
{ {
view.queryFilter = queryFilter; view.queryFilter = queryFilter;
doSetView(view) doSetView(view);
} }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// this force-update causes a re-render that'll see the changed filter hash/json string, and make an updateTable run (if appropriate) // // this force-update causes a re-render that'll see the changed filter hash/json string, and make an updateTable run (if appropriate) //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
forceUpdate(); forceUpdate();
} };
/******************************************************************************* /*******************************************************************************
** Wrapper around setQueryColumns that also sets column models for the grid, puts ** Wrapper around setQueryColumns that also sets column models for the grid, puts
@ -1327,9 +1356,9 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
if (!isFromActivateView) if (!isFromActivateView)
{ {
view.queryColumns = queryColumns; view.queryColumns = queryColumns;
doSetView(view) doSetView(view);
}
} }
};
/******************************************************************************* /*******************************************************************************
@ -1341,7 +1370,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setQuickFilterFieldNames([...(names ?? [])]); setQuickFilterFieldNames([...(names ?? [])]);
view.quickFilterFieldNames = names; view.quickFilterFieldNames = names;
doSetView(view) doSetView(view);
}; };
@ -1354,7 +1383,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
view.mode = newValue; view.mode = newValue;
doSetView(view); doSetView(view);
} };
/******************************************************************************* /*******************************************************************************
@ -1372,7 +1401,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
} }
return (selectedIds.length); return (selectedIds.length);
} };
/******************************************************************************* /*******************************************************************************
@ -1403,7 +1432,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
} }
return ""; return "";
} };
/******************************************************************************* /*******************************************************************************
@ -1568,7 +1597,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setCurrentSavedView(savedViewRecord); setCurrentSavedView(savedViewRecord);
const viewJson = savedViewRecord.values.get("viewJson") const viewJson = savedViewRecord.values.get("viewJson");
const newView = RecordQueryView.buildFromJSON(viewJson); const newView = RecordQueryView.buildFromJSON(viewJson);
activateView(newView); activateView(newView);
@ -1577,7 +1606,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
// todo can/should/does this move into the view's "identity"? // // todo can/should/does this move into the view's "identity"? //
//////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////
localStorage.setItem(currentSavedViewLocalStorageKey, `${savedViewRecord.values.get("id")}`); localStorage.setItem(currentSavedViewLocalStorageKey, `${savedViewRecord.values.get("id")}`);
} };
/******************************************************************************* /*******************************************************************************
@ -1587,7 +1616,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
{ {
setCurrentSavedView(null); setCurrentSavedView(null);
localStorage.removeItem(currentSavedViewLocalStorageKey); localStorage.removeItem(currentSavedViewLocalStorageKey);
} };
/******************************************************************************* /*******************************************************************************
@ -1603,7 +1632,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
newDefaultView.quickFilterFieldNames = []; newDefaultView.quickFilterFieldNames = [];
newDefaultView.mode = defaultMode; newDefaultView.mode = defaultMode;
return newDefaultView; return newDefaultView;
} };
/******************************************************************************* /*******************************************************************************
** event handler for SavedViews component, to handle user selecting a view ** event handler for SavedViews component, to handle user selecting a view
@ -1638,9 +1667,9 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////////////////////////// ///////////////////////////////////////////////
// activate a new default view for the table // // activate a new default view for the table //
/////////////////////////////////////////////// ///////////////////////////////////////////////
activateView(buildTableDefaultView(tableMetaData)) activateView(buildTableDefaultView(tableMetaData));
}
} }
};
/******************************************************************************* /*******************************************************************************
** utility function to fetch a saved view from the backend. ** utility function to fetch a saved view from the backend.
@ -1668,7 +1697,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
// such as, making values be what they'd be in the UI (not necessarily // // such as, making values be what they'd be in the UI (not necessarily //
// what they're like in the backend); similarly, set anything that's unset. // // what they're like in the backend); similarly, set anything that's unset. //
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
const viewJson = qRecord.values.get("viewJson") const viewJson = qRecord.values.get("viewJson");
const newView = RecordQueryView.buildFromJSON(viewJson); const newView = RecordQueryView.buildFromJSON(viewJson);
setWarningAlert(null); setWarningAlert(null);
@ -1689,11 +1718,11 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
newView.queryColumns = QQueryColumns.buildDefaultForTable(tableMetaData); newView.queryColumns = QQueryColumns.buildDefaultForTable(tableMetaData);
} }
qRecord.values.set("viewJson", JSON.stringify(newView)) qRecord.values.set("viewJson", JSON.stringify(newView));
} }
return (qRecord); return (qRecord);
} };
/******************************************************************************* /*******************************************************************************
@ -1798,7 +1827,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const plural = removedFieldCount > 1; const plural = removedFieldCount > 1;
setWarningAlert(`${removedFieldCount} field${plural ? "s" : ""} that ${plural ? "were" : "was"} part of this view ${plural ? "are" : "is"} no longer in this table, and ${plural ? "were" : "was"} removed from this view (${[...removedFieldNames.values()].join(", ")}).`); setWarningAlert(`${removedFieldCount} field${plural ? "s" : ""} that ${plural ? "were" : "was"} part of this view ${plural ? "are" : "is"} no longer in this table, and ${plural ? "were" : "was"} removed from this view (${[...removedFieldNames.values()].join(", ")}).`);
} }
} };
/******************************************************************************* /*******************************************************************************
@ -1834,8 +1863,8 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////// ///////////////////////////
// open the filter panel // // open the filter panel //
/////////////////////////// ///////////////////////////
gridApiRef.current.showPreferences(GridPreferencePanelsValue.filters) gridApiRef.current.showPreferences(GridPreferencePanelsValue.filters);
} };
/******************************************************************************* /*******************************************************************************
@ -2006,7 +2035,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
} }
else else
{ {
gridApiRef.current.showPreferences(GridPreferencePanelsValue.filters) gridApiRef.current.showPreferences(GridPreferencePanelsValue.filters);
} }
event.stopPropagation(); event.stopPropagation();
@ -2116,7 +2145,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
// this page // // this page //
/////////////// ///////////////
programmaticallySelectSomeOrAllRows(); programmaticallySelectSomeOrAllRows();
setSelectFullFilterState("checked") setSelectFullFilterState("checked");
} }
else if (selectedIndex == 1) else if (selectedIndex == 1)
{ {
@ -2124,7 +2153,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
// full query result // // full query result //
/////////////////////// ///////////////////////
programmaticallySelectSomeOrAllRows(); programmaticallySelectSomeOrAllRows();
setSelectFullFilterState("filter") setSelectFullFilterState("filter");
} }
else if (selectedIndex == 2) else if (selectedIndex == 2)
{ {
@ -2138,7 +2167,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////// /////////////////////
// clear selection // // clear selection //
///////////////////// /////////////////////
setSelectFullFilterState("n/a") setSelectFullFilterState("n/a");
setRowSelectionModel([]); setRowSelectionModel([]);
setSelectedIds([]); setSelectedIds([]);
} }
@ -2166,7 +2195,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
{ {
programmaticallySelectSomeOrAllRows(value); programmaticallySelectSomeOrAllRows(value);
setSelectionSubsetSize(value); setSelectionSubsetSize(value);
setSelectFullFilterState("filterSubset") setSelectFullFilterState("filterSubset");
} }
else else
{ {
@ -2453,7 +2482,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
// so the useEffect that monitors location will see the change, and will set viewIdInLocation // // so the useEffect that monitors location will see the change, and will set viewIdInLocation //
// so upon a re-render we'll hit this block again. // // so upon a re-render we'll hit this block again. //
///////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////
setPageState("loadedMetaData") setPageState("loadedMetaData");
return; return;
} }
@ -2487,7 +2516,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setTimeout(() => setTimeout(() =>
{ {
// @ts-ignore // @ts-ignore
basicAndAdvancedQueryControlsRef?.current?.ensureAllFilterCriteriaAreActiveQuickFilters(view.queryFilter, "defaultFilterLoaded") basicAndAdvancedQueryControlsRef?.current?.ensureAllFilterCriteriaAreActiveQuickFilters(view.queryFilter, "defaultFilterLoaded");
}); });
console.log("finished preparing grid, going to page state ready"); console.log("finished preparing grid, going to page state ready");
@ -2511,11 +2540,11 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
{ {
if (pageState == "ready") if (pageState == "ready")
{ {
pageLoadingState.setNotLoading() pageLoadingState.setNotLoading();
if (!tableVariantPromptOpen) if (!tableVariantPromptOpen)
{ {
updateTable("pageState is now ready") updateTable("pageState is now ready");
} }
} }
}, [pageState, tableVariantPromptOpen]); }, [pageState, tableVariantPromptOpen]);
@ -2563,7 +2592,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
let gotoVariantSubHeader = <></>; let gotoVariantSubHeader = <></>;
if (tableMetaData?.usesVariants) if (tableMetaData?.usesVariants)
{ {
gotoVariantSubHeader = <Box mb={2}>{getTableVariantHeader(tableVariant)}</Box> gotoVariantSubHeader = <Box mb={2}>{getTableVariantHeader(tableVariant)}</Box>;
} }
return ( return (
@ -2615,7 +2644,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
//////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////
const baseView = currentSavedView ? JSON.parse(currentSavedView.values.get("viewJson")) as RecordQueryView : tableDefaultView; const baseView = currentSavedView ? JSON.parse(currentSavedView.values.get("viewJson")) as RecordQueryView : tableDefaultView;
const viewDiffs: string[] = []; const viewDiffs: string[] = [];
SavedViewUtils.diffColumns(tableMetaData, baseView, view, viewDiffs) SavedViewUtils.diffColumns(tableMetaData, baseView, view, viewDiffs);
if (viewDiffs.length == 0 && currentSavedView) if (viewDiffs.length == 0 && currentSavedView)
{ {
@ -2653,7 +2682,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
color: buttonColor, color: buttonColor,
backgroundColor: buttonBackground, backgroundColor: buttonBackground,
} }
} };
return (<Box order="2"> return (<Box order="2">
<FieldListMenu <FieldListMenu
@ -2668,7 +2697,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
handleToggleField={handleChangeOneColumnVisibility} handleToggleField={handleChangeOneColumnVisibility}
/> />
</Box>); </Box>);
} };
////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////
// these numbers help set the height of the grid (so page won't scroll) based on spcae above & below it // // these numbers help set the height of the grid (so page won't scroll) based on spcae above & below it //

View File

@ -46,8 +46,6 @@ import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem"; import MenuItem from "@mui/material/MenuItem";
import Modal from "@mui/material/Modal"; import Modal from "@mui/material/Modal";
import Tooltip from "@mui/material/Tooltip/Tooltip"; import Tooltip from "@mui/material/Tooltip/Tooltip";
import React, {useContext, useEffect, useState} from "react";
import {useLocation, useNavigate, useParams} 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 AuditBody from "qqq/components/audits/AuditBody"; import AuditBody from "qqq/components/audits/AuditBody";
@ -65,6 +63,8 @@ import Client from "qqq/utils/qqq/Client";
import ProcessUtils from "qqq/utils/qqq/ProcessUtils"; import ProcessUtils from "qqq/utils/qqq/ProcessUtils";
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";
const qController = Client.getInstance(); const qController = Client.getInstance();
@ -166,50 +166,50 @@ function RecordView({table, launchProcess}: Props): JSX.Element
{ {
if (!e.metaKey && e.key === "n" && table.capabilities.has(Capability.TABLE_INSERT) && table.insertPermission) if (!e.metaKey && e.key === "n" && table.capabilities.has(Capability.TABLE_INSERT) && table.insertPermission)
{ {
e.preventDefault() e.preventDefault();
gotoCreate(); gotoCreate();
} }
else if (!e.metaKey && e.key === "e" && table.capabilities.has(Capability.TABLE_UPDATE) && table.editPermission) else if (!e.metaKey && e.key === "e" && table.capabilities.has(Capability.TABLE_UPDATE) && table.editPermission)
{ {
e.preventDefault() e.preventDefault();
navigate("edit"); navigate("edit");
} }
else if (!e.metaKey && e.key === "c" && table.capabilities.has(Capability.TABLE_INSERT) && table.insertPermission) else if (!e.metaKey && e.key === "c" && table.capabilities.has(Capability.TABLE_INSERT) && table.insertPermission)
{ {
e.preventDefault() e.preventDefault();
navigate("copy"); navigate("copy");
} }
else if (!e.metaKey && e.key === "d" && table.capabilities.has(Capability.TABLE_DELETE) && table.deletePermission) else if (!e.metaKey && e.key === "d" && table.capabilities.has(Capability.TABLE_DELETE) && table.deletePermission)
{ {
e.preventDefault() e.preventDefault();
handleClickDeleteButton(); handleClickDeleteButton();
} }
else if (!e.metaKey && e.key === "a" && metaData && metaData.tables.has("audit")) else if (!e.metaKey && e.key === "a" && metaData && metaData.tables.has("audit"))
{ {
e.preventDefault() e.preventDefault();
navigate("#audit"); navigate("#audit");
} }
} }
} };
document.addEventListener("keydown", down) document.addEventListener("keydown", down);
return () => return () =>
{ {
document.removeEventListener("keydown", down) document.removeEventListener("keydown", down);
} };
}, [dotMenuOpen, keyboardHelpOpen, showEditChildForm, showAudit, metaData, location]) }, [dotMenuOpen, keyboardHelpOpen, showEditChildForm, showAudit, metaData, location]);
const gotoCreate = () => const gotoCreate = () =>
{ {
const path = `${pathParts.slice(0, -1).join("/")}/create`; const path = `${pathParts.slice(0, -1).join("/")}/create`;
navigate(path); navigate(path);
} };
const gotoEdit = () => const gotoEdit = () =>
{ {
const path = `${pathParts.slice(0, -1).join("/")}/${record.values.get(table.primaryKeyField)}/edit`; const path = `${pathParts.slice(0, -1).join("/")}/${record.values.get(table.primaryKeyField)}/edit`;
navigate(path); navigate(path);
} };
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
// monitor location changes - if we've clicked a link from viewing one record to viewing another, // // monitor location changes - if we've clicked a link from viewing one record to viewing another, //
@ -349,7 +349,7 @@ function RecordView({table, launchProcess}: Props): JSX.Element
{ {
visibleJoinTables.add(tableForField.name); visibleJoinTables.add(tableForField.name);
} }
}) });
} }
return (visibleJoinTables); return (visibleJoinTables);
@ -361,15 +361,15 @@ function RecordView({table, launchProcess}: Props): JSX.Element
*******************************************************************************/ *******************************************************************************/
const getSectionHelp = (section: QTableSection) => const getSectionHelp = (section: QTableSection) =>
{ {
const helpRoles = ["VIEW_SCREEN", "READ_SCREENS", "ALL_SCREENS"] const helpRoles = ["VIEW_SCREEN", "READ_SCREENS", "ALL_SCREENS"];
const formattedHelpContent = <HelpContent helpContents={section.helpContents} roles={helpRoles} helpContentKey={`table:${tableName};section:${section.name}`} />; const formattedHelpContent = <HelpContent helpContents={section.helpContents} roles={helpRoles} helpContentKey={`table:${tableName};section:${section.name}`} />;
return formattedHelpContent && ( return formattedHelpContent && (
<Box px={"1.5rem"} fontSize={"0.875rem"} color={colors.blueGray.main}> <Box px={"1.5rem"} fontSize={"0.875rem"} color={colors.blueGray.main}>
{formattedHelpContent} {formattedHelpContent}
</Box> </Box>
) );
} };
if (!asyncLoadInited) if (!asyncLoadInited)
@ -401,11 +401,11 @@ function RecordView({table, launchProcess}: Props): JSX.Element
////////////////////////////////////////////////////// //////////////////////////////////////////////////////
// load processes that the routing needs to respect // // load processes that the routing needs to respect //
////////////////////////////////////////////////////// //////////////////////////////////////////////////////
const allTableProcesses = ProcessUtils.getProcessesForTable(metaData, tableName, true) // these include hidden ones (e.g., to find the bulks) const allTableProcesses = ProcessUtils.getProcessesForTable(metaData, tableName, true); // these include hidden ones (e.g., to find the bulks)
const runRecordScriptProcess = metaData?.processes.get("runRecordScript"); const runRecordScriptProcess = metaData?.processes.get("runRecordScript");
if (runRecordScriptProcess) if (runRecordScriptProcess)
{ {
allTableProcesses.unshift(runRecordScriptProcess) allTableProcesses.unshift(runRecordScriptProcess);
} }
setAllTableProcesses(allTableProcesses); setAllTableProcesses(allTableProcesses);
@ -522,13 +522,15 @@ function RecordView({table, launchProcess}: Props): JSX.Element
section.fieldNames.map((fieldName: string) => section.fieldNames.map((fieldName: string) =>
{ {
let [field, tableForField] = TableUtils.getFieldAndTable(tableMetaData, fieldName); let [field, tableForField] = TableUtils.getFieldAndTable(tableMetaData, fieldName);
if (field != null)
{
let label = field.label; let label = field.label;
const helpRoles = ["VIEW_SCREEN", "READ_SCREENS", "ALL_SCREENS"] const helpRoles = ["VIEW_SCREEN", "READ_SCREENS", "ALL_SCREENS"];
const showHelp = helpHelpActive || hasHelpContent(field.helpContents, helpRoles); const showHelp = helpHelpActive || hasHelpContent(field.helpContents, helpRoles);
const formattedHelpContent = <HelpContent helpContents={field.helpContents} roles={helpRoles} heading={label} helpContentKey={`table:${tableName};field:${fieldName}`} />; const formattedHelpContent = <HelpContent helpContents={field.helpContents} roles={helpRoles} heading={label} helpContentKey={`table:${tableName};field:${fieldName}`} />;
const labelElement = <Typography variant="button" textTransform="none" fontWeight="bold" pr={1} color="rgb(52, 71, 103)" sx={{cursor: "default"}}>{label}:</Typography> const labelElement = <Typography variant="button" textTransform="none" fontWeight="bold" pr={1} color="rgb(52, 71, 103)" sx={{cursor: "default"}}>{label}:</Typography>;
return ( return (
<Box key={fieldName} flexDirection="row" pr={2}> <Box key={fieldName} flexDirection="row" pr={2}>
@ -542,7 +544,8 @@ function RecordView({table, launchProcess}: Props): JSX.Element
</Typography> </Typography>
</> </>
</Box> </Box>
) );
}
}) })
} }
</Box> </Box>
@ -603,9 +606,9 @@ function RecordView({table, launchProcess}: Props): JSX.Element
setWarningMessage(state["warning"]); setWarningMessage(state["warning"]);
} }
delete state["createSuccess"] delete state["createSuccess"];
delete state["updateSuccess"] delete state["updateSuccess"];
delete state["warning"] delete state["warning"];
window.history.replaceState(state, ""); window.history.replaceState(state, "");
} }
@ -864,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

@ -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,9 +159,12 @@ 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 //
///////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////
if(!allowEmptyId)
{
row["id"] = "--"; row["id"] = "--";
} }
} }
}
rows.push(row); rows.push(row);
}); });
@ -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

@ -114,8 +114,11 @@ class FilterUtils
// e.g., ...values=[1]... // // e.g., ...values=[1]... //
// but we need them to be possibleValue objects (w/ id & label) so the label // // but we need them to be possibleValue objects (w/ id & label) so the label //
// can be shown in the filter dropdown. So, make backend call to look them up. // // can be shown in the filter dropdown. So, make backend call to look them up. //
// also, there are cases where we can get a null or "" as the only value in the //
// values array - avoid sending that to the backend, as it comes back w/ all //
// possible values, and a general "bad time" //
////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////
if (values && values.length > 0) if (values && values.length > 0 && values[0] !== null && values[0] !== undefined && values[0] !== "")
{ {
values = await qController.possibleValues(fieldTable.name, null, field.name, "", values); values = await qController.possibleValues(fieldTable.name, null, field.name, "", values);
} }
@ -156,6 +159,14 @@ class FilterUtils
criteria.values = values; criteria.values = values;
} }
////////////////////////////////////////////////
// recursively clean values in any subfilters //
////////////////////////////////////////////////
for (let j = 0; j < queryFilter?.subFilters?.length; j++)
{
await FilterUtils.cleanupValuesInFilerFromQueryString(qController, tableMetaData, queryFilter.subFilters[j]);
}
} }
@ -260,18 +271,24 @@ class FilterUtils
/******************************************************************************* /*******************************************************************************
** **
*******************************************************************************/ *******************************************************************************/
public static canFilterWorkAsBasic(tableMetaData: QTableMetaData, filter: QQueryFilter): { canFilterWorkAsBasic: boolean; reasonsWhyItCannot?: string[] } public static canFilterWorkAsBasic(tableMetaData: QTableMetaData, filter: QQueryFilter): { canFilterWorkAsBasic: boolean; canFilterWorkAsAdvanced: boolean, reasonsWhyItCannot?: string[] }
{ {
const reasonsWhyItCannot: string[] = []; const reasonsWhyItCannot: string[] = [];
if (filter == null) if (filter == null)
{ {
return ({canFilterWorkAsBasic: true}); return ({canFilterWorkAsBasic: true, canFilterWorkAsAdvanced: true});
} }
if (filter.booleanOperator == "OR") if (filter.booleanOperator == "OR")
{ {
reasonsWhyItCannot.push("Filter uses the 'OR' operator.") reasonsWhyItCannot.push("Filter uses the 'OR' operator.");
}
if (filter.subFilters?.length > 0)
{
reasonsWhyItCannot.push("Filter contains sub-filters.");
return ({canFilterWorkAsBasic: false, canFilterWorkAsAdvanced: false, reasonsWhyItCannot: reasonsWhyItCannot});
} }
if (filter.criteria) if (filter.criteria)
@ -306,11 +323,11 @@ class FilterUtils
if (reasonsWhyItCannot.length == 0) if (reasonsWhyItCannot.length == 0)
{ {
return ({canFilterWorkAsBasic: true}); return ({canFilterWorkAsBasic: true, canFilterWorkAsAdvanced: true});
} }
else else
{ {
return ({canFilterWorkAsBasic: false, reasonsWhyItCannot: reasonsWhyItCannot}); return ({canFilterWorkAsBasic: false, canFilterWorkAsAdvanced: true, reasonsWhyItCannot: reasonsWhyItCannot});
} }
} }
@ -369,7 +386,7 @@ class FilterUtils
} }
else if (fieldMetaData.type == QFieldType.BOOLEAN) else if (fieldMetaData.type == QFieldType.BOOLEAN)
{ {
labels.push(value == true ? "yes" : "no") labels.push(value == true ? "yes" : "no");
} }
else if (fieldMetaData.type == QFieldType.DATE_TIME) else if (fieldMetaData.type == QFieldType.DATE_TIME)
{ {
@ -447,7 +464,7 @@ class FilterUtils
for (let i = 0; i < queryFilter?.orderBys?.length; i++) for (let i = 0; i < queryFilter?.orderBys?.length; i++)
{ {
const orderBy = queryFilter.orderBys[i]; const orderBy = queryFilter.orderBys[i];
gridSortModel.push({field: orderBy.fieldName, sort: orderBy.isAscending ? "asc" : "desc"}) gridSortModel.push({field: orderBy.fieldName, sort: orderBy.isAscending ? "asc" : "desc"});
} }
return (gridSortModel); return (gridSortModel);
} }
@ -494,33 +511,33 @@ class FilterUtils
case QCriteriaOperator.LESS_THAN: case QCriteriaOperator.LESS_THAN:
if (isDate || isDateTime) if (isDate || isDateTime)
{ {
return ("is before") return ("is before");
} }
return ("less than"); return ("less than");
case QCriteriaOperator.LESS_THAN_OR_EQUALS: case QCriteriaOperator.LESS_THAN_OR_EQUALS:
if (isDate) if (isDate)
{ {
return ("is on or before") return ("is on or before");
} }
if (isDateTime) if (isDateTime)
{ {
return ("is at or before") return ("is at or before");
} }
return ("less than or equals"); return ("less than or equals");
case QCriteriaOperator.GREATER_THAN: case QCriteriaOperator.GREATER_THAN:
if (isDate || isDateTime) if (isDate || isDateTime)
{ {
return ("is after") return ("is after");
} }
return ("greater than or equals"); return ("greater than or equals");
case QCriteriaOperator.GREATER_THAN_OR_EQUALS: case QCriteriaOperator.GREATER_THAN_OR_EQUALS:
if (isDate) if (isDate)
{ {
return ("is on or after") return ("is on or after");
} }
if (isDateTime) if (isDateTime)
{ {
return ("is at or after") return ("is at or after");
} }
return ("greater than or equals"); return ("greater than or equals");
case QCriteriaOperator.IS_BLANK: case QCriteriaOperator.IS_BLANK:
@ -536,7 +553,7 @@ class FilterUtils
catch (e) catch (e)
{ {
console.log(`Error getting operator human string for ${JSON.stringify(criteria)}: ${e}`); console.log(`Error getting operator human string for ${JSON.stringify(criteria)}: ${e}`);
return criteria?.operator return criteria?.operator;
} }
} }
@ -564,7 +581,7 @@ class FilterUtils
{valuesString && <Box display="inline" p="0.125rem" pr="0.5rem" sx={{background: "#009971"}} borderRadius="0 0.5rem 0.5rem 0"> {valuesString}</Box>} {valuesString && <Box display="inline" p="0.125rem" pr="0.5rem" sx={{background: "#009971"}} borderRadius="0 0.5rem 0.5rem 0"> {valuesString}</Box>}
&nbsp; &nbsp;
</Box> </Box>
) );
} }
else else
{ {
@ -572,6 +589,29 @@ class FilterUtils
} }
} }
/*******************************************************************************
** after go-live of redesigin in march 2024, we had bugs where we could get a
** filter with a criteria w/ a null field name (e.g., by having an incomplete
** criteria in the Advanced filter builder - and that would sometimes break
** the screen! So, strip those away when storing or loading filters, via
** this function.
*******************************************************************************/
public static stripAwayIncompleteCriteria(filter: QQueryFilter)
{
if (filter?.criteria?.length > 0)
{
for (let i = 0; i < filter.criteria.length; i++)
{
if (!filter.criteria[i].fieldName)
{
filter.criteria.splice(i, 1);
i--;
}
}
}
}
} }
export default FilterUtils; export default FilterUtils;

View File

@ -30,62 +30,102 @@ 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;
{
allowedSections.push(section);
break; break;
} }
} }
if (additionalInclusionPredicate && additionalInclusionPredicate(section))
{
includeSection = true;
}
if(includeSection)
{
allowedSections.push(section);
} }
} }
console.log("allowedSections length: " + allowedSections.length);
return (allowedSections); return (allowedSections);
} }
else
{ ////////////////////////////////////////////////////////////////
// if there are no filters to apply, then return all sections //
////////////////////////////////////////////////////////////////
return (tableMetaData.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()]; let fieldNames = [...tableMetaData.fields.keys()];
if (allowedKeys) if (allowedFieldNames)
{ {
fieldNames = []; fieldNames = [];
for (const fieldName in tableMetaData.fields.keys()) for (const fieldName in tableMetaData.fields.keys())
{ {
if (allowedKeys[fieldName]) if (allowedFieldNames[fieldName])
{ {
fieldNames.push(fieldName); fieldNames.push(fieldName);
} }
} }
} }
return ([new QTableSection({ return ([new QTableSection({
iconName: "description", label: "All Fields", name: "allFields", fieldNames: [...fieldNames], iconName: "description", label: "All Fields", name: "allFields", fieldNames: [...fieldNames],
})]); })]);
} }
}
/******************************************************************************* /*******************************************************************************
@ -110,7 +150,7 @@ class TableUtils
return ([tableMetaData.fields.get(fieldName), tableMetaData]); return ([tableMetaData.fields.get(fieldName), tableMetaData]);
} }
return (null); return [null, null];
} }
@ -133,7 +173,7 @@ class TableUtils
catch (e) catch (e)
{ {
console.log(`Error getting full field label for ${fieldName} in table ${tableMetaData?.name}: ${e}`); console.log(`Error getting full field label for ${fieldName} in table ${tableMetaData?.name}: ${e}`);
return fieldName return fieldName;
} }
} }