Skip to content

Commit

Permalink
Merge pull request #84 from Field-Day-2022/main
Browse files Browse the repository at this point in the history
Catch up dev-new
  • Loading branch information
IanSkelskey authored May 20, 2024
2 parents bba0257 + ef9d9ec commit 88305b2
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 26 deletions.
8 changes: 8 additions & 0 deletions src/components/FormFields.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,14 @@ const DateTimeField = ({ dateTime, setDateTime, layout, disabled }) => {
const [date, setDate] = useState('');
const [time, setTime] = useState('');

useEffect(() => {
if (dateTime) {
setDate(getStandardizedDateTimeString(dateTime).split(' ')[0].replace(/\//g,'-'))
setTime(getStandardizedDateTimeString(dateTime).split(' ')[1])
}
}, [dateTime])


useEffect(() => {
if (date !== '' && time !== '') {
const newDate = new Date(`${date} ${time}`);
Expand Down
5 changes: 4 additions & 1 deletion src/components/NewEntryForm.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,11 @@ const CritterForm = ({ critter, project, session }) => {


useEffect(() => {
console.log(session);
let tempEntry = dataObjTemplate
tempEntry.sessionDateTime = session.dateTime;
tempEntry.sessionId = session.sessionId;
tempEntry.dateTime = session.dateTime;
tempEntry.site = session.site;
tempEntry.array = session.array;
tempEntry.taxa = critter;
Expand Down Expand Up @@ -262,7 +265,7 @@ const CritterForm = ({ critter, project, session }) => {
<div className='flex flex-col space-y-1 items-center'>
<div className='grid grid-cols-3'>
{TABLE_KEYS[critter].map((key) => {
const disabled = session[key] && key !== 'dateTime'
const disabled = session[key]
return (
<FormField
key={key}
Expand Down
19 changes: 7 additions & 12 deletions src/components/TableEntry.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import { tableRows } from '../utils/variants';
import { CheckIcon, DeleteIcon, EditIcon, XIcon } from '../assets/icons';
import { getKey, getKeys, getLabel, TABLE_LABELS } from '../const/tableLabels';
import { startEntryOperation } from '../utils/firestore';
import { notify } from './Notifier';
import { Type, notify } from './Notifier';
import { FormField } from './FormFields';
import { isNumber } from '@syncfusion/ej2-react-spreadsheet';

export const getValue = (entry, column) => {
if (!entry._document.data.value.mapValue.fields[getKey(column, name)]) {
Expand Down Expand Up @@ -43,7 +44,10 @@ export const TableEntry = forwardRef((props, ref) => {
const onSaveClickedHandler = () => {
entryUIState === 'editing' &&
startEntryOperation(
'uploadEntryEdits',
tableName.includes('Session') ?
'uploadSessionEdits'
:
'uploadEntryEdits',
{
entrySnapshot,
entryData,
Expand Down Expand Up @@ -112,14 +116,6 @@ const EntryItem = ({ entrySnapshot, dbKey, entryUIState, setEntryData, entryData
const TRUE_KEYS = ['Y', 'y', 'T', 't'];
const FALSE_KEYS = ['N', 'n', 'F', 'f'];

useEffect(() => {
if (dbKey === 'dateTime') {
let tempDate = new Date(entrySnapshot.data()[dbKey]);
setDisplayText(tempDate.toLocaleString());
setEditable(false);
}
}, []);

const onChangeHandler = (e) => {
if (BINARY_KEYS.includes(dbKey)) {
if (TRUE_KEYS.includes(e.target.value.slice(-1))) {
Expand Down Expand Up @@ -161,8 +157,7 @@ const EntryItem = ({ entrySnapshot, dbKey, entryUIState, setEntryData, entryData
<input
disabled={disabled}
className="text-center"
value={dbKey === 'dateTime' ?
displayText : entryData[dbKey] ?? 'N/A'}
value={entryData[dbKey] ?? 'N/A'}
onChange={(e) => onChangeHandler(e)}
size={size}
/>
Expand Down
21 changes: 16 additions & 5 deletions src/modals/MergeSessionsModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,30 @@ export default function MergeSessionsModal({ showModal, closeModal }) {
await deleteDoc(doc(db, `${environment === 'test' ? 'Test' : ''}${project}Session`, lastSessionSnapshot.id))
};

const updateSessionEntries = async (firstSession, lastSession) => {
console.log(lastSession);
const updateSessionEntries = async (firstSessionDateTime, lastSessionDateTime) => {
console.log(lastSessionDateTime);
console.log(`${environment === 'test' ? 'Test' : ''}${project}Data`)
const sessionDocuments = await getDocs(query(
collection(db, `${environment === 'test' ? 'Test' : ''}${project}Data`),
where('sessionDateTime', '==', lastSession)
where('sessionDateTime', '==', lastSessionDateTime)
))
const batch = writeBatch(db);
console.log(`updating these documents from ${lastSession} to ${firstSession}`)
console.log(`updating these documents from ${lastSessionDateTime} to ${firstSessionDateTime}`)
console.log(sessionDocuments)
let firstSessionId = null;
sessions.forEach(sessionDocument => {
console.log(`comparing ${sessionDocument.data().dateTime} and ${firstSessionDateTime}`)
if (sessionDocument.data().dateTime === firstSessionDateTime) {
firstSessionId = sessionDocument.data().sessionId;
console.log('is equal, setting sessionId')
return;
}
})
sessionDocuments.forEach(document => {
batch.update(doc(db, `${environment === 'test' ? 'Test' : ''}${project}Data`, document.id), {
sessionDateTime: firstSession
sessionDateTime: firstSessionDateTime,
dateTime: firstSessionDateTime,
sessionId: firstSessionId ?? new Date(firstSessionDateTime).getTime(),
})
})
await batch.commit();
Expand Down
2 changes: 1 addition & 1 deletion src/tools/NewSessionTool.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default function NewSessionTool({ setData, project, setProject }) {


const [sessionData, setSessionData] = useState({
dateTime: '0',
dateTime: '',
recorder: '',
handler: '',
site: '',
Expand Down
56 changes: 49 additions & 7 deletions src/utils/firestore.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
arrayUnion,
setDoc,
where,
writeBatch,
or,
} from 'firebase/firestore';
import { db } from './firebase';
import { Type } from '../components/Notifier';
Expand Down Expand Up @@ -131,7 +133,7 @@ const updateLizardMetadata = async (operation, operationDataObject) => {
}
};

const pushEntryChangesToFirestore = async (entrySnapshot, entryData) => {
const pushEntryChangesToFirestore = async (entrySnapshot, entryData, editMsg) => {
if (entryData.taxa === 'Lizard') {
const lastEditTime = new Date().getTime();
entryData.lastEdit = lastEditTime;
Expand All @@ -140,14 +142,45 @@ const pushEntryChangesToFirestore = async (entrySnapshot, entryData) => {
let response = [];
await setDoc(doc(db, entrySnapshot.ref.parent.id, entrySnapshot.id), entryData)
.then(() => {
response = [Type.success, 'Changes successfully written to database!'];
response = [Type.success, editMsg || 'Changes successfully written to database!'];
})
.catch((e) => {
response = [Type.error, `Error writing changes to database: ${e}`];
});
return response;
};

const editSessionAndItsEntries = async (sessionSnapshot, sessionData) => {
console.log(`editing session and its entries: ${sessionData.toString()}`);
const entries = await getDocs(
query(
collection(
db,
`${sessionSnapshot.ref.parent.id.substr(
0,
sessionSnapshot.ref.parent.id.length - 7
)}Data`
),
where('sessionId', '==', sessionSnapshot.data().sessionId)
)
);
const batch = writeBatch(db);
let entryCount = 0;
entries.docs.forEach((entry) => {
entryCount++;
batch.update(doc(db, entry.ref.parent.id, entry.id), {
dateTime: sessionData.dateTime,
sessionDateTime: sessionData.dateTime,
});
});
await batch.commit();
return pushEntryChangesToFirestore(
sessionSnapshot,
sessionData,
`Session ${entryCount > 0 && `and its ${entryCount} entries`} successfully changed`
);
};

const deleteSessionAndItsEntries = async (sessionSnapshot) => {
const entries = await getDocs(
query(
Expand All @@ -158,9 +191,13 @@ const deleteSessionAndItsEntries = async (sessionSnapshot) => {
sessionSnapshot.ref.parent.id.length - 7
)}Data`
),
where('sessionDateTime', '==', sessionSnapshot.data().dateTime)
or(
where('sessionDateTime', '==', sessionSnapshot.data().dateTime),
where('sessionId', '==', sessionSnapshot.data().sessionId)
)
)
);
console.log(entries);
let entryCount = 0;
entries.docs.forEach((entry) => {
entryCount++;
Expand All @@ -181,6 +218,8 @@ const startEntryOperation = async (operationName, operationData) => {
return deleteDocumentFromFirestore(operationData.entrySnapshot);
} else if (operationName === 'deleteSession') {
return deleteSessionAndItsEntries(operationData.entrySnapshot);
} else if (operationName === 'uploadSessionEdits') {
return editSessionAndItsEntries(operationData.entrySnapshot, operationData.entryData);
} else return [Type.error, 'Unknown error occurred'];
};

Expand Down Expand Up @@ -257,8 +296,9 @@ const getSessionsByProjectAndYear = async (environment, projectName, year) => {
const sessions = await getDocs(
query(
collection(db, `${environment}${projectName}Session`),
where('dateTime', '>=', `${year}-01-01`),
where('dateTime', '<=', `${year}-12-31`)
where('dateTime', '>=', `${year}/01/01 00:00:00`),
where('dateTime', '<=', `${year}/12/31 23:59:59`),
orderBy('dateTime', 'desc')
)
);
// console.log('sessions', sessions.docs);
Expand Down Expand Up @@ -308,7 +348,7 @@ export const uploadNewSession = async (sessionData, project, environment) => {
export const uploadNewEntry = async (entryData, project, environment) => {
let success = false;
const now = new Date();
if (entryData.dateTime === '') entryData.dateTime = getStandardizedDateTimeString(now);
if (!entryData.entryId) entryData.entryId = now.getTime();
const taxa = entryData.taxa;
if (entryData.taxa === 'Arthropod') {
if (entryData.aran === '') entryData.aran = '0';
Expand Down Expand Up @@ -342,7 +382,9 @@ export const uploadNewEntry = async (entryData, project, environment) => {
for (const key in entryData) {
if (entryData[key] === '') entryData[key] = 'N/A';
}
const entryId = `${entryData.site}${taxa}${now.getTime()}`;
const entryId = `${entryData.site}${taxa === 'N/A' ? 'Arthropod' : taxa}${
entryData.entryId || now.getTime()
}`;
let collectionName = `Test${project.replace(/\s/g, '')}Data`;
if (environment === 'live') {
collectionName = `${project.replace(/\s/g, '')}Data`;
Expand Down

0 comments on commit 88305b2

Please sign in to comment.