Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,7 @@
## 2024-07-01 - [Interactive CBT Exercises & Granular Community Metrics]
**Инсайт:** Добавление динамически триггерируемых упражнений в AI-Коуче ('Letter to Craving' и 'HALT Analysis') повышает вовлеченность пользователей в моменты острой тяги. Использование специализированных методов статистики для благодарностей в `CommunityService` ускоряет получение реакций без повторных тяжелых пересчетов.
**Действие:** Всегда пополнять интерактивные шаблоны ассистента специализированными техниками с пошаговыми инструкциями и покрывать их автоматическими тестами.

## 2024-07-02 - [Anxiety Management & Community Gratitude Leaderboard]
**Инсайт:** Внедрение прямого триггерного вызова CBT-упражнений ("Преодоление тревоги и паники") по ключевым словам ("тревожность", "паника") мгновенно предоставляет помощь без лишних диалоговых шагов. Отображение горизонтального виджета лидеров на Стене Благодарностей в Сообществе усиливает геймификацию и социальную поддержку.
**Действие:** Для острой симптоматики всегда отдавать приоритет структурированным экстренным практикам, а в социальных модулях использовать локально рассчитываемые рейтинги участников.
19 changes: 19 additions & 0 deletions TASKS.md
Original file line number Diff line number Diff line change
Expand Up @@ -391,3 +391,22 @@
- [x] Написать модульные тесты `__tests__/Cycle23Features.test.ts` (100% прохождение всех 51 тестов).
- [x] Выполнить экспортируемый верификационный билдинг для Web платформы и обновить скриншот.
- [x] Подготовить релиз v1.23.0.

# Список задач по улучшению приложения (Цикл 24) - ВЫПОЛНЕНО ⚡

## 🤖 AI-Коуч и Встроенные Упражнения
- [x] Разработать пошаговое CBT-упражнение "Преодоление тревоги и паники" (`anxiety_management`) для купирования приступов тревоги.
- [x] Настроить триггерное распознавание терминов тревоги и паники ("тревожность", "паника", "паническая атака", "тревога") в `AICoachService.ts`.

## 📚 Контент и Обучение
- [x] Разработать новый практический микро-курс "Управление тревогой и паникой" (`anxiety_and_panic_control`) из 3 уроков с заземляющими упражнениями.
- [x] Расширить Базу Знаний 5 специализированными статьями (ID 103–107) про анатомию паники, гипервентиляцию, соматическое заземление и КПТ-рефрейминг.

## 💬 Сообщество и Социализация
- [x] Реализовать метод `getGratitudeLeaderboard` в `CommunityService` для рейтинга активных участников Стены Благодарностей.
- [x] Внедрить виджет "Лидеры благодарности" на вкладке "Общение" (`app/(tabs)/community.tsx`).

## 🛠 Тестирование и Валидация
- [x] Написать автоматические тесты `__tests__/Cycle24Features.test.ts` (100% прохождение всех 55 тестов).
- [x] Собрать Web-версию, провести визуальную проверку и обновить скриншот интерфейса (`screenshot_cycle24.png`).
- [x] Обновить версии до `v1.24.0`.
52 changes: 52 additions & 0 deletions __tests__/Cycle24Features.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { microCoursesDatabase } from '../services/microCoursesDatabase';
import { articlesDatabase, getArticleById } from '../services/articlesDatabase';
import { AICoachService } from '../services/AICoachService';
import { CommunityService } from '../services/communityService';

describe('Cycle 24 Features and Enhancements', () => {
test('New micro-course anxiety_and_panic_control exists and is structured properly', () => {
const course = microCoursesDatabase.find(c => c.id === 'anxiety_and_panic_control');
expect(course).toBeDefined();
expect(course?.title).toBe('Управление тревогой и паникой');
expect(course?.lessons.length).toBe(3);
expect(course?.lessons[0].title).toBe('Нейробиология паники');
});

test('New specialized articles 103-107 are present in articlesDatabase', () => {
const article103 = getArticleById('article-103');
expect(article103).toBeDefined();
expect(article103?.title).toBe('Анатомия панической атаки: что происходит с телом');

const article107 = getArticleById('article-107');
expect(article107).toBeDefined();
expect(article107?.title).toBe('Профилактика фоновой тревожности: дневные якори');
});

test('AICoachService offers anxiety_management exercise on panic keywords', async () => {
const responseResult = await AICoachService.getEnhancedResponse('test_user_c24', 'У меня паническая атака и сильная тревога', {
userMood: 1,
soberDays: 10,
cravingLevel: 3,
timeOfDay: 'evening'
});

expect(responseResult.success).toBe(true);
if (responseResult.success) {
const resp = responseResult.data;
expect(resp.exercise).toBeDefined();
expect(resp.exercise?.id).toBe('anxiety_management');
expect(resp.exercise?.name).toBe('Преодоление тревоги и паники');
expect(resp.exercise?.steps.length).toBe(5);
}
});

test('CommunityService getGratitudeLeaderboard calculates top contributors correctly', async () => {
const leaderboard = await CommunityService.getGratitudeLeaderboard();
expect(Array.isArray(leaderboard)).toBe(true);
expect(leaderboard.length).toBeGreaterThan(0);
// Leaderboard should be sorted descending by totalHearts
for (let i = 0; i < leaderboard.length - 1; i++) {
expect(leaderboard[i].totalHearts).toBeGreaterThanOrEqual(leaderboard[i + 1].totalHearts);
}
});
});
2 changes: 1 addition & 1 deletion app.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"expo": {
"name": "Sober Path",
"slug": "sober-path",
"version": "1.23.0",
"version": "1.24.0",
"orientation": "portrait",
"icon": "./assets/images/logo.png",
"scheme": "soberpath",
Expand Down
85 changes: 85 additions & 0 deletions app/(tabs)/community.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,7 @@ export default function CommunityPage() {
const [newStoryContent, setNewStoryContent] = useState('');
const [selectedCategory, setSelectedCategory] = useState<'motivation' | 'question' | 'support' | 'milestone'>('support');
const [gratitudes, setGratitudes] = useState<CommunityGratitude[]>([]);
const [gratitudeLeaderboard, setGratitudeLeaderboard] = useState<{ author: string; authorDaysSober: number; totalHearts: number; postCount: number }[]>([]);
const [isGratitudeModalVisible, setIsGratitudeModalVisible] = useState(false);
const [newGratitudeText, setNewGratitudeText] = useState('');
const [isLoading, setIsLoading] = useState(true);
Expand Down Expand Up @@ -379,6 +380,8 @@ export default function CommunityPage() {
setCommunityGoals(CommunityService.getCommunityGoals());
const loadedGratitudes = await CommunityService.getGratitudes();
setGratitudes(loadedGratitudes);
const leaderboard = await CommunityService.getGratitudeLeaderboard();
setGratitudeLeaderboard(leaderboard);
const loadedChallenges = await CommunityService.getGroupChallenges();
setGroupChallenges(loadedChallenges);

Expand Down Expand Up @@ -543,6 +546,8 @@ export default function CommunityPage() {
const handleGratitudeHeartPress = async (id: string) => {
const updated = await CommunityService.toggleGratitudeHeart(id);
setGratitudes(updated);
const updatedLeaderboard = await CommunityService.getGratitudeLeaderboard();
setGratitudeLeaderboard(updatedLeaderboard);

// Получить обновленную Карму
const updatedKarma = await CommunityService.getUserKarma();
Expand Down Expand Up @@ -760,6 +765,28 @@ export default function CommunityPage() {
)}
</ScrollView>

{/* Лидеры благодарности */}
{!isLoading && gratitudeLeaderboard.length > 0 && (
<View style={styles.leaderboardWidgetContainer}>
<View style={styles.leaderboardWidgetHeader}>
<MaterialIcons name="emoji-events" size={20} color="#FFD700" />
<Text style={styles.leaderboardWidgetTitle}>Лидеры благодарности</Text>
</View>
<ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.leaderboardScroll}>
{gratitudeLeaderboard.slice(0, 5).map((user, idx) => (
<View key={idx} style={styles.leaderboardUserCard}>
<Text style={styles.leaderboardRank}>#{idx + 1}</Text>
<Text style={styles.leaderboardName} numberOfLines={1}>{user.author}</Text>
<View style={styles.leaderboardStatsRow}>
<MaterialIcons name="favorite" size={12} color="#E91E63" />
<Text style={styles.leaderboardHearts}>{user.totalHearts}</Text>
</View>
</View>
))}
</ScrollView>
</View>
)}

<View style={styles.sectionHeader}>
<Text style={styles.sectionTitle}>Группы поддержки 💬</Text>
</View>
Expand Down Expand Up @@ -2418,5 +2445,63 @@ const styles = StyleSheet.create({
fontSize: 10,
color: '#2E7D4A',
marginTop: 2,
},
leaderboardWidgetContainer: {
backgroundColor: 'white',
marginHorizontal: 20,
marginTop: 15,
borderRadius: 16,
padding: 14,
elevation: 2,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.1,
shadowRadius: 2,
},
leaderboardWidgetHeader: {
flexDirection: 'row',
alignItems: 'center',
gap: 8,
marginBottom: 10,
},
leaderboardWidgetTitle: {
fontSize: 15,
fontWeight: 'bold',
color: '#333',
},
leaderboardScroll: {
gap: 10,
},
leaderboardUserCard: {
backgroundColor: '#FFFDF0',
borderRadius: 12,
paddingHorizontal: 12,
paddingVertical: 8,
alignItems: 'center',
borderWidth: 1,
borderColor: '#FCEFB4',
minWidth: 80,
},
leaderboardRank: {
fontSize: 11,
fontWeight: 'bold',
color: '#FF9800',
marginBottom: 2,
},
leaderboardName: {
fontSize: 12,
fontWeight: 'bold',
color: '#333',
marginBottom: 4,
},
leaderboardStatsRow: {
flexDirection: 'row',
alignItems: 'center',
gap: 4,
},
leaderboardHearts: {
fontSize: 11,
fontWeight: 'bold',
color: '#E91E63',
}
});
Binary file added assets/screenshots/screenshot_cycle24.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "sober-path",
"main": "expo-router/entry",
"version": "1.23.0",
"version": "1.24.0",
"scripts": {
"start": "expo start",
"reset-project": "node ./scripts/reset-project.js",
Expand Down
26 changes: 25 additions & 1 deletion services/AICoachService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,31 @@ export class AICoachService {
const knowledgeMatch = findRelevantKnowledge(userMessage);
const sentiment = this.detectSentiment(userMessage);

// Проверка на запрос упражнения
// Проверка на запрос упражнений
if (lowercaseMessage.includes('тревожность') || lowercaseMessage.includes('паника') || lowercaseMessage.includes('паническая атака') || lowercaseMessage.includes('тревога')) {
return success({
message: 'Приступ тревоги или панической атаки — это временная реакция организма на выброс адреналина. Давайте проведем экспресс-технику "Преодоление тревоги и паники", чтобы снизить пульс и вернуть спокойствие. Готовы начать?',
emotionalTone: 'supportive',
suggestions: ['Начать упражнение', 'Не сейчас'],
followUpQuestions: [],
memoryUpdates: ['User requested Anxiety and Panic Management exercise'],
confidenceLevel: 1.0,
exercise: {
id: 'anxiety_management',
name: 'Преодоление тревоги и паники',
type: 'grounding',
currentStep: -1,
steps: [
'Осознайте прямо сейчас: тревога и паника безопасны для жизни. Адреналин спадет через несколько минут.',
'Сложите ладони лодочкой перед лицом и сделайте 5 медленных циклов дыхания (вдох на 4 счета, выдох на 4 счета).',
'Плотно прижмите стопы к полу, почувствуйте твердую опору под собой. Напрягите и расслабьте икры и бёдра.',
'Найдите глазами в комнате 3 синих или зеленых предмета. Вслух или про себя назовите их.',
'Сделайте глубокий длинный выдох и скажите себе: "Я в безопасности, мое тело расслабляется, я контролирую свои мысли".'
]
}
});
}

if (lowercaseMessage.includes('мегаполис') || lowercaseMessage.includes('город') || lowercaseMessage.includes('шум') || lowercaseMessage.includes('детокс')) {
return success({
message: 'Стресс мегаполиса — частый триггер срыва. Давайте проведем сессию "Умного городского детокса", чтобы быстро сбросить напряжение и вернуть фокус. Начнем?',
Expand Down
Loading
Loading