Compare commits

...

37 Commits

Author SHA1 Message Date
84e627467f CE-936 - Update to receive warnings within the response QRecord and display them (this fixes inserts that warn) 2024-03-19 11:13:58 -05:00
6c524c4eca CE-936 - Fix editing child records; fix warning icon on view screen 2024-03-19 10:41:03 -05:00
5c442b2024 qqq-frontend-core 1.0.89 2024-03-18 15:06:17 -05:00
b8c36bccd2 Add abiltiy to edit child records as an association on insert/edit screens. 2024-03-18 15:06:17 -05:00
67feb95c60 Add abiltiy to edit child records as an association on insert/edit screens. 2024-03-18 12:48:16 -05:00
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
809f01e43e CE-878: updated to allow sublabel to be displayed under label 2024-02-29 14:47:00 -06:00
8ebc2415fe Merged feature/CE-878-make-the-operations-dashboard into main 2024-02-29 09:39:08 -06:00
5f3957e897 CE-878 - Add tooltips from helpContent to widget labels & table-widget column headers 2024-02-28 14:59:27 -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
e6b9b34206 Merge branch 'main' into feature/CE-878-make-the-operations-dashboard 2024-02-22 10:55:26 -06:00
dee7bc693e Merge branch 'feature/CE-876-develop-missing-widget-types' into feature/CE-878-make-the-operations-dashboard 2024-02-22 10:52:37 -06:00
948aee70fd Disable 'c' hotkey for columns (broke with buiding custom columsn button instead of using data grid's) 2024-02-21 19:43:20 -06:00
f0c1af18d0 Fix last commit (shouldn't add layout to ChartSubheaderWithData) 2024-02-21 19:42:00 -06:00
fa65d6c0ad Add cursor:pointer to PieChart and StackedBarChart 2024-02-21 19:18:34 -06:00
630f0d2dc1 CE-876 add negative marginBottom to heading 2024-02-21 19:17:11 -06:00
d795bd8427 Merge branch 'feature/CE-876-develop-missing-widget-types' into feature/CE-878-make-the-operations-dashboard 2024-02-21 11:32:14 -06:00
d6c9bf79b1 Update circleci/browser-tools@1.4.7 and try to re-activate verify 2024-02-19 14:49:55 -06:00
677b93a09f Turn off broken selenium/int tests 2024-02-19 14:49:02 -06:00
314bf0fd67 Fix to clear out limit when using a select-all filter for launching processes 2024-02-19 13:47:04 -06:00
76642f13e9 HOTFIX - Change defaultRowsPerPage from 10 to 50 2024-02-16 11:23:31 -06:00
0eaf171523 Merge pull request #43 from Kingsrook/feature/CE-798-quick-filters-fixes
Feature/ce 798 quick filters fixes
2024-02-16 10:56:15 -06:00
b137b3346d CE-798 - A fix for last change here, where if criteria came from outside this component, then changing operator wouldn't take - another check of isOpen in some of the reset code. 2024-02-16 10:09:42 -06:00
63479ba282 CE-798 - Update to not change the criteria in the query (e.g., not fire a new query) until user clicks out of menu 2024-02-15 20:24:05 -06:00
967c557a58 CE-798 - fix typing 'o' bug in quick filters; add missing 'start of' in expression toString calls 2024-02-15 20:21:47 -06:00
41 changed files with 5318 additions and 3792 deletions

View File

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

View File

@ -28,8 +28,7 @@
},
"plugins": [
"react",
"@typescript-eslint",
"import"
"@typescript-eslint"
],
"rules": {
"brace-style": [
@ -43,41 +42,6 @@
"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",
"max-len": "off",
"no-console": "off",
@ -114,15 +78,6 @@
"quotes": [
"error",
"double"
],
"sort-imports": [
"error",
{
"ignoreCase": false,
"ignoreDeclarationSort": true,
"ignoreMemberSort": true,
"allowSeparatedGroups": false
}
]
},
"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",
"@emotion/react": "11.7.1",
"@emotion/styled": "11.6.0",
"@kingsrook/qqq-frontend-core": "1.0.86",
"@kingsrook/qqq-frontend-core": "1.0.90",
"@mui/icons-material": "5.4.1",
"@mui/material": "5.11.1",
"@mui/styles": "5.11.1",

View File

@ -66,7 +66,7 @@
<dependency>
<groupId>com.kingsrook.qqq</groupId>
<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>
<groupId>org.slf4j</groupId>

View File

@ -36,7 +36,7 @@ import Icon from "@mui/material/Icon";
import Typography from "@mui/material/Typography";
import {makeStyles} from "@mui/styles";
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 QContext from "QContext";
import HistoryUtils, {QHistoryEntry} from "qqq/utils/HistoryUtils";
@ -174,7 +174,9 @@ const CommandMenu = ({metaData}: Props) =>
})
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;
@ -222,7 +224,9 @@ const CommandMenu = ({metaData}: Props) =>
})
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(
<Command.Group heading="Tables">
@ -252,7 +256,9 @@ const CommandMenu = ({metaData}: Props) =>
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(
@ -286,7 +292,9 @@ const CommandMenu = ({metaData}: Props) =>
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>();
@ -354,8 +362,7 @@ const CommandMenu = ({metaData}: Props) =>
<Grid container columnSpacing={5} rowSpacing={1}>
<Grid item xs={6} className={classes.item}><span className={classes.keyboardKey}>n</span>Create a New Record</Grid>
<Grid item xs={6} className={classes.item}><span className={classes.keyboardKey}>r</span>Refresh the Query</Grid>
<Grid item xs={6} className={classes.item}><span className={classes.keyboardKey}>c</span>Open the Columns Panel</Grid>
<Grid item xs={6} className={classes.item}><span className={classes.keyboardKey}>f</span>Open the Filter Panel</Grid>
<Grid item xs={6} className={classes.item}><span className={classes.keyboardKey}>f</span>Open the Filter Builder (Advanced mode only)</Grid>
</Grid>
<Typography variant="h6" pt={3}>Record View</Typography>

View File

@ -22,7 +22,9 @@
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.utils.CollectionUtils;
/*******************************************************************************
@ -30,7 +32,39 @@ import com.kingsrook.qqq.backend.core.model.metadata.layout.QSupplementalAppMeta
*******************************************************************************/
public class MaterialDashboardAppMetaData extends QSupplementalAppMetaData
{
public static final String TYPE_NAME = "materialDashboard";
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
public String getType()
{
return ("materialDashboard");
return TYPE_NAME;
}
@ -85,4 +119,35 @@ public class MaterialDashboardAppMetaData extends QSupplementalAppMetaData
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 Tooltip from "@mui/material/Tooltip";
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 Client from "qqq/utils/qqq/Client";
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 [statusString, setStatusString] = useState("Loading audits...");
const [auditsByDate, setAuditsByDate] = useState([] as QRecord[][]);
const [auditDetailMap, setAuditDetailMap] = useState(null as Map<number, JSX.Element[]>)
const [fieldChangeMap, setFieldChangeMap] = 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 [sortDirection, setSortDirection] = useState(localStorage.getItem("audit.sortDirection") === "true");
const {accentColor} = useContext(QContext);
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
{
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
@ -79,10 +79,14 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
const fieldName = qRecord.values.get("auditDetail.fieldName");
const oldValue = qRecord.values.get("auditDetail.oldValue");
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
return (<tr><td>{fieldLabel}</td><td>{oldValue}</td><td>{newValue}</td></tr>)
const fieldLabel = tableMetaData?.fields?.get(fieldName)?.label ?? fieldName;
return (<tr>
<td>{fieldLabel}</td>
<td>{oldValue}</td>
<td>{newValue}</td>
</tr>);
}
return (null);
}
@ -93,22 +97,22 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
const fieldName = qRecord.values.get("auditDetail.fieldName");
const oldValue = qRecord.values.get("auditDetail.oldValue");
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;
if(oldValue !== undefined && newValue !== undefined)
if (oldValue !== undefined && newValue !== undefined)
{
return (<>{fieldLabel}: Changed from {(oldValue)} to <b>{(newValue)}</b></>);
}
else if(newValue !== undefined)
else if (newValue !== undefined)
{
return (<>{fieldLabel}: Set to <b>{(newValue)}</b></>);
}
else if(oldValue !== undefined)
else if (oldValue !== undefined)
{
return (<>{fieldLabel}: Removed value {(oldValue)}</>);
}
else if(message)
else if (message)
{
return (<>{message}</>);
}
@ -177,7 +181,7 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
}
*/
}
else if(message)
else if (message)
{
return (<>{message}</>);
}
@ -198,18 +202,18 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
new QFilterOrderBy("timestamp", sortDirection),
new QFilterOrderBy("id", sortDirection),
new QFilterOrderBy("auditDetail.id", true)
], "AND", 0, limit);
], null, "AND", 0, limit);
///////////////////////////////
// fetch audits in try-catch //
///////////////////////////////
let audits = [] as QRecord[]
let audits = [] as QRecord[];
try
{
audits = await qController.query("audit", filter, [new QueryJoin("auditDetail", true, "LEFT")]);
setAudits(audits);
}
catch(e)
catch (e)
{
if (e instanceof QException)
{
@ -233,33 +237,33 @@ 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) //
//////////////////////////////////////////////////////////////////////////////////////////////////////////
const unflattenedAudits: QRecord[] = []
const unflattenedAudits: QRecord[] = [];
const detailMap: Map<number, JSX.Element[]> = new Map();
const fieldChangeRowsMap: Map<number, JSX.Element[]> = new Map();
for (let i = 0; i < audits.length; i++)
{
let id = audits[i].values.get("id");
if(i == 0 || unflattenedAudits[unflattenedAudits.length-1].values.get("id") != id)
if (i == 0 || unflattenedAudits[unflattenedAudits.length - 1].values.get("id") != id)
{
unflattenedAudits.push(audits[i]);
}
let auditDetail = getAuditDetailElement(audits[i]);
if(auditDetail)
if (auditDetail)
{
if(!detailMap.has(id))
if (!detailMap.has(id))
{
detailMap.set(id, []);
}
detailMap.get(id).push(auditDetail)
detailMap.get(id).push(auditDetail);
}
// table version, probably not to commit
let fieldChangeRow = getAuditDetailFieldChangeRow(audits[i]);
if(auditDetail)
if (auditDetail)
{
if(!fieldChangeRowsMap.has(id))
if (!fieldChangeRowsMap.has(id))
{
fieldChangeRowsMap.set(id, []);
}
@ -273,7 +277,7 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
for (let i = 0; i < unflattenedAudits.length; i++)
{
let id = unflattenedAudits[i].values.get("id");
if(fieldChangeRowsMap.has(id) && fieldChangeRowsMap.get(id).length > 0)
if (fieldChangeRowsMap.has(id) && fieldChangeRowsMap.get(id).length > 0)
{
const fieldChangeTable = (
<table style={{fontSize: "0.875rem"}} className="auditDetailTable" cellSpacing="0">
@ -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>)}
</tbody>
</table>
)
);
fieldChangeMap.set(id, fieldChangeTable);
}
}
setFieldChangeMap(fieldChangeMap)
setFieldChangeMap(fieldChangeMap);
//////////////////////////////
// group the audits by date //
@ -350,7 +354,7 @@ function AuditBody({tableMetaData, recordId, record}: Props): JSX.Element
const changeSortDirection = () =>
{
setAudits([]);
const newSortDirection = !sortDirection
const newSortDirection = !sortDirection;
setSortDirection(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 * as Yup from "yup";
type DisabledFields = { [fieldName: string]: boolean } | string[];
/*******************************************************************************
** Meta-data to represent a single field in a table.
**
*******************************************************************************/
class DynamicFormUtils
{
public static getFormData(qqqFormFields: QFieldMetaData[])
/*******************************************************************************
**
*******************************************************************************/
public static getFormData(qqqFormFields: QFieldMetaData[], disabledFields?: DisabledFields)
{
const dynamicFormFields: any = {};
const formValidations: any = {};
qqqFormFields.forEach((field) =>
{
dynamicFormFields[field.name] = this.getDynamicField(field);
formValidations[field.name] = this.getValidationForField(field);
dynamicFormFields[field.name] = this.getDynamicField(field, disabledFields);
formValidations[field.name] = this.getValidationForField(field, disabledFields);
});
return {dynamicFormFields, formValidations};
}
public static getDynamicField(field: QFieldMetaData)
/*******************************************************************************
**
*******************************************************************************/
public static getDynamicField(field: QFieldMetaData, disabledFields?: DisabledFields)
{
let fieldType: string;
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;
label += field.isRequired ? " *" : "";
label += effectivelyIsRequired ? " *" : "";
return ({
fieldMetaData: field,
name: field.name,
label: label,
isRequired: field.isRequired,
isEditable: field.isEditable,
isRequired: effectivelyIsRequired,
isEditable: effectiveIsEditable,
type: fieldType,
displayFormat: field.displayFormat,
// todo invalidMsg: "Zipcode is not valid (e.g. 70000).",
@ -101,11 +118,18 @@ class DynamicFormUtils
});
}
public static getValidationForField(field: QFieldMetaData)
/*******************************************************************************
**
*******************************************************************************/
public static getValidationForField(field: QFieldMetaData, disabledFields?: DisabledFields)
{
if (field.isRequired)
const effectiveIsEditable = field.isEditable && !this.isFieldDynamicallyDisabled(field.name, disabledFields);
const effectivelyIsRequired = field.isRequired && effectiveIsEditable;
if (effectivelyIsRequired)
{
if(field.possibleValueSourceName)
if (field.possibleValueSourceName)
{
////////////////////////////////////////////////////////////////////////////////////////////
// the "nullable(true)" here doesn't mean that you're allowed to set the field to null... //
@ -121,6 +145,10 @@ class DynamicFormUtils
return (null);
}
/*******************************************************************************
**
*******************************************************************************/
public static addPossibleValueProps(dynamicFormFields: any, qFields: QFieldMetaData[], tableName: string, processName: string, displayValues: Map<string, string>)
{
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;

View File

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

View File

@ -61,7 +61,7 @@ const qController = Client.getInstance();
function hasGotoFieldNames(tableMetaData: QTableMetaData): boolean
{
const mdbMetaData = tableMetaData?.supplementalTableMetaData?.get("materialDashboard");
if(mdbMetaData && mdbMetaData.gotoFieldNames)
if (mdbMetaData && mdbMetaData.gotoFieldNames)
{
return (true);
}
@ -71,25 +71,25 @@ function hasGotoFieldNames(tableMetaData: QTableMetaData): boolean
function GotoRecordDialog(props: Props): JSX.Element
{
const fields: QFieldMetaData[] = []
const fields: QFieldMetaData[] = [];
let pkey = props?.tableMetaData?.fields.get(props?.tableMetaData?.primaryKeyField);
let addedPkey = false;
const mdbMetaData = props?.tableMetaData?.supplementalTableMetaData?.get("materialDashboard");
if(mdbMetaData)
if (mdbMetaData)
{
if(mdbMetaData.gotoFieldNames)
if (mdbMetaData.gotoFieldNames)
{
for(let i = 0; i<mdbMetaData.gotoFieldNames.length; i++)
for (let i = 0; i < mdbMetaData.gotoFieldNames.length; i++)
{
// todo - multi-field keys!!
let fieldName = mdbMetaData.gotoFieldNames[i][0];
let field = props.tableMetaData.fields.get(fieldName);
if(field)
if (field)
{
fields.push(field);
if(field.name == pkey.name)
if (field.name == pkey.name)
{
addedPkey = true;
}
@ -98,17 +98,17 @@ function GotoRecordDialog(props: Props): JSX.Element
}
}
if(pkey && !addedPkey)
if (pkey && !addedPkey)
{
fields.unshift(pkey);
}
const makeInitialValues = () =>
{
const rs = {} as {[field: string]: string};
const rs = {} as { [field: string]: string };
fields.forEach((field) => rs[field.name] = "");
return (rs);
}
};
const [error, setError] = useState("");
const [values, setValues] = useState(makeInitialValues());
@ -118,49 +118,49 @@ function GotoRecordDialog(props: Props): JSX.Element
{
values[fieldName] = newValue;
setValues(JSON.parse(JSON.stringify(values)));
}
};
const close = () =>
{
setError("");
setValues(makeInitialValues());
props.closeHandler();
}
};
const keyPressed = (e: React.KeyboardEvent<HTMLDivElement>) =>
{
// @ts-ignore
const targetId: string = e.target?.id;
if(e.key == "Esc")
if (e.key == "Esc")
{
if(props.mayClose)
if (props.mayClose)
{
close();
}
}
else if(e.key == "Enter" && targetId?.startsWith("gotoInput-"))
else if (e.key == "Enter" && targetId?.startsWith("gotoInput-"))
{
const index = targetId?.replaceAll("gotoInput-", "");
document.getElementById("gotoButton-" + index).click();
}
}
};
const closeRequested = () =>
{
if(props.mayClose)
if (props.mayClose)
{
close();
}
}
};
const goClicked = async (fieldName: string) =>
{
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
{
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)
{
setError("Record not found.");
@ -177,19 +177,19 @@ function GotoRecordDialog(props: Props): JSX.Element
setTimeout(() => setError(""), 3000);
}
}
catch(e)
catch (e)
{
// @ts-ignore
setError(`Error: ${(e && e.message) ? e.message : e}`);
setTimeout(() => setError(""), 6000);
}
}
};
if(props.tableMetaData)
if (props.tableMetaData)
{
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>
}
</Dialog>
)
);
}
interface GotoRecordButtonProps
@ -266,7 +266,7 @@ GotoRecordButton.defaultProps = {
export function GotoRecordButton(props: GotoRecordButtonProps): JSX.Element
{
const [gotoIsOpen, setGotoIsOpen] = useState(props.autoOpen)
const [gotoIsOpen, setGotoIsOpen] = useState(props.autoOpen);
function openGoto()
{
@ -282,7 +282,7 @@ export function GotoRecordButton(props: GotoRecordButtonProps): JSX.Element
return (
<React.Fragment>
{
props.buttonVisible && hasGotoFieldNames(props.tableMetaData) && <Button onClick={openGoto} >Go To...</Button>
props.buttonVisible && hasGotoFieldNames(props.tableMetaData) && <Button onClick={openGoto}>Go To...</Button>
}
<GotoRecordDialog metaData={props.metaData} tableMetaData={props.tableMetaData} tableVariant={props.tableVariant} isOpen={gotoIsOpen} closeHandler={closeGoto} mayClose={props.mayClose} subHeader={props.subHeader} />
</React.Fragment>

View File

@ -28,7 +28,7 @@ import QContext from "QContext";
interface Props
{
helpContents: QHelpContent[];
helpContents: null | QHelpContent | QHelpContent[];
roles: string[];
heading?: string;
helpContentKey?: string;
@ -93,9 +93,27 @@ const getMatchingHelpContent = (helpContents: QHelpContent[], roles: string[]):
/*******************************************************************************
** test if a list of help contents would find any matches from a list of roles.
*******************************************************************************/
export const hasHelpContent = (helpContents: QHelpContent[], roles: string[]) =>
export const hasHelpContent = (helpContents: null | QHelpContent | QHelpContent[], roles: string[]) =>
{
return getMatchingHelpContent(helpContents, roles) != null;
return getMatchingHelpContent(nullOrSingletonOrArrayToArray(helpContents), roles) != null;
}
/*******************************************************************************
**
*******************************************************************************/
const nullOrSingletonOrArrayToArray = (helpContents: null | QHelpContent | QHelpContent[]): QHelpContent[] =>
{
let array: QHelpContent[] = [];
if(Array.isArray(helpContents))
{
array = helpContents;
}
else if(helpContents != null)
{
array.push(helpContents);
}
return (array);
}
@ -106,7 +124,8 @@ export const hasHelpContent = (helpContents: QHelpContent[], roles: string[]) =>
function HelpContent({helpContents, roles, heading, helpContentKey}: Props): JSX.Element
{
const {helpHelpActive} = useContext(QContext);
let selectedHelpContent = getMatchingHelpContent(helpContents, roles);
const helpContentsArray = nullOrSingletonOrArrayToArray(helpContents);
let selectedHelpContent = getMatchingHelpContent(helpContentsArray, roles);
let content = null;
if (helpHelpActive)

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 {QFilterOrderBy} from "@kingsrook/qqq-frontend-core/lib/model/query/QFilterOrderBy";
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 Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
@ -38,9 +37,10 @@ import DialogContent from "@mui/material/DialogContent";
import DialogContentText from "@mui/material/DialogContentText";
import DialogTitle from "@mui/material/DialogTitle";
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 {GridApiPro} from "@mui/x-data-grid-pro/models/gridApiPro";
import React, {forwardRef, useContext, useImperativeHandle, useReducer, useState} from "react";
import QContext from "QContext";
import colors from "qqq/assets/theme/base/colors";
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 FilterUtils from "qqq/utils/qqq/FilterUtils";
import TableUtils from "qqq/utils/qqq/TableUtils";
import React, {forwardRef, useContext, useImperativeHandle, useReducer, useState} from "react";
interface BasicAndAdvancedQueryControlsProps
{
@ -89,14 +90,14 @@ let debounceTimeout: string | number | NodeJS.Timeout;
*******************************************************************************/
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 //
/////////////////////
const [defaultQuickFilterFieldNames, setDefaultQuickFilterFieldNames] = useState(getDefaultQuickFilterFieldNames(tableMetaData));
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 [showClearFiltersWarning, setShowClearFiltersWarning] = useState(false);
const [mouseOverElement, setMouseOverElement] = useState(null as string);
@ -104,6 +105,11 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
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 //
//////////////////////////////////////////////////////////////////////////////////
@ -122,7 +128,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
{
return (mode);
}
}
};
});
@ -176,7 +182,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
let foundIndex = null;
for (let i = 0; i < queryFilter?.criteria?.length; i++)
{
if(queryFilter.criteria[i].fieldName == newCriteria.fieldName)
if (queryFilter.criteria[i].fieldName == newCriteria.fieldName)
{
queryFilter.criteria[i] = newCriteria;
found = true;
@ -185,9 +191,9 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
}
}
if(doClearCriteria)
if (doClearCriteria)
{
if(found)
if (found)
{
queryFilter.criteria.splice(foundIndex, 1);
setQueryFilter(queryFilter);
@ -195,9 +201,9 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
return;
}
if(!found)
if (!found)
{
if(!queryFilter.criteria)
if (!queryFilter.criteria)
{
queryFilter.criteria = [];
}
@ -205,9 +211,9 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
found = true;
}
if(found)
if (found)
{
clearTimeout(debounceTimeout)
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(() =>
{
setQueryFilter(queryFilter);
@ -227,17 +233,17 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
const matches: QFilterCriteriaWithId[] = [];
for (let i = 0; i < queryFilter?.criteria?.length; i++)
{
if(queryFilter.criteria[i].fieldName == fieldName)
if (queryFilter.criteria[i].fieldName == fieldName)
{
matches.push(queryFilter.criteria[i] as QFilterCriteriaWithId);
}
}
if(matches.length == 0)
if (matches.length == 0)
{
return (null);
}
else if(matches.length == 1)
else if (matches.length == 1)
{
return (matches[0]);
}
@ -254,8 +260,8 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
*******************************************************************************/
const handleRemoveQuickFilterField = (fieldName: string): void =>
{
const index = quickFilterFieldNames.indexOf(fieldName)
if(index >= 0)
const index = quickFilterFieldNames.indexOf(fieldName);
if (index >= 0)
{
//////////////////////////////////////
// remove this field from the query //
@ -276,7 +282,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
{
setAddQuickFilterMenu(event.currentTarget);
setAddQuickFilterOpenCounter(addQuickFilterOpenCounter + 1);
}
};
/*******************************************************************************
@ -285,7 +291,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
const closeAddQuickFilterMenu = () =>
{
setAddQuickFilterMenu(null);
}
};
/*******************************************************************************
@ -306,7 +312,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
const fieldName = newValue ? newValue.fieldName : null;
if (fieldName)
{
if(defaultQuickFilterFieldNameMap[fieldName])
if (defaultQuickFilterFieldNameMap[fieldName])
{
return;
}
@ -322,12 +328,12 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// only do this when user has added the field (e.g., not when adding it because of a selected view or filter-in-url) //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(reason != "modeToggleClicked" && reason != "defaultFilterLoaded" && reason != "savedFilterSelected" && reason != "activatedView")
if (reason != "modeToggleClicked" && reason != "defaultFilterLoaded" && reason != "savedFilterSelected" && reason != "activatedView")
{
setTimeout(() => document.getElementById(`quickFilter.${fieldName}`)?.click(), 5);
}
}
else if(reason == "columnMenu")
else if (reason == "columnMenu")
{
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// if field was already on-screen, but user clicked an option from the columnMenu, then open the quick-filter field //
@ -346,13 +352,13 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
const handleFieldListMenuSelection = (field: QFieldMetaData, table: QTableMetaData): void =>
{
let fullFieldName = field.name;
if(table && table.name != tableMetaData.name)
if (table && table.name != tableMetaData.name)
{
fullFieldName = `${table.name}.${field.name}`;
}
addQuickFilterField({fieldName: fullFieldName}, "selectedFromAddFilterMenu");
}
};
/*******************************************************************************
@ -361,7 +367,10 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
*******************************************************************************/
const openFilterBuilder = (e: React.MouseEvent<HTMLAnchorElement> | React.MouseEvent<HTMLButtonElement>) =>
{
gridApiRef.current.showFilterPanel();
if (!isQueryTooComplex)
{
gridApiRef.current.showFilterPanel();
}
};
@ -385,15 +394,15 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
{
queryFilter.criteria.splice(index, 1);
setQueryFilter(queryFilter);
}
};
/*******************************************************************************
** 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)
{
return (<span></span>);
}
@ -402,18 +411,21 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
return (
<Box display="flex" flexWrap="wrap" fontSize="0.875rem">
{queryFilter.criteria.map((criteria, i) =>
{thisQueryFilter.criteria?.map((criteria, i) =>
{
const {criteriaIsValid} = validateCriteria(criteria, null);
if(criteriaIsValid)
if (criteriaIsValid)
{
counter++;
return (
<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)}
{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>
);
}
@ -422,6 +434,18 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
return (<span />);
}
})}
{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>
);
}))}
</Box>
);
};
@ -434,7 +458,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
{
if (newValue)
{
if(newValue == "basic")
if (newValue == "basic")
{
////////////////////////////////////////////////////////////////////////////////
// we're always allowed to go to advanced - //
@ -443,7 +467,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
const {canFilterWorkAsBasic} = FilterUtils.canFilterWorkAsBasic(tableMetaData, queryFilter);
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;
}
@ -470,11 +494,16 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
*******************************************************************************/
const ensureAllFilterCriteriaAreActiveQuickFilters = (tableMetaData: QTableMetaData, queryFilter: QQueryFilter, reason: "modeToggleClicked" | "defaultFilterLoaded" | "savedFilterSelected" | string, newMode?: string) =>
{
if(!tableMetaData || !queryFilter)
if (!tableMetaData || !queryFilter)
{
return;
}
//////////////////////////////////////////////
// set a flag if the query is 'too complex' //
//////////////////////////////////////////////
setIsQueryTooComplex(queryFilter.subFilters?.length > 0);
const {canFilterWorkAsBasic} = FilterUtils.canFilterWorkAsBasic(tableMetaData, queryFilter);
if (!canFilterWorkAsBasic)
{
@ -485,7 +514,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
}
const modeToUse = newMode ?? mode;
if(modeToUse == "basic")
if (modeToUse == "basic")
{
for (let i = 0; i < queryFilter?.criteria?.length; i++)
{
@ -496,7 +525,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
}
}
}
}
};
/*******************************************************************************
@ -508,13 +537,22 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
for (let i = 0; i < queryFilter?.criteria?.length; i++)
{
const {criteriaIsValid} = validateCriteria(queryFilter.criteria[i], null);
if(criteriaIsValid)
if (criteriaIsValid)
{
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;
}
};
/*******************************************************************************
@ -523,11 +561,11 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
const handleSetSort = (field: QFieldMetaData, table: QTableMetaData, isAscending: boolean = true): void =>
{
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);
forceUpdate();
}
};
/*******************************************************************************
@ -542,11 +580,11 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const isAscending = event.target.innerHTML == "arrow_upward";
const isDescending = event.target.innerHTML == "arrow_downward";
if(isAscending || isDescending)
if (isAscending || isDescending)
{
handleSetSort(field, table, isAscending);
}
}
};
/*******************************************************************************
@ -561,30 +599,30 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
setQueryFilter(queryFilter);
forceUpdate();
}
catch(e)
catch (e)
{
console.log(`Error toggling sort: ${e}`)
console.log(`Error toggling sort: ${e}`);
}
}
/////////////////////////////////
// set up the sort menu button //
/////////////////////////////////
let sortButtonContents = <>Sort...</>
if(queryFilter && queryFilter.orderBys && queryFilter.orderBys.length > 0)
let sortButtonContents = <>Sort...</>;
if (queryFilter && queryFilter.orderBys && queryFilter.orderBys.length > 0)
{
const orderBy = queryFilter.orderBys[0];
const orderByFieldName = orderBy.fieldName;
const [field, fieldTable] = TableUtils.getFieldAndTable(tableMetaData, orderByFieldName);
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></>;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// this is being used as a version of like forcing that we get re-rendered if the query filter changes... //
////////////////////////////////////////////////////////////////////////////////////////////////////////////
const [lastIndex, setLastIndex] = useState(queryFilterJSON);
if(queryFilterJSON != lastIndex)
if (queryFilterJSON != lastIndex)
{
ensureAllFilterCriteriaAreActiveQuickFilters(tableMetaData, queryFilter, "defaultFilterLoaded");
setLastIndex(queryFilterJSON);
@ -594,16 +632,22 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
// set some status flags based on current filter //
///////////////////////////////////////////////////
const hasValidFilters = queryFilter && countValidCriteria(queryFilter) > 0;
const {canFilterWorkAsBasic, reasonsWhyItCannot} = FilterUtils.canFilterWorkAsBasic(tableMetaData, queryFilter);
const {canFilterWorkAsBasic, canFilterWorkAsAdvanced, reasonsWhyItCannot} = FilterUtils.canFilterWorkAsBasic(tableMetaData, queryFilter);
let reasonWhyBasicIsDisabled = null;
if(reasonsWhyItCannot && reasonsWhyItCannot.length > 0)
if (canFilterWorkAsAdvanced && reasonsWhyItCannot && reasonsWhyItCannot.length > 0)
{
reasonWhyBasicIsDisabled = <>
Your current Filter cannot be managed using Basic mode because:
<ul style={{marginLeft: "1rem"}}>
{reasonsWhyItCannot.map((reason, i) => <li key={i}>{reason}</li>)}
</ul>
</>
</>;
}
if (isQueryTooComplex)
{
reasonWhyBasicIsDisabled = <>
Your current Filter is too complex to modify because it contains Sub-filters.
</>;
}
const borderGray = colors.grayLines.main;
@ -731,20 +775,20 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
<Button
className="filterBuilderButton"
onClick={(e) => openFilterBuilder(e)}
{... filterBuilderMouseEvents}
{...filterBuilderMouseEvents}
startIcon={<Icon>build</Icon>}
sx={{borderRadius: "0.75rem", padding: "0.5rem", pl: "1rem", fontSize: "0.875rem", fontWeight: 500, border: `1px solid ${accentColor}`, textTransform: "none"}}
>
Filter Builder
{
countValidCriteria(queryFilter) > 0 &&
<Box {... filterBuilderMouseEvents} sx={{backgroundColor: accentColor, marginLeft: "0.25rem", minWidth: "1rem", fontSize: "0.75rem"}} borderRadius="50%" color="#FFFFFF" position="relative" top="-2px" className="filterBuilderCountBadge">
{countValidCriteria(queryFilter) }
<Box {...filterBuilderMouseEvents} sx={{backgroundColor: accentColor, marginLeft: "0.25rem", minWidth: "1rem", fontSize: "0.75rem"}} borderRadius="50%" color="#FFFFFF" position="relative" top="-2px" className="filterBuilderCountBadge">
{countValidCriteria(queryFilter)}
</Box>
}
</Button>
{
hasValidFilters && mouseOverElement == "filterBuilderButton" && <span {... filterBuilderMouseEvents} className="filterBuilderXIcon"><XIcon shade="accent" position="default" onClick={() => setShowClearFiltersWarning(true)} /></span>
hasValidFilters && mouseOverElement == "filterBuilderButton" && <span {...filterBuilderMouseEvents} className="filterBuilderXIcon"><XIcon shade="accent" position="default" onClick={() => setShowClearFiltersWarning(true)} /></span>
}
</>
</Tooltip>
@ -777,7 +821,7 @@ const BasicAndAdvancedQueryControls = forwardRef((props: BasicAndAdvancedQueryCo
pb={"0.125rem"}
boxShadow={"inset 0px 0px 4px 2px #EFEFED"}
>
{queryToAdvancedString()}
{queryToAdvancedString(queryFilter)}
</Box>
}
</Box>

View File

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

View File

@ -94,6 +94,24 @@ export const makeTextField = (field: QFieldMetaData, criteria: QFilterCriteriaWi
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 = {};
inputProps.endAdornment = (
<InputAdornment position="end">
@ -110,6 +128,7 @@ export const makeTextField = (field: QFieldMetaData, criteria: QFilterCriteriaWi
autoComplete="off"
type={type}
onChange={(event) => valueChangeHandler(event, valueIndex)}
onKeyDown={handleKeyDown}
value={value}
InputLabelProps={inputLabelProps}
InputProps={inputProps}

View File

@ -30,7 +30,7 @@ import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Menu from "@mui/material/Menu";
import TextField from "@mui/material/TextField";
import React, {SyntheticEvent, useContext, useState} from "react";
import React, {SyntheticEvent, useContext, useReducer, useState} from "react";
import QContext from "QContext";
import {QFilterCriteriaWithId} from "qqq/components/query/CustomFilterPanel";
import {getDefaultCriteriaValue, getOperatorOptions, getValueModeRequiredCount, OperatorOption, validateCriteria} from "qqq/components/query/FilterCriteriaRow";
@ -148,7 +148,10 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
const [anchorEl, setAnchorEl] = useState(null);
const [isMouseOver, setIsMouseOver] = useState(false);
const [criteria, setCriteria] = useState(criteriaParamIsCriteria(criteriaParam) ? criteriaParam as QFilterCriteriaWithId : null);
////////////////////////////////////////////////////////////////////////////////////////////////////////
// copy the criteriaParam to a new object in here - so changes won't apply until user closes the menu //
////////////////////////////////////////////////////////////////////////////////////////////////////////
const [criteria, setCriteria] = useState(criteriaParamIsCriteria(criteriaParam) ? Object.assign({}, criteriaParam) as QFilterCriteriaWithId : null);
const [id, setId] = useState(criteriaParamIsCriteria(criteriaParam) ? (criteriaParam as QFilterCriteriaWithId).id : ++seedId);
const [operatorSelectedValue, setOperatorSelectedValue] = useState(getOperatorSelectedValue(operatorOptions, criteria, defaultOperator));
@ -158,6 +161,11 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
const {accentColor} = useContext(QContext);
//////////////////////
// ole' faithful... //
//////////////////////
const [, forceUpdate] = useReducer((x) => x + 1, 0);
/*******************************************************************************
**
@ -182,15 +190,30 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (criteriaParamIsCriteria(criteriaParam) && JSON.stringify(criteriaParam) !== JSON.stringify(criteria))
{
const newCriteria = criteriaParam as QFilterCriteriaWithId;
setCriteria(newCriteria);
const operatorOption = operatorOptions.filter(o => o.value == newCriteria.operator)[0];
setOperatorSelectedValue(operatorOption);
setOperatorInputValue(operatorOption.label);
if(isOpen)
{
////////////////////////////////////////////////////////////////////////////////
// this was firing too-often for case where: there was a criteria originally //
////////////////////////////////////////////////////////////////////////////////
console.log("Not handling outside change (A), because dropdown is-open");
}
else
{
////////////////////////////////////////////////////////////////////////////////////////////////////////
// copy the criteriaParam to a new object in here - so changes won't apply until user closes the menu //
////////////////////////////////////////////////////////////////////////////////////////////////////////
const newCriteria = Object.assign({}, criteriaParam) as QFilterCriteriaWithId;
setCriteria(newCriteria);
const operatorOption = operatorOptions.filter(o => o.value == newCriteria.operator)[0];
setOperatorSelectedValue(operatorOption);
setOperatorInputValue(operatorOption.label);
}
}
/*******************************************************************************
** Test if we need to construct a new criteria object
** This is (at least for some cases) for when the criteria gets changed
** from outside of this component - e.g., a reset on the query screen
*******************************************************************************/
const criteriaNeedsReset = (): boolean =>
{
@ -199,6 +222,16 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
const defaultOperatorOption = operatorOptions.filter(o => o.value == defaultOperator)[0];
if(criteria.operator !== defaultOperatorOption?.value || JSON.stringify(criteria.values) !== JSON.stringify(getDefaultCriteriaValue()))
{
if(isOpen)
{
//////////////////////////////////////////////////////////////////////////////////
// this was firing too-often for case where: there was no criteria originally, //
// so, by adding this is-open check, we eliminated those. //
//////////////////////////////////////////////////////////////////////////////////
console.log("Not handling outside change (B), because dropdown is-open");
return (false);
}
return (true);
}
}
@ -207,7 +240,7 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
}
/*******************************************************************************
** Construct a new criteria object - resetting the values tied to the oprator
** Construct a new criteria object - resetting the values tied to the operator
** autocomplete at the same time.
*******************************************************************************/
const makeNewCriteria = (): QFilterCriteria =>
@ -241,6 +274,11 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
*******************************************************************************/
const closeMenu = () =>
{
//////////////////////////////////////////////////////////////////////////////////
// when closing the menu, that's when we'll update the criteria from the caller //
//////////////////////////////////////////////////////////////////////////////////
updateCriteria(criteria, false, false);
setIsOpen(false);
setAnchorEl(null);
};
@ -286,7 +324,8 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
setOperatorInputValue("");
}
updateCriteria(criteria, false, false);
setCriteria(criteria);
forceUpdate();
};
/*******************************************************************************
@ -320,7 +359,8 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
criteria.values[valueIndex] = value;
}
updateCriteria(criteria, true, false);
setCriteria(criteria);
forceUpdate();
};
/*******************************************************************************
@ -464,7 +504,7 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
//////////////////////////////
// return the button & menu //
//////////////////////////////
const widthAndMaxWidth = 250
const widthAndMaxWidth = fieldMetaData?.type == QFieldType.DATE_TIME ? 275 : 250
return (
<>
{button}
@ -480,7 +520,12 @@ export default function QuickFilter({tableMetaData, fullFieldName, fieldMetaData
<Box display="inline-block" width={widthAndMaxWidth} maxWidth={widthAndMaxWidth} className="operatorColumn">
<Autocomplete
id={"criteriaOperator"}
renderInput={(params) => (<TextField {...params} label={"Operator"} variant="standard" autoComplete="off" type="search" InputProps={{...params.InputProps}} />)}
////////////////////////////////////////////////////////////////////////////////////////////////////
// ok, so, by default, if you type an 'o' as the first letter in the FilterCriteriaRowValues box, //
// something is causing THIS element to become selected, if the first letter in its label is 'O'. //
// ... work around is to put invisible &zwnj; entity as first character in label instead... //
////////////////////////////////////////////////////////////////////////////////////////////////////
renderInput={(params) => (<TextField {...params} label={<>&zwnj;Operator</>} variant="standard" autoComplete="off" type="search" InputProps={{...params.InputProps}} />)}
options={operatorOptions}
value={operatorSelectedValue as any}
inputValue={operatorInputValue}

View File

@ -28,9 +28,11 @@ import Icon from "@mui/material/Icon";
import Tooltip from "@mui/material/Tooltip/Tooltip";
import Typography from "@mui/material/Typography";
import parse from "html-react-parser";
import React, {useEffect, useState} from "react";
import React, {useContext, useEffect, useState} from "react";
import {NavigateFunction, useNavigate} from "react-router-dom";
import QContext from "QContext";
import colors from "qqq/assets/theme/base/colors";
import HelpContent, {hasHelpContent} from "qqq/components/misc/HelpContent";
import WidgetDropdownMenu, {DropdownOption} from "qqq/components/widgets/components/WidgetDropdownMenu";
import {WidgetUtils} from "qqq/components/widgets/WidgetUtils";
import HtmlUtils from "qqq/utils/HtmlUtils";
@ -140,7 +142,7 @@ export class HeaderIcon extends LabelComponent
borderRadius: "0.25rem"
};
if(this.role == "topLeftInsideCard")
if (this.role == "topLeftInsideCard")
{
styles["order"] = -1;
styles["marginRight"] = "0.5rem";
@ -167,15 +169,17 @@ export class AddNewRecordButton extends LabelComponent
label: string;
defaultValues: 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();
this.table = table;
this.label = label;
this.defaultValues = defaultValues;
this.disabledFields = disabledFields;
this.addNewRecordCallback = addNewRecordCallback;
}
openEditForm = (navigate: any, table: QTableMetaData, id: any = null, defaultValues: any, disabledFields: any) =>
@ -187,7 +191,7 @@ export class AddNewRecordButton extends LabelComponent
{
return (
<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>
);
};
@ -233,22 +237,22 @@ export class Dropdown extends LabelComponent
try
{
const localStorageOption = JSON.parse(localStorage.getItem(localStorageKey));
if(localStorageOption)
if (localStorageOption)
{
const id = localStorageOption.id;
for (let i = 0; i < this.options.length; i++)
{
if (this.options[i].id == id)
{
defaultValue = this.options[i]
defaultValue = this.options[i];
args.dropdownData[args.componentIndex] = defaultValue?.id;
}
}
}
}
catch(e)
catch (e)
{
console.log(`Error getting default value for dropdown [${this.dropdownName}] from local storage`, e)
console.log(`Error getting default value for dropdown [${this.dropdownName}] from local storage`, e);
}
}
@ -259,7 +263,7 @@ export class Dropdown extends LabelComponent
{
for (let i = 0; i < this.options.length; i++)
{
if(this.options[i].id == this.dropdownDefaultValue)
if (this.options[i].id == this.dropdownDefaultValue)
{
defaultValue = this.options[i];
args.dropdownData[args.componentIndex] = defaultValue?.id;
@ -359,9 +363,11 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
const [lastSeenLabel, setLastSeenLabel] = useState("");
const [usingLabelAsTitle, setUsingLabelAsTitle] = useState(false);
const {helpHelpActive} = useContext(QContext);
function renderComponent(component: LabelComponent, componentIndex: number)
{
if(component && component.render)
if (component && component.render)
{
return component.render({navigate: navigate, widgetProps: props, dropdownData: dropdownData, componentIndex: componentIndex, reloadFunction: doReload});
}
@ -397,7 +403,7 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
// for initial render, put right-components from props into the state variable //
/////////////////////////////////////////////////////////////////////////////////
const stateLabelComponentsRight = [] as LabelComponent[];
// console.log(`${props.widgetMetaData.name} init'ing right-components`);
// console.log(`${props.widgetMetaData.name} initiating right-components`);
if (props.labelAdditionalComponentsRight)
{
props.labelAdditionalComponentsRight.map((component) => stateLabelComponentsRight.push(component));
@ -431,11 +437,11 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
{
// console.log(`${props.widgetMetaData.name} building a Dropdown, data is: ${dropdownData}`);
let defaultValue = null;
if(props.widgetData.dropdownDefaultValueList && props.widgetData.dropdownDefaultValueList.length >= index)
if (props.widgetData.dropdownDefaultValueList && props.widgetData.dropdownDefaultValueList.length >= index)
{
defaultValue = props.widgetData.dropdownDefaultValueList[index];
}
if(props.widgetData?.dropdownLabelList && props.widgetData?.dropdownLabelList[index] && props.widgetMetaData?.dropdowns && props.widgetMetaData?.dropdowns[index] && props.widgetData?.dropdownNameList && props.widgetData?.dropdownNameList[index])
if (props.widgetData?.dropdownLabelList && props.widgetData?.dropdownLabelList[index] && props.widgetMetaData?.dropdowns && props.widgetMetaData?.dropdowns[index] && props.widgetData?.dropdownNameList && props.widgetData?.dropdownNameList[index])
{
updatedStateLabelComponentsRight.push(new Dropdown(props.widgetData.dropdownLabelList[index], props.widgetMetaData.dropdowns[index], dropdownData, defaultValue, props.widgetData.dropdownNameList[index], handleDataChange));
}
@ -550,7 +556,7 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
let localLabelAdditionalElementsLeft = [...props.labelAdditionalElementsLeft];
if (props.widgetMetaData?.showExportButton && props.widgetMetaData?.type !== "table" && props.widgetMetaData?.type !== "childRecordList")
{
if(!localLabelAdditionalElementsLeft)
if (!localLabelAdditionalElementsLeft)
{
localLabelAdditionalElementsLeft = [];
}
@ -585,12 +591,12 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
const isParentWidget = props.widgetMetaData.type == "parentWidget"; // todo - do we need to know top-level parent, vs. a nested parent?
let labelToUse = props.widgetData?.label ?? props.widgetMetaData?.label;
if(!labelToUse)
if (!labelToUse)
{
/////////////////////////////////////////////////////////////////////////////////////////////
// prevent the label from disappearing, especially when it's being used as the page header //
/////////////////////////////////////////////////////////////////////////////////////////////
if(lastSeenLabel && isParentWidget && usingLabelAsTitle)
if (lastSeenLabel && isParentWidget && usingLabelAsTitle)
{
labelToUse = lastSeenLabel;
}
@ -602,15 +608,32 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
</Typography>
);
if(labelToUse && labelToUse != lastSeenLabel)
let sublabelElement = (
<Box height="20px">
<Typography sx={{position: "relative", top: "-18px"}} variant="caption">
{props.widgetData?.sublabel}
</Typography>
</Box>
);
if (labelToUse && labelToUse != lastSeenLabel)
{
setLastSeenLabel(labelToUse)
setLastSeenLabel(labelToUse);
setUsingLabelAsTitle(props.widgetData.isLabelPageTitle);
}
if (props.widgetMetaData.tooltip)
const helpRoles = ["ALL_SCREENS"]
const slotName = "label";
const showHelp = helpHelpActive || hasHelpContent(props.widgetMetaData?.helpContent?.get(slotName), helpRoles);
if(showHelp)
{
labelElement = <Tooltip title={props.widgetMetaData.tooltip} arrow={false} followCursor={true} placement="bottom-start">{labelElement}</Tooltip>;
const formattedHelpContent = <HelpContent helpContents={props.widgetMetaData?.helpContent?.get(slotName)} roles={helpRoles} helpContentKey={`widget:${props.widgetMetaData?.name};slot:${slotName}`} />;
labelElement = <Tooltip title={formattedHelpContent} arrow={true} placement="bottom-start">{labelElement}</Tooltip>;
}
else if (props.widgetMetaData?.tooltip)
{
labelElement = <Tooltip title={props.widgetMetaData.tooltip} arrow={true} placement="bottom-start">{labelElement}</Tooltip>;
}
const isTable = props.widgetMetaData.type == "table";
@ -621,56 +644,63 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
{
needLabelBox &&
<Box display="flex" justifyContent="space-between" alignItems="flex-start" sx={{width: "100%", ...props.labelBoxAdditionalSx}} minHeight={"2.5rem"}>
<Box display="flex" alignItems="baseline">
{
hasPermission ?
props.widgetMetaData?.icon && (
<Box ml={1} mr={2} mt={-4} sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
width: "64px",
height: "64px",
borderRadius: "8px",
background: colors.info.main,
color: "#ffffff",
float: "left"
}}
>
<Icon fontSize="medium" color="inherit">
{props.widgetMetaData.icon}
</Icon>
</Box>
) :
(
<Box ml={3} mt={-4} sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
width: "64px",
height: "64px",
borderRadius: "8px",
background: colors.info.main,
color: "#ffffff",
float: "left"
}}
>
<Icon fontSize="medium" color="inherit">lock</Icon>
</Box>
<Box display="flex" flexDirection="column">
<Box display="flex" alignItems="baseline">
{
hasPermission ?
props.widgetMetaData?.icon && (
<Box ml={1} mr={2} mt={-4} sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
width: "64px",
height: "64px",
borderRadius: "8px",
background: colors.info.main,
color: "#ffffff",
float: "left"
}}
>
<Icon fontSize="medium" color="inherit">
{props.widgetMetaData.icon}
</Icon>
</Box>
) :
(
<Box ml={3} mt={-4} sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
width: "64px",
height: "64px",
borderRadius: "8px",
background: colors.info.main,
color: "#ffffff",
float: "left"
}}
>
<Icon fontSize="medium" color="inherit">lock</Icon>
</Box>
)
}
{
hasPermission && labelToUse && (labelElement)
}
{
hasPermission && (
labelComponentsLeft.map((component, i) =>
{
return (<React.Fragment key={i}>{renderComponent(component, i)}</React.Fragment>);
})
)
}
{
hasPermission && labelToUse && (labelElement)
}
{
hasPermission && (
labelComponentsLeft.map((component, i) =>
{
return (<React.Fragment key={i}>{renderComponent(component, i)}</React.Fragment>);
})
)
}
{localLabelAdditionalElementsLeft}
}
{localLabelAdditionalElementsLeft}
</Box>
<Box display="flex">
{
hasPermission && props.widgetData?.sublabel && (sublabelElement)
}
</Box>
</Box>
<Box>
{
@ -727,7 +757,7 @@ function Widget(props: React.PropsWithChildren<Props>): JSX.Element
// try to make tables fill their entire "parent" //
///////////////////////////////////////////////////
let noCardMarginBottom = "unset";
if(isTable)
if (isTable)
{
noCardMarginBottom = "-8px";
}

View File

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

View File

@ -20,14 +20,18 @@
*/
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
import {Tooltip} from "@mui/material";
import React, {ReactElement} from "react";
import React, {ReactElement, useContext} from "react";
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";
interface BlockElementWrapperProps
{
data: BlockData;
metaData: QWidgetMetaData;
slot: string
linkProps?: any;
children: ReactElement;
@ -36,8 +40,10 @@ interface BlockElementWrapperProps
/*******************************************************************************
** 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 tooltip: BlockTooltip;
@ -61,6 +67,26 @@ export default function BlockElementWrapper({data, slot, linkProps, children}: B
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;
if(link)

View File

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

View File

@ -28,19 +28,19 @@ import {StandardBlockComponentProps} from "qqq/components/widgets/blocks/BlockMo
**
** ${number} ${icon}
*******************************************************************************/
export default function NumberIconBadgeBlock({data}: StandardBlockComponentProps): JSX.Element
export default function NumberIconBadgeBlock({widgetMetaData, data}: StandardBlockComponentProps): JSX.Element
{
return (
<div style={{display: "inline-block", whiteSpace: "nowrap", color: data.styles.color}}>
{
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>
</BlockElementWrapper>
}
{
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>
</BlockElementWrapper>
}

View File

@ -35,14 +35,14 @@ import {StandardBlockComponentProps} from "qqq/components/widgets/blocks/BlockMo
** ${heading}
** ${bar} ${value}
*******************************************************************************/
export default function ProgressBarBlock({data}: StandardBlockComponentProps): JSX.Element
export default function ProgressBarBlock({widgetMetaData, data}: StandardBlockComponentProps): JSX.Element
{
return (
<Typography component="div" variant="button" color="text" fontWeight="light" sx={{textTransform: "none"}}>
{
data.values.heading &&
<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>
</BlockElementWrapper>
</div>
@ -50,7 +50,7 @@ export default function ProgressBarBlock({data}: StandardBlockComponentProps): J
<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"}}>
{
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>
<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>
</BlockElementWrapper>
</div>

View File

@ -29,7 +29,7 @@ import {StandardBlockComponentProps} from "qqq/components/widgets/blocks/BlockMo
**
** ${label} ${value}
*******************************************************************************/
export default function TableSubRowDetailRowBlock({data}: StandardBlockComponentProps): JSX.Element
export default function TableSubRowDetailRowBlock({widgetMetaData, data}: StandardBlockComponentProps): JSX.Element
{
return (
<div style={{display: "flex", maxWidth: "calc(100% - 24px)", justifyContent: "space-between"}}>
@ -37,7 +37,7 @@ export default function TableSubRowDetailRowBlock({data}: StandardBlockComponent
{
data.values.label &&
<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>
</BlockElementWrapper>
</div>
@ -45,7 +45,7 @@ export default function TableSubRowDetailRowBlock({data}: StandardBlockComponent
{
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>
</BlockElementWrapper>
}

View File

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

View File

@ -35,7 +35,7 @@ import {StandardBlockComponentProps} from "qqq/components/widgets/blocks/BlockMo
** ${icon} ${number}
** ${context}
*******************************************************************************/
export default function UpOrDownNumberBlock({data}: StandardBlockComponentProps): JSX.Element
export default function UpOrDownNumberBlock({widgetMetaData, data}: StandardBlockComponentProps): JSX.Element
{
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", 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>
<span style={{color: goodOrBadColor}}>{data.values.number}</span>
@ -70,7 +70,7 @@ export default function UpOrDownNumberBlock({data}: StandardBlockComponentProps)
</div>
<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>
</BlockElementWrapper>
</div>

View File

@ -39,65 +39,79 @@ ChartJS.register(
Legend
);
export const options = {
maintainAspectRatio: false,
responsive: true,
animation: {
duration: 0
},
elements: {
bar: {
borderRadius: 4
}
},
plugins: {
tooltip: {
// todo - some configs around this
callbacks: {
title: function(context: any)
{
return ("");
},
label: function(context: any)
{
if(context.dataset.label.startsWith(context.label))
{
return `${context.label}: ${context.formattedValue}`;
}
else
export const makeOptions = (data: DefaultChartData) =>
{
return({
maintainAspectRatio: false,
responsive: true,
animation: {
duration: 0
},
elements: {
bar: {
borderRadius: 4
}
},
onHover: function (event: any, elements: any[], chart: any)
{
if(event.type == "mousemove" && elements.length > 0 && data.urls && data.urls.length > elements[0].index && data.urls[elements[0].index])
{
chart.canvas.style.cursor = "pointer";
}
else
{
chart.canvas.style.cursor = "default";
}
},
plugins: {
tooltip: {
// todo - some configs around this
callbacks: {
title: function(context: any)
{
return ("");
},
label: function(context: any)
{
if(context.dataset.label.startsWith(context.label))
{
return `${context.label}: ${context.formattedValue}`;
}
else
{
return ("");
}
}
}
},
legend: {
position: "bottom",
labels: {
usePointStyle: true,
pointStyle: "circle",
boxHeight: 6,
boxWidth: 6,
padding: 12,
font: {
size: 14
}
}
}
},
legend: {
position: "bottom",
labels: {
usePointStyle: true,
pointStyle: "circle",
boxHeight: 6,
boxWidth: 6,
padding: 12,
font: {
size: 14
}
}
}
},
scales: {
x: {
stacked: true,
grid: {display: false},
ticks: {autoSkip: false, maxRotation: 90}
scales: {
x: {
stacked: true,
grid: {display: false},
ticks: {autoSkip: false, maxRotation: 90}
},
y: {
stacked: true,
position: "right",
ticks: {precision: 0}
},
},
y: {
stacked: true,
position: "right",
ticks: {precision: 0}
},
},
};
});
}
interface Props
{
@ -151,7 +165,7 @@ function StackedBarChart({data, chartSubheaderData}: Props): JSX.Element
<Box>
{chartSubheaderData && (<ChartSubheaderWithData chartSubheaderData={chartSubheaderData} />)}
<Box width="100%" height="300px">
<Bar data={data} options={options} getElementsAtEvent={handleClick} />
<Bar data={data} options={makeOptions(data)} getElementsAtEvent={handleClick} />
</Box>
</Box>
) : <Skeleton sx={{marginLeft: "20px", marginRight: "20px", height: "200px"}} />;

View File

@ -70,7 +70,7 @@ function PieChart({description, chartData, chartSubheaderData}: Props): JSX.Elem
chartData.dataset.backgroundColors = chartColors;
}
}
const {data, options} = configs(chartData?.labels || [], chartData?.dataset || {});
const {data, options} = configs(chartData?.labels || [], chartData?.dataset || {}, chartData?.dataset?.urls);
useEffect(() =>
{

View File

@ -23,7 +23,7 @@ import colors from "qqq/assets/theme/base/colors";
const {gradients, dark} = colors;
function configs(labels: any, datasets: any)
function configs(labels: any, datasets: any, urls: string[] | undefined)
{
const backgroundColors = [];
@ -66,6 +66,17 @@ function configs(labels: any, datasets: any)
options: {
maintainAspectRatio: false,
responsive: true,
onHover: function (event: any, elements: any[], chart: any)
{
if(event.type == "mousemove" && elements.length > 0 && urls && urls.length > elements[0].index && urls[elements[0].index])
{
chart.canvas.style.cursor = "pointer";
}
else
{
chart.canvas.style.cursor = "default";
}
},
plugins: {
tooltip: {
callbacks: {

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 {QFilterOrderBy} from "@kingsrook/qqq-frontend-core/lib/model/query/QFilterOrderBy";
import {QQueryFilter} from "@kingsrook/qqq-frontend-core/lib/model/query/QQueryFilter";
import {Chip} from "@mui/material";
import Alert from "@mui/material/Alert";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Chip from "@mui/material/Chip";
import Divider from "@mui/material/Divider";
import Grid from "@mui/material/Grid";
import Icon from "@mui/material/Icon";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemAvatar from "@mui/material/ListItemAvatar";
@ -42,8 +41,6 @@ import Snackbar from "@mui/material/Snackbar";
import Tab from "@mui/material/Tab";
import Tabs from "@mui/material/Tabs";
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 DataBagPreview from "qqq/components/databags/DataBagPreview";
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-json";
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";
const qController = Client.getInstance();
@ -64,12 +63,11 @@ const qController = Client.getInstance();
// Declaring props types for ViewForm
interface Props
{
dataBagId: number
dataBagId: number;
}
DataBagViewer.defaultProps =
{
};
{};
export default function DataBagViewer({dataBagId}: Props): JSX.Element
{
@ -77,12 +75,12 @@ export default function DataBagViewer({dataBagId}: Props): JSX.Element
const [asyncLoadInited, setAsyncLoadInited] = useState(false);
const [versionRecordList, setVersionRecordList] = useState(null as QRecord[]);
const [selectedVersionRecord, setSelectedVersionRecord] = useState(null as QRecord);
const [currentVersionId , setCurrentVersionId] = useState(null as number);
const [currentVersionId, setCurrentVersionId] = useState(null as number);
const [notFoundMessage, setNotFoundMessage] = useState(null);
const [selectedTab, setSelectedTab] = useState(0);
const [editorProps, setEditorProps] = useState(null as DataBagDataEditorProps);
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 [loadingSelectedVersion, _] = useState(new LoadingState(forceUpdate, "loading"));
@ -100,13 +98,13 @@ export default function DataBagViewer({dataBagId}: Props): JSX.Element
const criteria = [new QFilterCriteria("dataBagId", QCriteriaOperator.EQUALS, [dataBagId])];
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);
console.log("Fetched versions:");
console.log(versions);
setVersionRecordList(versions);
if(versions && versions.length > 0)
if (versions && versions.length > 0)
{
setCurrentVersionId(versions[0].values.get("id"));
const latestVersion = await qController.get("dataBagVersion", versions[0].values.get("id"));
@ -362,7 +360,7 @@ export default function DataBagViewer({dataBagId}: Props): JSX.Element
<Typography variant="h6" pl={3}>Data Preview (Version {selectedVersionRecord?.values?.get("sequenceNo")})</Typography>
</Box>
<Box height="400px" overflow="auto" ml={1} fontSize="14px">
{loadingSelectedVersion.isNotLoading() && selectedTab == 1 && selectedVersionRecord?.values?.get("data") && <DataBagPreview json={selectedVersionRecord?.values?.get("data")} /> }
{loadingSelectedVersion.isNotLoading() && selectedTab == 1 && selectedVersionRecord?.values?.get("data") && <DataBagPreview json={selectedVersionRecord?.values?.get("data")} />}
{loadingSelectedVersion.isLoadingSlow() && <Box pl={3}>Loading...</Box>}
</Box>
</Grid>
@ -377,7 +375,7 @@ export default function DataBagViewer({dataBagId}: Props): JSX.Element
<Modal open={editorProps !== null} onClose={(event, reason) => closeEditingScript(event, reason)}>
<DataBagDataEditor
closeCallback={closeEditingScript}
{... editorProps}
{...editorProps}
/>
</Modal>
}

View File

@ -25,28 +25,53 @@ import {QRecord} from "@kingsrook/qqq-frontend-core/lib/model/QRecord";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Icon from "@mui/material/Icon";
import IconButton from "@mui/material/IconButton";
import Tooltip from "@mui/material/Tooltip/Tooltip";
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 React, {useEffect, useRef, useState} from "react";
import {useNavigate, Link} from "react-router-dom";
import Widget, {AddNewRecordButton, LabelComponent} from "qqq/components/widgets/Widget";
import {DataGridPro, GridCallbackDetails, GridEventListener, GridRenderCellParams, GridRowParams, GridToolbarContainer, MuiEvent, useGridApiContext, useGridApiEventHandler} from "@mui/x-data-grid-pro";
import Widget, {AddNewRecordButton, LabelComponent, WidgetData} from "qqq/components/widgets/Widget";
import DataGridUtils from "qqq/utils/DataGridUtils";
import HtmlUtils from "qqq/utils/HtmlUtils";
import Client from "qqq/utils/qqq/Client";
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
{
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();
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 [rows, setRows] = useState([]);
@ -74,7 +99,7 @@ function RecordGridWidget({widgetMetaData, data}: Props): JSX.Element
}
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. //
@ -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);
setRecords(records)
setColumns(columns);
@ -195,7 +242,7 @@ function RecordGridWidget({widgetMetaData, data}: Props): JSX.Element
{
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) =>
{
if(disableRowClick)
{
return;
}
(async () =>
{
const qInstance = await qController.loadMetaData()
let tablePath = qInstance.getTablePathByName(data.childTableMetaData.name)
if(tablePath)
{
tablePath = `${tablePath}/${params.id}`;
tablePath = `${tablePath}/${params.row[data.childTableMetaData.primaryKeyField]}`;
DataGridUtils.handleRowClick(tablePath, event, gridMouseDownX, gridMouseDownY, navigate, instance);
}
})();
@ -266,6 +318,7 @@ function RecordGridWidget({widgetMetaData, data}: Props): JSX.Element
rowBuffer={10}
getRowClassName={(params) => (params.indexRelativeToCurrentPage % 2 === 0 ? "even" : "odd")}
onRowClick={handleRowClick}
getRowId={(row) => row.__rowIndex}
// getRowHeight={() => "auto"} // maybe nice? wraps values in cells...
components={{
Toolbar: CustomToolbar

View File

@ -46,9 +46,6 @@ import Snackbar from "@mui/material/Snackbar";
import Tab from "@mui/material/Tab";
import Tabs from "@mui/material/Tabs";
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 ScriptDocsForm from "qqq/components/scripts/ScriptDocsForm";
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-json";
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";
const qController = Client.getInstance();
@ -97,16 +97,16 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
const [versionRecordList, setVersionRecordList] = useState(null as QRecord[]);
const [selectedVersionRecord, setSelectedVersionRecord] = useState(null as QRecord);
const [scriptLogs, setScriptLogs] = useState({} as any);
const [scriptTypeRecord, setScriptTypeRecord] = useState(null as QRecord)
const [scriptTypeFileSchemaList, setScriptTypeFileSchemaList] = useState(null as QRecord[])
const [scriptTypeRecord, setScriptTypeRecord] = useState(null as QRecord);
const [scriptTypeFileSchemaList, setScriptTypeFileSchemaList] = useState(null as QRecord[]);
const [availableFileNames, setAvailableFileNames] = useState([] as string[]);
const [selectedFileName, setSelectedFileName] = useState("");
const [currentVersionId , setCurrentVersionId] = useState(null as number);
const [currentVersionId, setCurrentVersionId] = useState(null as number);
const [notFoundMessage, setNotFoundMessage] = useState(null);
const [selectedTab, setSelectedTab] = useState(0);
const [editorProps, setEditorProps] = useState(null as ScriptEditorProps);
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 [loadingSelectedVersion, _] = useState(new LoadingState(forceUpdate, "loading"));
@ -129,13 +129,13 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
let fileMode = scriptTypeRecord.values.get("fileMode");
let scriptTypeFileSchemaList: QRecord[] = null;
if(fileMode == 1) // SINGLE
if (fileMode == 1) // SINGLE
{
scriptTypeFileSchemaList = [new QRecord({values: {name: "Script.js", fileType: "javascript"}})];
}
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);
}
else // MULTI AD_HOC
@ -145,22 +145,22 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
}
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);
setSelectedFileName(availableFileNames[0])
setSelectedFileName(availableFileNames[0]);
}
const criteria = [new QFilterCriteria("scriptId", QCriteriaOperator.EQUALS, [scriptId])];
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);
console.log("Fetched versions:");
console.log(versions);
setVersionRecordList(versions);
if(versions && versions.length > 0)
if (versions && versions.length > 0)
{
selectVersion(versions[0]);
}
@ -253,31 +253,31 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
const handleSelectFile = (event: SelectChangeEvent) =>
{
setSelectedFileName(event.target.value);
}
};
const getSelectedFileCode = (): string =>
{
return (getSelectedVersionCode()[selectedFileName] ?? "");
}
};
const getSelectedFileType = (): string =>
{
for (let i = 0; i < scriptTypeFileSchemaList.length; i++)
{
let name = scriptTypeFileSchemaList[i].values.get("name");
if(name == selectedFileName)
if (name == selectedFileName)
{
return (scriptTypeFileSchemaList[i].values.get("fileType"));
}
}
return ("javascript"); // have some default...
}
};
const getSelectedVersionCode = (): {[name: string]: string} =>
const getSelectedVersionCode = (): { [name: string]: string } =>
{
let rs: {[name: string]: string} = {}
let files = selectedVersionRecord?.associatedRecords?.get("files")
let rs: { [name: string]: string } = {};
let files = selectedVersionRecord?.associatedRecords?.get("files");
for (let j = 0; j < files?.length; j++)
{
@ -286,7 +286,7 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
}
return (rs);
}
};
function getVersionsList(versionRecordList: QRecord[], selectedVersionRecord: QRecord)
{
@ -344,11 +344,11 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
const getScriptLogs = (scriptRevisionId: number) =>
{
if(!scriptLogs[scriptRevisionId])
if (!scriptLogs[scriptRevisionId])
{
(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);
setScriptLogs(scriptLogs);
forceUpdate();
@ -368,7 +368,7 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
}
return (<ScriptLogsView logs={logs} />);
}
};
let editButtonTooltip = "";
let editButtonText = "Create New Version";
@ -556,7 +556,7 @@ export default function ScriptViewer({scriptId, associatedScriptTableName, assoc
<Modal open={editorProps !== null} onClose={(event, reason) => closeEditingScript(event, reason)}>
<ScriptEditor
closeCallback={closeEditingScript}
{... editorProps}
{...editorProps}
/>
</Modal>
}

View File

@ -30,8 +30,8 @@ import TableContainer from "@mui/material/TableContainer";
import TableRow from "@mui/material/TableRow";
import Tooltip from "@mui/material/Tooltip";
import parse from "html-react-parser";
import {useEffect, useMemo, useState} from "react";
import {useAsyncDebounce, useGlobalFilter, usePagination, useSortBy, useTable, useExpanded} from "react-table";
import React, {useEffect, useMemo, useState} from "react";
import {useAsyncDebounce, useExpanded, useGlobalFilter, usePagination, useSortBy, useTable} from "react-table";
import colors from "qqq/assets/theme/base/colors";
import MDInput from "qqq/components/legacy/MDInput";
import MDPagination from "qqq/components/legacy/MDPagination";
@ -173,6 +173,17 @@ function DataTable({
);
}
if(table.columnHeaderTooltips)
{
for (let column of columnsToMemo)
{
if(table.columnHeaderTooltips[column.accessor])
{
column.tooltip = table.columnHeaderTooltips[column.accessor];
}
}
}
const columns = useMemo<any>(() => columnsToMemo, [table]);
const data = useMemo<any>(() => table.rows, [table]);
const gridTemplateColumns = widths.join(" ");
@ -324,6 +335,7 @@ function DataTable({
{...column.getHeaderProps(isSorted && column.getSortByToggleProps())}
align={column.align ? column.align : "left"}
sorted={setSortedValue(column)}
tooltip={column.tooltip}
>
{column.render("header")}
</DataTableHeadCell>

View File

@ -43,6 +43,7 @@ import Client from "qqq/utils/qqq/Client";
export interface TableDataInput
{
columns: { [key: string]: any }[];
columnHeaderTooltips?: { [columnName: string]: string | JSX.Element }
rows: { [key: string]: any }[];
}

View File

@ -23,7 +23,9 @@
import {QWidgetMetaData} from "@kingsrook/qqq-frontend-core/lib/model/metaData/QWidgetMetaData";
// @ts-ignore
import {htmlToText} from "html-to-text";
import React, {useEffect, useState} from "react";
import React, {useContext, useEffect, useState} from "react";
import QContext from "QContext";
import HelpContent, {hasHelpContent} from "qqq/components/misc/HelpContent";
import TableCard from "qqq/components/widgets/tables/TableCard";
import Widget, {WidgetData} from "qqq/components/widgets/Widget";
import {WidgetUtils} from "qqq/components/widgets/WidgetUtils";
@ -46,6 +48,7 @@ function TableWidget(props: Props): JSX.Element
const [isExportDisabled, setIsExportDisabled] = useState(false); // hmm, would like true here, but it broke...
const [csv, setCsv] = useState(null as string);
const [fileName, setFileName] = useState(null as string);
const {helpHelpActive} = useContext(QContext);
const rows = props.widgetData?.rows;
const columns = props.widgetData?.columns;
@ -133,6 +136,23 @@ function TableWidget(props: Props): JSX.Element
labelAdditionalElementsLeft.push(WidgetUtils.generateExportButton(onExportClick));
}
//////////////////////////////////////////////////////
// look for column-header tooltips from helpContent //
//////////////////////////////////////////////////////
const columnHeaderTooltips: {[columnName: string]: JSX.Element} = {}
for (let column of props.widgetData?.columns ?? [])
{
const helpRoles = ["ALL_SCREENS"]
const slotName = `columnHeader=${column.accessor}`;
const showHelp = helpHelpActive || hasHelpContent(props.widgetMetaData?.helpContent?.get(slotName), helpRoles);
if(showHelp)
{
const formattedHelpContent = <HelpContent helpContents={props.widgetMetaData?.helpContent?.get(slotName)} roles={helpRoles} helpContentKey={`widget:${props.widgetMetaData?.name};slot:${slotName}`} />;
columnHeaderTooltips[column.accessor] = formattedHelpContent;
}
}
return (
<Widget
widgetMetaData={props.widgetMetaData}
@ -148,7 +168,7 @@ function TableWidget(props: Props): JSX.Element
hidePaginationDropdown={props.widgetData?.hidePaginationDropdown}
fixedStickyLastRow={props.widgetData?.fixedStickyLastRow}
fixedHeight={props.widgetData?.fixedHeight}
data={{columns: props.widgetData?.columns, rows: props.widgetData?.rows}}
data={{columns: props.widgetData?.columns, rows: props.widgetData?.rows, columnHeaderTooltips: columnHeaderTooltips}}
widgetMetaData={props.widgetMetaData}
/>
</Widget>

View File

@ -22,6 +22,7 @@
import Box from "@mui/material/Box";
import Icon from "@mui/material/Icon";
import {Theme} from "@mui/material/styles";
import Tooltip from "@mui/material/Tooltip";
import {ReactNode} from "react";
import colors from "qqq/assets/theme/base/colors";
import {useMaterialUIController} from "qqq/context";
@ -33,9 +34,10 @@ interface Props
children: ReactNode;
sorted?: false | "none" | "asce" | "desc";
align?: "left" | "right" | "center";
tooltip?: string | JSX.Element;
}
function DataTableHeadCell({width, children, sorted, align, ...rest}: Props): JSX.Element
function DataTableHeadCell({width, children, sorted, align, tooltip, ...rest}: Props): JSX.Element
{
const [controller] = useMaterialUIController();
const {darkMode} = controller;
@ -73,39 +75,43 @@ function DataTableHeadCell({width, children, sorted, align, ...rest}: Props): JS
userSelect: sorted && "none",
})}
>
{children}
{sorted && (
<Box
position="absolute"
top={0}
right={align !== "right" ? "16px" : 0}
left={align === "right" ? "-5px" : "unset"}
sx={({typography: {size}}: any) => ({
fontSize: size.lg,
})}
>
<>
{
tooltip ? <Tooltip title={tooltip}><span style={{cursor: "default"}}>{children}</span></Tooltip> : children
}
{sorted && (
<Box
sx={{
position: "absolute",
top: -6,
color: sorted === "asce" ? "text" : "secondary",
opacity: sorted === "asce" ? 1 : 0.5
}}
position="absolute"
top={0}
right={align !== "right" ? "16px" : 0}
left={align === "right" ? "-5px" : "unset"}
sx={({typography: {size}}: any) => ({
fontSize: size.lg,
})}
>
<Icon>arrow_drop_up</Icon>
<Box
sx={{
position: "absolute",
top: -6,
color: sorted === "asce" ? "text" : "secondary",
opacity: sorted === "asce" ? 1 : 0.5
}}
>
<Icon>arrow_drop_up</Icon>
</Box>
<Box
sx={{
position: "absolute",
top: 0,
color: sorted === "desc" ? "text" : "secondary",
opacity: sorted === "desc" ? 1 : 0.5
}}
>
<Icon>arrow_drop_down</Icon>
</Box>
</Box>
<Box
sx={{
position: "absolute",
top: 0,
color: sorted === "desc" ? "text" : "secondary",
opacity: sorted === "desc" ? 1 : 0.5
}}
>
<Icon>arrow_drop_down</Icon>
</Box>
</Box>
)}
)}
</>
</Box>
</Box>
);

View File

@ -77,9 +77,11 @@ function AppHome({app}: Props): JSX.Element
const mdbMetaData = app?.supplementalAppMetaData?.get("materialDashboard");
let showAppLabelOnHomeScreen = true;
let includeTableCountsOnHomeScreen = true;
if(mdbMetaData)
{
showAppLabelOnHomeScreen = mdbMetaData.showAppLabelOnHomeScreen;
includeTableCountsOnHomeScreen = mdbMetaData.includeTableCountsOnHomeScreen;
}
useEffect(() =>
@ -129,48 +131,60 @@ function AppHome({app}: Props): JSX.Element
const tableCountTexts = new Map<string, string>();
newTables.forEach((table) =>
{
tableCounts.set(table.name, {isLoading: true, value: null});
setTimeout(async () =>
if(includeTableCountsOnHomeScreen)
{
const tableMetaData = await qController.loadTableMetaData(table.name);
let countResult = null;
if(tableMetaData.capabilities.has(Capability.TABLE_COUNT) && tableMetaData.readPermission)
tableCounts.set(table.name, {isLoading: true, value: null});
setTimeout(async () =>
{
try
const tableMetaData = await qController.loadTableMetaData(table.name);
let countResult = null;
if (tableMetaData.capabilities.has(Capability.TABLE_COUNT) && tableMetaData.readPermission)
{
[countResult] = await qController.count(table.name);
try
{
[countResult] = await qController.count(table.name);
if (countResult !== null && countResult !== undefined)
{
tableCountNumbers.set(table.name, countResult.toLocaleString());
tableCountTexts.set(table.name, countResult === 1 ? "total record" : "total records");
if (countResult !== null && countResult !== undefined)
{
tableCountNumbers.set(table.name, countResult.toLocaleString());
tableCountTexts.set(table.name, countResult === 1 ? "total record" : "total records");
}
else
{
tableCountNumbers.set(table.name, "");
tableCountTexts.set(table.name, " ");
}
}
else
catch (e)
{
console.log("Caught: " + e);
tableCountNumbers.set(table.name, "");
tableCountTexts.set(table.name, " ");
}
}
catch(e)
else
{
console.log("Caught: " + e);
tableCountNumbers.set(table.name, "");
tableCountTexts.set(table.name, " ");
}
}
else
{
tableCountNumbers.set(table.name, "");
tableCountTexts.set(table.name, " ");
}
tableCounts.set(table.name, {isLoading: false, value: countResult});
tableCounts.set(table.name, {isLoading: false, value: countResult});
setTableCounts(tableCounts);
setTableCountNumbers(tableCountNumbers);
setTableCountTexts(tableCountTexts);
setUpdatedTableCounts(new Date());
}, 1);
}
else
{
tableCounts.set(table.name, {isLoading: false, value: null});
tableCountNumbers.set(table.name, " ");
tableCountTexts.set(table.name, " ");
setTableCounts(tableCounts);
setTableCountNumbers(tableCountNumbers);
setTableCountTexts(tableCountTexts);
setUpdatedTableCounts(new Date());
}, 1);
}
});
setTableCounts(tableCounts);
@ -299,7 +313,7 @@ function AppHome({app}: Props): JSX.Element
</Box>
{
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>
</Box>
) : null
@ -340,7 +354,7 @@ function AppHome({app}: Props): JSX.Element
}
{
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>
</Box>
) : null
@ -383,7 +397,7 @@ function AppHome({app}: Props): JSX.Element
}
{
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>
</Box>
) : null
@ -395,6 +409,13 @@ function AppHome({app}: Props): JSX.Element
section.tables.map((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 (
<Grid key={table.name} item xs={12} md={12} lg={tileSizeLg}>
{hasTablePermission(tableName) ?
@ -402,8 +423,8 @@ function AppHome({app}: Props): JSX.Element
<Box className="big-icon" mb={3}>
<MiniStatisticsCard
title={{fontWeight: "bold", text: table.label}}
count={!tableCounts.has(table.name) || tableCounts.get(table.name).isLoading ? "..." : (tableCountNumbers.get(table.name))}
percentage={{color: "info", text: (!tableCounts.has(table.name) || tableCounts.get(table.name).isLoading ? "" : (tableCountTexts.get(table.name)))}}
count={count}
percentage={{color: "info", text: percentage}}
icon={{color: "info", component: <Icon>{table.iconName || app.iconName}</Icon>}}
/>
</Box>
@ -411,8 +432,8 @@ function AppHome({app}: Props): JSX.Element
<Box mb={3} title="You do not have permission to access this table">
<MiniStatisticsCard
title={{fontWeight: "bold", text: table.label}}
count={!tableCounts.has(table.name) || tableCounts.get(table.name).isLoading ? "..." : (tableCountNumbers.get(table.name))}
percentage={{color: "info", text: (!tableCounts.has(table.name) || tableCounts.get(table.name).isLoading ? "" : (tableCountTexts.get(table.name)))}}
count={count}
percentage={{color: "info", text: percentage}}
icon={{color: "info", component: <Icon>{table.iconName || app.iconName}</Icon>}}
isDisabled={true}
/>

View File

@ -44,11 +44,9 @@ import LinearProgress from "@mui/material/LinearProgress";
import MenuItem from "@mui/material/MenuItem";
import Modal from "@mui/material/Modal";
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 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 colors from "qqq/assets/theme/base/colors";
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 TableUtils from "qqq/utils/qqq/TableUtils";
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 DENSITY_LOCAL_STORAGE_KEY_ROOT = "qqq.density";
@ -112,7 +112,7 @@ const getLoadingScreen = () =>
return (<BaseLayout>
&nbsp;
</BaseLayout>);
}
};
/*******************************************************************************
@ -139,16 +139,16 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// manage "state" being passed from some screens (like delete) into query screen - by grabbing, and then deleting //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(location.state)
if (location.state)
{
let state: any = location.state;
if(state["deleteSuccess"])
if (state["deleteSuccess"])
{
setShowSuccessfullyDeletedAlert(true);
delete state["deleteSuccess"];
}
if(state["warning"])
if (state["warning"])
{
setWarningAlert(state["warning"]);
delete state["warning"];
@ -168,7 +168,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
// define some default values (e.g., to be used if nothing in local storage or no active view) //
/////////////////////////////////////////////////////////////////////////////////////////////////
let defaultSort = [] as GridSortItem[];
let defaultRowsPerPage = 10;
let defaultRowsPerPage = 50;
let defaultDensity = "standard" as GridDensity;
let defaultTableVariant: QTableVariant = null;
let defaultMode = "basic";
@ -181,7 +181,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const densityLocalStorageKey = `${DENSITY_LOCAL_STORAGE_KEY_ROOT}`;
// only load things out of local storage on the first render
if(firstRender)
if (firstRender)
{
console.log("This is firstRender, so reading defaults from local storage...");
if (localStorage.getItem(densityLocalStorageKey))
@ -200,7 +200,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setFirstRender(false);
}
if(defaultView == null)
if (defaultView == null)
{
defaultView = new RecordQueryView();
defaultView.queryFilter = new QQueryFilter();
@ -214,15 +214,15 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////////////////////////////////////////////////////////////////////
// in case the view is missing any of these attributes, give them a reasonable default //
/////////////////////////////////////////////////////////////////////////////////////////
if(!defaultView.rowsPerPage)
if (!defaultView.rowsPerPage)
{
defaultView.rowsPerPage = defaultRowsPerPage;
}
if(!defaultView.mode)
if (!defaultView.mode)
{
defaultView.mode = defaultMode;
}
if(!defaultView.quickFilterFieldNames)
if (!defaultView.quickFilterFieldNames)
{
defaultView.quickFilterFieldNames = [];
}
@ -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. //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const [pageState, setPageState] = useState("initial" as PageState)
const [pageState, setPageState] = useState("initial" as PageState);
/////////////////////////////////
// meta-data and derived state //
@ -260,8 +260,8 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////////////////////////////
// state of the view of the query screen //
///////////////////////////////////////////
const [view, setView] = useState(defaultView)
const [viewAsJson, setViewAsJson] = useState(JSON.stringify(defaultView))
const [view, setView] = useState(defaultView);
const [viewAsJson, setViewAsJson] = useState(JSON.stringify(defaultView));
const [queryFilter, setQueryFilter] = useState(defaultView.queryFilter);
const [queryColumns, setQueryColumns] = useState(defaultView.queryColumns);
const [lastFetchedQFilterJSON, setLastFetchedQFilterJSON] = useState("");
@ -309,7 +309,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////////////////////
const [columnStatsFieldName, setColumnStatsFieldName] = useState(null as string);
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);
///////////////////////////////////////////////////
@ -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 //
///////////////////////////////////////////////////////////////////////////////////////////
const [pageLoadingState, _] = useState(new LoadingState(forceUpdate))
const [pageLoadingState, _] = useState(new LoadingState(forceUpdate));
if(isFirstRenderAfterChangingTables)
if (isFirstRenderAfterChangingTables)
{
setIsFirstRenderAfterChangingTables(false);
console.log("This is the first render after changing tables - so - setting state based on 'defaults' from localStorage");
setView(defaultView)
setView(defaultView);
}
/*******************************************************************************
@ -386,7 +386,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const criteria = queryFilter.criteria[i];
const {criteriaIsValid} = validateCriteria(criteria, null);
const fieldName = criteria.fieldName;
if(criteriaIsValid && fieldName && fieldName.indexOf(".") > -1)
if (criteriaIsValid && fieldName && fieldName.indexOf(".") > -1)
{
visibleJoinTables.add(fieldName.split(".")[0]);
}
@ -407,7 +407,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const join = tableMetaData.exposedJoins[i];
if (visibleJoinTables.has(join.joinTable.name))
{
if(join.isMany)
if (join.isMany)
{
return (true);
}
@ -415,7 +415,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
}
}
return (false);
}
};
/*******************************************************************************
@ -423,7 +423,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
*******************************************************************************/
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++)
{
const criteria = sourceFilter.criteria[i];
@ -442,7 +442,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 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)));
}
}
@ -451,7 +451,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
filterForBackend.limit = rowsPerPage;
return filterForBackend;
}
};
/*******************************************************************************
@ -475,7 +475,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////////////////////////////
// build the export menu, for the header //
///////////////////////////////////////////
let exportMenu = <></>
let exportMenu = <></>;
try
{
const exportMenuItemRestProps =
@ -485,7 +485,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
columnsModel: columnsModel,
columnVisibilityModel: columnVisibilityModel,
queryFilter: prepQueryFilterForBackend(queryFilter)
}
};
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>
@ -503,7 +503,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
</Menu>
</>);
}
catch(e)
catch (e)
{
console.log("Error preparing export menu for page header: " + e);
}
@ -515,7 +515,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
{
let label: string = tableMetaData?.label ?? "";
if(currentSavedView?.values?.get("label"))
if (currentSavedView?.values?.get("label"))
{
label += " / " + currentSavedView?.values?.get("label");
}
@ -536,12 +536,12 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
}
let joinLabelsString = joinLabels.join(", ");
if(joinLabels.length == 2)
if (joinLabels.length == 2)
{
let lastCommaIndex = joinLabelsString.lastIndexOf(",");
joinLabelsString = joinLabelsString.substring(0, lastCommaIndex) + " and " + joinLabelsString.substring(lastCommaIndex + 1);
}
if(joinLabels.length > 2)
if (joinLabels.length > 2)
{
let lastCommaIndex = joinLabelsString.lastIndexOf(",");
joinLabelsString = joinLabelsString.substring(0, lastCommaIndex) + ", and " + joinLabelsString.substring(lastCommaIndex + 1);
@ -552,9 +552,9 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
<ul style={{marginLeft: "1rem"}}>
{joinLabels.map((name) => <li key={name}>{name}</li>)}
</ul>
</div>
</div>;
return(
return (
<div>
{label} {exportMenu}
<CustomWidthTooltip title={tooltipHTML}>
@ -586,7 +586,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
</Tooltip>
</Typography>
);
}
};
///////////////////////
// Keyboard handling //
@ -598,42 +598,45 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const type = (e.target as any).type;
const validType = (type !== "text" && type !== "textarea" && type !== "input" && type !== "search");
if(validType && !dotMenuOpen && !keyboardHelpOpen && !activeModalProcess)
if (validType && !dotMenuOpen && !keyboardHelpOpen && !activeModalProcess)
{
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`);
}
else if (! e.metaKey && e.key === "r")
else if (!e.metaKey && e.key === "r")
{
e.preventDefault()
e.preventDefault();
updateTable("'r' keyboard event");
}
/*
// disable until we add a ... ref down to let us programmatically open Columns button
else if (! e.metaKey && e.key === "c")
{
e.preventDefault()
gridApiRef.current.showPreferences(GridPreferencePanelsValue.columns)
}
else if (! e.metaKey && e.key === "f")
*/
else if (!e.metaKey && e.key === "f")
{
e.preventDefault()
e.preventDefault();
// @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 () =>
{
document.removeEventListener("keydown", down)
}
}, [dotMenuOpen, keyboardHelpOpen, metaData, activeModalProcess])
document.removeEventListener("keydown", down);
};
}, [dotMenuOpen, keyboardHelpOpen, metaData, activeModalProcess]);
/*******************************************************************************
@ -642,7 +645,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const urlLooksLikeProcess = (): boolean =>
{
return (pathParts[pathParts.length - 2] === tableName);
}
};
//////////////////////////////////////////////////////////////////////////////////////////////
// monitor location changes - if our url looks like a savedView, then load that view, kinda //
@ -700,7 +703,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setView(view);
setViewAsJson(JSON.stringify(view));
localStorage.setItem(viewLocalStorageKey, JSON.stringify(view));
}
};
/*******************************************************************************
@ -709,10 +712,10 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const handleColumnVisibilityChange = (columnVisibilityModel: GridColumnVisibilityModel) =>
{
setColumnVisibilityModel(columnVisibilityModel);
queryColumns.updateVisibility(columnVisibilityModel)
queryColumns.updateVisibility(columnVisibilityModel);
view.queryColumns = queryColumns;
doSetView(view)
doSetView(view);
forceUpdate();
};
@ -727,12 +730,12 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
// set the field's value in the view //
///////////////////////////////////////
let fieldName = field.name;
if(table && table.name != tableMetaData.name)
if (table && table.name != tableMetaData.name)
{
fieldName = `${table.name}.${field.name}`;
}
view.queryColumns.setIsVisible(fieldName, newValue)
view.queryColumns.setIsVisible(fieldName, newValue);
/////////////////////
// update the grid //
@ -742,13 +745,13 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////////////////////////////
// update the view (e.g., write local storage) //
/////////////////////////////////////////////////
doSetView(view)
doSetView(view);
///////////////////
// ole' faithful //
///////////////////
forceUpdate();
}
};
/*******************************************************************************
@ -787,7 +790,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setPinnedColumns(queryColumns.toGridPinnedColumns());
setColumnVisibilityModel(queryColumns.toColumnVisibilityModel());
setColumnsModel(columns);
}
};
/*******************************************************************************
@ -796,7 +799,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const promptForTableVariantSelection = () =>
{
setTableVariantPromptOpen(true);
}
};
/*******************************************************************************
@ -810,10 +813,10 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
for (let i = 0; i < queryFilter?.orderBys?.length; i++)
{
const fieldName = queryFilter.orderBys[i].fieldName;
if(fieldName.indexOf(".") > -1)
if (fieldName.indexOf(".") > -1)
{
const joinTableName = fieldName.replaceAll(/\..*/g, "");
if(!vjtToUse.has(joinTableName))
if (!vjtToUse.has(joinTableName))
{
const [field, fieldTable] = TableUtils.getFieldAndTable(tableMetaData, fieldName);
handleChangeOneColumnVisibility(field, fieldTable, true);
@ -823,7 +826,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
}
return (rs);
}
};
/*******************************************************************************
@ -831,13 +834,13 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
*******************************************************************************/
const updateTable = (reason?: string) =>
{
if(pageState != "ready")
if (pageState != "ready")
{
console.log(`In updateTable, but pageSate[${pageState}] is not ready, so returning with noop`);
return;
}
if(tableMetaData?.usesVariants && (!tableVariant || tableVariantPromptOpen))
if (tableMetaData?.usesVariants && (!tableVariant || tableVariantPromptOpen))
{
console.log("In updateTable, but a variant is needed, so returning with noop");
return;
@ -891,7 +894,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
});
}
if(!tableMetaData.capabilities.has(Capability.TABLE_QUERY))
if (!tableMetaData.capabilities.has(Capability.TABLE_QUERY))
{
console.log("Cannot update table - it does not have QUERY capability.");
return;
@ -966,7 +969,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setDistinctRecords(countResults[latestQueryId][1]);
delete countResults[latestQueryId];
}
catch(e)
catch (e)
{
console.log(e);
}
@ -996,7 +999,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
// count how many distinct primary keys are on this page //
///////////////////////////////////////////////////////////
let distinctPrimaryKeySet = new Set<string>();
for(let i = 0; i < results.length; i++)
for (let i = 0; i < results.length; i++)
{
distinctPrimaryKeySet.add(results[i].values.get(tableMetaData.primaryKeyField) as string);
}
@ -1052,7 +1055,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setRowsPerPage(size);
view.rowsPerPage = size;
doSetView(view)
doSetView(view);
};
/*******************************************************************************
@ -1061,11 +1064,11 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const handlePinnedColumnsChange = (pinnedColumns: GridPinnedColumns) =>
{
setPinnedColumns(pinnedColumns);
queryColumns.setPinnedLeftColumns(pinnedColumns.left)
queryColumns.setPinnedRightColumns(pinnedColumns.right)
queryColumns.setPinnedLeftColumns(pinnedColumns.left);
queryColumns.setPinnedRightColumns(pinnedColumns.right);
view.queryColumns = queryColumns;
doSetView(view)
doSetView(view);
};
/*******************************************************************************
@ -1118,7 +1121,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
let selectedPrimaryKeys = new Set<string>();
selectionModel.forEach((value: GridRowId, index: number) =>
{
checkboxesChecked++
checkboxesChecked++;
const valueToPush = latestQueryResults[value as number].values.get(tableMetaData.primaryKeyField);
selectedPrimaryKeys.add(valueToPush as string);
});
@ -1147,7 +1150,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
queryColumns.updateColumnOrder(columnOrdering);
view.queryColumns = queryColumns;
doSetView(view)
doSetView(view);
};
@ -1159,7 +1162,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
queryColumns.updateColumnWidth(params.colDef.field, params.width);
view.queryColumns = queryColumns;
doSetView(view)
doSetView(view);
};
@ -1182,13 +1185,13 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
{
const fieldName = gridSort[i].field;
const isAscending = gridSort[i].sort == "asc";
queryFilter.orderBys.push(new QFilterOrderBy(fieldName, isAscending))
queryFilter.orderBys.push(new QFilterOrderBy(fieldName, isAscending));
}
//////////////////////////////////////////////////////////
// set a default order-by, if none is otherwise present //
//////////////////////////////////////////////////////////
if(queryFilter.orderBys.length == 0)
if (queryFilter.orderBys.length == 0)
{
queryFilter.orderBys.push(new QFilterOrderBy(tableMetaData.primaryKeyField, false));
}
@ -1206,7 +1209,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
const handleColumnHeaderClick = (params: GridColumnHeaderParams, event: MuiEvent, details: GridCallbackDetails): void =>
{
event.defaultMuiPrevented = true;
}
};
/*******************************************************************************
@ -1224,7 +1227,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setRowsPerPage(view.rowsPerPage ?? defaultRowsPerPage);
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 //
@ -1237,7 +1240,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////////////////////////////////////////////////////////////////////////////////////////
// @ts-ignore
setTimeout(() => basicAndAdvancedQueryControlsRef?.current?.ensureAllFilterCriteriaAreActiveQuickFilters(view.queryFilter, "activatedView"));
}
};
/*******************************************************************************
@ -1255,7 +1258,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////////////////////////////////////
// in case there's no orderBys, set default here //
///////////////////////////////////////////////////
if(!queryFilter.orderBys || queryFilter.orderBys.length == 0)
if (!queryFilter.orderBys || queryFilter.orderBys.length == 0)
{
queryFilter.orderBys = [new QFilterOrderBy(tableMetaData?.primaryKeyField, false)];
view.queryFilter = queryFilter;
@ -1281,17 +1284,17 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////////////////////////////////
// put this query filter in the current view //
///////////////////////////////////////////////
if(!isFromActivateView)
if (!isFromActivateView)
{
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) //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
forceUpdate();
}
};
/*******************************************************************************
** Wrapper around setQueryColumns that also sets column models for the grid, puts
@ -1321,12 +1324,12 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////////////////////////////
// put these columns in the current view //
///////////////////////////////////////////
if(!isFromActivateView)
if (!isFromActivateView)
{
view.queryColumns = queryColumns;
doSetView(view)
doSetView(view);
}
}
};
/*******************************************************************************
@ -1338,7 +1341,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setQuickFilterFieldNames([...(names ?? [])]);
view.quickFilterFieldNames = names;
doSetView(view)
doSetView(view);
};
@ -1351,7 +1354,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
view.mode = newValue;
doSetView(view);
}
};
/*******************************************************************************
@ -1369,7 +1372,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
}
return (selectedIds.length);
}
};
/*******************************************************************************
@ -1380,7 +1383,10 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
{
if (selectFullFilterState === "filter")
{
return `?recordsParam=filterJSON&filterJSON=${encodeURIComponent(JSON.stringify(prepQueryFilterForBackend(queryFilter)))}`;
const filterForBackend = prepQueryFilterForBackend(queryFilter);
filterForBackend.skip = 0;
filterForBackend.limit = null;
return `?recordsParam=filterJSON&filterJSON=${encodeURIComponent(JSON.stringify(filterForBackend))}`;
}
if (selectFullFilterState === "filterSubset")
@ -1397,7 +1403,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
}
return "";
}
};
/*******************************************************************************
@ -1408,7 +1414,10 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
{
if (selectFullFilterState === "filter")
{
setRecordIdsForProcess(prepQueryFilterForBackend(queryFilter));
const filterForBackend = prepQueryFilterForBackend(queryFilter);
filterForBackend.skip = 0;
filterForBackend.limit = null;
setRecordIdsForProcess(filterForBackend);
}
else if (selectFullFilterState === "filterSubset")
{
@ -1550,7 +1559,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
*******************************************************************************/
const doSetCurrentSavedView = (savedViewRecord: QRecord) =>
{
if(savedViewRecord == null)
if (savedViewRecord == null)
{
console.log("doSetCurrentView called with a null view record - calling doClearCurrentSavedView instead.");
doClearCurrentSavedView();
@ -1559,7 +1568,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setCurrentSavedView(savedViewRecord);
const viewJson = savedViewRecord.values.get("viewJson")
const viewJson = savedViewRecord.values.get("viewJson");
const newView = RecordQueryView.buildFromJSON(viewJson);
activateView(newView);
@ -1568,7 +1577,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
// todo can/should/does this move into the view's "identity"? //
////////////////////////////////////////////////////////////////
localStorage.setItem(currentSavedViewLocalStorageKey, `${savedViewRecord.values.get("id")}`);
}
};
/*******************************************************************************
@ -1578,7 +1587,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
{
setCurrentSavedView(null);
localStorage.removeItem(currentSavedViewLocalStorageKey);
}
};
/*******************************************************************************
@ -1594,7 +1603,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
newDefaultView.quickFilterFieldNames = [];
newDefaultView.mode = defaultMode;
return newDefaultView;
}
};
/*******************************************************************************
** event handler for SavedViews component, to handle user selecting a view
@ -1629,9 +1638,9 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////////////////////////////////
// activate a new default view for the table //
///////////////////////////////////////////////
activateView(buildTableDefaultView(tableMetaData))
activateView(buildTableDefaultView(tableMetaData));
}
}
};
/*******************************************************************************
** utility function to fetch a saved view from the backend.
@ -1659,7 +1668,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
// 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. //
//////////////////////////////////////////////////////////////////////////////
const viewJson = qRecord.values.get("viewJson")
const viewJson = qRecord.values.get("viewJson");
const newView = RecordQueryView.buildFromJSON(viewJson);
setWarningAlert(null);
@ -1675,16 +1684,16 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////////////
// set columns if absent //
///////////////////////////
if(!newView.queryColumns || !newView.queryColumns.columns || newView.queryColumns.columns?.length == 0)
if (!newView.queryColumns || !newView.queryColumns.columns || newView.queryColumns.columns?.length == 0)
{
newView.queryColumns = QQueryColumns.buildDefaultForTable(tableMetaData);
}
qRecord.values.set("viewJson", JSON.stringify(newView))
qRecord.values.set("viewJson", JSON.stringify(newView));
}
return (qRecord);
}
};
/*******************************************************************************
@ -1784,12 +1793,12 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
}
const removedFieldCount = removedFieldNames.size;
if(removedFieldCount > 0)
if (removedFieldCount > 0)
{
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(", ")}).`);
}
}
};
/*******************************************************************************
@ -1799,7 +1808,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
{
const newCriteria = new QFilterCriteria(fieldName, null, []);
if(!queryFilter.criteria)
if (!queryFilter.criteria)
{
queryFilter.criteria = [];
}
@ -1825,8 +1834,8 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////////////
// open the filter panel //
///////////////////////////
gridApiRef.current.showPreferences(GridPreferencePanelsValue.filters)
}
gridApiRef.current.showPreferences(GridPreferencePanelsValue.filters);
};
/*******************************************************************************
@ -1921,7 +1930,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
<MenuItem onClick={(e) =>
{
hideMenu(e);
if(mode == "advanced")
if (mode == "advanced")
{
handleColumnMenuAdvancedFilterSelection(currentColumn.field);
}
@ -1980,24 +1989,24 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
for (let i = 0; i < queryFilter?.criteria?.length; i++)
{
const criteria = queryFilter.criteria[i];
if(criteria.fieldName == props.field && validateCriteria(criteria, null).criteriaIsValid)
if (criteria.fieldName == props.field && validateCriteria(criteria, null).criteriaIsValid)
{
showFilter = true;
}
}
if(showFilter)
if (showFilter)
{
return (<IconButton size="small" sx={{p: "2px"}} onClick={(event) =>
{
if(mode == "basic")
if (mode == "basic")
{
// @ts-ignore !?
basicAndAdvancedQueryControlsRef.current.addField(props.field);
}
else
{
gridApiRef.current.showPreferences(GridPreferencePanelsValue.filters)
gridApiRef.current.showPreferences(GridPreferencePanelsValue.filters);
}
event.stopPropagation();
@ -2101,23 +2110,35 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
*******************************************************************************/
const selectionMenuCallback = (selectedIndex: number) =>
{
if(selectedIndex == 0)
if (selectedIndex == 0)
{
///////////////
// this page //
///////////////
programmaticallySelectSomeOrAllRows();
setSelectFullFilterState("checked")
setSelectFullFilterState("checked");
}
else if(selectedIndex == 1)
else if (selectedIndex == 1)
{
///////////////////////
// full query result //
///////////////////////
programmaticallySelectSomeOrAllRows();
setSelectFullFilterState("filter")
setSelectFullFilterState("filter");
}
else if(selectedIndex == 2)
else if (selectedIndex == 2)
{
////////////////////////////
// subset of query result //
////////////////////////////
setSelectionSubsetSizePromptOpen(true);
}
else if(selectedIndex == 3)
else if (selectedIndex == 3)
{
setSelectFullFilterState("n/a")
/////////////////////
// clear selection //
/////////////////////
setSelectFullFilterState("n/a");
setRowSelectionModel([]);
setSelectedIds([]);
}
@ -2139,13 +2160,13 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
{
setSelectionSubsetSizePromptOpen(false);
if(value !== undefined)
if (value !== undefined)
{
if(typeof value === "number" && value > 0)
if (typeof value === "number" && value > 0)
{
programmaticallySelectSomeOrAllRows(value);
setSelectionSubsetSize(value);
setSelectFullFilterState("filterSubset")
setSelectFullFilterState("filterSubset");
}
else
{
@ -2249,7 +2270,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////////////////////////////////////////////////////////////
const [filterHash, setFilterHash] = useState("");
if(pageState == "ready")
if (pageState == "ready")
{
const newFilterHash = JSON.stringify(prepQueryFilterForBackend(queryFilter));
if (filterHash != newFilterHash)
@ -2362,7 +2383,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
for (let i = 0; i < queryFilter?.criteria?.length; i++)
{
const criteria = queryFilter.criteria[i];
if(criteria.operator == QCriteriaOperator.NOT_EQUALS)
if (criteria.operator == QCriteriaOperator.NOT_EQUALS)
{
criteria.operator = QCriteriaOperator.NOT_EQUALS_OR_IS_NULL;
}
@ -2380,14 +2401,14 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////////////////////////////////////////////////////////////////////////
doClearCurrentSavedView();
}
catch(e)
catch (e)
{
setAlertContent("Error parsing filter from URL");
}
}
else if (viewIdInLocation)
{
if(view.viewIdentity == `savedView:${viewIdInLocation}`)
if (view.viewIdentity == `savedView:${viewIdInLocation}`)
{
/////////////////////////////////////////////////////////////////////////////////////////////////
// if the view id in the location is the same as the view that was most-recently active here, //
@ -2432,7 +2453,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
// 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. //
/////////////////////////////////////////////////////////////////////////////////////////////////////
setPageState("loadedMetaData")
setPageState("loadedMetaData");
return;
}
@ -2466,7 +2487,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
setTimeout(() =>
{
// @ts-ignore
basicAndAdvancedQueryControlsRef?.current?.ensureAllFilterCriteriaAreActiveQuickFilters(view.queryFilter, "defaultFilterLoaded")
basicAndAdvancedQueryControlsRef?.current?.ensureAllFilterCriteriaAreActiveQuickFilters(view.queryFilter, "defaultFilterLoaded");
});
console.log("finished preparing grid, going to page state ready");
@ -2488,13 +2509,13 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
////////////////////////////////////////////////////////////////////////
useEffect(() =>
{
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]);
@ -2523,7 +2544,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
/////////////////////////////////////////////////////////////////////////////////////////////
if (tableMetaData && !tableMetaData.capabilities.has(Capability.TABLE_QUERY) && tableMetaData.capabilities.has(Capability.TABLE_GET))
{
if(tableMetaData?.usesVariants && (!tableVariant || tableVariantPromptOpen))
if (tableMetaData?.usesVariants && (!tableVariant || tableVariantPromptOpen))
{
return (
<BaseLayout>
@ -2540,9 +2561,9 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
// if the table uses variants, then put the variant-selector into the goto dialog //
////////////////////////////////////////////////////////////////////////////////////
let gotoVariantSubHeader = <></>;
if(tableMetaData?.usesVariants)
if (tableMetaData?.usesVariants)
{
gotoVariantSubHeader = <Box mb={2}>{getTableVariantHeader(tableVariant)}</Box>
gotoVariantSubHeader = <Box mb={2}>{getTableVariantHeader(tableVariant)}</Box>;
}
return (
@ -2555,7 +2576,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
///////////////////////////////////////////////////////////
// render a loading screen if the page state isn't ready //
///////////////////////////////////////////////////////////
if(pageState != "ready")
if (pageState != "ready")
{
console.log(`page state is ${pageState}... no-op while those complete async's run...`);
return (getLoadingScreen());
@ -2565,13 +2586,13 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
// if the table isn't loaded yet, display loading screen. //
// this shouldn't be possible, to be out-of-sync with pageState, but just as a fail-safe //
///////////////////////////////////////////////////////////////////////////////////////////
if(!tableMetaData)
if (!tableMetaData)
{
return (getLoadingScreen());
}
let savedViewsComponent = null;
if(metaData && metaData.processes.has("querySavedView"))
if (metaData && metaData.processes.has("querySavedView"))
{
savedViewsComponent = (<SavedViews qController={qController} metaData={metaData} tableMetaData={tableMetaData} view={view} viewAsJson={viewAsJson} currentSavedView={currentSavedView} tableDefaultView={tableDefaultView} viewOnChangeCallback={handleSavedViewChange} loadingSavedView={loadingSavedView} />);
}
@ -2594,9 +2615,9 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
////////////////////////////////////////////////////////////////////////////////////////////////////////////
const baseView = currentSavedView ? JSON.parse(currentSavedView.values.get("viewJson")) as RecordQueryView : tableDefaultView;
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)
{
/////////////////////////////////////////////////////////////////
// if 's a saved view, and it's "clean", show it in main style //
@ -2605,7 +2626,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
buttonBorder = accentColor;
buttonColor = "#FFFFFF";
}
else if(viewDiffs.length > 0)
else if (viewDiffs.length > 0)
{
///////////////////////////////////////////////////
// else if there are diffs, show alt/light style //
@ -2632,7 +2653,7 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
color: buttonColor,
backgroundColor: buttonBackground,
}
}
};
return (<Box order="2">
<FieldListMenu
@ -2647,19 +2668,19 @@ function RecordQuery({table, launchProcess}: Props): JSX.Element
handleToggleField={handleChangeOneColumnVisibility}
/>
</Box>);
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// these numbers help set the height of the grid (so page won't scroll) based on spcae above & below it //
//////////////////////////////////////////////////////////////////////////////////////////////////////////
let spaceBelowGrid = 40;
let spaceAboveGrid = 205;
if(tableMetaData?.usesVariants)
if (tableMetaData?.usesVariants)
{
spaceAboveGrid += 30;
}
if(mode == "advanced")
if (mode == "advanced")
{
spaceAboveGrid += 60;
}

View File

@ -46,8 +46,6 @@ import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Modal from "@mui/material/Modal";
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 colors from "qqq/assets/theme/base/colors";
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 TableUtils from "qqq/utils/qqq/TableUtils";
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();
@ -864,7 +864,7 @@ function RecordView({table, launchProcess}: Props): JSX.Element
}
{
warningMessage ?
<Alert color="warning" sx={{mb: 3}} onClose={() =>
<Alert color="warning" sx={{mb: 3}} icon={<Icon>warning</Icon>} onClose={() =>
{
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 {GridFilterOperator} from "@mui/x-data-grid/models/gridFilterOperator";
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 {buildQGridPvsOperators, QGridBlobOperators, QGridBooleanOperators, QGridNumericOperators, QGridStringOperators} from "qqq/pages/records/query/GridFilterOperators";
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;
@ -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 rows = [] as any[];
@ -159,7 +159,10 @@ export default class DataGridUtils
/////////////////////////////////////////////////////////////////////////////////////////
// DataGrid gets very upset about a null or undefined here, so, try to make it happier //
/////////////////////////////////////////////////////////////////////////////////////////
row["id"] = "--";
if(!allowEmptyId)
{
row["id"] = "--";
}
}
}
@ -279,7 +282,7 @@ export default class DataGridUtils
if (key === tableMetaData.primaryKeyField && linkBase)
{
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

@ -64,7 +64,6 @@ class FilterUtils
let rs = [];
for (let i = 0; i < param.length; i++)
{
console.log(param[i]);
if (param[i] && param[i].id && param[i].label)
{
/////////////////////////////////////////////////////////////
@ -115,8 +114,11 @@ class FilterUtils
// e.g., ...values=[1]... //
// 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. //
// 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);
}
@ -261,39 +263,45 @@ 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[] = [];
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.criteria)
if (filter.subFilters?.length > 0)
{
const usedFields: {[name: string]: boolean} = {};
const warnedFields: {[name: string]: boolean} = {};
reasonsWhyItCannot.push("Filter contains sub-filters.");
return ({canFilterWorkAsBasic: false, canFilterWorkAsAdvanced: false, reasonsWhyItCannot: reasonsWhyItCannot});
}
if (filter.criteria)
{
const usedFields: { [name: string]: boolean } = {};
const warnedFields: { [name: string]: boolean } = {};
for (let i = 0; i < filter.criteria.length; i++)
{
const criteriaName = filter.criteria[i].fieldName;
if(!criteriaName)
if (!criteriaName)
{
continue;
}
if(usedFields[criteriaName])
if (usedFields[criteriaName])
{
if(!warnedFields[criteriaName])
if (!warnedFields[criteriaName])
{
const [field, tableForField] = TableUtils.getFieldAndTable(tableMetaData, criteriaName);
let fieldLabel = field.label;
if(tableForField.name != tableMetaData.name)
if (tableForField.name != tableMetaData.name)
{
let fieldLabel = `${tableForField.label}: ${field.label}`;
}
@ -305,13 +313,13 @@ class FilterUtils
}
}
if(reasonsWhyItCannot.length == 0)
if (reasonsWhyItCannot.length == 0)
{
return ({canFilterWorkAsBasic: true});
return ({canFilterWorkAsBasic: true, canFilterWorkAsAdvanced: true});
}
else
{
return ({canFilterWorkAsBasic: false, reasonsWhyItCannot: reasonsWhyItCannot});
return ({canFilterWorkAsBasic: false, canFilterWorkAsAdvanced: true, reasonsWhyItCannot: reasonsWhyItCannot});
}
}
@ -323,7 +331,7 @@ class FilterUtils
{
let valuesString = "";
if(criteria.operator == QCriteriaOperator.IS_BLANK || criteria.operator == QCriteriaOperator.IS_NOT_BLANK)
if (criteria.operator == QCriteriaOperator.IS_BLANK || criteria.operator == QCriteriaOperator.IS_NOT_BLANK)
{
///////////////////////////////////////////////
// we don't want values for these operators. //
@ -340,7 +348,7 @@ class FilterUtils
{
maxLoops = maxValuesToShow;
}
else if(maxValuesToShow == 1 && criteria.values.length > 1)
else if (maxValuesToShow == 1 && criteria.values.length > 1)
{
maxLoops = 1;
}
@ -361,17 +369,22 @@ class FilterUtils
else if (value.type == "ThisOrLastPeriod")
{
const expression = new ThisOrLastPeriodExpression(value);
labels.push(expression.toString());
let startOfPrefix = "";
if (fieldMetaData.type == QFieldType.DATE_TIME || expression.timeUnit != "DAYS")
{
startOfPrefix = "start of ";
}
labels.push(`${startOfPrefix}${expression.toString()}`);
}
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)
{
labels.push(ValueUtils.formatDateTime(value));
}
else if(fieldMetaData.type == QFieldType.DATE)
else if (fieldMetaData.type == QFieldType.DATE)
{
labels.push(ValueUtils.formatDate(value));
}
@ -394,7 +407,7 @@ class FilterUtils
labels.push(` and ${n} other value${n == 1 ? "" : "s"}.`);
break;
case "+N":
labels[labels.length-1] += ` +${n}`;
labels[labels.length - 1] += ` +${n}`;
break;
}
}
@ -443,7 +456,7 @@ class FilterUtils
for (let i = 0; i < queryFilter?.orderBys?.length; 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);
}
@ -454,7 +467,7 @@ class FilterUtils
*******************************************************************************/
public static operatorToHumanString(criteria: QFilterCriteria, field: QFieldMetaData): string
{
if(criteria == null || criteria.operator == null)
if (criteria == null || criteria.operator == null)
{
return (null);
}
@ -464,7 +477,7 @@ class FilterUtils
try
{
switch(criteria.operator)
switch (criteria.operator)
{
case QCriteriaOperator.EQUALS:
return ("equals");
@ -488,35 +501,35 @@ class FilterUtils
case QCriteriaOperator.NOT_CONTAINS:
return ("does not contain");
case QCriteriaOperator.LESS_THAN:
if(isDate || isDateTime)
if (isDate || isDateTime)
{
return ("is before")
return ("is before");
}
return ("less than");
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");
case QCriteriaOperator.GREATER_THAN:
if(isDate || isDateTime)
if (isDate || isDateTime)
{
return ("is after")
return ("is after");
}
return ("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");
case QCriteriaOperator.IS_BLANK:
@ -529,10 +542,10 @@ class FilterUtils
return ("is not between");
}
}
catch(e)
catch (e)
{
console.log(`Error getting operator human string for ${JSON.stringify(criteria)}: ${e}`);
return criteria?.operator
return criteria?.operator;
}
}
@ -542,7 +555,7 @@ class FilterUtils
*******************************************************************************/
public static criteriaToHumanString(table: QTableMetaData, criteria: QFilterCriteria, styled = false): string | JSX.Element
{
if(criteria == null)
if (criteria == null)
{
return (null);
}
@ -551,7 +564,7 @@ class FilterUtils
const fieldLabel = TableUtils.getFieldFullLabel(table, criteria.fieldName);
const valuesString = FilterUtils.getValuesString(field, criteria);
if(styled)
if (styled)
{
return (
<Box display="inline" whiteSpace="nowrap" color="#FFFFFF" mb={"0.5rem"}>
@ -560,7 +573,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>}
&nbsp;
</Box>
)
);
}
else
{

View File

@ -30,61 +30,101 @@ import {QueryJoin} from "@kingsrook/qqq-frontend-core/lib/model/query/QueryJoin"
*******************************************************************************/
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 (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[] = [];
for (let i = 0; i < tableMetaData.sections.length; 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]))
{
allowedSections.push(section);
break;
}
includeSection = true;
break;
}
}
if (additionalInclusionPredicate && additionalInclusionPredicate(section))
{
includeSection = true;
}
if(includeSection)
{
allowedSections.push(section);
}
}
console.log("allowedSections length: " + allowedSections.length);
return (allowedSections);
}
else
{
return (tableMetaData.sections);
}
////////////////////////////////////////////////////////////////
// if there are no filters to apply, then return all sections //
////////////////////////////////////////////////////////////////
return (tableMetaData.sections);
}
else
///////////////////////////////////////////////////////////////////////////////////////////////
// else, if the table had no sections, then make a pseudo-one with either all of the fields, //
// or a subset based on the allowedFieldNames //
///////////////////////////////////////////////////////////////////////////////////////////////
let fieldNames = [...tableMetaData.fields.keys()];
if (allowedFieldNames)
{
let fieldNames = [...tableMetaData.fields.keys()];
if (allowedKeys)
fieldNames = [];
for (const fieldName in tableMetaData.fields.keys())
{
fieldNames = [];
for (const fieldName in tableMetaData.fields.keys())
if (allowedFieldNames[fieldName])
{
if (allowedKeys[fieldName])
{
fieldNames.push(fieldName);
}
fieldNames.push(fieldName);
}
}
return ([new QTableSection({
iconName: "description", label: "All Fields", name: "allFields", fieldNames: [...fieldNames],
})]);
}
return ([new QTableSection({
iconName: "description", label: "All Fields", name: "allFields", fieldNames: [...fieldNames],
})]);
}