Refine schedule/todo UI and integrate Google Photos API

This commit is contained in:
kihong.kim
2026-02-01 00:30:32 +09:00
parent 7ddd29dfed
commit c614c883d4
15 changed files with 2124 additions and 565 deletions

View File

@@ -0,0 +1,18 @@
const mongoose = require("mongoose");
const googleConfigSchema = new mongoose.Schema(
{
key: { type: String, required: true, unique: true }, // e.g., 'photos_auth'
tokens: {
access_token: String,
refresh_token: String,
scope: String,
token_type: String,
expiry_date: Number,
},
albumId: { type: String }, // Optional: to filter by a specific album
},
{ timestamps: true }
);
module.exports = mongoose.model("GoogleConfig", googleConfigSchema);

File diff suppressed because it is too large Load Diff

View File

@@ -15,6 +15,7 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"express": "^4.19.2", "express": "^4.19.2",
"googleapis": "^171.0.0",
"mongoose": "^8.9.0", "mongoose": "^8.9.0",
"multer": "^1.4.5-lts.1" "multer": "^1.4.5-lts.1"
} }

View File

@@ -2,13 +2,24 @@ const express = require("express");
const path = require("path"); const path = require("path");
const fs = require("fs"); const fs = require("fs");
const multer = require("multer"); const multer = require("multer");
const { google } = require("googleapis");
const axios = require("axios");
const Photo = require("../models/Photo"); const Photo = require("../models/Photo");
const GoogleConfig = require("../models/GoogleConfig");
const router = express.Router(); const router = express.Router();
const uploadsDir = path.join(__dirname, "..", "uploads"); const uploadsDir = path.join(__dirname, "..", "uploads");
fs.mkdirSync(uploadsDir, { recursive: true }); fs.mkdirSync(uploadsDir, { recursive: true });
const oauth2Client = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
process.env.GOOGLE_REDIRECT_URI
);
const PHOTOS_SCOPE = ["https://www.googleapis.com/auth/photoslibrary.readonly"];
const storage = multer.diskStorage({ const storage = multer.diskStorage({
destination: (req, file, cb) => { destination: (req, file, cb) => {
cb(null, uploadsDir); cb(null, uploadsDir);
@@ -22,15 +33,106 @@ const storage = multer.diskStorage({
const upload = multer({ storage }); const upload = multer({ storage });
// OAuth Endpoints
router.get("/auth/url", (req, res) => {
const url = oauth2Client.generateAuthUrl({
access_type: "offline",
scope: PHOTOS_SCOPE,
prompt: "consent",
});
res.json({ url });
});
router.get("/auth/callback", async (req, res) => {
const { code } = req.query;
try {
const { tokens } = await oauth2Client.getToken(code);
await GoogleConfig.findOneAndUpdate(
{ key: "photos_auth" },
{ tokens },
{ upsert: true }
);
res.send("<h1>Authentication successful!</h1><p>You can close this window and return to the application.</p>");
} catch (error) {
console.error("Auth error:", error);
res.status(500).send("Authentication failed");
}
});
router.get("/status", async (req, res) => {
try {
const config = await GoogleConfig.findOne({ key: "photos_auth" });
res.json({ connected: !!config && !!config.tokens });
} catch (error) {
res.status(500).json({ message: "Failed to check status" });
}
});
router.get("/disconnect", async (req, res) => {
try {
await GoogleConfig.deleteOne({ key: "photos_auth" });
res.json({ ok: true });
} catch (error) {
res.status(500).json({ message: "Failed to disconnect" });
}
});
// Fetching Routes
router.get("/", async (req, res) => { router.get("/", async (req, res) => {
try { try {
const filter = {}; const filter = {};
if (req.query.active === "true") { if (req.query.active === "true") {
filter.active = true; filter.active = true;
} }
const photos = await Photo.find(filter).sort({ createdAt: -1 });
res.json(photos); // Get local photos
const localPhotos = await Photo.find(filter).sort({ createdAt: -1 });
// Check if Google Photos is connected
const config = await GoogleConfig.findOne({ key: "photos_auth" });
if (config && config.tokens) {
try {
oauth2Client.setCredentials(config.tokens);
// Refresh token if needed
if (config.tokens.expiry_date <= Date.now()) {
const { tokens } = await oauth2Client.refreshAccessToken();
config.tokens = tokens;
await config.save();
oauth2Client.setCredentials(tokens);
}
const tokensInfo = await oauth2Client.getAccessToken();
const accessToken = tokensInfo.token;
const response = await axios.get(
"https://photoslibrary.googleapis.com/v1/mediaItems?pageSize=100",
{
headers: { Authorization: `Bearer ${accessToken}` },
}
);
const googlePhotos = (response.data.mediaItems || []).map((item) => ({
id: item.id,
url: `${item.baseUrl}=w2048-h1024`,
caption: item.description || "Google Photo",
active: true,
source: "google"
}));
// Combine local and google photos
return res.json([...localPhotos, ...googlePhotos]);
} catch (gError) {
console.error("Error fetching Google Photos:", gError);
// Fallback to local photos only if Google fails
return res.json(localPhotos);
}
}
res.json(localPhotos);
} catch (error) { } catch (error) {
console.error("Fetch error:", error);
res.status(500).json({ message: "Failed to fetch photos" }); res.status(500).json({ message: "Failed to fetch photos" });
} }
}); });

View File

@@ -3,6 +3,7 @@ import 'dart:typed_data';
import 'package:file_picker/file_picker.dart'; import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../models/bible_verse.dart'; import '../../models/bible_verse.dart';
import '../../models/family_member.dart'; import '../../models/family_member.dart';
import '../../models/photo.dart'; import '../../models/photo.dart';
@@ -567,8 +568,79 @@ class PhotoManagerTab extends StatefulWidget {
@override @override
State<PhotoManagerTab> createState() => _PhotoManagerTabState(); State<PhotoManagerTab> createState() => _PhotoManagerTabState();
} }
class _PhotoManagerTabState extends State<PhotoManagerTab> { class _PhotoManagerTabState extends State<PhotoManagerTab> {
Widget _buildGooglePhotosHeader() {
return FutureBuilder<bool>(
future: Provider.of<PhotoService>(context, listen: false).getGoogleStatus(),
builder: (context, snapshot) {
final isConnected = snapshot.data ?? false;
return Container(
padding: const EdgeInsets.all(16),
margin: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: isConnected ? Colors.green.withOpacity(0.1) : Colors.blue.withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: isConnected ? Colors.green : Colors.blue,
width: 1,
),
),
child: Row(
children: [
Icon(
isConnected ? Icons.cloud_done : Icons.cloud_off,
color: isConnected ? Colors.green : Colors.blue,
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
isConnected ? 'Google Photos Connected' : 'Google Photos Not Connected',
style: const TextStyle(fontWeight: FontWeight.bold),
),
Text(
isConnected
? 'Photos will be synced automatically.'
: 'Connect to sync your Google Photos albums.',
style: TextStyle(color: Colors.grey[600], fontSize: 12),
),
],
),
),
ElevatedButton(
onPressed: () async {
if (isConnected) {
await Provider.of<PhotoService>(context, listen: false).disconnectGoogle();
setState(() {});
} else {
try {
final url = await Provider.of<PhotoService>(context, listen: false).getGoogleAuthUrl();
final uri = Uri.parse(url);
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.externalApplication);
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Failed to connect: $e')),
);
}
}
},
style: ElevatedButton.styleFrom(
backgroundColor: isConnected ? Colors.red.withOpacity(0.1) : null,
foregroundColor: isConnected ? Colors.red : null,
),
child: Text(isConnected ? 'Disconnect' : 'Connect'),
),
],
),
);
},
);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
@@ -576,7 +648,11 @@ class _PhotoManagerTabState extends State<PhotoManagerTab> {
onPressed: () => _showAddPhotoDialog(context), onPressed: () => _showAddPhotoDialog(context),
child: const Icon(Icons.add_a_photo), child: const Icon(Icons.add_a_photo),
), ),
body: FutureBuilder<List<Photo>>( body: Column(
children: [
_buildGooglePhotosHeader(),
Expanded(
child: FutureBuilder<List<Photo>>(
future: Provider.of<PhotoService>(context).fetchPhotos(), future: Provider.of<PhotoService>(context).fetchPhotos(),
builder: (context, snapshot) { builder: (context, snapshot) {
if (!snapshot.hasData) if (!snapshot.hasData)
@@ -607,16 +683,21 @@ class _PhotoManagerTabState extends State<PhotoManagerTab> {
}, },
), ),
), ),
child: Image.network( child: photo.url.startsWith('http')
? Image.network(
photo.url, photo.url,
fit: BoxFit.cover, fit: BoxFit.cover,
errorBuilder: (_, __, ___) => errorBuilder: (_, __, ___) =>
const Center(child: Icon(Icons.broken_image)), const Center(child: Icon(Icons.broken_image)),
)
: const Center(child: Icon(Icons.photo)),
);
},
);
},
), ),
); ),
}, ],
);
},
), ),
); );
} }
@@ -780,6 +861,7 @@ class _BibleVerseManagerTabState extends State<BibleVerseManagerTab> {
itemBuilder: (context, index) { itemBuilder: (context, index) {
final verse = verses[index]; final verse = verses[index];
return ListTile( return ListTile(
onTap: () => _showEditVerseDialog(context, verse),
title: Text(verse.reference), title: Text(verse.reference),
subtitle: Text( subtitle: Text(
verse.text, verse.text,
@@ -795,6 +877,10 @@ class _BibleVerseManagerTabState extends State<BibleVerseManagerTab> {
style: style:
const TextStyle(fontSize: 12, color: Colors.grey), const TextStyle(fontSize: 12, color: Colors.grey),
), ),
IconButton(
icon: const Icon(Icons.edit, color: Colors.blue),
onPressed: () => _showEditVerseDialog(context, verse),
),
IconButton( IconButton(
icon: const Icon(Icons.delete, color: Colors.red), icon: const Icon(Icons.delete, color: Colors.red),
onPressed: () async { onPressed: () async {
@@ -816,17 +902,28 @@ class _BibleVerseManagerTabState extends State<BibleVerseManagerTab> {
} }
void _showAddVerseDialog(BuildContext context) { void _showAddVerseDialog(BuildContext context) {
final textController = TextEditingController(); _showVerseDialog(context, null);
final referenceController = TextEditingController(); }
final dateController = TextEditingController();
bool isActive = true; void _showEditVerseDialog(BuildContext context, BibleVerse verse) {
_showVerseDialog(context, verse);
}
void _showVerseDialog(BuildContext context, BibleVerse? verse) {
final isEditing = verse != null;
final textController = TextEditingController(text: verse?.text ?? '');
final referenceController = TextEditingController(text: verse?.reference ?? '');
final dateController = TextEditingController(text: verse?.date ?? '');
bool isActive = verse?.active ?? true;
showDialog( showDialog(
context: context, context: context,
builder: (context) => StatefulBuilder( builder: (context) => StatefulBuilder(
builder: (context, setDialogState) => AlertDialog( builder: (context, setDialogState) => AlertDialog(
title: const Text('Add Bible Verse'), title: Text(isEditing ? 'Edit Bible Verse' : 'Add Bible Verse'),
content: SingleChildScrollView( content: SizedBox(
width: 600, // Increased width
child: SingleChildScrollView(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
@@ -834,23 +931,44 @@ class _BibleVerseManagerTabState extends State<BibleVerseManagerTab> {
controller: referenceController, controller: referenceController,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Reference (e.g., Psalms 23:1)', labelText: 'Reference (e.g., Psalms 23:1)',
border: OutlineInputBorder(),
), ),
), ),
const SizedBox(height: 8), const SizedBox(height: 16),
TextField( TextField(
controller: textController, controller: textController,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Verse Text (Korean)', labelText: 'Verse Text (Korean)',
hintText: 'Enter verse text here. Use \\n for line breaks.',
border: OutlineInputBorder(),
alignLabelWithHint: true,
), ),
maxLines: 3, maxLines: 8, // Increased maxLines
), ),
const SizedBox(height: 8), const SizedBox(height: 16),
TextField( TextField(
controller: dateController, controller: dateController,
readOnly: true,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Date (YYYY-MM-DD) - Optional', labelText: 'Date (YYYY-MM-DD) - Optional',
hintText: '2024-01-01', hintText: 'Click to select date',
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.calendar_today),
), ),
onTap: () async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2101),
);
if (picked != null) {
setDialogState(() {
dateController.text =
picked.toIso8601String().split('T')[0];
});
}
},
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
SwitchListTile( SwitchListTile(
@@ -865,36 +983,48 @@ class _BibleVerseManagerTabState extends State<BibleVerseManagerTab> {
], ],
), ),
), ),
),
actions: [ actions: [
TextButton( TextButton(
onPressed: () => Navigator.pop(context), onPressed: () => Navigator.pop(context),
child: const Text('Cancel'), child: const Text('Cancel'),
), ),
TextButton( ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
),
onPressed: () async { onPressed: () async {
if (textController.text.isNotEmpty && if (textController.text.isNotEmpty &&
referenceController.text.isNotEmpty) { referenceController.text.isNotEmpty) {
await Provider.of<BibleVerseService>( final newVerse = BibleVerse(
context, id: verse?.id ?? '',
listen: false,
).createVerse(
BibleVerse(
id: '',
text: textController.text, text: textController.text,
reference: referenceController.text, reference: referenceController.text,
date: dateController.text.isEmpty date: dateController.text.isEmpty
? null ? null
: dateController.text, : dateController.text,
active: isActive, active: isActive,
),
); );
if (isEditing) {
await Provider.of<BibleVerseService>(
context,
listen: false,
).updateVerse(newVerse);
} else {
await Provider.of<BibleVerseService>(
context,
listen: false,
).createVerse(newVerse);
}
if (mounted) { if (mounted) {
Navigator.pop(context); Navigator.pop(context);
setState(() {}); setState(() {});
} }
} }
}, },
child: const Text('Add'), child: Text(isEditing ? 'Save Verse' : 'Add Verse'),
), ),
], ],
), ),
@@ -938,6 +1068,7 @@ class _AnnouncementManagerTabState extends State<AnnouncementManagerTab> {
itemBuilder: (context, index) { itemBuilder: (context, index) {
final announcement = announcements[index]; final announcement = announcements[index];
return ListTile( return ListTile(
onTap: () => _showEditAnnouncementDialog(context, announcement),
title: Text(announcement.title), title: Text(announcement.title),
subtitle: Text( subtitle: Text(
announcement.content, announcement.content,
@@ -950,23 +1081,32 @@ class _AnnouncementManagerTabState extends State<AnnouncementManagerTab> {
if (announcement.priority > 0) if (announcement.priority > 0)
Container( Container(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 2), horizontal: 8,
vertical: 2,
),
margin: const EdgeInsets.only(right: 8),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.orangeAccent, color: Colors.orange,
borderRadius: BorderRadius.circular(4), borderRadius: BorderRadius.circular(4),
), ),
child: Text( child: Text(
'P${announcement.priority}', 'P${announcement.priority}',
style: const TextStyle( style: const TextStyle(
color: Colors.white, fontSize: 10), fontSize: 10,
color: Colors.white,
),
), ),
), ),
const SizedBox(width: 8),
Icon( Icon(
announcement.active ? Icons.check_circle : Icons.cancel, announcement.active ? Icons.check_circle : Icons.cancel,
color: announcement.active ? Colors.green : Colors.grey, color: announcement.active ? Colors.green : Colors.grey,
size: 16, size: 16,
), ),
IconButton(
icon: const Icon(Icons.edit, color: Colors.blue),
onPressed: () =>
_showEditAnnouncementDialog(context, announcement),
),
IconButton( IconButton(
icon: const Icon(Icons.delete, color: Colors.red), icon: const Icon(Icons.delete, color: Colors.red),
onPressed: () async { onPressed: () async {
@@ -988,35 +1128,61 @@ class _AnnouncementManagerTabState extends State<AnnouncementManagerTab> {
} }
void _showAddAnnouncementDialog(BuildContext context) { void _showAddAnnouncementDialog(BuildContext context) {
final titleController = TextEditingController(); _showAnnouncementDialog(context, null);
final contentController = TextEditingController(); }
final priorityController = TextEditingController(text: '0');
bool isActive = true; void _showEditAnnouncementDialog(
BuildContext context, Announcement announcement) {
_showAnnouncementDialog(context, announcement);
}
void _showAnnouncementDialog(BuildContext context, Announcement? announcement) {
final isEditing = announcement != null;
final titleController =
TextEditingController(text: announcement?.title ?? '');
final contentController =
TextEditingController(text: announcement?.content ?? '');
final priorityController =
TextEditingController(text: announcement?.priority.toString() ?? '0');
bool isActive = announcement?.active ?? true;
showDialog( showDialog(
context: context, context: context,
builder: (context) => StatefulBuilder( builder: (context) => StatefulBuilder(
builder: (context, setDialogState) => AlertDialog( builder: (context, setDialogState) => AlertDialog(
title: const Text('Add Announcement'), title: Text(isEditing ? 'Edit Announcement' : 'Add Announcement'),
content: SingleChildScrollView( content: SizedBox(
width: 600,
child: SingleChildScrollView(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
TextField( TextField(
controller: titleController, controller: titleController,
decoration: const InputDecoration(labelText: 'Title'), decoration: const InputDecoration(
labelText: 'Title',
border: OutlineInputBorder(),
), ),
),
const SizedBox(height: 16),
TextField( TextField(
controller: contentController, controller: contentController,
decoration: const InputDecoration(labelText: 'Content'), decoration: const InputDecoration(
labelText: 'Content',
border: OutlineInputBorder(),
),
maxLines: 3, maxLines: 3,
), ),
const SizedBox(height: 16),
TextField( TextField(
controller: priorityController, controller: priorityController,
decoration: decoration: const InputDecoration(
const InputDecoration(labelText: 'Priority (0-10)'), labelText: 'Priority (0-10)',
border: OutlineInputBorder(),
),
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
), ),
const SizedBox(height: 8),
SwitchListTile( SwitchListTile(
title: const Text('Active'), title: const Text('Active'),
value: isActive, value: isActive,
@@ -1029,33 +1195,46 @@ class _AnnouncementManagerTabState extends State<AnnouncementManagerTab> {
], ],
), ),
), ),
),
actions: [ actions: [
TextButton( TextButton(
onPressed: () => Navigator.pop(context), onPressed: () => Navigator.pop(context),
child: const Text('Cancel'), child: const Text('Cancel'),
), ),
TextButton( ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
),
onPressed: () async { onPressed: () async {
if (titleController.text.isNotEmpty) { if (titleController.text.isNotEmpty) {
await Provider.of<AnnouncementService>( final newAnnouncement = Announcement(
context, id: announcement?.id ?? '',
listen: false,
).createAnnouncement(
Announcement(
id: '',
title: titleController.text, title: titleController.text,
content: contentController.text, content: contentController.text,
priority: int.tryParse(priorityController.text) ?? 0, priority: int.tryParse(priorityController.text) ?? 0,
active: isActive, active: isActive,
),
); );
if (isEditing) {
await Provider.of<AnnouncementService>(
context,
listen: false,
).updateAnnouncement(newAnnouncement);
} else {
await Provider.of<AnnouncementService>(
context,
listen: false,
).createAnnouncement(newAnnouncement);
}
if (mounted) { if (mounted) {
Navigator.pop(context); Navigator.pop(context);
setState(() {}); setState(() {});
} }
} }
}, },
child: const Text('Add'), child:
Text(isEditing ? 'Save Announcement' : 'Add Announcement'),
), ),
], ],
), ),
@@ -1099,6 +1278,7 @@ class _ScheduleManagerTabState extends State<ScheduleManagerTab> {
itemBuilder: (context, index) { itemBuilder: (context, index) {
final schedule = schedules[index]; final schedule = schedules[index];
return ListTile( return ListTile(
onTap: () => _showEditScheduleDialog(context, schedule),
title: Text(schedule.title), title: Text(schedule.title),
subtitle: Text( subtitle: Text(
'${schedule.description}\n${schedule.startDate.toIso8601String().split('T')[0]} ~ ${schedule.endDate.toIso8601String().split('T')[0]}', '${schedule.description}\n${schedule.startDate.toIso8601String().split('T')[0]} ~ ${schedule.endDate.toIso8601String().split('T')[0]}',
@@ -1106,7 +1286,14 @@ class _ScheduleManagerTabState extends State<ScheduleManagerTab> {
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
isThreeLine: true, isThreeLine: true,
trailing: IconButton( trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.edit, color: Colors.blue),
onPressed: () => _showEditScheduleDialog(context, schedule),
),
IconButton(
icon: const Icon(Icons.delete, color: Colors.red), icon: const Icon(Icons.delete, color: Colors.red),
onPressed: () async { onPressed: () async {
await Provider.of<ScheduleService>( await Provider.of<ScheduleService>(
@@ -1116,6 +1303,8 @@ class _ScheduleManagerTabState extends State<ScheduleManagerTab> {
setState(() {}); setState(() {});
}, },
), ),
],
),
); );
}, },
); );
@@ -1125,55 +1314,109 @@ class _ScheduleManagerTabState extends State<ScheduleManagerTab> {
} }
void _showAddScheduleDialog(BuildContext context) { void _showAddScheduleDialog(BuildContext context) {
final titleController = TextEditingController(); _showScheduleDialog(context, null);
final descriptionController = TextEditingController(); }
void _showEditScheduleDialog(BuildContext context, ScheduleItem schedule) {
_showScheduleDialog(context, schedule);
}
void _showScheduleDialog(BuildContext context, ScheduleItem? schedule) {
final isEditing = schedule != null;
final titleController = TextEditingController(text: schedule?.title ?? '');
final descriptionController =
TextEditingController(text: schedule?.description ?? '');
final startController = TextEditingController( final startController = TextEditingController(
text: DateTime.now().toIso8601String().split('T')[0], text: schedule?.startDate.toIso8601String().split('T')[0] ??
DateTime.now().toIso8601String().split('T')[0],
); );
final endController = TextEditingController( final endController = TextEditingController(
text: DateTime.now().toIso8601String().split('T')[0], text: schedule?.endDate.toIso8601String().split('T')[0] ??
DateTime.now().toIso8601String().split('T')[0],
); );
bool isAllDay = true; const bool isAllDay = true; // Forcing all day as requested
String? selectedFamilyMemberId; String? selectedFamilyMemberId = schedule?.familyMemberId;
showDialog( showDialog(
context: context, context: context,
builder: (context) => StatefulBuilder( builder: (context) => StatefulBuilder(
builder: (context, setDialogState) => AlertDialog( builder: (context, setDialogState) => AlertDialog(
title: const Text('Add Schedule'), title: Text(isEditing ? 'Edit Schedule' : 'Add Schedule'),
content: SingleChildScrollView( content: SizedBox(
width: 600,
child: SingleChildScrollView(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
TextField( TextField(
controller: titleController, controller: titleController,
decoration: const InputDecoration(labelText: 'Title'), decoration: const InputDecoration(
labelText: 'Title',
border: OutlineInputBorder(),
), ),
),
const SizedBox(height: 16),
TextField( TextField(
controller: descriptionController, controller: descriptionController,
decoration: const InputDecoration(labelText: 'Description'), decoration: const InputDecoration(
labelText: 'Description',
border: OutlineInputBorder(),
), ),
maxLines: 2,
),
const SizedBox(height: 16),
TextField( TextField(
controller: startController, controller: startController,
readOnly: true,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Start Date (YYYY-MM-DD)', labelText: 'Start Date (YYYY-MM-DD)',
suffixIcon: Icon(Icons.calendar_today),
border: OutlineInputBorder(),
), ),
), onTap: () async {
TextField( final DateTime? picked = await showDatePicker(
controller: endController, context: context,
decoration: const InputDecoration( initialDate: DateTime.tryParse(startController.text) ??
labelText: 'End Date (YYYY-MM-DD)', DateTime.now(),
), firstDate: DateTime(2000),
), lastDate: DateTime(2101),
SwitchListTile( );
title: const Text('All Day'), if (picked != null) {
value: isAllDay,
onChanged: (value) {
setDialogState(() { setDialogState(() {
isAllDay = value; startController.text =
picked.toIso8601String().split('T')[0];
}); });
}
}, },
), ),
const SizedBox(height: 16),
TextField(
controller: endController,
readOnly: true,
decoration: const InputDecoration(
labelText: 'End Date (YYYY-MM-DD)',
suffixIcon: Icon(Icons.calendar_today),
border: OutlineInputBorder(),
),
onTap: () async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: DateTime.tryParse(endController.text) ??
DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2101),
);
if (picked != null) {
setDialogState(() {
endController.text =
picked.toIso8601String().split('T')[0];
});
}
},
),
const SizedBox(height: 8),
// All Day toggle removed as requested
const SizedBox(height: 8),
FutureBuilder<List<FamilyMember>>( FutureBuilder<List<FamilyMember>>(
future: Provider.of<FamilyService>(context, listen: false) future: Provider.of<FamilyService>(context, listen: false)
.fetchFamilyMembers(), .fetchFamilyMembers(),
@@ -1184,6 +1427,7 @@ class _ScheduleManagerTabState extends State<ScheduleManagerTab> {
value: selectedFamilyMemberId, value: selectedFamilyMemberId,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Family Member', labelText: 'Family Member',
border: OutlineInputBorder(),
), ),
items: members.map((member) { items: members.map((member) {
return DropdownMenuItem( return DropdownMenuItem(
@@ -1202,12 +1446,13 @@ class _ScheduleManagerTabState extends State<ScheduleManagerTab> {
], ],
), ),
), ),
),
actions: [ actions: [
TextButton( TextButton(
onPressed: () => Navigator.pop(context), onPressed: () => Navigator.pop(context),
child: const Text('Cancel'), child: const Text('Cancel'),
), ),
TextButton( ElevatedButton(
onPressed: () async { onPressed: () async {
if (titleController.text.isNotEmpty) { if (titleController.text.isNotEmpty) {
final startDate = final startDate =
@@ -1215,27 +1460,35 @@ class _ScheduleManagerTabState extends State<ScheduleManagerTab> {
final endDate = final endDate =
DateTime.tryParse(endController.text) ?? DateTime.now(); DateTime.tryParse(endController.text) ?? DateTime.now();
await Provider.of<ScheduleService>( final newSchedule = ScheduleItem(
context, id: schedule?.id ?? '',
listen: false,
).createSchedule(
ScheduleItem(
id: '',
title: titleController.text, title: titleController.text,
description: descriptionController.text, description: descriptionController.text,
startDate: startDate, startDate: startDate,
endDate: endDate, endDate: endDate,
familyMemberId: selectedFamilyMemberId ?? '', familyMemberId: selectedFamilyMemberId ?? '',
isAllDay: isAllDay, isAllDay: isAllDay,
),
); );
if (isEditing) {
await Provider.of<ScheduleService>(
context,
listen: false,
).updateSchedule(newSchedule);
} else {
await Provider.of<ScheduleService>(
context,
listen: false,
).createSchedule(newSchedule);
}
if (mounted) { if (mounted) {
Navigator.pop(context); Navigator.pop(context);
setState(() {}); setState(() {});
} }
} }
}, },
child: const Text('Add'), child: Text(isEditing ? 'Save Schedule' : 'Add Schedule'),
), ),
], ],
), ),
@@ -1279,6 +1532,7 @@ class _TodoManagerTabState extends State<TodoManagerTab> {
itemBuilder: (context, index) { itemBuilder: (context, index) {
final todo = todos[index]; final todo = todos[index];
return ListTile( return ListTile(
onTap: () => _showEditTodoDialog(context, todo),
leading: Checkbox( leading: Checkbox(
value: todo.completed, value: todo.completed,
onChanged: (val) async { onChanged: (val) async {
@@ -1349,33 +1603,87 @@ class _TodoManagerTabState extends State<TodoManagerTab> {
void _showTodoDialog(BuildContext context, TodoItem? todo) { void _showTodoDialog(BuildContext context, TodoItem? todo) {
final isEditing = todo != null; final isEditing = todo != null;
final titleController = TextEditingController(text: todo?.title ?? ''); final titleController = TextEditingController(text: todo?.title ?? '');
final todoDueDate = todo?.dueDate;
final dateController = TextEditingController( final dateController = TextEditingController(
text: todo?.dueDate?.toIso8601String().split('T')[0] ?? '', text: todoDueDate != null ? todoDueDate.toIso8601String().split('T')[0] : '',
);
final timeController = TextEditingController(
text: todoDueDate != null ? TimeOfDay.fromDateTime(todoDueDate).format(context) : '',
); );
String? selectedFamilyMemberId = todo?.familyMemberId; String? selectedFamilyMemberId = todo?.familyMemberId;
bool isCompleted = todo?.completed ?? false; bool isCompleted = todo?.completed ?? false;
TimeOfDay? selectedTime = todoDueDate != null ? TimeOfDay.fromDateTime(todoDueDate) : null;
showDialog( showDialog(
context: context, context: context,
builder: (context) => StatefulBuilder( builder: (context) => StatefulBuilder(
builder: (context, setDialogState) => AlertDialog( builder: (context, setDialogState) => AlertDialog(
title: Text(isEditing ? 'Edit Todo' : 'Add Todo'), title: Text(isEditing ? 'Edit Todo' : 'Add Todo'),
content: SingleChildScrollView( content: SizedBox(
width: 600,
child: SingleChildScrollView(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
TextField( TextField(
controller: titleController, controller: titleController,
decoration: const InputDecoration(labelText: 'Title'), decoration: const InputDecoration(
labelText: 'Title',
border: OutlineInputBorder(),
), ),
),
const SizedBox(height: 16),
TextField( TextField(
controller: dateController, controller: dateController,
readOnly: true,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Due Date (YYYY-MM-DD)', labelText: 'Due Date',
hintText: '2024-01-01', hintText: 'Select date',
suffixIcon: Icon(Icons.calendar_today),
border: OutlineInputBorder(),
), ),
onTap: () async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: DateTime.tryParse(dateController.text) ??
DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2101),
);
if (picked != null) {
setDialogState(() {
dateController.text =
picked.toIso8601String().split('T')[0];
});
}
},
), ),
const SizedBox(height: 16),
TextField(
controller: timeController,
readOnly: true,
decoration: const InputDecoration(
labelText: 'Time (Optional)',
hintText: 'Select time',
suffixIcon: Icon(Icons.access_time),
border: OutlineInputBorder(),
),
onTap: () async {
final TimeOfDay? picked = await showTimePicker(
context: context,
initialTime: selectedTime ?? TimeOfDay.now(),
);
if (picked != null) {
setDialogState(() {
selectedTime = picked;
timeController.text = picked.format(context);
});
}
},
),
const SizedBox(height: 16),
FutureBuilder<List<FamilyMember>>( FutureBuilder<List<FamilyMember>>(
future: Provider.of<FamilyService>(context, listen: false) future: Provider.of<FamilyService>(context, listen: false)
.fetchFamilyMembers(), .fetchFamilyMembers(),
@@ -1386,6 +1694,7 @@ class _TodoManagerTabState extends State<TodoManagerTab> {
value: selectedFamilyMemberId, value: selectedFamilyMemberId,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Family Member', labelText: 'Family Member',
border: OutlineInputBorder(),
), ),
items: members.map((member) { items: members.map((member) {
return DropdownMenuItem( return DropdownMenuItem(
@@ -1414,25 +1723,39 @@ class _TodoManagerTabState extends State<TodoManagerTab> {
], ],
), ),
), ),
),
actions: [ actions: [
TextButton( TextButton(
onPressed: () => Navigator.pop(context), onPressed: () => Navigator.pop(context),
child: const Text('Cancel'), child: const Text('Cancel'),
), ),
TextButton( ElevatedButton(
onPressed: () async { onPressed: () async {
if (titleController.text.isNotEmpty && if (titleController.text.isNotEmpty &&
selectedFamilyMemberId != null) { selectedFamilyMemberId != null) {
final date = dateController.text.isNotEmpty DateTime? fullDate;
? DateTime.tryParse(dateController.text) if (dateController.text.isNotEmpty) {
: null; final baseDate = DateTime.tryParse(dateController.text);
if (baseDate != null) {
fullDate = baseDate;
if (selectedTime != null) {
fullDate = DateTime(
fullDate.year,
fullDate.month,
fullDate.day,
selectedTime!.hour,
selectedTime!.minute,
);
}
}
}
final newItem = TodoItem( final newItem = TodoItem(
id: todo?.id ?? '', id: todo?.id ?? '',
familyMemberId: selectedFamilyMemberId!, familyMemberId: selectedFamilyMemberId!,
title: titleController.text, title: titleController.text,
completed: isCompleted, completed: isCompleted,
dueDate: date, dueDate: fullDate,
); );
if (isEditing) { if (isEditing) {
@@ -1458,7 +1781,7 @@ class _TodoManagerTabState extends State<TodoManagerTab> {
); );
} }
}, },
child: Text(isEditing ? 'Save' : 'Add'), child: Text(isEditing ? 'Save Todo' : 'Add Todo'),
), ),
], ],
), ),

View File

@@ -90,26 +90,37 @@ class _TvDashboardScreenState extends State<TvDashboardScreen> {
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
// Left Column: Calendar, Schedule, Announcement // Left Column: Calendar, Bible Verse (Swapped)
Expanded( Expanded(
flex: 3, flex: 3,
child: Column( child: Column(
children: [ children: [
const Expanded( const Expanded(
flex: 4, child: CalendarWidget()), flex: 3, child: CalendarWidget()), // Increased flex from 2 to 3
const SizedBox(height: 16), const SizedBox(height: 16),
const Expanded( const Expanded(
flex: 4, child: ScheduleListWidget()), flex: 3, child: BibleVerseWidget()), // Reduced flex from 4 to 3
const SizedBox(height: 16),
const Expanded(
flex: 2, child: AnnouncementWidget()),
], ],
), ),
), ),
const SizedBox(width: 24), const SizedBox(width: 24),
// Center Column: Photo Slideshow // Center Column: Todos, Weekly Schedule (Swapped)
Expanded( Expanded(
flex: 4, flex: 3, // Reduced from 4 to 3
child: Column(
children: [
const Expanded(
flex: 6, child: TodoListWidget()),
const SizedBox(height: 16),
const Expanded(
flex: 6, child: ScheduleListWidget()),
],
),
),
const SizedBox(width: 24),
// Right Column: Photo Slideshow
Expanded(
flex: 4, // Increased from 3 to 4
child: Container( child: Container(
decoration: BoxDecoration( decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
@@ -125,20 +136,6 @@ class _TvDashboardScreenState extends State<TvDashboardScreen> {
child: const PhotoSlideshowWidget(), child: const PhotoSlideshowWidget(),
), ),
), ),
const SizedBox(width: 24),
// Right Column: Todos, Bible Verse
Expanded(
flex: 3,
child: Column(
children: [
const Expanded(
flex: 6, child: TodoListWidget()),
const SizedBox(height: 16),
const Expanded(
flex: 3, child: BibleVerseWidget()),
],
),
),
], ],
), ),
), ),

View File

@@ -76,4 +76,22 @@ class PhotoService {
} }
await _client.delete("${ApiConfig.photos}/$id"); await _client.delete("${ApiConfig.photos}/$id");
} }
Future<String> getGoogleAuthUrl() async {
final data = await _client.get("${ApiConfig.photos}/auth/url");
return data["url"] as String;
}
Future<bool> getGoogleStatus() async {
try {
final data = await _client.get("${ApiConfig.photos}/status");
return data["connected"] as bool? ?? false;
} catch (e) {
return false;
}
}
Future<void> disconnectGoogle() async {
await _client.get("${ApiConfig.photos}/disconnect");
}
} }

View File

@@ -88,7 +88,7 @@ class _AnnouncementWidgetState extends State<AnnouncementWidget> {
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
child: const Center( child: const Center(
child: Text( child: Text(
'Welcome Home! Have a great day.', '우리 집에 오신 것을 환영합니다! 좋은 하루 되세요.',
style: TextStyle(color: Colors.white70, fontSize: 18), style: TextStyle(color: Colors.white70, fontSize: 18),
), ),
), ),

View File

@@ -39,7 +39,7 @@ class _BibleVerseWidgetState extends State<BibleVerseWidget> {
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.white10), border: Border.all(color: Colors.white10),
), ),
padding: const EdgeInsets.all(24), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 20), // Reduced horizontal padding
child: FutureBuilder<BibleVerse>( child: FutureBuilder<BibleVerse>(
future: _verseFuture, future: _verseFuture,
builder: (context, snapshot) { builder: (context, snapshot) {
@@ -65,29 +65,40 @@ class _BibleVerseWidgetState extends State<BibleVerseWidget> {
return Column( return Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
const Icon( // Quote icon removed as requested
Icons.format_quote, Expanded(
color: Color(0xFFBB86FC), child: Center(
size: 32, child: FittedBox(
fit: BoxFit.scaleDown,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 600), // Increased width to utilize space
child: Text(
verse.text.replaceAll('\\n', '\n'), // Just handle line breaks, keep original text
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white,
fontSize: 36,
height: 1.4,
fontStyle: FontStyle.italic,
fontWeight: FontWeight.bold,
),
),
),
),
),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
Text( FittedBox(
verse.text, fit: BoxFit.scaleDown,
textAlign: TextAlign.center, child: Text(
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Colors.white,
height: 1.5,
fontStyle: FontStyle.italic,
),
),
const SizedBox(height: 8),
Text(
verse.reference, verse.reference,
style: TextStyle( style: TextStyle(
color: Theme.of(context).colorScheme.primary, color: Theme.of(context).colorScheme.primary,
fontSize: 24, // Reduced from 32
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
), ),
),
], ],
); );
}, },

View File

@@ -1,9 +1,51 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../models/schedule_item.dart';
import '../services/schedule_service.dart';
class CalendarWidget extends StatelessWidget { class CalendarWidget extends StatefulWidget {
const CalendarWidget({super.key}); const CalendarWidget({super.key});
@override
State<CalendarWidget> createState() => _CalendarWidgetState();
}
class _CalendarWidgetState extends State<CalendarWidget> {
List<ScheduleItem> _schedules = [];
@override
void initState() {
super.initState();
_loadSchedules();
}
Future<void> _loadSchedules() async {
try {
final schedules =
await Provider.of<ScheduleService>(context, listen: false)
.fetchMonthlySchedules();
if (mounted) {
setState(() {
_schedules = schedules;
});
}
} catch (e) {
debugPrint('Error loading schedules: $e');
}
}
bool _hasScheduleOn(DateTime date) {
final checkDate = DateTime(date.year, date.month, date.day);
return _schedules.any((s) {
final start =
DateTime(s.startDate.year, s.startDate.month, s.startDate.day);
final end = DateTime(s.endDate.year, s.endDate.month, s.endDate.day);
return (checkDate.isAtSameMomentAs(start) || checkDate.isAfter(start)) &&
(checkDate.isAtSameMomentAs(end) || checkDate.isBefore(end));
});
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final now = DateTime.now(); final now = DateTime.now();
@@ -12,19 +54,10 @@ class CalendarWidget extends StatelessWidget {
final daysInMonth = lastDayOfMonth.day; final daysInMonth = lastDayOfMonth.day;
final startingWeekday = firstDayOfMonth.weekday; // Mon=1, Sun=7 final startingWeekday = firstDayOfMonth.weekday; // Mon=1, Sun=7
// Simple calendar logic int offset = startingWeekday % 7;
// We need to pad the beginning with empty slots
// If week starts on Sunday, adjust accordingly. Let's assume Mon start for now or use locale.
// Let's assume standard Sun-Sat or Mon-Sun. Let's go with Sun-Sat for standard calendar view often seen in KR/US.
// DateTime.weekday: Mon=1, Sun=7.
// If we want Sun start: Sun=0, Mon=1...
// Let's adjust so Sunday is first.
int offset = startingWeekday %
7; // If startingWeekday is 7 (Sun), offset is 0. If 1 (Mon), offset is 1.
return Container( return Container(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(8),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Theme.of(context).cardTheme.color, color: Theme.of(context).cardTheme.color,
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
@@ -32,38 +65,45 @@ class CalendarWidget extends StatelessWidget {
child: Column( child: Column(
children: [ children: [
// Header // Header
Row( Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Text( Text(
DateFormat('MMMM yyyy').format(now), DateFormat('yyyy년 M월').format(now),
style: Theme.of(context).textTheme.titleLarge?.copyWith( style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: Colors.white, color: Colors.white,
fontSize: 20,
), ),
), ),
const Icon(Icons.calendar_today, color: Colors.white54), const Icon(Icons.calendar_today,
color: Colors.white54, size: 20),
], ],
), ),
const SizedBox(height: 16), ),
const SizedBox(height: 8),
// Days Header // Days Header
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: ['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((day) { children: ['', '', '', '', '', '', ''].asMap().entries.map((entry) {
final isSunday = entry.key == 0;
return Expanded( return Expanded(
child: Center( child: Center(
child: Text( child: Text(
day, entry.value,
style: const TextStyle( style: TextStyle(
color: Colors.white54, color: isSunday ? Colors.redAccent : Colors.white54,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
fontSize: 14,
), ),
), ),
), ),
); );
}).toList(), }).toList(),
), ),
const SizedBox(height: 8), const SizedBox(height: 4),
// Days Grid // Days Grid
Expanded( Expanded(
child: Column( child: Column(
@@ -73,37 +113,61 @@ class CalendarWidget extends StatelessWidget {
children: List.generate(7, (col) { children: List.generate(7, (col) {
final index = row * 7 + col; final index = row * 7 + col;
final dayNumber = index - offset + 1; final dayNumber = index - offset + 1;
final isSunday = col == 0;
if (dayNumber < 1 || dayNumber > daysInMonth) { if (dayNumber < 1 || dayNumber > daysInMonth) {
return const Expanded(child: SizedBox.shrink()); return const Expanded(child: SizedBox.shrink());
} }
final dayDate =
DateTime(now.year, now.month, dayNumber);
final isToday = dayNumber == now.day; final isToday = dayNumber == now.day;
final hasSchedule = _hasScheduleOn(dayDate);
return Expanded( return Expanded(
child: Container( child: Container(
margin: const EdgeInsets.all(2), margin: const EdgeInsets.all(1),
decoration: isToday decoration: isToday
? BoxDecoration( ? BoxDecoration(
border: Border.all(
color: Theme.of(context).colorScheme.primary, color: Theme.of(context).colorScheme.primary,
width: 2,
),
shape: BoxShape.circle, shape: BoxShape.circle,
) )
: null, : null,
child: Center( child: Stack(
alignment: Alignment.center,
children: [
Center(
child: FittedBox( child: FittedBox(
fit: BoxFit.scaleDown, fit: BoxFit.scaleDown,
child: Text( child: Text(
'$dayNumber', '$dayNumber',
style: TextStyle( style: TextStyle(
color: isToday ? Colors.black : Colors.white, color: isToday
fontWeight: isToday ? Theme.of(context).colorScheme.primary
? FontWeight.bold : (isSunday ? Colors.redAccent : Colors.white),
: FontWeight.normal, fontWeight: FontWeight.bold,
fontSize: 12, fontSize: 18,
), ),
), ),
), ),
), ),
if (hasSchedule) // Show indicator even if it's today
Positioned(
bottom: 2,
child: Container(
width: 14,
height: 4,
decoration: BoxDecoration(
color: Colors.yellowAccent,
borderRadius: BorderRadius.circular(2),
),
),
),
],
),
), ),
); );
}), }),

View File

@@ -73,7 +73,7 @@ class _ScheduleListWidgetState extends State<ScheduleListWidget> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
'Weekly Schedule', '주간 일정',
style: Theme.of(context).textTheme.titleLarge?.copyWith( style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: Colors.white, color: Colors.white,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@@ -102,17 +102,31 @@ class _ScheduleListWidgetState extends State<ScheduleListWidget> {
); );
} }
if (_schedules.isEmpty) { // Correctly filter for current week (Sunday to Saturday)
final now = DateTime.now();
final today = DateTime(now.year, now.month, now.day);
// In Dart, weekday is 1 (Mon) to 7 (Sun).
// To get Sunday: if Mon(1), subtract 1. if Sun(7), subtract 0.
final daysToSubtract = now.weekday % 7;
final startOfWeek = today.subtract(Duration(days: daysToSubtract));
final endOfWeek = startOfWeek.add(const Duration(days: 6, hours: 23, minutes: 59, seconds: 59));
final filteredSchedules = _schedules.where((item) {
// Overlap check: schedule starts before week ends AND schedule ends after week starts
return item.startDate.isBefore(endOfWeek) && item.endDate.isAfter(startOfWeek);
}).toList();
if (filteredSchedules.isEmpty) {
return const Center( return const Center(
child: Text( child: Text(
'No schedules this week', '이번 주 일정이 없습니다',
style: TextStyle(color: Colors.white54), style: TextStyle(color: Colors.white54),
), ),
); );
} }
// Sort by date // Sort by date
final sortedSchedules = List<ScheduleItem>.from(_schedules); final sortedSchedules = List<ScheduleItem>.from(filteredSchedules);
sortedSchedules.sort((a, b) => a.startDate.compareTo(b.startDate)); sortedSchedules.sort((a, b) => a.startDate.compareTo(b.startDate));
return ListView.separated( return ListView.separated(
@@ -121,31 +135,44 @@ class _ScheduleListWidgetState extends State<ScheduleListWidget> {
const Divider(color: Colors.white10), const Divider(color: Colors.white10),
itemBuilder: (context, index) { itemBuilder: (context, index) {
final item = sortedSchedules[index]; final item = sortedSchedules[index];
final timeStr = item.isAllDay
? 'All Day' // Multi-day check
: DateFormat('HH:mm').format(item.startDate); final isMultiDay = item.startDate.year != item.endDate.year ||
item.startDate.month != item.endDate.month ||
item.startDate.day != item.endDate.day;
String? dateRangeStr;
if (isMultiDay) {
final startStr = DateFormat('MM/dd').format(item.startDate);
final endStr = DateFormat('MM/dd').format(item.endDate);
dateRangeStr = '$startStr ~ $endStr';
}
return ListTile( return ListTile(
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
leading: Container( leading: Container(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
horizontal: 12, horizontal: 10,
vertical: 8, vertical: 6,
), ),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.white10, color: isMultiDay ? Colors.blue.withOpacity(0.2) : Colors.white10,
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
border: isMultiDay ? Border.all(color: Colors.blue.withOpacity(0.5)) : null,
), ),
child: FittedBox(
fit: BoxFit.scaleDown,
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Text( Text(
DateFormat('d').format(item.startDate), DateFormat('d').format(item.startDate),
style: const TextStyle( style: TextStyle(
color: Colors.white, color: isMultiDay ? Colors.blue : Colors.white,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
fontSize: 18, fontSize: 18,
height: 1.2,
), ),
), ),
Text( Text(
@@ -153,11 +180,13 @@ class _ScheduleListWidgetState extends State<ScheduleListWidget> {
style: const TextStyle( style: const TextStyle(
color: Colors.white70, color: Colors.white70,
fontSize: 12, fontSize: 12,
height: 1.2,
), ),
), ),
], ],
), ),
), ),
),
title: Text( title: Text(
item.title, item.title,
style: const TextStyle( style: const TextStyle(
@@ -165,10 +194,15 @@ class _ScheduleListWidgetState extends State<ScheduleListWidget> {
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
), ),
), ),
subtitle: Text( subtitle: dateRangeStr != null
timeStr, ? Text(
style: const TextStyle(color: Colors.white54), dateRangeStr,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
), ),
)
: null,
); );
}, },
); );

View File

@@ -1,5 +1,6 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../models/todo_item.dart'; import '../models/todo_item.dart';
import '../models/family_member.dart'; import '../models/family_member.dart';
@@ -85,7 +86,7 @@ class _TodoListWidgetState extends State<TodoListWidget> {
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Text( Text(
"Today's Todos", "오늘의 할 일",
style: Theme.of(context).textTheme.titleLarge?.copyWith( style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: Colors.white, color: Colors.white,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@@ -128,7 +129,7 @@ class _TodoListWidgetState extends State<TodoListWidget> {
Icon(Icons.thumb_up, color: Colors.white24, size: 32), Icon(Icons.thumb_up, color: Colors.white24, size: 32),
SizedBox(height: 8), SizedBox(height: 8),
Text( Text(
'All done for today!', '오늘 할 일을 모두 마쳤습니다!',
style: TextStyle(color: Colors.white54), style: TextStyle(color: Colors.white54),
), ),
], ],
@@ -218,6 +219,12 @@ class _TodoListWidgetState extends State<TodoListWidget> {
decorationColor: Colors.white54, decorationColor: Colors.white54,
), ),
), ),
subtitle: todo.dueDate != null && (todo.dueDate!.hour != 0 || todo.dueDate!.minute != 0)
? Text(
DateFormat('HH:mm').format(todo.dueDate!),
style: const TextStyle(color: Colors.white54, fontSize: 12),
)
: null,
trailing: Checkbox( trailing: Checkbox(
value: todo.completed, value: todo.completed,
onChanged: (val) async { onChanged: (val) async {

View File

@@ -1,3 +1,4 @@
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
@@ -32,65 +33,6 @@ class _WeatherWidgetState extends State<WeatherWidget> {
super.dispose(); super.dispose();
} }
Widget _buildAqiIcon(int aqi) {
Color color;
IconData icon;
String label;
switch (aqi) {
case 1: // Good
color = Colors.blue;
icon = Icons.sentiment_very_satisfied;
label = "좋음";
break;
case 2: // Fair
color = Colors.green;
icon = Icons.sentiment_satisfied;
label = "보통";
break;
case 3: // Moderate
color = Colors.yellow[700]!;
icon = Icons.sentiment_neutral;
label = "주의";
break;
case 4: // Poor
color = Colors.orange;
icon = Icons.sentiment_dissatisfied;
label = "나쁨";
break;
case 5: // Very Poor
color = Colors.red;
icon = Icons.sentiment_very_dissatisfied;
label = "매우 나쁨";
break;
default:
return const SizedBox.shrink();
}
return Column(
children: [
Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: color.withOpacity(0.2),
shape: BoxShape.circle,
border: Border.all(color: color, width: 2),
),
child: Icon(icon, color: color, size: 20),
),
const SizedBox(height: 2),
Text(
label,
style: TextStyle(
color: color,
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
],
);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return FutureBuilder<WeatherInfo>( return FutureBuilder<WeatherInfo>(
@@ -100,116 +42,133 @@ class _WeatherWidgetState extends State<WeatherWidget> {
).fetchWeather(), ).fetchWeather(),
builder: (context, snapshot) { builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) { if (snapshot.connectionState == ConnectionState.waiting) {
return const Center( return const SizedBox.shrink();
child: SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
);
} }
if (snapshot.hasError) { if (snapshot.hasError || !snapshot.hasData) {
debugPrint('Weather Error: ${snapshot.error}');
return const Text(
'Weather Unavailable',
style: TextStyle(color: Colors.white54),
);
}
if (!snapshot.hasData) {
return const SizedBox.shrink(); return const SizedBox.shrink();
} }
final weather = snapshot.data!; final weather = snapshot.data!;
// Assuming OpenWeatherMap icon format final weatherIcon = _getWeatherIcon(weather.icon);
final iconUrl = (ApiConfig.useMockData || kIsWeb)
? null
: (weather.icon.isNotEmpty
? "https://openweathermap.org/img/wn/${weather.icon}@2x.png"
: null);
return Row( return Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.5),
borderRadius: BorderRadius.circular(24),
border: Border.all(color: Colors.white24, width: 1.5),
),
child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [ children: [
// Weather Icon // 1. Weather Icon (Material Icon)
if (iconUrl != null) Icon(
Image.network( weatherIcon.icon,
iconUrl, color: weatherIcon.color,
width: 72, size: 40,
height: 72, ),
errorBuilder: (_, __, ___) =>
const Icon(Icons.wb_sunny, color: Colors.amber),
)
else
const Icon(Icons.wb_sunny, color: Colors.amber, size: 60),
const SizedBox(width: 16), const SizedBox(width: 16),
// Temperature & City info // 2. Temperatures
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row( Row(
crossAxisAlignment: CrossAxisAlignment.baseline, crossAxisAlignment: CrossAxisAlignment.center,
textBaseline: TextBaseline.alphabetic,
children: [ children: [
// Current
Text( Text(
'${weather.temperature.round()}°', '${weather.temperature.round()}°',
style: Theme.of(context).textTheme.displaySmall?.copyWith( style: const TextStyle(
fontSize: 42, // Slightly larger to stand out fontSize: 42, // Reduced from 54
color: Colors.yellowAccent,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: Colors.white,
height: 1.0, height: 1.0,
), ),
), ),
const SizedBox(width: 20),
// Max
const Text('', style: TextStyle(color: Colors.redAccent, fontSize: 16)),
Text(
'${weather.tempMax.round()}°',
style: const TextStyle(
fontSize: 26,
fontWeight: FontWeight.bold,
color: Colors.white, // Reverted to white
),
),
const SizedBox(width: 12), const SizedBox(width: 12),
Column(
crossAxisAlignment: CrossAxisAlignment.start, // Min
children: [ const Text('', style: TextStyle(color: Colors.lightBlueAccent, fontSize: 16)),
Text( Text(
'${weather.city} · ${weather.description}', '${weather.tempMin.round()}°',
style: Theme.of(context).textTheme.titleLarge?.copyWith( style: const TextStyle(
color: Colors.white70, fontSize: 26,
fontWeight: FontWeight.w500, fontWeight: FontWeight.bold,
fontSize: 20 color: Colors.white, // Reverted to white
), ),
), ),
const SizedBox(height: 4),
Text(
'최고:${weather.tempMax.round()}° 최저:${weather.tempMin.round()}°',
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.bold
),
),
],
),
],
),
], ],
), ),
// AQI Indicator (Right side) // 3. AQI
if (weather.aqi > 0) ...[ if (weather.aqi > 0) ...[
const SizedBox(width: 24), const SizedBox(width: 24),
Container( Container(width: 2, height: 36, color: Colors.white24),
height: 50,
width: 2,
color: Colors.white24,
),
const SizedBox(width: 24), const SizedBox(width: 24),
// Scaled up AQI _buildAqiBadge(weather.aqi),
Transform.scale( ],
scale: 1.2, ],
child: _buildAqiIcon(weather.aqi),
), ),
],
],
); );
}, },
); );
} }
// Helper to map OWM icon codes to Material Icons
({IconData icon, Color color}) _getWeatherIcon(String iconCode) {
// Standard OWM codes: https://openweathermap.org/weather-conditions
if (iconCode.startsWith('01')) { // Clear sky
return (icon: Icons.sunny, color: Colors.amber);
} else if (iconCode.startsWith('02') || iconCode.startsWith('03') || iconCode.startsWith('04')) { // Clouds
return (icon: Icons.cloud, color: Colors.white70);
} else if (iconCode.startsWith('09') || iconCode.startsWith('10')) { // Rain
return (icon: Icons.umbrella, color: Colors.blueAccent);
} else if (iconCode.startsWith('11')) { // Thunderstorm
return (icon: Icons.thunderstorm, color: Colors.yellow);
} else if (iconCode.startsWith('13')) { // Snow
return (icon: Icons.ac_unit, color: Colors.lightBlueAccent);
} else if (iconCode.startsWith('50')) { // Mist/Fog
return (icon: Icons.waves, color: Colors.white54);
}
return (icon: Icons.wb_sunny, color: Colors.amber); // Fallback
}
Widget _buildAqiBadge(int aqi) {
Color color;
IconData icon;
String label;
switch (aqi) {
case 1: color = Colors.blue; icon = Icons.sentiment_very_satisfied; label = "좋음"; break;
case 2: color = Colors.green; icon = Icons.sentiment_satisfied; label = "보통"; break;
case 3: color = Colors.yellow[700]!; icon = Icons.sentiment_neutral; label = "주의"; break;
case 4: color = Colors.orange; icon = Icons.sentiment_dissatisfied; label = "나쁨"; break;
case 5: color = Colors.red; icon = Icons.sentiment_very_dissatisfied; label = "매우 나쁨"; break;
default: return const SizedBox.shrink();
}
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, color: color, size: 36),
const SizedBox(width: 10),
Text(
label,
style: TextStyle(color: color, fontSize: 24, fontWeight: FontWeight.bold),
),
],
);
}
} }

View File

@@ -405,6 +405,70 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.4.0" version: "1.4.0"
url_launcher:
dependency: "direct main"
description:
name: url_launcher
sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8
url: "https://pub.dev"
source: hosted
version: "6.3.2"
url_launcher_android:
dependency: transitive
description:
name: url_launcher_android
sha256: "767344bf3063897b5cf0db830e94f904528e6dd50a6dfaf839f0abf509009611"
url: "https://pub.dev"
source: hosted
version: "6.3.28"
url_launcher_ios:
dependency: transitive
description:
name: url_launcher_ios
sha256: cfde38aa257dae62ffe79c87fab20165dfdf6988c1d31b58ebf59b9106062aad
url: "https://pub.dev"
source: hosted
version: "6.3.6"
url_launcher_linux:
dependency: transitive
description:
name: url_launcher_linux
sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a
url: "https://pub.dev"
source: hosted
version: "3.2.2"
url_launcher_macos:
dependency: transitive
description:
name: url_launcher_macos
sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18"
url: "https://pub.dev"
source: hosted
version: "3.2.5"
url_launcher_platform_interface:
dependency: transitive
description:
name: url_launcher_platform_interface
sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029"
url: "https://pub.dev"
source: hosted
version: "2.3.2"
url_launcher_web:
dependency: transitive
description:
name: url_launcher_web
sha256: d0412fcf4c6b31ecfdb7762359b7206ffba3bbffd396c6d9f9c4616ece476c1f
url: "https://pub.dev"
source: hosted
version: "2.4.2"
url_launcher_windows:
dependency: transitive
description:
name: url_launcher_windows
sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f"
url: "https://pub.dev"
source: hosted
version: "3.1.5"
vector_math: vector_math:
dependency: transitive dependency: transitive
description: description:

View File

@@ -15,6 +15,7 @@ dependencies:
provider: ^6.1.2 provider: ^6.1.2
google_fonts: ^6.1.0 google_fonts: ^6.1.0
file_picker: ^8.0.5 file_picker: ^8.0.5
url_launcher: ^6.3.2
dev_dependencies: dev_dependencies:
flutter_test: flutter_test: