Compare commits

..

No commits in common. "develop" and "v1.0.0-staging.4" have entirely different histories.

28 changed files with 288 additions and 1535 deletions

View File

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

View File

@ -1,27 +0,0 @@
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"

28
.gitlab-ci.yml Normal file
View File

@ -0,0 +1,28 @@
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
View File

@ -1,24 +0,0 @@
# 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,6 +21,7 @@ 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)
@ -45,7 +46,7 @@ Un tracker d'habitudes pour performer au boulot et dans la vie de tous les jours
```sh
# Cloner le projet
git clone git@github.com:theoludwig/p61-project.git
git clone git@git.unistra.fr:rrll/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.1.1",
"version": "1.0.0-staging.4",
"orientation": "portrait",
"icon": "./presentation/assets/images/icon.png",
"scheme": "p61-project",
@ -15,7 +15,7 @@
"assetBundlePatterns": ["**/*"],
"ios": {
"supportsTablet": true,
"buildNumber": "1.1.1"
"buildNumber": "1.0.0"
},
"android": {
"adaptiveIcon": {
@ -23,7 +23,7 @@
"backgroundColor": "#ffffff"
},
"package": "com.theoludwig.p61project",
"versionCode": 6
"versionCode": 2
},
"web": {
"bundler": "metro",

View File

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

View File

@ -1,26 +0,0 @@
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

@ -0,0 +1,50 @@
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

@ -1,23 +0,0 @@
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,11 +1,10 @@
import { Button, Text } from "react-native-paper"
import { View } from "react-native"
import { Button } from "react-native-paper"
import { About } from "@/presentation/react-native/components/About"
import { useAuthentication } from "@/presentation/react/contexts/Authentication"
const SettingsPage: React.FC = () => {
const { logout, authenticationPresenter, user } = useAuthentication()
const { logout, authenticationPresenter } = useAuthentication()
const handleLogout = async (): Promise<void> => {
await authenticationPresenter.logout()
@ -24,34 +23,6 @@ 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>
}
/>
)
}

1
docs/ARCHITECTURE.md Normal file
View File

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

View File

@ -19,7 +19,7 @@ npm run test
npm run test -- --u
```
Une pipeline CI est en place pour vérifier que le code respecte ces bonnes pratiques et que les tests passent.
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.
## GitFlow

View File

@ -11,12 +11,6 @@ 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,29 +96,4 @@ 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,16 +51,6 @@ 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.1.1",
"version": "1.0.0-staging.4",
"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.2",
"@hookform/resolvers": "3.4.0",
"@react-native-async-storage/async-storage": "1.23.1",
"@react-navigation/native": "6.1.17",
"@supabase/supabase-js": "2.43.2",
@ -35,23 +35,19 @@
"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.5",
"react-hook-form": "7.51.4",
"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",
@ -69,21 +65,21 @@
"@types/node": "20.12.12",
"@types/react": "18.2.79",
"@types/react-test-renderer": "18.3.0",
"@typescript-eslint/eslint-plugin": "7.10.0",
"@typescript-eslint/parser": "7.10.0",
"@typescript-eslint/eslint-plugin": "7.9.0",
"@typescript-eslint/parser": "7.9.0",
"eslint": "8.57.0",
"eslint-config-conventions": "14.2.0",
"eslint-config-conventions": "14.1.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": "53.0.0",
"eslint-plugin-unicorn": "51.0.1",
"husky": "9.0.11",
"jest": "29.7.0",
"jest-expo": "51.0.2",
"jest-junit": "16.0.0",
"lint-staged": "15.2.4",
"lint-staged": "15.2.2",
"prettier": "3.2.5",
"react-test-renderer": "18.2.0",
"supabase": "1.167.4",

View File

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

View File

@ -185,6 +185,19 @@ 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,7 +4,6 @@ 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"
@ -31,19 +30,12 @@ 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[] => {
const results = fuse.search(icon).map((result) => {
return result.item
})
const uniqueResults = Array.from(new Set(results))
return uniqueResults.slice(0, 50)
return iconNames
.filter((name, index, self) => {
return name.includes(icon) && self.indexOf(name) === index
})
.slice(0, 50)
}
export const IconSelectorModal: React.FC<IconSelectorModalProps> = ({

View File

@ -1,268 +0,0 @@
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,17 +1,16 @@
import type { IconName } from "@fortawesome/free-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome"
import { Link, useRouter } from "expo-router"
import { useRouter } from "expo-router"
import type LottieView from "lottie-react-native"
import { useState } from "react"
import { View } from "react-native"
import { Button, Checkbox, List, Text } from "react-native-paper"
import { 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
@ -81,32 +80,14 @@ 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 (
<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>
<Text>
{goalProgress.progress.toLocaleString()} /{" "}
{goalProgress.goal.target.value.toLocaleString()}{" "}
{goalProgress.goal.target.unit}
</Text>
</View>
)
}

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 { LOCALE, capitalize } from "@/utils/strings"
import { 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(LOCALE, {
{selectedDate.toLocaleDateString("en-US", {
weekday: "long",
year: "numeric",
month: "long",

View File

@ -1,116 +0,0 @@
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

@ -1,83 +0,0 @@
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)
})
})
})

View File

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

View File

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