Compare commits

..

26 Commits

Author SHA1 Message Date
fbbe74a082
docs: update to use GitHub instead of GitLab 2024-05-27 18:42:52 +02:00
8029204d44
chore: add MIT License 2024-05-23 23:13:39 +02:00
15ab592513
ci: usage of GitHub Actions 2024-05-23 23:03:36 +02:00
beac8b37dc
docs: delete ARCHITECTURE.md file as not done yet 2024-05-23 22:53:16 +02:00
0793720f70
chore(release): v1.1.1 2024-05-23 15:56:22 +02:00
Maxime RICHARD
b789fad149 fix: center 2024-05-23 15:55:00 +02:00
Maxime RICHARD
671639862c fix: added scrollview to the stats page 2024-05-23 15:46:25 +02:00
5099e472bc
chore(release): v1.1.0 2024-05-23 14:00:04 +02:00
Xc165543337
ab6af07a31 feat: user name display in settings 2024-05-23 13:51:22 +02:00
Xc165543337
66501cc595 feat: numeric habit progress with history 2024-05-23 13:42:31 +02:00
Xc165543337
fdbbec3e11 feat: numeric habit progress with icon 2024-05-23 13:22:02 +02:00
89aab00e6e
chore(release): v1.0.0 2024-05-23 00:36:52 +02:00
47bf926fd8
fix: habits statistics center CircularProgress 2024-05-23 00:33:29 +02:00
c455326f8e
feat: update habit progress numeric 2024-05-23 00:31:21 +02:00
dbc19d7056 Merge branch 'perf/search-icons-with-fuse-js' into 'develop'
perf: search icons with Fuse.js

See merge request rrll/p61-project!7
2024-05-22 17:24:09 +00:00
Xc165543337
35b3c5b965 fix: duplicated icons in list 2024-05-22 19:18:54 +02:00
Xc165543337
1bf5fdeaca perf: implementation of Fuse.js for fuzzy searching icons 2024-05-22 19:05:01 +02:00
d98f3144cb Merge branch 'feat/stats' into 'develop'
feat: habits statistics

See merge request rrll/p61-project!6
2024-05-22 11:46:14 +00:00
e15a3982fd
fix: habits statistics 2024-05-22 13:44:54 +02:00
ca122e9fce
Revert "feat: finish stas"
This reverts commit 42f5623c92ff8d2950ff6e48d6058af208c22c1c.
2024-05-22 12:46:51 +02:00
Maxime RICHARD
42f5623c92 feat: finish stas 2024-05-21 23:35:04 +02:00
2ab7413f32
Merge branch 'develop' into feat/stats 2024-05-20 23:56:21 +02:00
2b15e9f28e
fix: usage of svg in production build 2024-05-20 16:22:58 +02:00
Maxime RICHARD
e68fe6075e feat: stats v1 2024-05-20 15:35:49 +02:00
Maxime RICHARD
c03cd2b96d feat: stats continue 2024-04-12 15:27:11 +02:00
Maxime RICHARD
b6395b71b9 feat: debut page stats 2024-04-12 13:43:49 +02:00
28 changed files with 1535 additions and 288 deletions

View File

@ -1,4 +1,5 @@
{
"root": true,
"extends": [
"conventions",
"plugin:react/recommended",
@ -15,9 +16,6 @@
"version": "detect"
}
},
"parserOptions": {
"project": "./tsconfig.json"
},
"rules": {
"react/react-in-jsx-scope": "off",
"react/prop-types": "off",
@ -35,8 +33,9 @@
{
"files": ["*.ts", "*.tsx"],
"parser": "@typescript-eslint/parser",
"rules": {
"@typescript-eslint/member-delimiter-style": "off"
"plugins": ["@typescript-eslint"],
"parserOptions": {
"project": "./tsconfig.json"
}
}
]

27
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,27 @@
name: "ci"
on:
push:
branches: [develop]
pull_request:
branches: [main, develop, staging]
jobs:
ci:
runs-on: "ubuntu-latest"
steps:
- uses: "actions/checkout@v4.1.6"
- name: "Setup Node.js"
uses: "actions/setup-node@v4.0.2"
with:
node-version: "20.x"
cache: "npm"
- run: "npm clean-install"
- run: "npm run expo:typed-routes"
- run: 'npm run lint:commit -- --to "${{ github.sha }}"'
- run: "npm run lint:prettier"
- run: "npm run lint:eslint"
- run: "npm run lint:typescript"
- run: "npm run test"

View File

@ -1,28 +0,0 @@
default:
image: "node:20.13.1"
stages:
- "test"
test:
stage: "test"
only:
- "merge_requests"
- "develop"
script:
- "npm clean-install"
- "npm run expo:typed-routes"
- 'echo "${CI_COMMIT_MESSAGE}" | npm run lint:commit'
- "npm run lint:prettier"
- "npm run lint:eslint"
- "npm run lint:typescript"
- "npm run test"
# artifacts:
# paths:
# - "coverage/"
# reports:
# coverage_report:
# coverage_format: "cobertura"
# path: "coverage/cobertura-coverage.xml"
# junit: "junit.xml"
# coverage: '/All files[^|]*\|[^|]*\s+([\d\.]+)/'

24
LICENSE Normal file
View File

@ -0,0 +1,24 @@
# MIT License
Copyright (c) Théo LUDWIG <contact@theoludwig.fr>
Copyright (c) Haoxuan LI <haoxuan.li@etu.unistra.fr>
Copyright (c) Maxime RUMPLER <mrumpler68@gmail.com>
Copyright (c) Maxime RICHARD <maxime.richard2@etu.unistra.fr>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -21,7 +21,6 @@ Un tracker d'habitudes pour performer au boulot et dans la vie de tous les jours
- [Sujet](./docs/SUJET.md) + [Cahier des charges](./docs/CAHIER-DES-CHARGES.md)
- [Modèle Logique des Données (MLD)](./docs/MLD.md)
- [Architecture](./docs/ARCHITECTURE.md)
- [Conventions développement informatique](./docs/CONVENTIONS.md)
- [Kanban Board (Trello)](https://trello.com/b/8kYlcLA8/habits-tracker)
@ -46,7 +45,7 @@ Un tracker d'habitudes pour performer au boulot et dans la vie de tous les jours
```sh
# Cloner le projet
git clone git@git.unistra.fr:rrll/p61-project.git
git clone git@github.com:theoludwig/p61-project.git
# Se déplacer dans le répertoire du projet
cd p61-project

View File

@ -2,7 +2,7 @@
"expo": {
"name": "Habits Tracker",
"slug": "p61-project",
"version": "1.0.0-staging.4",
"version": "1.1.1",
"orientation": "portrait",
"icon": "./presentation/assets/images/icon.png",
"scheme": "p61-project",
@ -15,7 +15,7 @@
"assetBundlePatterns": ["**/*"],
"ios": {
"supportsTablet": true,
"buildNumber": "1.0.0"
"buildNumber": "1.1.1"
},
"android": {
"adaptiveIcon": {
@ -23,7 +23,7 @@
"backgroundColor": "#ffffff"
},
"package": "com.theoludwig.p61project",
"versionCode": 2
"versionCode": 6
},
"web": {
"bundler": "metro",

View File

@ -45,11 +45,11 @@ const TabLayout: React.FC = () => {
}}
/>
<Tabs.Screen
name="habits/history"
name="habits/statistics"
options={{
title: "History",
title: "Statistics",
tabBarIcon: ({ color }) => {
return <TabBarIcon name="history" color={color} />
return <TabBarIcon name="line-chart" color={color} />
},
}}
/>

View File

@ -0,0 +1,26 @@
import { Redirect, useLocalSearchParams } from "expo-router"
import { HabitProgress } from "@/presentation/react-native/components/HabitProgress"
import { useHabitsTracker } from "@/presentation/react/contexts/HabitsTracker"
const HabitProgressPage: React.FC = () => {
const { habitId, selectedDate } = useLocalSearchParams()
const { habitsTracker } = useHabitsTracker()
const habitHistory = habitsTracker.getHabitHistoryById(habitId as string)
const selectedDateParsed = new Date(selectedDate as string)
if (habitHistory == null) {
return <Redirect href="/application/habits/" />
}
return (
<HabitProgress
habitHistory={habitHistory}
key={habitHistory.habit.id}
selectedDate={selectedDateParsed}
/>
)
}
export default HabitProgressPage

View File

@ -1,50 +0,0 @@
import { useMemo, useState } from "react"
import { View } from "react-native"
import { Agenda } from "react-native-calendars"
import { Text } from "react-native-paper"
import { SafeAreaView } from "react-native-safe-area-context"
import { getISODate, getNowDateUTC } from "@/utils/dates"
const HistoryPage: React.FC = () => {
const today = useMemo(() => {
return getNowDateUTC()
}, [])
const todayISO = getISODate(today)
const [selectedDate, setSelectedDate] = useState<Date>(today)
const selectedISODate = getISODate(selectedDate)
return (
<SafeAreaView
style={[
{
flex: 1,
backgroundColor: "white",
},
]}
>
<Agenda
firstDay={1}
showClosingKnob
showOnlySelectedDayItems
onDayPress={(date) => {
setSelectedDate(new Date(date.dateString))
}}
markedDates={{
[todayISO]: { marked: true },
}}
selected={selectedISODate}
renderList={() => {
return (
<View>
<Text>{selectedDate.toISOString()}</Text>
</View>
)
}}
/>
</SafeAreaView>
)
}
export default HistoryPage

View File

@ -0,0 +1,23 @@
import { SafeAreaView } from "react-native-safe-area-context"
import { HabitsStatistics } from "@/presentation/react-native/components/HabitsStatistics"
import { useHabitsTracker } from "@/presentation/react/contexts/HabitsTracker"
const StatisticsPage: React.FC = () => {
const { habitsTracker } = useHabitsTracker()
return (
<SafeAreaView
style={[
{
flex: 1,
backgroundColor: "white",
},
]}
>
<HabitsStatistics habitsTracker={habitsTracker} />
</SafeAreaView>
)
}
export default StatisticsPage

View File

@ -1,10 +1,11 @@
import { Button } from "react-native-paper"
import { Button, Text } from "react-native-paper"
import { View } from "react-native"
import { About } from "@/presentation/react-native/components/About"
import { useAuthentication } from "@/presentation/react/contexts/Authentication"
const SettingsPage: React.FC = () => {
const { logout, authenticationPresenter } = useAuthentication()
const { logout, authenticationPresenter, user } = useAuthentication()
const handleLogout = async (): Promise<void> => {
await authenticationPresenter.logout()
@ -23,6 +24,34 @@ const SettingsPage: React.FC = () => {
Logout
</Button>
}
footer={
<View
style={{
alignItems: "center",
marginVertical: 20,
}}
>
<Text
style={{
fontWeight: "bold",
fontSize: 18,
textAlign: "center",
}}
>
Currenty logged in as
</Text>
<Text
style={{
marginTop: 6,
fontWeight: "bold",
fontSize: 16,
textAlign: "center",
}}
>
{user?.displayName}
</Text>
</View>
}
/>
)
}

View File

@ -1 +0,0 @@
# Clean Architecture

View File

@ -19,7 +19,7 @@ npm run test
npm run test -- --u
```
Une pipeline CI ([`.gitlab-ci.yml`](../.gitlab-ci.yml)) est en place pour vérifier que le code respecte ces bonnes pratiques et que les tests passent.
Une pipeline CI est en place pour vérifier que le code respecte ces bonnes pratiques et que les tests passent.
## GitFlow

View File

@ -11,6 +11,12 @@ export const GOAL_FREQUENCIES = GOAL_FREQUENCIES_ZOD.map((frequency) => {
})
export type GoalFrequency = (typeof GOAL_FREQUENCIES)[number]
export const GOAL_FREQUENCIES_TYPES = {
daily: "day",
weekly: "week",
monthly: "month",
} as const
export const GOAL_TYPES_ZOD = [
z.literal("boolean"),
z.literal("numeric"),

View File

@ -96,4 +96,29 @@ export class HabitsTracker implements HabitsTrackerData {
)
})
}
public getHabitsStatisticsByDateAndFrequency({
selectedDate,
frequency,
}: {
selectedDate: Date
frequency: GoalFrequency
}): {
totalGoalsSuccess: number
totalGoals: number
} {
const habitsHistory = this.getHabitsHistoriesByDate({
selectedDate,
frequency,
})
let totalGoalsSuccess = 0
const totalGoals = habitsHistory.length
for (const habitHistory of habitsHistory) {
const goalProgress = habitHistory.getGoalProgressByDate(selectedDate)
if (goalProgress.isCompleted()) {
totalGoalsSuccess++
}
}
return { totalGoalsSuccess, totalGoals }
}
}

View File

@ -51,6 +51,16 @@ export class HabitGoalProgressUpdateUseCase
})
}
if (goalProgress.isNumeric()) {
return await this.habitProgressCreateRepository.execute({
habitProgressData: {
date,
goalProgress,
habitId: habitHistory.habit.id,
},
})
}
throw new Error("Not implemented")
}
}

961
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,7 @@
"name": "p61-project",
"private": true,
"main": "expo-router/entry",
"version": "1.0.0-staging.4",
"version": "1.1.1",
"scripts": {
"start": "expo start",
"android": "expo start --android",
@ -24,7 +24,7 @@
"@fortawesome/fontawesome-svg-core": "6.5.2",
"@fortawesome/free-solid-svg-icons": "6.5.2",
"@fortawesome/react-native-fontawesome": "0.3.1",
"@hookform/resolvers": "3.4.0",
"@hookform/resolvers": "3.4.2",
"@react-native-async-storage/async-storage": "1.23.1",
"@react-navigation/native": "6.1.17",
"@supabase/supabase-js": "2.43.2",
@ -35,19 +35,23 @@
"expo-status-bar": "1.12.1",
"expo-system-ui": "3.0.4",
"expo-web-browser": "13.0.3",
"fuse.js": "7.0.0",
"immer": "10.1.1",
"lottie-react-native": "6.7.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-hook-form": "7.51.4",
"react-hook-form": "7.51.5",
"react-native": "0.74.1",
"react-native-calendars": "1.1305.0",
"react-native-circular-progress-indicator": "4.4.2",
"react-native-elements": "3.4.3",
"react-native-gesture-handler": "2.16.2",
"react-native-paper": "5.12.3",
"react-native-reanimated": "3.10.1",
"react-native-safe-area-context": "4.10.1",
"react-native-screens": "3.31.1",
"react-native-svg": "15.2.0",
"react-native-svg-transformer": "1.4.0",
"react-native-url-polyfill": "2.0.0",
"react-native-vector-icons": "10.1.0",
"react-native-web": "0.19.11",
@ -65,21 +69,21 @@
"@types/node": "20.12.12",
"@types/react": "18.2.79",
"@types/react-test-renderer": "18.3.0",
"@typescript-eslint/eslint-plugin": "7.9.0",
"@typescript-eslint/parser": "7.9.0",
"@typescript-eslint/eslint-plugin": "7.10.0",
"@typescript-eslint/parser": "7.10.0",
"eslint": "8.57.0",
"eslint-config-conventions": "14.1.0",
"eslint-config-conventions": "14.2.0",
"eslint-plugin-import": "2.29.1",
"eslint-plugin-promise": "6.1.1",
"eslint-plugin-react": "7.34.1",
"eslint-plugin-react-hooks": "4.6.2",
"eslint-plugin-react-native": "4.1.0",
"eslint-plugin-unicorn": "51.0.1",
"eslint-plugin-unicorn": "53.0.0",
"husky": "9.0.11",
"jest": "29.7.0",
"jest-expo": "51.0.2",
"jest-junit": "16.0.0",
"lint-staged": "15.2.2",
"lint-staged": "15.2.4",
"prettier": "3.2.5",
"react-test-renderer": "18.2.0",
"supabase": "1.167.4",

View File

@ -7,10 +7,11 @@ import { getVersion } from "@/utils/version"
export interface AboutProps {
actionButton: React.ReactNode
footer?: React.ReactNode
}
export const About: React.FC<AboutProps> = (props) => {
const { actionButton } = props
const { actionButton, footer } = props
const version = getVersion()
@ -19,9 +20,15 @@ export const About: React.FC<AboutProps> = (props) => {
style={{
flex: 1,
paddingHorizontal: 20,
justifyContent: "center",
}}
>
<View style={{ alignItems: "center", marginVertical: 20 }}>
<View
style={{
alignItems: "center",
marginVertical: 20,
}}
>
<Text
style={{
fontWeight: "bold",
@ -67,6 +74,8 @@ export const About: React.FC<AboutProps> = (props) => {
P61 Mobile Development
</Text>
{footer}
<View
style={{
justifyContent: "center",

View File

@ -185,19 +185,6 @@ export const HabitCreateForm: React.FC<HabitCreateFormProps> = ({ user }) => {
]}
>
Habit Type
{/* <Tooltip
title="Routine habits are activities performed regularly, while Target habits involve setting specific objectives to be achieved through repeated actions."
enterTouchDelay={50}
leaveTouchDelay={25}
>
<IconButton
icon="chat-question-outline"
selected
size={24}
onPress={() => {}}
style={{ alignSelf: "center" }}
/>
</Tooltip> */}
</Text>
<SegmentedButtons
style={[{ width: "96%" }]}

View File

@ -4,6 +4,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome"
import { memo, useCallback, useEffect, useState, useTransition } from "react"
import { Modal, ScrollView, View } from "react-native"
import { Button, List, Text, TextInput } from "react-native-paper"
import Fuse from "fuse.js"
import { IconsList } from "./IconsList"
@ -30,12 +31,19 @@ const iconNames = Object.keys(fas).map((key) => {
return fas[key]?.iconName ?? key
})
const fuseOptions = {
keys: ["iconName"],
threshold: 0.4,
}
const fuse = new Fuse(iconNames, fuseOptions)
const findIconsInLibrary = (icon: string): string[] => {
return iconNames
.filter((name, index, self) => {
return name.includes(icon) && self.indexOf(name) === index
})
.slice(0, 50)
const results = fuse.search(icon).map((result) => {
return result.item
})
const uniqueResults = Array.from(new Set(results))
return uniqueResults.slice(0, 50)
}
export const IconSelectorModal: React.FC<IconSelectorModalProps> = ({

View File

@ -0,0 +1,268 @@
import { useState } from "react"
import { ScrollView, StyleSheet, View } from "react-native"
import { Button, Snackbar, Text, TextInput } from "react-native-paper"
import { SafeAreaView } from "react-native-safe-area-context"
import type { IconName } from "@fortawesome/free-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome"
import type { GoalNumeric } from "@/domain/entities/Goal"
import { GoalNumericProgress } from "@/domain/entities/Goal"
import type { HabitHistory } from "@/domain/entities/HabitHistory"
import { useHabitsTracker } from "@/presentation/react/contexts/HabitsTracker"
import { LOCALE, capitalize } from "@/utils/strings"
export interface HabitProgressProps {
habitHistory: HabitHistory
selectedDate: Date
}
export const HabitProgress: React.FC<HabitProgressProps> = ({
habitHistory,
selectedDate,
}) => {
const { habitsTrackerPresenter, habitGoalProgressUpdate } = useHabitsTracker()
const [isVisibleSnackbar, setIsVisibleSnackbar] = useState(false)
const onDismissSnackbar = (): void => {
setIsVisibleSnackbar(false)
}
const goalProgress = habitHistory.getGoalProgressByDate(selectedDate)
const goalProgresses = habitHistory.getProgressesByDate(selectedDate)
const values = {
progress: 0,
min: 0,
max: 0,
}
if (goalProgress.isNumeric()) {
values.max = goalProgress.goal.target.value
}
const [progressValue, setProgressValue] = useState(values.progress)
if (!goalProgress.isNumeric()) {
return <></>
}
const progressTotal = goalProgress.progress + progressValue
const handleSave = async (): Promise<void> => {
setIsVisibleSnackbar(true)
await habitsTrackerPresenter.habitUpdateProgress({
date: selectedDate,
habitHistory,
goalProgress: new GoalNumericProgress({
goal: habitHistory.habit.goal as GoalNumeric,
progress: progressValue,
}),
})
setProgressValue(0)
}
return (
<SafeAreaView style={{ flex: 1, justifyContent: "space-between" }}>
<View
style={{
justifyContent: "center",
alignItems: "center",
paddingHorizontal: 20,
}}
>
<View
style={{
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
gap: 15,
}}
>
<FontAwesomeIcon
size={24}
icon={habitHistory.habit.icon as IconName}
style={[
{
width: 30,
},
]}
/>
<Text
style={{
fontWeight: "bold",
fontSize: 28,
textAlign: "center",
}}
>
{habitHistory.habit.name}
</Text>
</View>
<Text
style={{
marginTop: 10,
fontWeight: "bold",
fontSize: 18,
textAlign: "center",
}}
>
{capitalize(habitHistory.habit.goal.frequency)} Progress
</Text>
<Text
style={{
fontSize: 16,
textAlign: "center",
marginBottom: 15,
}}
>
{selectedDate.toLocaleDateString(LOCALE, {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
})}
</Text>
<View
style={{
width: "100%",
borderBottomWidth: 1,
borderColor: "#f57c00",
marginVertical: 10,
}}
/>
<Text style={{ marginVertical: 10, fontWeight: "bold", fontSize: 18 }}>
{goalProgress.progress.toLocaleString(LOCALE)} /{" "}
{goalProgress.goal.target.value.toLocaleString(LOCALE)}{" "}
{goalProgress.goal.target.unit}
</Text>
<TextInput
placeholder="Progress to add (e.g: 5 000)"
value={progressValue === 0 ? "" : progressValue.toString()}
onChangeText={(text) => {
const hasDigits = /\d+$/.test(text)
if (text.length <= 0 || !hasDigits) {
setProgressValue(0)
return
}
setProgressValue(Number.parseInt(text, 10))
}}
style={[
styles.spacing,
{
width: "80%",
},
]}
mode="outlined"
keyboardType="numeric"
/>
{goalProgress.progress > 0 && progressValue > 0 ? (
<Text
style={{
fontSize: 16,
textAlign: "center",
marginBottom: 15,
}}
>
{goalProgress.progress.toLocaleString()} +{" "}
{progressValue.toLocaleString()} = {progressTotal.toLocaleString()}{" "}
{goalProgress.goal.target.unit}
</Text>
) : (
<></>
)}
<Button
mode="contained"
onPress={handleSave}
loading={habitGoalProgressUpdate.state === "loading"}
disabled={
habitGoalProgressUpdate.state === "loading" || progressValue === 0
}
style={[styles.spacing, { width: "80%" }]}
>
Save Progress
</Button>
<View
style={{
width: "100%",
borderBottomWidth: 1,
borderColor: "#f57c00",
marginVertical: 10,
}}
/>
<Text
style={{
fontWeight: "bold",
fontSize: 18,
margin: 15,
}}
>
Progress History
</Text>
<ScrollView
style={{
width: "100%",
marginVertical: 20,
}}
>
{goalProgresses.map((habitProgress, index) => {
if (!habitProgress.goalProgress.isNumeric()) {
return <></>
}
return (
<View
key={habitProgress.id + index}
style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingVertical: 10,
paddingHorizontal: 20,
borderBottomWidth: 1,
borderColor: "#f57c00",
width: "100%",
}}
>
<Text>
{habitProgress.date.toLocaleDateString(LOCALE, {
year: "numeric",
month: "long",
day: "numeric",
})}
</Text>
<Text>
{habitProgress.goalProgress.progress.toLocaleString(LOCALE)}{" "}
{habitProgress.goalProgress.goal.target.unit}
</Text>
</View>
)
})}
</ScrollView>
</View>
<Snackbar
visible={isVisibleSnackbar}
onDismiss={onDismissSnackbar}
duration={2_000}
>
Habit Saved successfully!
</Snackbar>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
spacing: {
marginVertical: 16,
},
})

View File

@ -1,16 +1,17 @@
import type { IconName } from "@fortawesome/free-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome"
import { useRouter } from "expo-router"
import { Link, useRouter } from "expo-router"
import type LottieView from "lottie-react-native"
import { useState } from "react"
import { View } from "react-native"
import { Checkbox, List, Text } from "react-native-paper"
import { Button, Checkbox, List, Text } from "react-native-paper"
import type { GoalBoolean } from "@/domain/entities/Goal"
import { GoalBooleanProgress } from "@/domain/entities/Goal"
import type { HabitHistory } from "@/domain/entities/HabitHistory"
import { useHabitsTracker } from "@/presentation/react/contexts/HabitsTracker"
import { getColorRGBAFromHex } from "@/utils/colors"
import { getISODate } from "@/utils/dates"
export interface HabitCardProps {
habitHistory: HabitHistory
@ -80,14 +81,32 @@ export const HabitCard: React.FC<HabitCardProps> = (props) => {
}}
right={() => {
if (goalProgress.isNumeric()) {
const href = {
pathname: "/application/habits/[habitId]/progress/[selectedDate]/",
params: {
habitId: habit.id,
selectedDate: getISODate(selectedDate),
},
}
return (
<View>
<Text>
{goalProgress.progress.toLocaleString()} /{" "}
{goalProgress.goal.target.value.toLocaleString()}{" "}
{goalProgress.goal.target.unit}
</Text>
</View>
<Link href={href}>
<View>
<Text>
{goalProgress.progress.toLocaleString()} /{" "}
{goalProgress.goal.target.value.toLocaleString()}{" "}
{goalProgress.goal.target.unit}
</Text>
<Button
mode="elevated"
onPress={() => {
router.push(href)
}}
>
Edit
</Button>
</View>
</Link>
)
}

View File

@ -6,7 +6,7 @@ import { Divider, List, Text } from "react-native-paper"
import { GOAL_FREQUENCIES, type GoalFrequency } from "@/domain/entities/Goal"
import type { HabitHistory } from "@/domain/entities/HabitHistory"
import type { HabitsTracker } from "@/domain/entities/HabitsTracker"
import { capitalize } from "@/utils/strings"
import { LOCALE, capitalize } from "@/utils/strings"
import confettiJSON from "../../../assets/confetti.json"
import { HabitCard } from "./HabitCard"
@ -96,7 +96,7 @@ export const HabitsList: React.FC<HabitsListProps> = (props) => {
marginTop: 20,
}}
>
{selectedDate.toLocaleDateString("en-US", {
{selectedDate.toLocaleDateString(LOCALE, {
weekday: "long",
year: "numeric",
month: "long",

View File

@ -0,0 +1,116 @@
import { Card, Divider, Text } from "react-native-paper"
import CircularProgress from "react-native-circular-progress-indicator"
import { Agenda } from "react-native-calendars"
import { useState } from "react"
import { ScrollView } from "react-native"
import { getNowDateUTC, getISODate } from "@/utils/dates"
import type { HabitsTracker } from "@/domain/entities/HabitsTracker"
import { LOCALE } from "@/utils/strings"
import {
GOAL_FREQUENCIES,
GOAL_FREQUENCIES_TYPES,
} from "@/domain/entities/Goal"
import { calculateRatio } from "@/utils/maths"
export interface HabitsStatisticsProps {
habitsTracker: HabitsTracker
}
export const HabitsStatistics: React.FC<HabitsStatisticsProps> = (props) => {
const { habitsTracker } = props
const today = getNowDateUTC()
const todayISO = getISODate(today)
const [selectedDate, setSelectedDate] = useState<Date>(today)
const selectedDateISO = getISODate(selectedDate)
return (
<Agenda
firstDay={1}
showClosingKnob
onDayPress={(date) => {
setSelectedDate(new Date(date.dateString))
}}
markedDates={{
[todayISO]: { marked: true, today: true },
}}
maxDate={todayISO}
selected={selectedDateISO}
renderList={() => {
return (
<ScrollView>
<Divider />
<Text
style={{
fontWeight: "bold",
fontSize: 22,
textAlign: "center",
marginVertical: 10,
}}
>
{selectedDate.toLocaleDateString(LOCALE, {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
})}
</Text>
{GOAL_FREQUENCIES.map((frequency) => {
const { totalGoalsSuccess, totalGoals } =
habitsTracker.getHabitsStatisticsByDateAndFrequency({
selectedDate,
frequency,
})
const percentage =
calculateRatio(totalGoalsSuccess, totalGoals) * 100
return {
totalGoalsSuccess,
totalGoals,
percentage,
frequency,
}
})
.filter(({ totalGoals }) => {
return totalGoals > 0
})
.map(
({ frequency, totalGoals, totalGoalsSuccess, percentage }) => {
return (
<Card
key={frequency}
mode="elevated"
style={{ marginVertical: 8, marginHorizontal: 10 }}
>
<Card.Content
style={{
justifyContent: "center",
alignItems: "center",
}}
>
<Text variant="bodyMedium" style={{ marginBottom: 5 }}>
{totalGoalsSuccess} achieved goals in the{" "}
{GOAL_FREQUENCIES_TYPES[frequency]} out of{" "}
{totalGoals}.
</Text>
<CircularProgress
value={percentage}
progressValueColor={"#ecf0f1"}
circleBackgroundColor="black"
titleColor="white"
title="%"
/>
</Card.Content>
</Card>
)
},
)}
</ScrollView>
)
}}
/>
)
}

View File

@ -0,0 +1,83 @@
import { calculateRatio } from "../maths"
describe("utils/maths", () => {
describe("calculateRatio", () => {
it("should calculate the ratio of a value to a total", () => {
// Arrange - Given
const value = 3
const total = 10
// Act - When
const result = calculateRatio(value, total)
// Assert - Then
const expected = 0.3
expect(result).toEqual(expected)
})
it("should return 0 if the total is 0", () => {
// Arrange - Given
const value = 3
const total = 0
// Act - When
const result = calculateRatio(value, total)
// Assert - Then
const expected = 0
expect(result).toEqual(expected)
})
it("should return 0 if the total is negative", () => {
// Arrange - Given
const value = 3
const total = -1
// Act - When
const result = calculateRatio(value, total)
// Assert - Then
const expected = 0
expect(result).toEqual(expected)
})
it("should return 0 if the value is 0", () => {
// Arrange - Given
const value = 0
const total = 10
// Act - When
const result = calculateRatio(value, total)
// Assert - Then
const expected = 0
expect(result).toEqual(expected)
})
it("should return 1 if the value is equal to the total", () => {
// Arrange - Given
const value = 10
const total = 10
// Act - When
const result = calculateRatio(value, total)
// Assert - Then
const expected = 1
expect(result).toEqual(expected)
})
it("should return 1 if the value is greater than the total", () => {
// Arrange - Given
const value = 11
const total = 10
// Act - When
const result = calculateRatio(value, total)
// Assert - Then
const expected = 1
expect(result).toEqual(expected)
})
})
})

9
utils/maths.ts Normal file
View File

@ -0,0 +1,9 @@
export const calculateRatio = (value: number, total: number): number => {
if (total <= 0) {
return 0
}
if (value >= total) {
return 1
}
return value / total
}

View File

@ -1,3 +1,5 @@
export const LOCALE = "en-US"
export const capitalize = (string: string): string => {
return string.charAt(0).toUpperCase() + string.slice(1)
}