modified th api's for bin, contract and task to have as passed in as a prop and not get it ffrom the global state directly in the api

This commit is contained in:
csawatzky 2025-04-17 13:33:27 -06:00
parent 4bcac4e346
commit e2f5eb0557
31 changed files with 155 additions and 507 deletions

View file

@ -129,7 +129,7 @@ export default function BinComponentTypes(props: Props) {
const [selectedComponentKey, setSelectedComponentKey] = useState("");
const [selectedComponentSubtype, setSelectedComponentSubtype] = useState(0);
const [selectedComponentTopNode, setSelectedComponentTopNode] = useState(0);
const [{ user }] = useGlobalState();
const [{ user, as }] = useGlobalState();
useEffect(() => {
if (user.settings.temperatureUnit) {
@ -152,7 +152,7 @@ export default function BinComponentTypes(props: Props) {
p.type = type;
p.node = topNode ?? 0;
binAPI
.updateComponentPreferences(bin, component, p)
.updateComponentPreferences(bin, component, p, as)
.then(() => {
snackbar.success("Component preferences updated");
preferences.set(component, p!);
@ -163,7 +163,7 @@ export default function BinComponentTypes(props: Props) {
});
}
},
[bin, binAPI, preferences, setPreferences, snackbar]
[bin, binAPI, preferences, setPreferences, snackbar, as]
);
useEffect(() => {

View file

@ -30,7 +30,7 @@ import { Component, Device } from "models";
import { pond } from "protobuf-ts/pond";
import React, { useCallback, useEffect, useState } from "react";
import { useComponentAPI, useDeviceAPI, useSnackbar } from "hooks";
import { useBinAPI } from "providers";
import { useBinAPI, useGlobalState } from "providers";
import { GetComponentIcon } from "pbHelpers/ComponentType";
import { CheckBox as CheckBoxIcon, CheckBoxOutlineBlank, Remove } from "@mui/icons-material";
import ResponsiveDialog from "common/ResponsiveDialog";
@ -85,6 +85,7 @@ interface Option {
export default function BinComponents(props: Props) {
const { components, bin, setComponents, updateBinStatus, binGrain } = props;
const [{as}] = useGlobalState();
const classes = useStyles();
const binAPI = useBinAPI();
const theme = useTheme();
@ -208,7 +209,7 @@ export default function BinComponents(props: Props) {
// }, [selectedDevice, componentAPI, deviceComponents, snackbar]);
const removeComponent = (component: string) => {
binAPI.removeComponent(bin, component).then(() => {
binAPI.removeComponent(bin, component, as).then(() => {
if (components && setComponents) {
if (components.delete(component)) {
let newComponents = new Map(components);
@ -312,7 +313,7 @@ export default function BinComponents(props: Props) {
type: preset,
node: component.settings.grainFilledTo ?? 0
});
binAPI.addComponent(bin, device, component.key(), preferences).then(resp => {
binAPI.addComponent(bin, device, component.key(), preferences, as).then(resp => {
if (components && setComponents) {
if (components.set(component.key(), component)) {
let newComponents = new Map(components);
@ -337,7 +338,7 @@ export default function BinComponents(props: Props) {
}
});
} else {
binAPI.removeComponent(bin, component.key()).then(resp => {
binAPI.removeComponent(bin, component.key(), as).then(resp => {
if (components && setComponents) {
if (components.delete(component.key())) {
let newComponents = new Map(components);
@ -350,7 +351,7 @@ export default function BinComponents(props: Props) {
};
const removeAll = () => {
binAPI.removeAllComponents(bin).then(resp => {
binAPI.removeAllComponents(bin, as).then(resp => {
if (setComponents) {
setComponents(new Map());
}

View file

@ -195,7 +195,7 @@ export default function BinsFansStatusTable(props: Props) {
let bin = selectedBinRow.bin;
bin.settings.fanId = newFanID;
binAPI
.updateBin(bin.key(), bin.settings)
.updateBin(bin.key(), bin.settings, as)
.then(resp => {
//when an update succeeds update the table with the fan information
//let dataMap = tableDataMap

View file

@ -3,7 +3,7 @@ import { createStyles, makeStyles } from "@mui/styles";
//import { MatchParams } from "navigation/Routes";
import DiffHistory, { ListResult, Record } from "common/DiffHistory";
import { useSnackbar, useMobile } from "hooks";
import { useBinAPI } from "providers";
import { useBinAPI, useGlobalState } from "providers";
import { Bin } from "models";
import { TranslateKey, TranslateValue } from "pbHelpers/Bin";
import { pond } from "protobuf-ts/pond";
@ -37,6 +37,7 @@ export default function BinHistory(props: Props) {
//const params = useParams<MatchParams>();
const {binID, drawer} = props
const classes = useStyles();
const [{as}] = useGlobalState();
const { openSnack } = useSnackbar();
const binAPI = useBinAPI();
//const binID = props.binID ?? params.binID;
@ -46,14 +47,14 @@ export default function BinHistory(props: Props) {
useEffect(() => {
binAPI
.getBin(binID)
.getBin(binID, as)
.then((response: any) => {
setBin(Bin.any(response.data));
})
.catch(err => {
openSnack("There was a problem loading your bin");
});
}, [binAPI, binID, openSnack]);
}, [binAPI, binID, openSnack, as]);
let list = (limit: number, offset: number): Promise<ListResult> => {
return new Promise(resolve => {

View file

@ -408,7 +408,7 @@ export default function BinSettings(props: Props) {
if (form.inventory) form.inventory.inventoryControl = inventoryControl;
binAPI
.addBin(form)
.addBin(form, as)
.then(resp => {
openSnack("Successfully created bin");
if (!coords) {
@ -451,7 +451,7 @@ export default function BinSettings(props: Props) {
form.autoGrainNode = autoTopNode;
if (form.inventory) form.inventory.inventoryControl = inventoryControl;
binAPI
.updateBin(bin.key(), form)
.updateBin(bin.key(), form, as)
.then(response => {
openSnack("Updated " + bin.name());
close(true);
@ -491,7 +491,7 @@ export default function BinSettings(props: Props) {
const removeBin = () => {
if (bin && bin.key()) {
binAPI
.removeBin(bin.key())
.removeBin(bin.key(), as)
.then(response => {
openSnack(bin.name() + " was removed");
navigate("/bins");

View file

@ -22,7 +22,7 @@ import { GrainCable } from "models/GrainCable";
import { UnitMeasurement } from "models/UnitMeasurement";
import Co2Icon from "products/CommonIcons/co2Icon";
import { pond } from "protobuf-ts/pond";
import { useBinAPI, useSnackbar } from "providers";
import { useBinAPI, useGlobalState, useSnackbar } from "providers";
import React, { useEffect, useState } from "react";
import { avg, getTemperatureUnit } from "utils";
import { makeStyles } from "@mui/styles";
@ -133,6 +133,7 @@ export default function BinStorageConditions(props: Props) {
const binAPI = useBinAPI();
const { openSnack } = useSnackbar();
const { bin, headspaceCO2, cables } = props;
const [{as}] = useGlobalState()
const [sliderTemps, setSliderTemps] = useState<number[]>([-40, 40]);
//boolean that if a cable is missing its filled to display an icon or something to let the user know not all of the cables have their fill set
const [missingTopNodeWarning, setMissingTopNodeWarning] = useState(false);
@ -309,7 +310,7 @@ export default function BinStorageConditions(props: Props) {
}
binAPI
.updateBin(bin.key(), settings)
.updateBin(bin.key(), settings, as)
.then(_resp => {
openSnack("Updated bin thresholds");
})

View file

@ -228,6 +228,7 @@ export default function BinVisualizer(props: Props) {
binPresets
} = props;
const binAPI = useBinAPI();
const [{as}] = useGlobalState()
const isMobile = useMobile();
const classes = useStyles();
const theme = useTheme();
@ -1814,7 +1815,7 @@ export default function BinVisualizer(props: Props) {
setModeTime(moment(newTimestamp));
status.lastModeChange = newTimestamp;
binAPI
.updateBinStatus(bin.key(), status)
.updateBinStatus(bin.key(), status, as)
.then(resp => {
openSnack("Reset the storage time");
})
@ -2066,7 +2067,7 @@ export default function BinVisualizer(props: Props) {
b.settings.outdoorHumidity = Number(outdoorHumidityInput);
b.settings.mode = newPreset;
binAPI.updateBin(bin.key(), b.settings).then(resp => {
binAPI.updateBin(bin.key(), b.settings, as).then(resp => {
refresh();
});
};

View file

@ -287,7 +287,7 @@ export default function BinyardDisplay(props: Props) {
}, []);
const duplicateBin = (bin: Bin) => {
binAPI.addBin(bin.settings).then(resp => {
binAPI.addBin(bin.settings, as).then(resp => {
loadBins();
});
};

View file

@ -2,7 +2,7 @@ import { Button, Card, Grid2 as Grid, Slider } from "@mui/material";
import { useMobile } from "hooks";
import { GrainCable } from "models/GrainCable";
import { pond } from "protobuf-ts/pond";
import { useBinAPI } from "providers";
import { useBinAPI, useGlobalState } from "providers";
import React, { useEffect, useState } from "react";
interface Props {
@ -21,6 +21,7 @@ interface CableNodeInfo {
export default function CableTopNodeSummary(props: Props) {
const { binKey, cables, componentDevMap } = props;
const [{as}] = useGlobalState()
const [cableNodes, setCableNodes] = useState<CableNodeInfo[]>([]);
const isMobile = useMobile();
const binAPI = useBinAPI();
@ -53,7 +54,7 @@ export default function CableTopNodeSummary(props: Props) {
);
});
binAPI
.updateTopNodes(binKey, newTopNodes)
.updateTopNodes(binKey, newTopNodes, as)
.then(resp => {
console.log("Set Top Nodes for cables, components and interactions have been updated");
})

View file

@ -86,7 +86,7 @@ export default function GrainNodeInteractions(props: Props) {
const [nodeTemp, setNodeTemp] = useState<number>();
const [nodeHum, setNodeHum] = useState<number>();
const [nodeMoist, setNodeMoist] = useState<number | undefined>();
const [{ user }] = useGlobalState();
const [{ user, as }] = useGlobalState();
const tempDescriber = describeMeasurement(quack.MeasurementType.MEASUREMENT_TYPE_TEMPERATURE);
const humDescriber = describeMeasurement(quack.MeasurementType.MEASUREMENT_TYPE_PERCENT);
const moistureDescriber = describeMeasurement(quack.MeasurementType.MEASUREMENT_TYPE_GRAIN_EMC);
@ -195,7 +195,7 @@ export default function GrainNodeInteractions(props: Props) {
});
//update the bins preferences to have the new top node for the cable
binAPI
.updateComponentPreferences(binKey, cable.key(), pref)
.updateComponentPreferences(binKey, cable.key(), pref, as)
.then(resp => {
openSnack("Updated cables top node");
updateComponentCallback(cable.key());

View file

@ -111,7 +111,7 @@ export default function BinGraphs(props: Props) {
const [recentPlenumTrend, setRecentPlenumTrend] = useState<TrendPoint | undefined>();
const [recentCableTrend, setRecentCableTrend] = useState<DataPoint | undefined>();
const [recentWaterContent, setRecentWaterContent] = useState<WaterPoint | undefined>();
const [{ user }] = useGlobalState();
const [{ user, as }] = useGlobalState();
const [measurementsLoading, setMeasurementsLoading] = useState(false);
const isMobile = useMobile();
const [{ showErrors }, dispatch] = useGlobalState();
@ -142,7 +142,8 @@ export default function BinGraphs(props: Props) {
bin.key(),
startDate.toISOString(),
endDate.toISOString(),
showErrors
showErrors,
as
)
.then(resp => {
resp.data.measurements.forEach((um: any) => {

View file

@ -12,7 +12,7 @@ import BarGraph, { BarData, RefArea } from "charts/BarGraph";
import { Bin } from "models";
import moment, { Moment } from "moment";
import { pond, quack } from "protobuf-ts/pond";
import { useBinAPI } from "providers";
import { useBinAPI, useGlobalState } from "providers";
import { useEffect, useState } from "react";
import { Legend } from "recharts";
import { getGrainUnit } from "utils";
@ -30,6 +30,7 @@ interface Props {
export default function BinLevelOverTime(props: Props) {
const { bin, fertilizerBin, colour, startDate, endDate, customHeight } = props;
const binAPI = useBinAPI();
const [{as}] = useGlobalState();
const [showCable, setShowCable] = useState(false);
const [manualData, setManualData] = useState<BarData[]>([]);
const [cableData, setCableData] = useState<BarData[]>([]);
@ -157,7 +158,7 @@ export default function BinLevelOverTime(props: Props) {
if (cableDataLoading || bin.key() === "") return;
setCableDataLoading(true);
binAPI
.listBinMeasurements(bin.key(), startDate, endDate, 500, 0, "asc")
.listBinMeasurements(bin.key(), startDate, endDate, 500, 0, "asc", undefined, undefined, undefined, undefined, as)
.then(resp => {
resp.data.measurements.forEach(objMeasurement => {
//set the bushel cable measurements
@ -186,7 +187,7 @@ export default function BinLevelOverTime(props: Props) {
.finally(() => {
setCableDataLoading(false);
});
}, [binAPI, bin, startDate, endDate, fertilizerBin]); // eslint-disable-line react-hooks/exhaustive-deps
}, [binAPI, bin, startDate, endDate, fertilizerBin, as]); // eslint-disable-line react-hooks/exhaustive-deps
const legend = () => {
return (

View file

@ -40,7 +40,7 @@ export default function BinWaterLevel(props: Props) {
bin.settings.inventory?.targetMoisture.toString() ?? ""
);
const [reference, setReference] = useState(0);
// const [{ newStructure }] = useGlobalState();
const [{ as }] = useGlobalState();
const [loading, setLoading] = useState(false);
useEffect(() => {
@ -70,7 +70,8 @@ export default function BinWaterLevel(props: Props) {
plenumKey,
cableKey,
pressureKey,
fanKey
fanKey,
as
)
.then(resp => {
let lastData: DataPoint | undefined;
@ -93,7 +94,7 @@ export default function BinWaterLevel(props: Props) {
});
}
}
}, [binAPI, range, bin, grainMoisture, plenumKey, cableKey, pressureKey]); // eslint-disable-line react-hooks/exhaustive-deps
}, [binAPI, range, bin, grainMoisture, plenumKey, cableKey, pressureKey, as]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<React.Fragment>

View file

@ -39,6 +39,7 @@ import { Label, Pie, PieChart, ResponsiveContainer, Text } from "recharts";
import { stringToMaterialColour } from "utils";
import { makeStyles } from "@mui/styles";
import { useNavigate } from "react-router-dom";
import { useGlobalState } from "providers";
interface Props {
contracts: Contract[];
@ -59,6 +60,7 @@ const useStyles = makeStyles((theme: Theme) => ({
export default function ContractsList(props: Props) {
const { contracts, contractPermissions, updateList } = props;
const theme = useTheme();
const [{as}] = useGlobalState();
//will need map for contracts that have supported grain types
const [supportedTypes, setSupportedTypes] = useState<Map<pond.Grain, Contract[]>>(new Map());
//will need need map for custom contracts
@ -115,7 +117,7 @@ export default function ContractsList(props: Props) {
const deleteContract = () => {
if (currentContract) {
contractAPI
.removeContract(currentContract.key())
.removeContract(currentContract.key(), as)
.then(resp => {
let c = contracts;
contracts.splice(c.indexOf(currentContract), 1);

View file

@ -45,6 +45,7 @@ export default function ContractSettings(props: Props) {
const { open, close, contract } = props;
const contractAPI = useContractAPI();
const [name, setName] = useState("");
const [{as}] = useGlobalState();
const [contractID, setContractID] = useState(""); //id
const [holder, setHolder] = useState(""); //holder
const [deliveryStart, setDeliveryStart] = useState(moment().format("YYYY-MM-DD")); //deliverystart
@ -136,7 +137,7 @@ export default function ContractSettings(props: Props) {
});
taskAPI
.addTask(task)
.addTask(task, as)
.then(resp => {
console.log("Task Created");
})
@ -171,7 +172,7 @@ export default function ContractSettings(props: Props) {
settings.contractDate = contractDate;
contractAPI
.updateContract(contract.key(), name, settings)
.updateContract(contract.key(), name, settings, as)
.then(resp => {
console.log("Updated Contract");
close();
@ -198,7 +199,7 @@ export default function ContractSettings(props: Props) {
settings.contractDate = contractDate;
contractAPI
.addContract(name, settings)
.addContract(name, settings, as)
.then(resp => {
if (createDeliveryTask) {
createTask(resp.data.key);
@ -214,7 +215,7 @@ export default function ContractSettings(props: Props) {
const deleteContract = () => {
if (contract) {
contractAPI
.removeContract(contract.key())
.removeContract(contract.key(), as)
.then(resp => {
console.log("contract deleted");
close();

View file

@ -21,7 +21,7 @@ import moment from "moment";
import ObjectDescriber from "objects/ObjectDescriber";
import DeleteIcon from "products/AgIcons/Delete";
import { pond } from "protobuf-ts/pond";
import { useBinAPI, useGrainBagAPI, useSnackbar, useTransactionAPI, useUserAPI } from "providers";
import { useBinAPI, useGlobalState, useGrainBagAPI, useSnackbar, useTransactionAPI, useUserAPI } from "providers";
import React, { useEffect, useState } from "react";
import TransactionDataDisplay from "transactions/transactionDataDisplay";
import ContractTransactionFile from "./contractTransactionFile";
@ -51,6 +51,7 @@ export default function ContractTransactionTable(props: Props) {
const [displayData, setDisplayData] = useState<Transaction[]>([]);
const [tablePage, setTablePage] = useState(0)
const [pageSize, setPageSize] = useState(10)
const [{as}] = useGlobalState();
const userAPI = useUserAPI();
const [userProfiles, setUserProfiles] = useState<Map<string, pond.UserProfile>>(new Map());
const [openRevokeDialog, setOpenRevokeDialog] = useState(false);
@ -97,7 +98,7 @@ export default function ContractTransactionTable(props: Props) {
setTransactionSource(undefined);
switch (transaction.transaction.fromObject) {
case pond.ObjectType.OBJECT_TYPE_BIN:
binAPI.getBin(transaction.transaction.fromKey).then(resp => {
binAPI.getBin(transaction.transaction.fromKey, as).then(resp => {
let bin = Bin.create(resp.data);
setTransactionSource(bin);
});
@ -366,8 +367,8 @@ export default function ContractTransactionTable(props: Props) {
rows={displayData}
columns={columns}
total={tableData.length}
handleRowsPerPageChange={()=>{}}
setPage={()=>{}}
handleRowsPerPageChange={(e)=>{setPageSize(e.target.value)}}
setPage={(page)=>{setTablePage(page)}}
/>
{/* <MaterialTable
title={"Deliveries"}

View file

@ -1,385 +0,0 @@
import ResponsiveDialog from "common/ResponsiveDialog";
import { Bin, Field, HarvestYear } from "models";
import React, { useCallback } from "react";
import { useFieldAPI, useBinAPI, useHarvestYearAPI, useGlobalState } from "providers";
import {
Box,
Button,
DialogActions,
DialogContent,
DialogTitle,
FormControl,
FormControlLabel,
MenuItem,
Radio,
RadioGroup,
TextField
} from "@mui/material";
import { useState } from "react";
import { useEffect } from "react";
import { pond } from "protobuf-ts/pond";
import { useSnackbar } from "hooks";
import moment from "moment";
import GrainDescriber from "./GrainDescriber";
interface Props {
activeBinSettings: pond.BinSettings;
newGrainInventory: number;
dialogControl: boolean;
onClose(cancel?: boolean): void;
afterUpdate?(secondBin?: Bin): void;
}
//this component is going to be deprecated by grain transaction
export default function GrainInventory(props: Props) {
const { activeBinSettings, newGrainInventory, dialogControl, onClose, afterUpdate } = props;
const binAPI = useBinAPI();
const fieldAPI = useFieldAPI();
const hYearAPI = useHarvestYearAPI();
const [{ as }] = useGlobalState();
const [binIndex, setBinIndex] = useState(0);
const [fieldIndex, setFieldIndex] = useState<number>(-1);
const [yearIndex, setYearIndex] = useState(0);
const [bins, setBins] = useState<Bin[]>([]);
const [fields, setFields] = useState<Field[]>([]);
const [hYears, setHYears] = useState<Map<number, HarvestYear>>(new Map<number, HarvestYear>());
const [currentBushels, setCurrentBushels] = useState(0);
const { openSnack } = useSnackbar();
const [increaseMode, setIncreaseMode] = useState<"correction" | "purchased" | "grown">(
"correction"
);
const [decreaseMode, setDecreaseMode] = useState<"correction" | "sold" | "moved">("correction");
useEffect(() => {
if (activeBinSettings.inventory && dialogControl) {
setCurrentBushels(activeBinSettings.inventory.grainBushels);
}
}, [activeBinSettings, dialogControl]);
const loadBins = useCallback(() => {
if (!dialogControl) return;
binAPI
.listBins(50, 0, "asc", "name", undefined, as)
.then(resp => {
setBins(resp.data.bins.map(b => Bin.any(b)));
})
.catch();
}, [binAPI, as, dialogControl]);
const loadHYears = useCallback(() => {
if (fields.length > 0 && fieldIndex > -1) {
hYearAPI.listHarvestYears(50, 0, "asc", "year", fields[fieldIndex].fieldName()).then(resp => {
let tempMap = new Map<number, HarvestYear>();
resp.data.harvestYear.forEach(hy => {
let tempHY = HarvestYear.any(hy);
tempMap.set(tempHY.year(), tempHY);
});
setHYears(tempMap);
});
}
}, [hYearAPI, fields, fieldIndex]);
useEffect(() => {
loadHYears();
}, [loadHYears]);
useEffect(() => {
loadBins();
fieldAPI
.listFields(500, 0, "asc", "fieldName", undefined, as)
.then(resp => {
setFields(resp.data.fields.map(f => Field.any(f)));
})
.catch();
}, [loadBins, fieldAPI, as]);
const grainName = (bin: Bin) => {
return bin.storage() === pond.BinStorage.BIN_STORAGE_SUPPORTED_GRAIN
? GrainDescriber(bin.grain()).name
: bin.customType();
};
const dialogContent = () => {
if (newGrainInventory < currentBushels) {
return (
<Box>
<FormControl>
<RadioGroup value={decreaseMode} name="radio-buttons-group">
<FormControlLabel
value="correction"
control={<Radio />}
label="Correction"
onChange={() => setDecreaseMode("correction")}
/>
{/* Doesnt Actually Do Anything yet */}
{/* <FormControlLabel
value="sold"
control={<Radio />}
label="Sold"
onChange={() => setDecreaseMode("sold")}
/> */}
<FormControlLabel
value="moved"
control={<Radio />}
label="Moved"
onChange={() => setDecreaseMode("moved")}
/>
</RadioGroup>
</FormControl>
{decreaseMode === "moved" && (
<TextField
id="bins"
fullWidth
margin="normal"
select
label="Bin grain moved to"
value={binIndex}
onChange={e => setBinIndex(+e.target.value)}>
{bins.map((option, i) => (
<MenuItem key={i} value={i} disabled={option.key() === activeBinSettings.key}>
{option.name()} - {grainName(option)}
</MenuItem>
))}
</TextField>
)}
</Box>
);
} else {
return (
<Box>
<FormControl>
<RadioGroup value={increaseMode} name="radio-buttons-group">
<FormControlLabel
value="correction"
control={<Radio />}
label="Correction"
onChange={() => setIncreaseMode("correction")}
/>
{/* Doesnt Actually Do Anything yet */}
{/* <FormControlLabel
value="purchased"
control={<Radio />}
label="Purchased"
onChange={() => setIncreaseMode("purchased")}
/> */}
<FormControlLabel
value="grown"
control={<Radio />}
label="Grown"
onChange={() => setIncreaseMode("grown")}
/>
</RadioGroup>
</FormControl>
{increaseMode === "grown" && (
<Box>
<TextField
id="fields"
fullWidth
margin="normal"
select
label="Field"
helperText="Select the field that provided the grain"
value={fieldIndex}
onChange={e => setFieldIndex(+e.target.value)}>
<MenuItem key="noField" value={-1}>
No Field Selected
</MenuItem>
{fields.map((option, i) => (
<MenuItem key={i} value={i}>
{option.fieldName()}
</MenuItem>
))}
</TextField>
<TextField
id="harvestYear"
fullWidth
margin="normal"
select
label="Harvest Year"
helperText="Select which Year to track"
value={yearIndex}
onChange={e => setYearIndex(+e.target.value)}
disabled={fieldIndex < 0}>
<MenuItem key={0} value={0}>
New Harvest Year
</MenuItem>
{Array.from(hYears.values()).length > 0 &&
Array.from(hYears.values()).map(option => (
<MenuItem key={option.year()} value={option.year()}>
{option.year()}
</MenuItem>
))}
</TextField>
</Box>
)}
</Box>
);
}
};
const increaseInv = () => {
let bin = activeBinSettings;
let binInv = pond.BinInventory.fromObject({
...bin.inventory
});
if (binInv.grainBushels === 0 && bin.mode === pond.BinMode.BIN_MODE_NONE) {
bin.mode = pond.BinMode.BIN_MODE_STORAGE;
}
binInv.grainBushels = newGrainInventory;
if (fields.length > 0 && fieldIndex > -1) {
if (fields[fieldIndex].crop() !== activeBinSettings.inventory?.grainType) {
openSnack("Grain type of this bin does not match the Field");
return;
} else if (yearIndex === 0 && hYears.has(moment().year())) {
openSnack("Current year already exists for this field");
return;
}
binInv.grainSubtype = fields[fieldIndex].subtype();
}
bin.inventory = binInv;
binAPI
.updateBin(activeBinSettings.key, bin)
.then(() => {
if (increaseMode === "grown") {
if (yearIndex === 0) {
let hy = HarvestYear.create();
hy.settings.field = fields[fieldIndex].fieldName();
hy.settings.grain = fields[fieldIndex].crop();
hy.settings.year = moment().year();
hy.settings.bushels = newGrainInventory - currentBushels;
hYearAPI.addHarvestYear(hy.settings).then(resp => {
loadHYears();
});
} else {
let hy = hYears.get(yearIndex);
if (hy) {
hy.settings.bushels = hy.totalBushels() + (newGrainInventory - currentBushels);
hYearAPI.updateHarvestYear(hy.key(), hy.settings).then(resp => {
loadHYears();
});
}
}
} else if (increaseMode === "purchased") {
}
})
.catch(err => {
openSnack("Failed to update grain inventory");
})
.finally(() => {
if (afterUpdate) {
loadBins();
afterUpdate();
}
closeDialog();
});
};
const decreaseInv = () => {
let binFrom = activeBinSettings;
let binTo: Bin;
let binFromInv = pond.BinInventory.fromObject({
...binFrom.inventory
});
if (decreaseMode === "moved") {
//TODO-CS: re-think the logic for moving between bins since the addition of custom types,
//possibly remove restrictions and just have a confirmation for the user to change the destination bins grain type
binTo = bins[binIndex];
if (binTo.settings.inventory && binTo.settings.specs) {
let binToInv = binTo.settings.inventory;
//check to make sure the grain types of both bins are the same
if (binFromInv.grainType !== binToInv.grainType) {
if (
binToInv.grainType === pond.Grain.GRAIN_NONE ||
binToInv.grainType === pond.Grain.GRAIN_INVALID ||
binToInv.grainBushels < 1
) {
binTo.settings.inventory.grainType = binFromInv.grainType;
} else {
openSnack("Grain types of both bins must match");
return;
}
}
//check if the other bin has enough space to move the grain
let space = binTo.settings.specs.bushelCapacity - binTo.settings.inventory.grainBushels;
if (space < currentBushels - newGrainInventory) {
openSnack("Bin does not have enough space");
return;
}
binToInv.grainBushels = binToInv.grainBushels + (currentBushels - newGrainInventory);
}
}
binFromInv.grainBushels = newGrainInventory;
binFrom.inventory = binFromInv;
binAPI
.updateBin(activeBinSettings.key, binFrom)
.then(() => {
//update inventory of the bin that the grain was moved to if it was a decrease
if (decreaseMode === "moved") {
binAPI
.updateBin(bins[binIndex].key(), binTo.settings)
.then(() => {
openSnack("Grain inventory updated");
})
.catch(err => {
openSnack("Failed to update grain inventory");
})
.finally(() => {
if (afterUpdate) {
afterUpdate(binTo);
}
});
}
})
.catch(err => {
openSnack("Failed to update grain inventory");
})
.finally(() => {
if (decreaseMode !== "moved" && afterUpdate) {
afterUpdate();
}
closeDialog();
});
};
const setNewInventory = () => {
if (currentBushels > newGrainInventory) {
decreaseInv();
} else {
increaseInv();
}
};
const closeDialog = (useCallback?: boolean) => {
onClose(useCallback);
};
const disableButton = () => {
if (increaseMode === "grown") {
if (fields.length === 0 || fieldIndex < 0) {
return true;
}
}
return false;
};
return (
<ResponsiveDialog open={dialogControl} onClose={() => closeDialog(true)}>
<DialogTitle>Grain Adjustment for {activeBinSettings.name}</DialogTitle>
<DialogContent>{dialogContent()}</DialogContent>
<DialogActions>
<Button onClick={() => closeDialog(true)} color="primary">
Cancel
</Button>
<Button onClick={setNewInventory} color="primary" disabled={disableButton()}>
Confirm
</Button>
</DialogActions>
</ResponsiveDialog>
);
}

View file

@ -10,7 +10,7 @@ import ResponsiveDialog from "common/ResponsiveDialog";
import { Field, HarvestPlan, Task } from "models";
import moment from "moment";
import { pond } from "protobuf-ts/pond";
import { useHarvestPlanAPI, useTaskAPI } from "providers";
import { useGlobalState, useHarvestPlanAPI, useTaskAPI } from "providers";
import { useCallback, useEffect, useState } from "react";
interface Props {
@ -22,6 +22,7 @@ interface Props {
export default function DuplicateHarvestPlan(props: Props) {
const { open, close, fields, plan } = props;
const [{as}] = useGlobalState();
const [newFieldIndex, setNewFieldIndex] = useState(0);
const [planTasks, setPlanTasks] = useState<Task[]>([]);
const [title, setTitle] = useState("");
@ -30,7 +31,7 @@ export default function DuplicateHarvestPlan(props: Props) {
const [ready, setReady] = useState(false);
const loadTasks = useCallback(() => {
taskAPI.listTasks(50, 0, "asc", "start", plan.key()).then(resp => {
taskAPI.listTasks(50, 0, "asc", "start", plan.key(), undefined).then(resp => {
setPlanTasks(resp.data.tasks.map(t => Task.any(t)));
setReady(true);
});
@ -51,7 +52,7 @@ export default function DuplicateHarvestPlan(props: Props) {
let tasks = planTasks;
tasks.forEach(task => {
task.settings.objectKey = resp.data.harvestPlan;
taskAPI.addTask(task.settings);
taskAPI.addTask(task.settings, as);
});
});
close();

View file

@ -25,7 +25,7 @@ import { useMobile, useSnackbar } from "hooks";
import { Field, HarvestPlan, Task } from "models";
import moment from "moment";
import { pond } from "protobuf-ts/pond";
import { useHarvestPlanAPI, useTaskAPI } from "providers";
import { useGlobalState, useHarvestPlanAPI, useTaskAPI } from "providers";
import React, { useCallback, useEffect, useState } from "react";
import TaskSettings from "tasks/TaskSettings";
@ -161,6 +161,7 @@ const steps = ["Pre-Seeding", "Seeding", "Post-Seeding", "Harvest", "Fall"];
export default function HarvestSettings(props: Props) {
const { open, plan, close, field, update } = props;
const [{as}] = useGlobalState()
const [planKey, setPlanKey] = useState<string>();
const [newPlan, setNewPlan] = useState(HarvestPlan.create());
const [activeStep, setActiveStep] = useState(0);
@ -185,11 +186,11 @@ export default function HarvestSettings(props: Props) {
const loadTasks = useCallback(() => {
if (planKey) {
taskAPI.getMultiTasks([planKey]).then(resp => {
taskAPI.getMultiTasks([planKey], as).then(resp => {
setPlanTasks(resp.data.tasks.map(t => Task.any(t)));
});
}
}, [taskAPI, planKey]);
}, [taskAPI, planKey, as]);
useEffect(() => {
loadTasks();

View file

@ -4,7 +4,7 @@ import MapMarkerSettings from "maps/MapMarkerSettings";
import { Bin as IBin } from "models";
//import Bin from "pages/Bin";
import { pond } from "protobuf-ts/pond";
import { useBinAPI, useSnackbar } from "providers";
import { useBinAPI, useGlobalState, useSnackbar } from "providers";
import React, { lazy, useEffect, useState } from "react";
const Bin = lazy(() => import("pages/Bin"));
@ -21,6 +21,7 @@ interface Props {
export default function BinDrawer(props: Props) {
const { open, onClose, selectedBin, bins, removeMarker, updateMarker, moveMap } = props;
const [{as}] = useGlobalState()
const [bin, setBin] = useState<IBin>(IBin.create());
const [openMarkerSettings, setOpenMarkerSettings] = useState(false);
const binAPI = useBinAPI();
@ -96,7 +97,7 @@ export default function BinDrawer(props: Props) {
settings.location = null;
binAPI
.updateBin(bin.key(), settings)
.updateBin(bin.key(), settings, as)
.then(resp => {
openSnack("Removed bin marker");
removeMarker(bin.key());
@ -135,7 +136,7 @@ export default function BinDrawer(props: Props) {
let settings = bin.settings;
settings.theme = newTheme;
binAPI
.updateBin(bin.key(), settings)
.updateBin(bin.key(), settings, as)
.then(resp => {
openSnack("marker settings updated");
updateMarker(bin.key(), settings);

View file

@ -983,7 +983,7 @@ import { Result } from "@mapbox/mapbox-gl-geocoder";
const updateBinMarkers = (bin: IBin, long: number, lat: number, newMarker?: boolean) => {
bin.setLocation(long, lat);
binAPI
.updateBin(bin.key(), bin.settings)
.updateBin(bin.key(), bin.settings, as)
.then(resp => {
openSnack("Bin Location Updated");
//remove from options

View file

@ -2,7 +2,7 @@ import { Button, Grid2 as Grid, InputAdornment, TextField } from "@mui/material"
import SearchSelect, { Option } from "common/SearchSelect";
import { GrainOptions } from "grain";
import { pond } from "protobuf-ts/pond";
import { useBinAPI, useSnackbar } from "providers";
import { useBinAPI, useGlobalState, useSnackbar } from "providers";
import React, { useState } from "react";
import { fahrenheitToCelsius, getDistanceUnit, getTemperatureUnit } from "utils";
@ -19,6 +19,7 @@ export default function BulkBinSettings(props: Props) {
const gridItemWidth = 3;
// bin settings variables
const [name, setName] = useState<string | undefined>();
const [{as}] = useGlobalState();
const [grainType, setGrainType] = useState<pond.Grain | undefined>();
const [grainOption, setGrainOption] = useState<Option | null>();
const [height, setHeight] = useState<number | undefined>();
@ -70,7 +71,7 @@ export default function BulkBinSettings(props: Props) {
}
});
binAPI
.bulkBinUpdate(binsToEdit)
.bulkBinUpdate(binsToEdit, as)
.then(resp => {
if (resp.data.successfull > 0) {
refreshCallback(true);

View file

@ -168,7 +168,7 @@ export default function Bin(props: Props) {
// const binID = binKey ?? match.params.binID;
const binID = binKey ?? useParams<{ binID: string }>()?.binID ?? "";
const binAPI = useBinAPI();
const [{ user }] = useGlobalState();
const [{ user, as }] = useGlobalState();
const [binLoading, setBinLoading] = useState(false);
const loadRef = useRef<boolean>(false);
const [bin, setBin] = useState<IBin>(IBin.create());
@ -269,7 +269,7 @@ export default function Bin(props: Props) {
loadRef.current = true;
//add the presets to the bin page data load
binAPI
.getBinPageData(binID, user.id(), showErrors)
.getBinPageData(binID, user.id(), showErrors, as)
.then(resp => {
if (resp.data.grainCompositionNames) {
let tempMap: Map<string, string> = new Map();
@ -347,7 +347,7 @@ export default function Bin(props: Props) {
loadRef.current = false;
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [binID, user.id(), binAPI, showErrors]);
}, [binID, user.id(), binAPI, showErrors, as]);
useEffect(() => {
load();
@ -788,7 +788,7 @@ export default function Bin(props: Props) {
}
});
//update the bins status with the new values based on the components changed
binAPI.updateBinStatus(bin.key(), bin.status);
binAPI.updateBinStatus(bin.key(), bin.status, as);
};
const binComponents = (preferences: Map<string, pond.BinComponentPreferences>) => {

View file

@ -503,7 +503,7 @@ export default function Bins(props: Props) {
}, [loadBins, props.insert, contentFilter]);
const duplicateBin = (bin: Bin) => {
binAPI.addBin(bin.settings).then(resp => {
binAPI.addBin(bin.settings, as).then(resp => {
loadBins();
});
};

View file

@ -117,7 +117,7 @@ export default function Contract() {
if (!loading) {
setLoading(true);
contractAPI
.getContractPageData(contractKey)
.getContractPageData(contractKey, as)
.then(resp => {
setContract(IContract.any(resp.data.contract));
//setValidTransactions(resp.data.transactions.map(t => Transaction.create(t)));
@ -150,7 +150,7 @@ export default function Contract() {
//setInvalid(true);
});
}
}, [contractKey, contractAPI]); // eslint-disable-line react-hooks/exhaustive-deps
}, [contractKey, contractAPI, as]); // eslint-disable-line react-hooks/exhaustive-deps
const contractDisplay = () => {
return (

View file

@ -56,7 +56,7 @@ export default function Contracts() {
})
.catch(err => {});
}
}, [contractAPI, year]); // eslint-disable-line react-hooks/exhaustive-deps
}, [contractAPI, year, as]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<PageContainer>

View file

@ -10,32 +10,36 @@ import { useGlobalState } from "providers";
import { quack } from "protobuf-ts/quack";
export interface IBinAPIContext {
addBin: (bin: pond.BinSettings) => Promise<AxiosResponse<pond.AddBinResponse>>;
updateBin: (key: string, bin: pond.BinSettings) => Promise<AxiosResponse<pond.UpdateBinResponse>>;
bulkBinUpdate: (bins: pond.BinSettings[]) => Promise<AxiosResponse<pond.BulkBinUpdateResponse>>;
addBin: (bin: pond.BinSettings, as?: string) => Promise<AxiosResponse<pond.AddBinResponse>>;
updateBin: (key: string, bin: pond.BinSettings, as?: string) => Promise<AxiosResponse<pond.UpdateBinResponse>>;
bulkBinUpdate: (bins: pond.BinSettings[], as?: string) => Promise<AxiosResponse<pond.BulkBinUpdateResponse>>;
updateBinStatus: (
key: string,
binStatus: pond.BinStatus
binStatus: pond.BinStatus,
as?: string
) => Promise<AxiosResponse<pond.UpdateBinResponse>>;
removeBin: (key: string) => Promise<AxiosResponse<pond.RemoveBinResponse>>;
getBin: (key: string) => Promise<AxiosResponse<pond.Bin>>;
removeBin: (key: string, as?: string) => Promise<AxiosResponse<pond.RemoveBinResponse>>;
getBin: (key: string, as?: string) => Promise<AxiosResponse<pond.Bin>>;
addComponent: (
bin: string,
device: number,
component: string,
preferences?: pond.BinComponentPreferences
preferences?: pond.BinComponentPreferences,
as?: string
) => Promise<AxiosResponse<pond.AddBinComponentResponse>>;
removeComponent: (
bin: string,
component: string
component: string,
as?: string
) => Promise<AxiosResponse<pond.RemoveBinComponentResponse>>;
removeAllComponents: (bin: string) => Promise<AxiosResponse<pond.RemoveAllBinComponentsResponse>>;
removeAllComponents: (bin: string, as?: string) => Promise<AxiosResponse<pond.RemoveAllBinComponentsResponse>>;
updateComponentPreferences: (
bin: string,
component: string,
preferences: pond.BinComponentPreferences
preferences: pond.BinComponentPreferences,
as?: string
) => Promise<AxiosResponse<pond.UpdateBinComponentPreferencesResponse>>;
getBinPageData: (binKey: string, userKey: string, showErrors?: boolean) => Promise<AxiosResponse<pond.GetBinPageDataResponse>>;
getBinPageData: (binKey: string, userKey: string, showErrors?: boolean, as?: string) => Promise<AxiosResponse<pond.GetBinPageDataResponse>>;
listBins: (
limit: number,
offset: number,
@ -84,13 +88,14 @@ export interface IBinAPIContext {
key: string,
start: string,
end: string,
showErrors?: boolean
showErrors?: boolean,
as?: string
) => Promise<AxiosResponse<pond.ListBinComponentsMeasurementsResponse>>;
updateBinPermissions: (
key: string,
users: User[]
) => Promise<AxiosResponse<pond.UpdateBinResponse>>;
getBinMetrics: (search?: string) => Promise<AxiosResponse<pond.GetBinMetricsResponse>>;
getBinMetrics: (search?: string, as?: string) => Promise<AxiosResponse<pond.GetBinMetricsResponse>>;
listBinLiters: (
key: string,
start: string,
@ -99,12 +104,14 @@ export interface IBinAPIContext {
plenum: string,
cable: string,
pressure: string,
fan?: string // the fan controller is optional so that if they don't have one the fan is assumed on
fan?: string, // the fan controller is optional so that if they don't have one the fan is assumed on
as?: string
) => Promise<AxiosResponse<pond.ListBinLiterResponse>>;
listBinPrefs: (key: string) => Promise<AxiosResponse<pond.ListBinComponentPreferencesResponse>>;
updateTopNodes: (
key: string,
newTopNodes: pond.NewTopNode[]
newTopNodes: pond.NewTopNode[],
as?: string
) => Promise<AxiosResponse<pond.UpdateTopNodesResponse>>;
listBinMeasurements: (
key: string,
@ -116,7 +123,8 @@ export interface IBinAPIContext {
measurementType?: number | quack.MeasurementType,
keys?: string[],
types?: string[],
showErrors?: boolean
showErrors?: boolean,
as?: string
) => Promise<AxiosResponse<pond.ListObjectMeasurementsResponse>>;
}
@ -128,9 +136,9 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
const { children } = props;
const { get, post, put, del } = useHTTP();
const permissionAPI = usePermissionAPI();
const [{ as }] = useGlobalState();
//const [{ as }] = useGlobalState();
const addBin = (bin: pond.BinSettings) => {
const addBin = (bin: pond.BinSettings, as?: string) => {
const url = "/bins" + (as ? "?as=" + as : "")
return new Promise<AxiosResponse<pond.AddBinResponse>>((resolve, reject)=>{
post<pond.AddBinResponse>(pondURL(url), bin).then(resp => {
@ -142,7 +150,7 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
})
};
const updateBin = (key: string, bin: pond.BinSettings) => {
const updateBin = (key: string, bin: pond.BinSettings, as?: string) => {
const url = "/bins/" + key + (as ? "?as=" + as : "")
return new Promise<AxiosResponse<pond.UpdateBinResponse>>((resolve, reject)=>{
put<pond.UpdateBinResponse>(pondURL(url), bin).then(resp => {
@ -154,7 +162,7 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
})
};
const bulkBinUpdate = (bins: pond.BinSettings[]) => {
const bulkBinUpdate = (bins: pond.BinSettings[], as?: string) => {
let url = "/bulkBins/update"
if (as) url = url + "?as=" + as
return new Promise<AxiosResponse<pond.BulkBinUpdateResponse>>((resolve, reject)=>{
@ -167,7 +175,7 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
})
};
const updateBinStatus = (key: string, binStatus: pond.BinStatus) => {
const updateBinStatus = (key: string, binStatus: pond.BinStatus, as?: string) => {
let url = "/bins/" + key + "/status"
if (as) url = url + "?as=" + as
return new Promise<AxiosResponse<pond.UpdateBinStatusResponse>>((resolve, reject)=>{
@ -180,7 +188,7 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
})
};
const removeBin = (key: string) => {
const removeBin = (key: string, as?: string) => {
let url = "/bins/" + key
if (as) url = url + "?as=" + as
return new Promise<AxiosResponse<pond.RemoveBinResponse>>((resolve, reject) => {
@ -193,7 +201,7 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
})
};
const getBin = (key: string) => {
const getBin = (key: string, as?: string) => {
const url = "/bins/" + key + (as ? "?as=" + as : "")
return new Promise<AxiosResponse<pond.Bin>>((resolve, reject)=>{
get<pond.Bin>(pondURL(url))
@ -211,7 +219,8 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
bin: string,
device: number,
component: string,
preferences?: pond.BinComponentPreferences
preferences?: pond.BinComponentPreferences,
as?: string
) => {
let url = "/bins/" + bin + "/addComponent/" + device + "/" + component;
if (as) {
@ -233,7 +242,7 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
})
};
const removeComponent = (bin: string, component: string) => {
const removeComponent = (bin: string, component: string, as?: string) => {
let url = "/bins/" + bin + "/removeComponent/" + component;
if (as) url = url + "?as=" + as;
return new Promise<AxiosResponse<pond.RemoveBinComponentResponse>>((resolve, reject)=>{
@ -246,7 +255,7 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
})
};
const removeAllComponents = (bin: string) => {
const removeAllComponents = (bin: string, as?: string) => {
let url = "/bins/" + bin + "/removeAllComponents";
if (as) url = url + "?as=" + as;
return new Promise<AxiosResponse<pond.RemoveAllBinComponentsResponse>>((resolve, reject)=>{
@ -262,7 +271,8 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
const updateComponentPreferences = (
bin: string,
component: string,
preferences: pond.BinComponentPreferences
preferences: pond.BinComponentPreferences,
as?: string
) => {
let url = "/bins/" + bin + "/updateComponent/" + component + "/preferences";
if (as) url = url + "/?as=" + as;
@ -280,7 +290,7 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
})
};
const getBinPageData = (binKey: string, userKey: string, showErrors = true) => {
const getBinPageData = (binKey: string, userKey: string, showErrors = true, as?: string) => {
const url = "/bins/" +
binKey +
"/users/" +
@ -419,7 +429,8 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
key: string,
start: string,
end: string,
showErrors = false
showErrors = false,
as?: string
) => {
let url = "/bins/" +
key +
@ -475,7 +486,7 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
return permissionAPI.updatePermissions(binScope(key.toString()), users);
};
const getBinMetrics = (search?: string) => {
const getBinMetrics = (search?: string, as?: string) => {
let url = "/metrics/bins" + (search ? "?search=" + search : "")
if (as) {
if (search){
@ -501,7 +512,8 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
plenum: string,
cable: string,
pressure: string,
fan?: string
fan?: string,
as?: string
) => {
const url = "/bins/" +
key +
@ -531,7 +543,7 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
})
};
const listBinPrefs = (key: string) => {
const listBinPrefs = (key: string, as?: string) => {
const url = "/bins/" + key + "/componentPreferences?as=" + as
return new Promise<AxiosResponse<pond.ListBinComponentPreferencesResponse>>((resolve, reject)=>{
get<pond.ListBinComponentPreferencesResponse>(pondURL(url))
@ -544,7 +556,7 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
})
};
const updateTopNodes = (key: string, newTopNodes: pond.NewTopNode[]) => {
const updateTopNodes = (key: string, newTopNodes: pond.NewTopNode[], as?: string) => {
let body: pond.TopNodeList = pond.TopNodeList.create({ newTopNodes: newTopNodes });
let url = "/bins/" + key + "/updateTopNodes" + (as ? "?as=" + as : "")
return new Promise<AxiosResponse<pond.UpdateTopNodesResponse>>((resolve,response) => {
@ -567,7 +579,8 @@ export default function BinProvider(props: PropsWithChildren<Props>) {
measurementType?: number | quack.MeasurementType,
keys?: string[],
types?: string[],
showErrors?: boolean
showErrors?: boolean,
as?: string
) => {
const url = pondURL(
"/objects/" +

View file

@ -8,7 +8,8 @@ import { useGlobalState } from "providers";
export interface IContractInterface {
addContract: (
name: string,
settings: pond.ContractSettings
settings: pond.ContractSettings,
as?: string
) => Promise<AxiosResponse<pond.AddContractResponse>>;
listContracts: (
limit: number,
@ -25,9 +26,10 @@ export interface IContractInterface {
updateContract: (
key: string,
name: string,
settings: pond.ContractSettings
settings: pond.ContractSettings,
as?: string
) => Promise<AxiosResponse<pond.UpdateContractResponse>>;
removeContract: (key: string) => Promise<AxiosResponse<pond.RemoveContractResponse>>;
removeContract: (key: string, as?: string) => Promise<AxiosResponse<pond.RemoveContractResponse>>;
listContractsByYear: (
limit: number,
offset: number,
@ -42,7 +44,7 @@ export interface IContractInterface {
as?: string
) => Promise<AxiosResponse<pond.ListContractsByYearResponse>>;
//list contract page data
getContractPageData: (key: string) => Promise<AxiosResponse<pond.GetContractPageDataResponse>>;
getContractPageData: (key: string, as?: string) => Promise<AxiosResponse<pond.GetContractPageDataResponse>>;
//for the moment however simply passing the contract from the earlier list is sufficient
}
@ -53,10 +55,10 @@ interface Props {}
export default function ContractProvider(props: PropsWithChildren<Props>) {
const { children } = props;
const { get, del, post, put } = useHTTP();
const [{ as }] = useGlobalState();
//const [{ as }] = useGlobalState();
//add
const addContract = (name: string, settings: pond.ContractSettings) => {
const addContract = (name: string, settings: pond.ContractSettings, as?: string) => {
if (as) {
return post<pond.AddContractResponse>(
pondURL("/contracts?name=" + name + "&as=" + as),
@ -75,7 +77,8 @@ export default function ContractProvider(props: PropsWithChildren<Props>) {
keys?: string[],
types?: string[],
numerical?: boolean,
specificUser?: string
specificUser?: string,
as?: string
) => {
let asText = "";
if (as) asText = "&as=" + as;
@ -130,7 +133,7 @@ export default function ContractProvider(props: PropsWithChildren<Props>) {
);
};
//update
const updateContract = (key: string, name: string, settings: pond.ContractSettings) => {
const updateContract = (key: string, name: string, settings: pond.ContractSettings, as?: string) => {
if (as) {
return put<pond.UpdateContractResponse>(
pondURL("/contracts/" + key + "?as=" + as + "&name=" + name),
@ -143,14 +146,14 @@ export default function ContractProvider(props: PropsWithChildren<Props>) {
);
};
//remove
const removeContract = (key: string) => {
const removeContract = (key: string, as?: string) => {
if (as) {
return del<pond.RemoveContractResponse>(pondURL("/contracts/" + key + "?as=" + as));
}
return del<pond.RemoveContractResponse>(pondURL("/contracts/" + key + "?as=" + as));
};
const getContractPageData = (key: string) => {
const getContractPageData = (key: string, as?: string) => {
if (as) {
return get<pond.GetContractPageDataResponse>(pondURL("/contractsPage/" + key + "?as=" + as));
}

View file

@ -6,8 +6,8 @@ import { createContext, PropsWithChildren, useContext } from "react";
import { pondURL } from "./pond";
export interface ITaskAPIContext {
addTask: (task: pond.TaskSettings) => Promise<AxiosResponse<pond.AddTaskResponse>>;
getTask: (taskID: string) => Promise<AxiosResponse<pond.Task>>;
addTask: (task: pond.TaskSettings, as?: string) => Promise<AxiosResponse<pond.AddTaskResponse>>;
getTask: (taskID: string, as?: string) => Promise<AxiosResponse<pond.Task>>;
listTasks: (
limit: number,
offset: number,
@ -19,13 +19,14 @@ export interface ITaskAPIContext {
from?: string,
to?: string
) => Promise<AxiosResponse<pond.ListTasksResponse>>;
removeTask: (taskID: string) => Promise<AxiosResponse<pond.RemoveTaskResponse>>;
removeTask: (taskID: string, as?: string) => Promise<AxiosResponse<pond.RemoveTaskResponse>>;
updateTask: (
key: string,
task: pond.TaskSettings,
asRoot?: true
asRoot?: true,
as?: string
) => Promise<AxiosResponse<pond.UpdateTaskResponse>>;
getMultiTasks: (objectKeys: string[]) => Promise<AxiosResponse<pond.GetMultiTasksResponse>>;
getMultiTasks: (objectKeys: string[], as?: string) => Promise<AxiosResponse<pond.GetMultiTasksResponse>>;
}
export const TaskAPIContext = createContext<ITaskAPIContext>({} as ITaskAPIContext);
@ -35,19 +36,19 @@ interface Props {}
export default function TaskProvider(props: PropsWithChildren<Props>) {
const { children } = props;
const { get, del, post, put } = useHTTP();
const [{ as }] = useGlobalState();
//const [{ as }] = useGlobalState();
const addTask = (task: pond.TaskSettings) => {
const addTask = (task: pond.TaskSettings, as?: string) => {
if (as) return post<pond.AddTaskResponse>(pondURL("/tasks?as=" + as), task);
return post<pond.AddTaskResponse>(pondURL("/tasks"), task);
};
const getTask = (taskID: string) => {
const getTask = (taskID: string, as?: string) => {
if (as) return get<pond.Task>(pondURL("/task/" + taskID + "?as=" + as));
return get<pond.Task>(pondURL("/task/" + taskID));
};
const removeTask = (key: string) => {
const removeTask = (key: string, as?: string) => {
if (as) return del<pond.RemoveTaskResponse>(pondURL("/tasks/" + key + "?as=" + as));
return del<pond.RemoveTaskResponse>(pondURL("/tasks/" + key));
};
@ -81,7 +82,7 @@ export default function TaskProvider(props: PropsWithChildren<Props>) {
);
};
const updateTask = (key: string, task: pond.TaskSettings, asRoot?: boolean) => {
const updateTask = (key: string, task: pond.TaskSettings, asRoot?: boolean, as?: string) => {
if (as)
return put<pond.UpdateTaskResponse>(
pondURL("/tasks/" + key + "?as=" + as + (asRoot ? "&asRoot=" + asRoot.toString() : "")),
@ -93,7 +94,7 @@ export default function TaskProvider(props: PropsWithChildren<Props>) {
);
};
const getMultiTasks = (objectKeys: string[]) => {
const getMultiTasks = (objectKeys: string[], as?: string) => {
if (as)
return get<pond.GetMultiTasksResponse>(
pondURL("/multitasks?objectKeys=" + objectKeys.join(",") + "&as=" + as)

View file

@ -119,7 +119,7 @@ export default function TaskSettings(props: Props) {
returnTask.settings = taskSettings;
taskAPI
.addTask(taskSettings)
.addTask(taskSettings, as)
.then(resp => {
props.onClose(true);
})
@ -145,7 +145,7 @@ export default function TaskSettings(props: Props) {
: 0;
taskAPI
.updateTask(task.key, task.settings)
.updateTask(task.key, task.settings, undefined, as)
.then(resp => {
props.onClose(true);
})

View file

@ -144,7 +144,7 @@ export default function TaskViewer(props: ViewProps) {
let temp = new Map<string, Task>();
setLoaded(false);
taskAPI
.getMultiTasks(loadKeys)
.getMultiTasks(loadKeys, as)
.then(resp => {
resp.data.tasks.forEach(task => {
if (task.settings) {
@ -158,7 +158,7 @@ export default function TaskViewer(props: ViewProps) {
openSnack("Failed to load");
});
}
}, [loadKeys, openSnack, taskAPI]);
}, [loadKeys, openSnack, taskAPI, as]);
//loads tasks from the backend database
const loadTasks = useCallback(() => {
@ -194,7 +194,7 @@ export default function TaskViewer(props: ViewProps) {
task.settings.complete = !task.settings.complete;
taskAPI
.updateTask(task.key, task.settings)
.updateTask(task.key, task.settings, undefined, as)
.then(resp => {
openSnack("Task Updated");
loadTasks();
@ -206,7 +206,7 @@ export default function TaskViewer(props: ViewProps) {
const deleteTask = (task: Task) => {
taskAPI
.removeTask(task.key)
.removeTask(task.key, as)
.then(resp => {
openSnack("Task Removed");
loadTasks();