Skip to content

Commit

Permalink
Merge pull request #845 from BIDMCDigitalPsychiatry/self-help
Browse files Browse the repository at this point in the history
Self-help changes
  • Loading branch information
sarithapillai8 authored Dec 3, 2024
2 parents 791c195 + 2107dd7 commit 24eae20
Show file tree
Hide file tree
Showing 17 changed files with 1,809 additions and 82 deletions.
1 change: 0 additions & 1 deletion src/components/ActivityCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ export default function ActivityCard({
)
.map((v: any) => Object.assign({}, ...v))
.reduce((x, y) => x.concat(y), [])
console.log(each)
let eachData = []
each = each.map((d, key) => {
let keys = Object.keys(d)
Expand Down
11 changes: 10 additions & 1 deletion src/components/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import ImportActivity from "./Researcher/ActivityList/ImportActivity"
import PreventPage from "./PreventPage"
import { sensorEventUpdate } from "./BottomMenu"
import TwoFA from "./TwoFA"
import demo_db from "../demo_db.json"
import self_help_db from "../self_help_db.json"

function ErrorFallback({ error }) {
const [trace, setTrace] = useState([])
Expand Down Expand Up @@ -129,6 +131,11 @@ function AppRouter({ ...props }) {
const serverAddressFro2FA = ["api-staging.lamp.digital", "api.lamp.digital"]

useEffect(() => {
if (localStorage.getItem("demo_mode") === "try_it") {
LAMP.initializeDemoDB(demo_db)
} else if (localStorage.getItem("demo_mode") === "self_help") {
LAMP.initializeDemoDB(self_help_db)
}
let query = window.location.hash.split("?")
if (!!query && query.length > 1) {
let src = Object.fromEntries(new URLSearchParams(query[1]))["src"]
Expand Down Expand Up @@ -276,7 +283,9 @@ function AppRouter({ ...props }) {
}, [state])

let reset = async (identity?: any) => {
Service.deleteUserDB()
if (identity?.id != "[email protected]") {
Service.deleteUserDB()
}
Service.deleteDB()
if (typeof identity === "undefined" && LAMP.Auth._type === "participant") {
await sensorEventUpdate(null, (state.identity as any)?.id ?? null, null)
Expand Down
23 changes: 23 additions & 0 deletions src/components/DBService/DBService.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,18 @@ class DBService {
})
}

getActivityEventData(tablespace: any, key: string) {
return userDbPromise
.then(async (db) => {
return (await db.transaction([tablespace], "readonly").objectStore(tablespace).getAll()).filter(
(event) => event.activity === key
)
})
.catch((error) => {
// Do something?
})
}

addData(tablespace: any, data: any) {
return dbPromise
.then((db) => {
Expand All @@ -189,6 +201,17 @@ class DBService {
})
}

addUserDBRow(tablespace: any, data: any) {
return userDbPromise
.then((db) => {
let store = db.transaction(tablespace, "readwrite").objectStore(tablespace)
store.put(data)
})
.catch((error) => {
// Do something?
})
}

addRow(tablespace: any, data: any) {
return dbPromise
.then((db) => {
Expand Down
15 changes: 15 additions & 0 deletions src/components/DBService/UserDB.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,17 @@ interface LampUSERDB extends DBSchema {
}
indexes: { id: string }
}
activityEvents: {
key: string
value: {
activity: string
timestamp: string
duration: any
static_data: object
temporal_slices: []
}
indexes: { id: number }
}
}

export const userDbPromise = idb.openDB<LampUSERDB>(DATABASE_NAME, 1, {
Expand All @@ -21,5 +32,9 @@ export const userDbPromise = idb.openDB<LampUSERDB>(DATABASE_NAME, 1, {
const user = lampUserDb.createObjectStore("activitytags", { keyPath: "id" })
user.createIndex("id", "id", { unique: true })
}
if (!lampUserDb.objectStoreNames.contains("activityEvents")) {
const activityEvents = lampUserDb.createObjectStore("activityEvents", { autoIncrement: true })
activityEvents.createIndex("id", "id", { unique: true })
}
},
})
6 changes: 6 additions & 0 deletions src/components/EmbeddedActivity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { useTranslation } from "react-i18next"
import LAMP from "lamp-core"
import { useSnackbar } from "notistack"
import { sensorEventUpdate } from "./BottomMenu"
import { Service } from "./DBService/DBService"
const useStyles = makeStyles((theme: Theme) =>
createStyles({
backdrop: {
Expand Down Expand Up @@ -129,6 +130,11 @@ export default function EmbeddedActivity({ participant, activity, name, onComple
data["timestamp"] = activityTimestamp
data["duration"] = new Date().getTime() - activityTimestamp
setData(data)
if (LAMP.Auth._auth.id === "[email protected]") {
setTimeout(() => {
Service.addUserDBRow("activityEvents", data)
}, 500)
}
setEmbeddedActivity(undefined)
setSettings(null)
} else {
Expand Down
6 changes: 5 additions & 1 deletion src/components/Feed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ import zhLocale from "date-fns/locale/zh-CN"
import esLocale from "date-fns/locale/es"
import enLocale from "date-fns/locale/en-US"
import hiLocale from "date-fns/locale/hi"
import { getSelfHelpAllActivityEvents } from "./Participant"

const userLanguages = ["en-US", "es-ES", "hi-IN", "de-DE", "da-DK", "fr-FR", "ko-KR", "it-IT", "zh-CN"]

Expand Down Expand Up @@ -470,7 +471,10 @@ export default function Feed({
date.setSeconds(0)
let startTime = date.getTime()
let endTime = startTime + 86400000
let activityEvents = await LAMP.ActivityEvent.allByParticipant(participant.id, null, startTime, endTime, null, true)
let activityEvents =
LAMP.Auth._auth.id === "[email protected]"
? await getSelfHelpAllActivityEvents(startTime, endTime)
: await LAMP.ActivityEvent.allByParticipant(participant.id, null, startTime, endTime, null, true)
return activityEvents
}

Expand Down
32 changes: 28 additions & 4 deletions src/components/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ import { ReactComponent as Logo } from "../icons/Logo.svg"
import { ReactComponent as Logotext } from "../icons/mindLAMP.svg"
import { useTranslation } from "react-i18next"
import { Autocomplete } from "@mui/material"

import demo_db from "../demo_db.json"
import self_help_db from "../self_help_db.json"
type SuggestedUrlOption = {
label: string
}
Expand Down Expand Up @@ -58,7 +59,13 @@ const useStyles = makeStyles((theme: Theme) =>
buttonNav: {
"& button": { width: 200, "& span": { textTransform: "capitalize", fontSize: 16, fontWeight: "bold" } },
},
linkBlue: { color: "#6083E7", fontWeight: "bold", cursor: "pointer", "&:hover": { textDecoration: "underline" } },
linkBlue: {
color: "#6083E7",
fontWeight: "bold",
cursor: "pointer",
marginRight: "20px",
"&:hover": { textDecoration: "underline" },
},
loginContainer: { height: "90vh", paddingTop: "3%" },
loginInner: { maxWidth: 320 },
loginDisabled: {
Expand Down Expand Up @@ -178,7 +185,9 @@ export default function Login({ setIdentity, lastDomain, onComplete, ...props })
)
;(async () => {
await Service.deleteDB()
await Service.deleteUserDB()
if (mode != "selfHelp") {
await Service.deleteUserDB()
}
})()
setLoginClick(false)
onComplete()
Expand Down Expand Up @@ -375,10 +384,25 @@ export default function Login({ setIdentity, lastDomain, onComplete, ...props })
<Link
underline="none"
className={classes.linkBlue}
onClick={(event) => setTryitMenu(event.currentTarget)}
onClick={(event) => {
LAMP.initializeDemoDB(demo_db)
localStorage.setItem("demo_mode", "try_it")
setTryitMenu(event.currentTarget)
}}
>
{`${t("Try it")}`}
</Link>
<Link
underline="none"
className={classes.linkBlue}
onClick={(event) => {
LAMP.initializeDemoDB(self_help_db)
localStorage.setItem("demo_mode", "self_help")
handleLogin(event, "selfHelp")
}}
>
{`${t("Self Help")}`}
</Link>
<br />
<Link
underline="none"
Expand Down
75 changes: 56 additions & 19 deletions src/components/Participant.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,17 +93,52 @@ async function getHiddenEvents(participant: ParticipantObj): Promise<string[]> {
return !!_hidden.error ? [] : (_hidden.data as string[])
}

export async function getSelfHelpActivityEvents(activityId: string, from: number, to: number) {
let result = []
return await Service.getActivityEventData("activityEvents", activityId).then((res) => {
if (res) {
result = res
if (from != null) {
result = res?.filter((val) => val.timestamp >= from)
}
if (to != null) {
result = res?.filter((val) => val?.timestamp <= to)
}
}
return result.reverse()
})
}

export async function getSelfHelpAllActivityEvents(from?: number, to?: number) {
let result = []
return await Service.getAllTags("activityEvents").then((res) => {
if (res) {
result = res
if (from != null) {
result = res.filter((val) => val.timestamp >= from)
}
if (to != null) {
result = res.filter((val) => val?.timestamp <= to)
}
}
return result
})
}

export async function getEvents(participant: any, activityId: string) {
let from = new Date()
from.setMonth(from.getMonth() - 6)
let activityEvents = await LAMP.ActivityEvent.allByParticipant(
participant?.id ?? participant,
activityId,
from.getTime(),
new Date().getTime(),
null,
true
)
let activityEvents =
LAMP.Auth._auth.id === "[email protected]"
? await getSelfHelpActivityEvents(activityId, from.getTime(), new Date().getTime())
: await LAMP.ActivityEvent.allByParticipant(
participant?.id ?? participant,
activityId,
from.getTime(),
new Date().getTime(),
null,
true
)
let dates = []
let streak = 0
activityEvents.map((activityEvent, i) => {
Expand Down Expand Up @@ -168,17 +203,19 @@ export default function Participant({

useEffect(() => {
setLoading(true)
LAMP.Activity.allByParticipant(participant.id, null).then((activities) => {
setActivities(activities)
props.activeTab(tab, participant.id)
let language = !!localStorage.getItem("LAMP_user_" + participant.id)
? JSON.parse(localStorage.getItem("LAMP_user_" + participant.id)).language
: getSelectedLanguage()
? getSelectedLanguage()
: "en-US"
i18n.changeLanguage(language)
// getShowWelcome(participant).then(setOpen)
})
LAMP.Activity.allByParticipant(participant.id, null, !(LAMP.Auth._auth.serverAddress === "demo.lamp.digital")).then(
(activities) => {
setActivities(activities)
props.activeTab(tab, participant.id)
let language = !!localStorage.getItem("LAMP_user_" + participant.id)
? JSON.parse(localStorage.getItem("LAMP_user_" + participant.id)).language
: getSelectedLanguage()
? getSelectedLanguage()
: "en-US"
i18n.changeLanguage(language)
// getShowWelcome(participant).then(setOpen)
}
)
getHiddenEvents(participant).then(setHiddenEvents)
tempHideCareTeam(participant).then(setHideCareTeam)
}, [])
Expand Down
6 changes: 5 additions & 1 deletion src/components/Prevent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ const localeMap = {
"zh-HK": zhHKLocale,
}
import DateFnsUtils from "@date-io/date-fns"
import { getSelfHelpAllActivityEvents } from "./Participant"

export const dateInUTCformat = (val) => {
let month =
Expand Down Expand Up @@ -188,7 +189,10 @@ async function getActivityEvents(
from: number,
to: number
): Promise<{ [groupName: string]: ActivityEventObj[] }> {
let original = (await LAMP.ActivityEvent.allByParticipant(participant.id, null, from, to, null, true))
let original = (LAMP.Auth._auth.id === "[email protected]"
? await getSelfHelpAllActivityEvents(from, to)
: await LAMP.ActivityEvent.allByParticipant(participant.id, null, from, to, null, true)
)
.map((x) => ({
...x,
activity: _activities.find((y) => x.activity === y.id),
Expand Down
16 changes: 12 additions & 4 deletions src/components/PreventPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import PreventDBT from "./PreventDBT"
import PreventData from "./PreventData"
import PreventGoalData from "./PreventGoalData"
import VoiceRecoding from "./VoiceRecoding"
import { getSelfHelpAllActivityEvents } from "./Participant"

const useStyles = makeStyles((theme: Theme) =>
createStyles({
Expand Down Expand Up @@ -208,10 +209,17 @@ export default function PreventPage({ activityId, type, participantId, ...props
setLoading(true)
LAMP.Activity.view(activityId).then((data) => {
setActivity(data)
LAMP.ActivityEvent.allByParticipant(participantId).then((events) => {
setActivityEvents(events.filter((event) => event.activity === activityId))
setLoading(false)
})
if (LAMP.Auth._auth.id === "[email protected]") {
getSelfHelpAllActivityEvents().then((events) => {
setActivityEvents(events.filter((event) => event.activity === activityId))
setLoading(false)
})
} else {
LAMP.ActivityEvent.allByParticipant(participantId).then((events) => {
setActivityEvents(events.filter((event) => event.activity === activityId))
setLoading(false)
})
}
})
}, [])

Expand Down
15 changes: 8 additions & 7 deletions src/components/PreventSelectedActivities.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import fr from "javascript-time-ago/locale/fr"
import TimeAgo from "javascript-time-ago"
import { useTranslation } from "react-i18next"
import { VegaLite } from "react-vega"
import { getSelfHelpAllActivityEvents } from "./Participant"
TimeAgo.addLocale(en)
const timeAgo = new TimeAgo("en-US")

Expand Down Expand Up @@ -186,8 +187,6 @@ const useStyles = makeStyles((theme: Theme) =>

export const strategies = {
"lamp.survey": (slices, activity, scopedItem) =>
// (slices || []).map((x) => x.duration).reduce((prev, cur) => prev + cur, 0) / slices.length / 1000,

(slices ?? [])
.filter((x, idx) => (scopedItem !== undefined ? idx === scopedItem : true))
.map((x, idx) => {
Expand Down Expand Up @@ -216,15 +215,14 @@ export const strategies = {
} else return Number(x?.value.replace(/\"/g, "")) || 0
})
.reduce((prev, curr) => prev + curr, 0),

"lamp.spin_wheel": (slices, activity, scopedItem) => slices[slices.length - 1]?.type ?? 0,
"lamp.jewels_a": (slices, activity, scopedItem) =>
"lamp.trails_b": (slices, activity, scopedItem) =>
slices.score == "NaN"
? 0
: (parseInt(slices.score ?? 0).toFixed(1) || 0) > 100
? 100
: parseInt(slices.score ?? 0).toFixed(1) || 0,
"lamp.trails_b": (slices, activity, scopedItem) =>
"lamp.spin_wheel": (slices, activity, scopedItem) => slices[slices.length - 1]?.type ?? 0,
"lamp.jewels_a": (slices, activity, scopedItem) =>
slices.score == "NaN"
? 0
: (parseInt(slices.score ?? 0).toFixed(1) || 0) > 100
Expand Down Expand Up @@ -289,7 +287,10 @@ export const strategies = {
*/
const getPercentageSettings = async (participantId, activities: ActivityObj[]) => {
let percentage = []
let activityEvents = await LAMP.ActivityEvent.allByParticipant(participantId)
let activityEvents =
LAMP.Auth._auth.id === "[email protected]"
? await getSelfHelpAllActivityEvents()
: await LAMP.ActivityEvent.allByParticipant(participantId)
return await Promise.all(
percentage.concat(
activities.map(async (activity) => {
Expand Down
Loading

0 comments on commit 24eae20

Please sign in to comment.