[Developer] #204 Phase 1 MVP — Flutter app skeleton complete

- Drift 21 tables (8 catalog + 11 user + habit_dose_variants + meta_kv)
  with R1~R10 CHECK constraints and 19 indexes
- 8 hand-crafted seed JSON catalogs in app/assets/seed/
  (refs 84, protocols 34, methodologies 21, frame_patterns 30,
   reward_menu_items 30, break_protocols 8, common_frames 5, diet_patterns 5)
- 6 domain functions: recommend_variant, compute_streak,
  validate_frame_level, active_habit_quota, weekly_minimum_ratio,
  seed_importer (transactional, idempotent)
- 4 vertical-slice Riverpod screens: HabitList, HabitCreate, CheckIn, Streak
- 31 unit tests passing; flutter analyze clean
- OQ-5 streak semantics: missing entry ≠ explicit blank
  (missing = end of history; only TrackerValue.blank triggers Never-miss-twice)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-12 10:33:03 +09:00
parent 29befe4d97
commit 8fe6a8f378
76 changed files with 29059 additions and 0 deletions

View File

@@ -0,0 +1,82 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/time.dart';
import '../../data/db/daos/tracker_dao.dart';
import '../../state/providers.dart';
class CheckInScreen extends ConsumerStatefulWidget {
final String habitId;
const CheckInScreen({super.key, required this.habitId});
@override
ConsumerState<CheckInScreen> createState() => _CheckInScreenState();
}
class _CheckInScreenState extends ConsumerState<CheckInScreen> {
bool _saving = false;
Future<void> _record(String value) async {
setState(() => _saving = true);
try {
final dao = ref.read(trackerDaoProvider);
await dao.recordCheckIn(TrackerEntryDraft(
habitId: widget.habitId,
date: _ymd(nowKst()),
value: value,
));
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(value == 'done' ? '체크인 완료' : '오늘은 비움')),
);
Navigator.of(context).pop();
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('실패: $e')),
);
} finally {
if (mounted) setState(() => _saving = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('체크인')),
body: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('오늘 (${_ymd(nowKst())})',
style: Theme.of(context).textTheme.titleLarge,
textAlign: TextAlign.center),
const SizedBox(height: 32),
FilledButton(
onPressed: _saving ? null : () => _record('done'),
child: const Padding(
padding: EdgeInsets.symmetric(vertical: 16),
child: Text('완료', style: TextStyle(fontSize: 18)),
),
),
const SizedBox(height: 12),
OutlinedButton(
onPressed: _saving ? null : () => _record('blank'),
child: const Padding(
padding: EdgeInsets.symmetric(vertical: 12),
child: Text('비움'),
),
),
],
),
),
);
}
}
String _ymd(DateTime d) =>
'${d.year.toString().padLeft(4, '0')}-'
'${d.month.toString().padLeft(2, '0')}-'
'${d.day.toString().padLeft(2, '0')}';

View File

@@ -0,0 +1,137 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/constants.dart';
import '../../core/time.dart';
import '../../data/db/daos/habit_dao.dart';
import '../../domain/models/habit.dart';
import '../../domain/rules/active_habit_quota.dart';
import '../../state/providers.dart';
class HabitCreateScreen extends ConsumerStatefulWidget {
const HabitCreateScreen({super.key});
@override
ConsumerState<HabitCreateScreen> createState() => _HabitCreateScreenState();
}
class _HabitCreateScreenState extends ConsumerState<HabitCreateScreen> {
final _formKey = GlobalKey<FormState>();
final _titleCtrl = TextEditingController();
final _framedCtrl = TextEditingController();
HabitType _type = HabitType.build;
FrameLevel _level = FrameLevel.l2;
bool _saving = false;
@override
void dispose() {
_titleCtrl.dispose();
_framedCtrl.dispose();
super.dispose();
}
Future<void> _save() async {
if (!_formKey.currentState!.validate()) return;
setState(() => _saving = true);
try {
final dao = ref.read(habitDaoProvider);
final count = await dao.countActive(
userId: kLocalDefaultUserId,
type: _type,
);
final quota = judgeActiveHabitQuota(type: _type, currentActiveCount: count);
if (!quota.allowed) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(quota.reason)),
);
return;
}
await dao.insertWithVariants(HabitDraft(
userId: kLocalDefaultUserId,
type: _type,
title: _titleCtrl.text.trim(),
// Placeholder: vertical-slice uses the first seeded protocol.
protocolId: _type == HabitType.build ? 'morning_sunlight' : null,
breakProtocolId: _type == HabitType.breakHabit ? 'alcohol' : null,
frameLevel: _level,
frameFramedText: _framedCtrl.text.trim(),
startedAt: _ymd(nowKst()),
));
if (!mounted) return;
Navigator.of(context).pop();
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('저장 실패: $e')),
);
} finally {
if (mounted) setState(() => _saving = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('새 습관')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: ListView(
children: [
TextFormField(
controller: _titleCtrl,
decoration: const InputDecoration(labelText: '제목'),
validator: (v) =>
(v == null || v.trim().isEmpty) ? '제목을 입력하세요' : null,
),
const SizedBox(height: 16),
DropdownButtonFormField<HabitType>(
initialValue: _type,
items: const [
DropdownMenuItem(value: HabitType.build, child: Text('만들기 (build)')),
DropdownMenuItem(
value: HabitType.breakHabit, child: Text('없애기 (break)')),
],
onChanged: (v) => setState(() => _type = v ?? HabitType.build),
decoration: const InputDecoration(labelText: '타입'),
),
const SizedBox(height: 16),
DropdownButtonFormField<FrameLevel>(
initialValue: _level,
items: const [
DropdownMenuItem(value: FrameLevel.l2, child: Text('L2 · 조건부 긍정')),
DropdownMenuItem(value: FrameLevel.l3, child: Text('L3 · 정체성')),
],
onChanged: (v) => setState(() => _level = v ?? FrameLevel.l2),
decoration: const InputDecoration(labelText: '프레임 레벨'),
),
const SizedBox(height: 16),
TextFormField(
controller: _framedCtrl,
decoration: const InputDecoration(
labelText: '프레임 문구',
hintText: '예: 아침 햇빛을 10분 받는다',
),
maxLines: 2,
validator: (v) =>
(v == null || v.trim().isEmpty) ? '프레임 문구를 입력하세요' : null,
),
const SizedBox(height: 24),
FilledButton(
onPressed: _saving ? null : _save,
child: Text(_saving ? '저장 중...' : '저장'),
),
],
),
),
),
);
}
}
String _ymd(DateTime d) =>
'${d.year.toString().padLeft(4, '0')}-'
'${d.month.toString().padLeft(2, '0')}-'
'${d.day.toString().padLeft(2, '0')}';

View File

@@ -0,0 +1,72 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../state/providers.dart';
import 'check_in_screen.dart';
import 'habit_create_screen.dart';
import 'streak_screen.dart';
class HabitListScreen extends ConsumerWidget {
const HabitListScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final boot = ref.watch(bootstrapProvider);
final habitsAsync = ref.watch(activeHabitsProvider);
return Scaffold(
appBar: AppBar(title: const Text('습관')),
body: boot.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, st) => Center(child: Text('초기화 실패: $e')),
data: (_) => habitsAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, st) => Center(child: Text('로드 실패: $e')),
data: (habits) {
if (habits.isEmpty) {
return const Center(
child: Text('아직 습관이 없습니다. + 버튼으로 추가하세요.'),
);
}
return ListView.separated(
itemCount: habits.length,
separatorBuilder: (_, _) => const Divider(height: 1),
itemBuilder: (context, i) {
final h = habits[i];
return ListTile(
title: Text(h.title),
subtitle: Text(
'${h.type} · ${h.frameLevel} · ${h.frameFramedText}',
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
trailing: IconButton(
icon: const Icon(Icons.show_chart),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => StreakScreen(habitId: h.id),
));
},
),
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => CheckInScreen(habitId: h.id),
));
},
);
},
);
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => const HabitCreateScreen(),
));
},
child: const Icon(Icons.add),
),
);
}
}

View File

@@ -0,0 +1,102 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/time.dart';
import '../../domain/models/tracker_entry.dart';
import '../../domain/streak/compute_streak.dart';
import '../../state/providers.dart';
class StreakScreen extends ConsumerWidget {
final String habitId;
const StreakScreen({super.key, required this.habitId});
@override
Widget build(BuildContext context, WidgetRef ref) {
final db = ref.watch(appDatabaseProvider);
final habitFuture = (db.select(db.habits)
..where((t) => t.id.equals(habitId)))
.getSingle();
final entriesFuture = ref.read(trackerDaoProvider).entriesForHabit(habitId);
return Scaffold(
appBar: AppBar(title: const Text('스트릭')),
body: FutureBuilder(
future: Future.wait([habitFuture, entriesFuture]),
builder: (context, snap) {
if (!snap.hasData) {
return const Center(child: CircularProgressIndicator());
}
if (snap.hasError) {
return Center(child: Text('실패: ${snap.error}'));
}
final habit = snap.data![0] as dynamic;
final entryRows = snap.data![1] as List;
final entries = entryRows.map((r) {
return TrackerEntryModel(
id: r.id as String,
habitId: r.habitId as String,
date: r.date as String,
value: (r.value as String) == 'done'
? TrackerValue.done
: TrackerValue.blank,
variantId: r.variantId as String?,
ctxLocation: r.ctxLocation as String?,
ctxCondition: r.ctxCondition as String?,
note: r.note as String?,
loggedAt: r.loggedAt as String?,
);
}).toList();
final state = computeStreak(
entries: entries,
asOf: nowKst(),
habitStartedAt: habit.startedAt as String,
);
return Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(habit.title as String,
style: Theme.of(context).textTheme.titleLarge),
const SizedBox(height: 24),
_Row('현재 스트릭', '${state.currentStreak}'),
_Row('최장 스트릭', '${state.longestStreak}'),
_Row('최근 30일 / 완료', '${state.doneCountInWindow30}'),
_Row('Phase 42일 / 완료', '${state.doneCountInPhase42}'),
const Divider(height: 32),
_Row('현재 티어', state.currentTier.dbValue),
if (state.neverMissTwiceBroken)
const Padding(
padding: EdgeInsets.only(top: 12),
child: Text(
'⚠ Never miss twice 발동 — 티어 강등',
style: TextStyle(color: Colors.redAccent),
),
),
],
),
);
},
),
);
}
}
class _Row extends StatelessWidget {
final String label;
final String value;
const _Row(this.label, this.value);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
children: [
Expanded(child: Text(label)),
Text(value, style: const TextStyle(fontWeight: FontWeight.w600)),
],
),
);
}
}