temporary update

This commit is contained in:
2024-09-08 18:16:51 +09:00
parent 2c0bb06e74
commit e37c4ceebd
32 changed files with 1235 additions and 1189 deletions

View File

@ -61,7 +61,7 @@ class ApiService extends GetxService{
final indexController = Get.find<IndexController>();
if (indexController.currentUser.isNotEmpty) {
token = indexController.currentUser[0]['token'] ?? '';
print("Get token = $token");
//print("Get token = $token");
}else{
token = "";
}
@ -77,7 +77,7 @@ class ApiService extends GetxService{
final indexController = Get.find<IndexController>();
if (indexController.currentUser.isNotEmpty) {
token = indexController.currentUser[0]['token'] ?? '';
print("Get token = $token");
//print("Get token = $token");
}else{
token = "";
}
@ -87,7 +87,7 @@ class ApiService extends GetxService{
Future<dynamic> _handleRequest(Future<http.Response> Function() request) async {
try {
final response = await request();
if (response.statusCode == 200) {
if (response.statusCode == 200 || response.statusCode == 201 ) {
return json.decode(utf8.decode(response.bodyBytes));
} else if (response.statusCode == 401) {
await _handleUnauthorized();
@ -117,42 +117,6 @@ class ApiService extends GetxService{
}
Future<List<Team>> getTeams_old() async {
init();
final token = await getToken2();
try {
final response = await http.get(
Uri.parse('$baseUrl/teams/'),
headers: {'Authorization': 'Token $token',"Content-Type": "application/json; charset=UTF-8"},
);
if (response.statusCode == 200) {
// UTF-8でデコード
final decodedResponse = utf8.decode(response.bodyBytes);
//print('User Response body: $decodedResponse');
List<dynamic> teamsJson = json.decode(decodedResponse);
List<Team> teams = [];
for (var teamJson in teamsJson) {
//print('\nTeam Data:');
//_printDataComparison(teamJson, Team);
teams.add(Team.fromJson(teamJson));
}
return teams;
} else {
throw Exception('Failed to load teams. Status code: ${response.statusCode}');
}
} catch (e, stackTrace) {
print('Error in getTeams: $e');
print('Stack trace: $stackTrace');
rethrow;
}
}
Future<List<NewCategory>> getCategories() async {
init();
getToken();
@ -165,7 +129,7 @@ class ApiService extends GetxService{
if (response.statusCode == 200) {
final decodedResponse = utf8.decode(response.bodyBytes);
print('User Response body: $decodedResponse');
//print('User Response body: $decodedResponse');
List<dynamic> categoriesJson = json.decode(decodedResponse);
List<NewCategory> categories = [];
@ -200,26 +164,6 @@ class ApiService extends GetxService{
)).then((data) => NewCategory.fromJson(data));
}
Future<NewCategory> getZekkenNumber_old(int categoryId) async {
try {
final response = await http.post(
Uri.parse('$baseUrl/categories-viewset/$categoryId/get_zekken_number/'),
headers: {'Authorization': 'Token $token',"Content-Type": "application/json; charset=UTF-8"},
);
if (response.statusCode == 200) {
final decodedResponse = utf8.decode(response.bodyBytes);
print('User Response body: $decodedResponse');
final categoriesJson = json.decode(decodedResponse);
return NewCategory.fromJson(categoriesJson);
} else {
throw Exception('Failed to increment category number');
}
} catch (e) {
throw Exception('Error incrementing category number: $e');
}
}
Future<User> getCurrentUser() async {
init();
final token = getToken();
@ -324,30 +268,6 @@ class ApiService extends GetxService{
)).then((data) => Team.fromJson(data));
}
Future<Team> createTeam_old(String teamName, int categoryId) async {
init();
getToken();
final response = await http.post(
Uri.parse('$baseUrl/teams/'),
headers: {
'Authorization': 'Token $token',
"Content-Type": "application/json; charset=UTF-8",
},
body: json.encode({
'team_name': teamName,
'category': categoryId,
}),
);
if (response.statusCode == 201) {
final decodedResponse = utf8.decode(response.bodyBytes);
return Team.fromJson(json.decode(decodedResponse));
} else {
throw Exception('Failed to create team');
}
}
Future<Team> updateTeam(int teamId, String teamName, int categoryId) async {
final token = await getToken2();
return _handleRequest(() => http.put(
@ -357,31 +277,6 @@ class ApiService extends GetxService{
)).then((data) => Team.fromJson(data));
}
Future<Team> updateTeam_old(int teamId, String teamName, int categoryId) async {
init();
getToken();
final response = await http.put(
Uri.parse('$baseUrl/teams/$teamId/'),
headers: {
'Authorization': 'Token $token',
'Content-Type': 'application/json; charset=UTF-8',
},
body: json.encode({
'team_name': teamName,
'category': categoryId,
}),
);
if (response.statusCode == 200) {
final decodedResponse = utf8.decode(response.bodyBytes);
return Team.fromJson(json.decode(decodedResponse));
} else {
throw Exception('Failed to update team');
}
}
Future<void> deleteTeam(int teamId) async {
final token = await getToken2();
await _handleRequest(() => http.delete(
@ -390,24 +285,6 @@ class ApiService extends GetxService{
));
}
Future<void> deleteTeamold_(int teamId) async {
init();
getToken();
final response = await http.delete(
Uri.parse('$baseUrl/teams/$teamId/'),
headers: {'Authorization': 'Token $token','Content-Type': 'application/json; charset=UTF-8'},
);
if( response.statusCode == 400) {
final decodedResponse = utf8.decode(response.bodyBytes);
print('User Response body: $decodedResponse');
throw Exception('まだメンバーが残っているので、チームを削除できません。');
}else if (response.statusCode != 204) {
throw Exception('Failed to delete team');
}
}
Future<List<User>> getTeamMembers(int teamId) async {
final token = await getToken2();
return _handleRequest(() => http.get(
@ -416,26 +293,6 @@ class ApiService extends GetxService{
)).then((data) => (data as List).map((json) => User.fromJson(json)).toList());
}
Future<List<User>> getTeamMembers_old(int teamId) async {
init();
getToken();
final response = await http.get(
Uri.parse('$baseUrl/teams/$teamId/members/'),
headers: {'Authorization': 'Token $token','Content-Type': 'application/json; charset=UTF-8'},
);
if (response.statusCode == 200) {
final decodedResponse = utf8.decode(response.bodyBytes);
print('User Response body: $decodedResponse');
List<dynamic> membersJson = json.decode(decodedResponse);
return membersJson.map((json) => User.fromJson(json)).toList();
} else {
throw Exception('Failed to load team members');
}
}
Future<User> createTeamMember(int teamId, String? email, String? firstname, String? lastname, DateTime? dateOfBirth, bool? female) async {
final token = await getToken2();
String? formattedDateOfBirth = dateOfBirth != null ? DateFormat('yyyy-MM-dd').format(dateOfBirth) : null;
@ -452,45 +309,6 @@ class ApiService extends GetxService{
)).then((data) => User.fromJson(data));
}
Future<User> createTeamMember_old(int teamId, String? email, String? firstname, String? lastname, DateTime? dateOfBirth,bool? female) async {
init();
getToken();
// emailが値を持っている場合の処理
if (email != null && email.isNotEmpty) {
firstname ??= "dummy";
lastname ??= "dummy";
dateOfBirth ??= DateTime.now();
female ??= false;
}
String? formattedDateOfBirth;
if (dateOfBirth != null) {
formattedDateOfBirth = DateFormat('yyyy-MM-dd').format(dateOfBirth);
}
final response = await http.post(
Uri.parse('$baseUrl/teams/$teamId/members/'),
headers: {
'Authorization': 'Token $token',
'Content-Type': 'application/json; charset=UTF-8',
},
body: json.encode({
'email': email,
'firstname': firstname,
'lastname': lastname,
'date_of_birth': formattedDateOfBirth,
'female': female,
}),
);
if (response.statusCode == 200 || response.statusCode == 201) {
final decodedResponse = utf8.decode(response.bodyBytes);
return User.fromJson(json.decode(decodedResponse));
} else {
throw Exception('Failed to create team member');
}
}
Future<User> updateTeamMember(int teamId, int? memberId, String firstname, String lastname, DateTime? dateOfBirth, bool? female) async {
final token = await getToken2();
@ -507,37 +325,6 @@ class ApiService extends GetxService{
)).then((data) => User.fromJson(data));
}
Future<User> updateTeamMember_old(int teamId,int? memberId, String firstname, String lastname, DateTime? dateOfBirth,bool? female) async {
init();
getToken();
String? formattedDateOfBirth;
if (dateOfBirth != null) {
formattedDateOfBirth = DateFormat('yyyy-MM-dd').format(dateOfBirth);
}
final response = await http.put(
Uri.parse('$baseUrl/teams/$teamId/members/$memberId/'),
headers: {
'Authorization': 'Token $token',
'Content-Type': 'application/json; charset=UTF-8',
},
body: json.encode({
'firstname': firstname,
'lastname': lastname,
'date_of_birth': formattedDateOfBirth,
'female': female,
}),
);
if (response.statusCode == 200) {
final decodedResponse = utf8.decode(response.bodyBytes);
return User.fromJson(json.decode(decodedResponse));
} else {
throw Exception('Failed to update team member');
}
}
Future<void> deleteTeamMember(int teamId, int memberId) async {
final token = await getToken2();
await _handleRequest(() => http.delete(
@ -546,20 +333,6 @@ class ApiService extends GetxService{
));
}
Future<void> deleteTeamMember_old(int teamId,int memberId) async {
init();
getToken();
final response = await http.delete(
Uri.parse('$baseUrl/teams/$teamId/members/$memberId/'),
headers: {'Authorization': 'Token $token'},
);
if (response.statusCode != 204) {
throw Exception('Failed to delete team member');
}
}
Future<void> deleteAllTeamMembers(int teamId) async {
final response = await http.delete(
Uri.parse('$baseUrl/teams/$teamId/members/destroy_all/?confirm=true'),
@ -594,24 +367,6 @@ class ApiService extends GetxService{
)).then((data) => (data as List).map((json) => Entry.fromJson(json)).toList());
}
Future<List<Entry>> getEntries_old() async {
init();
getToken();
final response = await http.get(
Uri.parse('$baseUrl/entry/'),
headers: {'Authorization': 'Token $token', 'Content-Type': 'application/json; charset=UTF-8',
},
);
if (response.statusCode == 200) {
final decodedResponse = utf8.decode(response.bodyBytes);
List<dynamic> entriesJson = json.decode(decodedResponse);
return entriesJson.map((json) => Entry.fromJson(json)).toList();
} else {
throw Exception('Failed to load entries');
}
}
Future<List<Entry>> getTeamEntries(int teamId) async {
try {
@ -632,6 +387,21 @@ class ApiService extends GetxService{
}
}
Future<Entry> updateEntryStatus(int entryId, bool hasParticipated, bool hasGoaled) async {
final token = await getToken2();
return _handleRequest(() => http.patch(
Uri.parse('$baseUrl/entries/$entryId/update-status/'),
headers: {
'Authorization': 'Token $token',
'Content-Type': 'application/json; charset=UTF-8'
},
body: json.encode({
'hasParticipated': hasParticipated,
'hasGoaled': hasGoaled,
}),
)).then((data) => Entry.fromJson(data));
}
Future<List<Event>> getEvents() async {
init();
getToken();
@ -669,39 +439,6 @@ class ApiService extends GetxService{
)).then((data) => Entry.fromJson(data));
}
Future<Entry> createEntry_old(int teamId, int eventId, int categoryId, DateTime date,String zekkenNumber) async {
init();
getToken();
String? formattedDate;
formattedDate = DateFormat('yyyy-MM-dd').format(date);
final response = await http.post(
Uri.parse('$baseUrl/entry/'),
headers: {
'Authorization': 'Token $token',
'Content-Type': 'application/json; charset=UTF-8',
},
body: json.encode({
'team': teamId,
'event': eventId,
'category': categoryId,
'date': formattedDate,
'zekken_number':zekkenNumber,
}),
);
if (response.statusCode == 201) {
final decodedResponse = utf8.decode(response.bodyBytes);
return Entry.fromJson(json.decode(decodedResponse));
} else {
final decodedResponse = utf8.decode(response.bodyBytes);
print("decodedResponse = $decodedResponse");
final errorInfo = json.decode(decodedResponse);
throw Exception(errorInfo['error']);
}
}
Future<void> updateUserInfo(int userId, Entry entry) async {
final token = await getToken2();
@ -719,40 +456,6 @@ class ApiService extends GetxService{
));
}
Future<void> updateUserInfo_old(int userId, Entry entry) async {
init();
getToken();
final entryId = entry.id;
DateTime? date = entry.date;
String? formattedDate;
formattedDate = DateFormat('yyyy-MM-dd').format(date!);
final response = await http.put(
Uri.parse('$baseUrl/userinfo/$userId/'),
headers: {
'Authorization': 'Token $token',
'Content-Type': 'application/json; charset=UTF-8',
},
body: json.encode({
'zekken_number': entry.zekkenNumber,
'event_code': entry.event.eventName,
'group': entry.team.category.categoryName,
'team_name': entry.team.teamName,
'date': formattedDate,
}),
);
if (response.statusCode == 200) {
final decodedResponse = utf8.decode(response.bodyBytes);
final updatedUserInfo = json.decode(decodedResponse);
//Get.find<IndexController>().updateUserInfo(updatedUserInfo);
} else {
throw Exception('Failed to update entry');
}
}
Future<Entry> updateEntry(int entryId, int teamId, int eventId, int categoryId, DateTime date,int zekkenNumber) async {
init();

View File

@ -87,8 +87,7 @@ class AuthService {
return changePassword;
}
static Future<Map<String, dynamic>> login(
String email, String password) async {
static Future<Map<String, dynamic>> login(String email, String password) async {
//print("------- in logged email $email pwd $password ###### --------");
Map<String, dynamic> cats = {};
String serverUrl = ConstValues.currentServer();
@ -116,17 +115,12 @@ class AuthService {
var errorBody = json.decode(utf8.decode(response.bodyBytes));
errorMessage = errorBody['non_field_errors']?[0] ?? 'パスワードが正しくありません。';
}
Get.snackbar(
"エラー",
errorMessage,
backgroundColor: Colors.red,
colorText: Colors.white,
snackPosition: SnackPosition.TOP,
duration: const Duration(seconds: 3),
);
cats = {};
throw Exception(errorMessage);
}
} catch( e ){
print('Error in login: $e');
throw e; // エラーを上位に伝播させる
/*
print('Error in login: $e');
Get.snackbar("通信エラーがおきました", "サーバーと通信できませんでした",
backgroundColor: Colors.red,
@ -142,7 +136,8 @@ class AuthService {
duration: const Duration(seconds: 3),
//backgroundColor: Colors.yellow,
);
cats = {};
*/
//cats = {};
}
return cats;
}
@ -171,7 +166,7 @@ class AuthService {
Map<String, dynamic> cats = {};
String serverUrl = ConstValues.currentServer();
String url = '$serverUrl/api/register/';
debugPrint('++++++++$url');
//debugPrint('++++++++$url');
final http.Response response = await http.post(
Uri.parse(url),
headers: <String, String>{

View File

@ -1,6 +1,8 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gifunavi/pages/entry/entry_controller.dart';
import 'package:gifunavi/services/api_service.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:gifunavi/model/rog.dart';
@ -33,6 +35,8 @@ class ExternalService {
Future<Map<String, dynamic>> startRogaining() async {
final IndexController indexController = Get.find<IndexController>();
//final TeamController teamController = Get.find<TeamController>();
final ApiService apiService = Get.find<ApiService>();
final EntryController entryController = Get.find<EntryController>();
debugPrint("== startRogaining ==");
@ -68,23 +72,42 @@ class ExternalService {
} else {
debugPrint("== startRogaining processing==");
String serverUrl = ConstValues.currentServer();
String url = '$serverUrl/gifuroge/start_from_rogapp';
print('++++++++$url');
final http.Response response = await http.post(
Uri.parse(url),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(
<String, String>{'team_name': team, 'event_code': eventCode}),
);
try {
// 新しい API 呼び出しを使用
final updatedEntry = await apiService.updateEntryStatus(
entryController.currentEntry.value!.id!,
true, // hasParticipated を true に設定
false // hasGoaled は変更しない
);
print("---- start rogianing api status ---- ${response.statusCode}");
// start_rogaining を本サーバーに送る。 TODO
// // 'has_participated': true ... Server 側の修正が必要 TODO
if (response.statusCode == 200) {
res = json.decode(utf8.decode(response.bodyBytes));
//print('----_res : $res ----');
String serverUrl = ConstValues.currentServer();
String url = '$serverUrl/gifuroge/start_from_rogapp';
//print('++++++++$url');
final http.Response response = await http.post(
Uri.parse(url),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(
<String, String>{'team_name': team, 'event_code': eventCode}),
// 'has_participated': true ... Server 側の修正が必要 TODO
);
print("---- start rogianing api status ---- ${response.statusCode}");
if (response.statusCode == 200) {
res = json.decode(utf8.decode(response.bodyBytes));
//print('----_res : $res ----');
// ローカルのユーザーデータを更新
indexController.updateUserParticipationStatus(true);
}
}catch (e) {
print('Error in startRogaining: $e');
Get.snackbar('エラー', 'ロゲイニングの開始に失敗しました');
}
}
return res;
@ -226,6 +249,8 @@ class ExternalService {
final IndexController indexController = Get.find<IndexController>();
final DestinationController destinationController =
Get.find<DestinationController>();
final ApiService apiService = Get.find<ApiService>();
final EntryController entryController = Get.find<EntryController>();
// チームIDを取得
@ -253,65 +278,83 @@ class ExternalService {
final im1Bytes = File(image).readAsBytesSync();
String im1_64 = base64Encode(im1Bytes);
final http.Response response = await http.post(
Uri.parse(url1),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Token $token'
},
// 'id', 'user', 'goalimage', 'goaltime', 'team_name', 'event_code','cp_number'
body: jsonEncode(<String, String>{
'user': userId.toString(), //userId.toString(),
'team_name': teamname,
'event_code': eventcode,
'goaltime': goalTime,
'goalimage': im1_64,
'cp_number': "-1"
}),
);
try {
// 新しい API呼び出しを使用
final updatedEntry = await apiService.updateEntryStatus(
entryController.currentEntry.value!.id!,
true, // hasParticipated を true に設定
true // hasGoaled を true に設定
);
//String serverUrl = ConstValues.currentServer();
String url = '$serverUrl/gifuroge/goal_from_rogapp';
//print('++++++++$url');
if (response.statusCode == 201) {
try {
Map<String, dynamic> res = json.decode(utf8.decode(response.bodyBytes));
// print('----_res : $res ----');
// print('---- image url ${res["goalimage"]} ----');
final http.Response response2 = await http.post(
Uri.parse(url),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
final http.Response response = await http.post(
Uri.parse(url1),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Token $token'
},
// 'id', 'user', 'goalimage', 'goaltime', 'team_name', 'event_code','cp_number'
body: jsonEncode(<String, String>{
'user': userId.toString(), //userId.toString(),
'team_name': teamname,
'event_code': eventcode,
'goaltime': goalTime,
'goalimage': im1_64,
'cp_number': "-1"
}),
);
//String serverUrl = ConstValues.currentServer();
String url = '$serverUrl/gifuroge/goal_from_rogapp';
//print('++++++++$url');
if (response.statusCode == 201) {
try {
Map<String, dynamic> res = json.decode(
utf8.decode(response.bodyBytes));
// print('----_res : $res ----');
// print('---- image url ${res["goalimage"]} ----');
final http.Response response2 = await http.post(
Uri.parse(url),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'team_name': teamname,
'event_code': eventcode,
'goal_time': goalTime,
'image': res["goalimage"].toString().replaceAll(
'http://localhost:8100', serverUrl)
// 'has_goaled': true ... サーバー側の修正が必要 TODO
//'http://rogaining.sumasen.net')
}),
);
String rec = jsonEncode(<String, String>{
'team_name': teamname,
'event_code': eventcode,
'goal_time': goalTime,
'image': res["goalimage"].toString().replaceAll(
'http://localhost:8100', serverUrl)
'image': res["goalimage"]
.toString()
.replaceAll('http://localhost:8100', serverUrl)
//'http://rogaining.sumasen.net')
}),
);
String rec = jsonEncode(<String, String>{
'team_name': teamname,
'event_code': eventcode,
'goal_time': goalTime,
'image': res["goalimage"]
.toString()
.replaceAll('http://localhost:8100', serverUrl)
//'http://rogaining.sumasen.net')
});
//print("-- json -- $rec");
//print('----- response2 is $response2 --------');
if (response2.statusCode == 200) {
res2 = json.decode(utf8.decode(response2.bodyBytes));
} else {
res2 = json.decode(utf8.decode(response2.bodyBytes));
});
//print("-- json -- $rec");
//print('----- response2 is $response2 --------');
if (response2.statusCode == 200) {
res2 = json.decode(utf8.decode(response2.bodyBytes));
// ローカルのユーザーデータを更新
indexController.updateUserGoalStatus(true);
} else {
res2 = json.decode(utf8.decode(response2.bodyBytes));
// ここはどうする? TODO
}
} catch (e) {
print("Error {$e}");
}
} catch(e){
print( "Error {$e}" );
}
}catch(e) {
print("Error in makeGoal: $e");
Get.snackbar('エラー', 'ゴール処理に失敗しました');
}
//}
destinationController.resetRogaining(isgoal: true);
return res2;

View File

@ -17,6 +17,19 @@ class MotionService {
}
}
Future<dynamic> _handleMotionData(MethodCall call) async {
switch (call.method) {
case 'onMotionData':
final Map<String, dynamic> motionData = call.arguments;
// ここでモーションデータを処理します
print('Received motion data: $motionData');
// 例: データを状態管理システムに渡す、UIを更新する等
break;
default:
print('Unknown method ${call.method}');
}
}
static Future<void> stopMotionUpdates() async {
if (Platform.isIOS) {
try {