Commit e05a1210 authored by Ilham Maulana's avatar Ilham Maulana 💻

fix: common bug

parent c38d625c
class User {
int id;
int accountId;
String username;
String email;
String? firstName;
String? lastName;
bool isStaff;
User(this.id, this.accountId, this.username, this.email, this.firstName,
this.lastName, this.isStaff);
User(this.id, this.username, this.email, this.firstName, this.lastName,
this.isStaff);
factory User.fromJson(Map<String, dynamic> data) {
return User(
data['id'] as int,
data['account_id'] as int,
data['username'] as String,
data['email'] as String,
data['first_name'] as String?,
......@@ -36,7 +34,6 @@ class User {
final User initialUser = User(
1,
2,
"test_user",
"test@email.com",
"Test",
......
......@@ -10,7 +10,9 @@ import 'package:library_app/src/models/user.dart';
class AuthProvider with ChangeNotifier {
final storage = const FlutterSecureStorage();
String baseUrl = 'http://localhost:8000/api/v1';
String? message;
User? user;
bool isAuthenticated = false;
......@@ -57,7 +59,7 @@ class AuthProvider with ChangeNotifier {
headers: {'Content-Type': 'application/json'},
);
if (response.statusCode == 200) {
if (response.statusCode == 201) {
final data = jsonDecode(response.body);
String token = Token.fromJson(data)!.key;
await storeAccessToken(token);
......@@ -132,12 +134,12 @@ class AuthProvider with ChangeNotifier {
"password": password,
};
final response = await http.post(
Uri.parse('$baseUrl/members/auth/register'),
Uri.parse('$baseUrl/auth/register'),
body: jsonEncode(body),
headers: {'Content-Type': 'application/json'},
);
if (response.statusCode == 200) {
if (response.statusCode == 201) {
final data = jsonDecode(response.body);
String token = Token.fromJson(data)!.key;
storeAccessToken(token);
......@@ -169,15 +171,17 @@ class AuthProvider with ChangeNotifier {
Uri.parse('$baseUrl/user'),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token'
'Authorization': 'Bearer $token',
},
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
user = User.fromJson(data);
message = null;
} else {
debugPrint('Error fetching user details: ${response.statusCode}');
debugPrint(
'Error fetching user details: ${response.statusCode} ${response.body}');
}
setLoading(false);
......@@ -189,6 +193,7 @@ class AuthProvider with ChangeNotifier {
}
Future<void> updateUserDetail(
BuildContext context,
int id,
String username,
String email,
......@@ -201,14 +206,15 @@ class AuthProvider with ChangeNotifier {
if (token != null) {
try {
final body = jsonEncode({
final data = {
"username": username,
"email": email,
"first_name": firstName,
"last_name": lastName,
});
};
final body = jsonEncode(data);
final response = await http.put(
Uri.parse('$baseUrl/user/$id/'),
Uri.parse('$baseUrl/user/update'),
body: body,
headers: {
'Content-Type': 'application/json',
......@@ -217,9 +223,14 @@ class AuthProvider with ChangeNotifier {
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
user = User.fromJson(data);
await getUserDetail();
message = null;
if (context.mounted) {
context.pop();
}
} else {
final data = jsonDecode(response.body);
message = data["message"];
debugPrint(
'Error update user details: ${response.statusCode}, ${response.body}');
}
......@@ -234,19 +245,20 @@ class AuthProvider with ChangeNotifier {
Future<void> changePassword(
BuildContext context,
int accountId,
String oldPassword,
String newPassword,
String newPassword1,
String newPassword2,
) async {
final token = await getAccessToken();
try {
setLoading(true);
final response = await http.post(
Uri.parse('$baseUrl/members/$accountId/change-password'),
final response = await http.put(
Uri.parse('$baseUrl/auth/change-password'),
body: jsonEncode({
"old_password": oldPassword,
"new_password": newPassword,
"new_password1": newPassword1,
"new_password2": newPassword2,
}),
headers: {
'Content-Type': 'application/json',
......@@ -255,11 +267,14 @@ class AuthProvider with ChangeNotifier {
);
if (response.statusCode == 200) {
message = null;
if (context.mounted) {
context.go("/");
}
changePasswordSucced = true;
} else {
final data = jsonDecode(response.body);
message = data["message"];
debugPrint(
'Change password failed: ${response.statusCode}, ${response.body}');
}
......@@ -271,18 +286,24 @@ class AuthProvider with ChangeNotifier {
}
}
Future<void> resetPassword(String email) async {
Future<void> resetPassword(BuildContext context, String email) async {
try {
setLoading(true);
final response = await http.post(
Uri.parse('$baseUrl/reset-password/request-token'),
Uri.parse('$baseUrl/auth/reset-password'),
body: jsonEncode({"email": email}),
headers: {'Content-Type': 'application/json'},
);
if (response.statusCode == 200) {
message = null;
resetPasswordTokenSended = true;
if (context.mounted) {
context.go("/confirm-reset-password");
}
} else {
final data = jsonDecode(response.body);
message = data["message"];
debugPrint(
'Error reset user password: ${response.statusCode}, ${response.body}');
}
......@@ -295,7 +316,11 @@ class AuthProvider with ChangeNotifier {
}
Future<void> confirmResetPassword(
int pin, String password1, String password2) async {
BuildContext context,
int pin,
String password1,
String password2,
) async {
setLoading(true);
final body = jsonEncode({
"pin": pin,
......@@ -305,14 +330,20 @@ class AuthProvider with ChangeNotifier {
try {
final response = await http.post(
Uri.parse('$baseUrl/reset-password/confirm'),
Uri.parse('$baseUrl/auth/reset-password-confirm'),
body: body,
headers: {'Content-Type': 'application/json'},
);
if (response.statusCode == 200) {
message = null;
resetPasswordSucced = true;
if (context.mounted) {
context.go("/");
}
} else {
final data = jsonDecode(response.body);
message = data["message"];
debugPrint(
'Error confirm reset user password: ${response.statusCode}, ${response.body}');
}
......@@ -328,7 +359,7 @@ class AuthProvider with ChangeNotifier {
setLoading(true);
final token = await getAccessToken();
String url = '$baseUrl/members/${user?.accountId}/loans/';
String url = '$baseUrl/user/loans';
if (filterByUpcoming) {
url += '?near_outstanding=True';
} else if (filterByOverdued) {
......@@ -347,9 +378,12 @@ class AuthProvider with ChangeNotifier {
);
if (response.statusCode == 200) {
message = null;
final data = jsonDecode(response.body);
memberLoans = data["results"];
memberLoans = data;
} else {
final data = jsonDecode(response.body);
message = data["message"];
debugPrint(
"Failed to get member loan. ${response.statusCode}: ${response.body}");
}
......@@ -377,6 +411,7 @@ class AuthProvider with ChangeNotifier {
Future<void> createMemberLoan(int memberId, int bookId, int loanDay) async {
final token = await getAccessToken();
String url = '$baseUrl/user/loans';
final now = DateTime.now();
final dueDate = now.add(Duration(days: loanDay));
......@@ -390,7 +425,7 @@ class AuthProvider with ChangeNotifier {
try {
setLoading(true);
final response = await http.post(
Uri.parse('$baseUrl/members/$memberId/loans/'),
Uri.parse(url),
body: jsonEncode(body),
headers: {
'Content-Type': 'application/json',
......@@ -399,18 +434,20 @@ class AuthProvider with ChangeNotifier {
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
memberLoans = data["results"];
message = null;
await getMemberLoan();
} else {
final data = jsonDecode(response.body);
message = data["message"];
debugPrint(
"Failed to create member loan. ${response.statusCode}: ${response.body}");
"Failed to add member loan. ${response.statusCode}: ${response.body}");
}
loanBookSuccess = true;
setLoading(false);
notifyListeners();
} catch (error) {
debugPrint("Failed to create member loan. $error");
debugPrint("Failed to add member loan. $error");
}
}
......
......@@ -23,7 +23,7 @@ class BookProvider with ChangeNotifier {
setLoading(true);
String url = '$baseUrl/books';
if (filterByCategory != null) {
url += '?category__name=$filterByCategory';
url += '?category=$filterByCategory';
} else if (searchKeyword != null) {
url += "?search=$searchKeyword";
}
......@@ -35,7 +35,7 @@ class BookProvider with ChangeNotifier {
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
books = data["results"];
books = data;
} else {
final code = response.statusCode;
debugPrint("Error: Fetch books failed, $code");
......
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:library_app/src/models/category.dart';
import 'package:library_app/src/providers/auth_provider.dart';
import 'package:library_app/src/providers/book_provider.dart';
......@@ -73,31 +74,53 @@ class _MemberListScreen extends State<MemberListScreen> {
const BookList(),
// Loans
LoanList(
memberId: authProvider.user?.accountId ?? 0,
memberId: authProvider.user?.id ?? 0,
),
// Profile
const Profile(),
][navProvider.currentPageIndex],
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: List.generate(
category != null ? category.length : 0,
(index) {
if (category != null) {
return ListTile(
title: Text(category.elementAt(index).name),
onTap: () {
bookProvider.filterBookByCategory(
category!.elementAt(index).name);
bookProvider.getBooks();
Navigator.pop(context);
},
);
}
return Container();
},
),
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10.0, vertical: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
ElevatedButton(
child: const Row(
children: [Icon(Icons.arrow_back), Text("Back")],
),
onPressed: () {
bookProvider.filterBookByCategory(null);
bookProvider.getBooks();
context.pop();
},
),
],
),
),
Expanded(
child: ListView.builder(
itemCount: category != null ? category.length : 0,
itemBuilder: (context, index) {
if (category != null) {
return ListTile(
title: Text(category.elementAt(index).name),
onTap: () {
bookProvider.filterBookByCategory(
category!.elementAt(index).name);
bookProvider.getBooks();
Navigator.pop(context);
},
);
}
return Container();
},
),
),
],
),
),
);
......
......@@ -27,9 +27,9 @@ class _BookList extends State<BookList> {
builder: (context, bookProvider, child) {
if (!bookProvider.isLoading) {
final Iterable<Book> books = bookProvider.books!.map((book) {
if (book["category_detail"] != null) {
if (book["category"] != null) {
final Category category = Category.fromJson(
book["category_detail"],
book["category"],
);
return Book(
book["id"],
......@@ -127,14 +127,9 @@ class _TopAppBar extends State<TopAppBar> {
leading: !showWidget
? IconButton(
onPressed: () {
if (category != null) {
bookProvider.filterBookByCategory(null);
bookProvider.getBooks();
} else {
Scaffold.of(context).openDrawer();
}
Scaffold.of(context).openDrawer();
},
icon: Icon(category != null ? Icons.arrow_back : Icons.menu),
icon: const Icon(Icons.menu),
)
: null,
elevation: 10.0,
......
......@@ -91,7 +91,7 @@ class _LoanBookForm extends State<LoanBookForm> {
if (_formKey.currentState!.validate()) {}
authProvider
.createMemberLoan(
authProvider.user!.accountId,
authProvider.user!.id,
widget.bookId,
int.parse(loanDayController.text),
)
......
......@@ -15,7 +15,8 @@ class ChangePasswordForm extends StatefulWidget {
class _ChangePasswordForm extends State<ChangePasswordForm> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final oldPasswordController = TextEditingController();
final newPasswordController = TextEditingController();
final newPasswordController1 = TextEditingController();
final newPasswordController2 = TextEditingController();
bool passwordVisible = false;
......@@ -28,7 +29,8 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
@override
void dispose() {
oldPasswordController.dispose();
newPasswordController.dispose();
newPasswordController1.dispose();
newPasswordController2.dispose();
super.dispose();
}
......@@ -37,6 +39,7 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
Size screenSize = MediaQuery.of(context).size;
return Consumer<AuthProvider>(builder: (context, authProvider, child) {
final message = authProvider.message;
return Column(
children: [
Padding(
......@@ -79,7 +82,7 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
),
),
validator: (String? value) {
if (value == null || value.isEmpty) {
if (value == null) {
return "Please enter your old password";
} else {
return null;
......@@ -88,7 +91,7 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
keyboardType: TextInputType.visiblePassword,
),
TextFormField(
controller: newPasswordController,
controller: newPasswordController1,
obscureText: passwordVisible,
decoration: InputDecoration(
hintText: "Enter your New Password",
......@@ -107,7 +110,7 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
),
),
validator: (String? value) {
if (value == null || value.isEmpty) {
if (value == null) {
return "Please enter your new password";
} else {
return null;
......@@ -115,6 +118,24 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
},
keyboardType: TextInputType.visiblePassword,
),
TextFormField(
controller: newPasswordController2,
decoration: const InputDecoration(
hintText: "Confirm your New Password",
labelText: "Confirm New Password",
),
validator: (String? value) {
if (value == null) {
return "Please enter your confirm new password";
} else {
return null;
}
},
),
Text(
message ?? "",
style: const TextStyle(color: Colors.red),
),
const SizedBox(
height: 20.0,
),
......@@ -127,9 +148,9 @@ class _ChangePasswordForm extends State<ChangePasswordForm> {
if (_formKey.currentState!.validate()) {}
authProvider.changePassword(
context,
authProvider.user!.accountId,
oldPasswordController.text,
newPasswordController.text,
newPasswordController1.text,
newPasswordController2.text,
);
},
child: authProvider.isLoading
......
......@@ -43,6 +43,7 @@ class _ProfileEditForm extends State<ProfileEditForm> {
lastNameControler.text = user?.lastName ?? "";
return Consumer<AuthProvider>(builder: (context, authProvider, child) {
final message = authProvider.message;
return Column(
children: [
Form(
......@@ -62,6 +63,7 @@ class _ProfileEditForm extends State<ProfileEditForm> {
if (value == null || value.isEmpty) {
return "Please enter your username";
}
return null;
},
),
......@@ -75,6 +77,7 @@ class _ProfileEditForm extends State<ProfileEditForm> {
if (value == null || value.isEmpty) {
return "Please enter your email";
}
return null;
},
),
......@@ -92,6 +95,10 @@ class _ProfileEditForm extends State<ProfileEditForm> {
labelText: "Last Name",
),
),
Text(
message ?? "",
style: const TextStyle(color: Colors.red),
),
Padding(
padding: const EdgeInsets.only(top: 40.0),
child: SizedBox(
......@@ -99,18 +106,15 @@ class _ProfileEditForm extends State<ProfileEditForm> {
child: FilledButton(
onPressed: () {
if (_formKey.currentState!.validate()) {}
authProvider
.updateUserDetail(
authProvider.user!.id,
usernameControler.text,
emailControler.text,
firstNameControler.text,
lastNameControler.text,
authProvider.user!.isStaff,
)
.then(
(res) => Navigator.pop(context),
);
authProvider.updateUserDetail(
context,
authProvider.user!.id,
usernameControler.text,
emailControler.text,
firstNameControler.text,
lastNameControler.text,
authProvider.user!.isStaff,
);
},
child: const Text("Submit"),
),
......
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:library_app/src/providers/auth_provider.dart';
import 'package:library_app/src/screens/form_screen.dart';
import 'package:library_app/src/widgets/loading.dart';
import 'package:provider/provider.dart';
......@@ -22,6 +22,8 @@ class _ResetPasswordForm extends State<ResetPasswordForm> {
const String formText = "Confirm your email to continue reset password";
return Consumer<AuthProvider>(builder: (context, authProvider, child) {
final message = authProvider.message;
return Column(
children: [
Container(
......@@ -67,13 +69,14 @@ class _ResetPasswordForm extends State<ResetPasswordForm> {
validator: (String? value) {
if (value == null || value.isEmpty) {
return "Please enter your email";
} else if (!value.contains("@")) {
return "Email should include '@'";
}
return null;
},
),
// Flutter, iwant to go to ConfirmResetPasswordScreen after authProvider.resetPassword succeed with response 200
Text(
message ?? "",
style: const TextStyle(color: Colors.red),
),
Container(
padding: const EdgeInsets.symmetric(
vertical: 20.0,
......@@ -85,22 +88,8 @@ class _ResetPasswordForm extends State<ResetPasswordForm> {
child: FilledButton(
onPressed: () {
if (_formKey.currentState!.validate()) {}
authProvider
.resetPassword(emailController.text)
.then(
(response) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
const ConfirmResetPasswordScreen(),
),
);
},
).catchError(
(error) {
debugPrint('Exception: $error');
},
);
authProvider.resetPassword(
context, emailController.text);
},
child: authProvider.isLoading
? const Loading()
......@@ -142,12 +131,7 @@ class _ConfirmResetPasswordForm extends State<ConfirmResetPasswordForm> {
const String formText = "Enter the pin that we just sent to your email";
return Consumer<AuthProvider>(builder: (context, authProvider, child) {
if (authProvider.isLoading) {
return const Center(
child: CircularProgressIndicator(),
);
}
final message = authProvider.message;
return Column(
children: [
Container(
......@@ -190,6 +174,17 @@ class _ConfirmResetPasswordForm extends State<ConfirmResetPasswordForm> {
labelText: "confirmation pin",
suffixIcon: Icon(Icons.password),
),
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
validator: (String? value) {
if (value == null) {
return "Please enter your pin";
} else if (value is int) {
return "Please enter pin in number";
}
return null;
},
),
TextFormField(
controller: password1Controller,
......@@ -241,12 +236,16 @@ class _ConfirmResetPasswordForm extends State<ConfirmResetPasswordForm> {
validator: (String? value) {
if (value == null || value.isEmpty) {
return "Please enter your password";
} else {
return null;
}
return null;
},
keyboardType: TextInputType.visiblePassword,
),
Text(
message ?? "",
style: const TextStyle(color: Colors.red),
),
Container(
padding: const EdgeInsets.symmetric(
vertical: 20.0,
......@@ -258,28 +257,16 @@ class _ConfirmResetPasswordForm extends State<ConfirmResetPasswordForm> {
child: FilledButton(
onPressed: () {
if (_formKey.currentState!.validate()) {}
authProvider
.confirmResetPassword(
authProvider.confirmResetPassword(
context,
int.parse(pinController.text),
password1Controller.text,
password2Controller.text,
)
.then(
(response) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
const LoginScreen(),
),
);
},
).catchError(
(error) {
debugPrint('Exception: $error');
},
);
},
child: const Text("Submit"),
child: authProvider.isLoading
? const Loading()
: const Text("Submit"),
),
),
],
......
......@@ -27,14 +27,16 @@ class _SearchForm extends State<SearchForm> {
hintText: "Enter keywords...",
elevation: WidgetStateProperty.all(0),
onChanged: (value) {
Future.delayed(
Duration.zero,
() {
Provider.of<BookProvider>(context, listen: false)
.setSearchKeyword(value);
Provider.of<BookProvider>(context, listen: false).getBooks();
},
);
if (value.length >= 3) {
Future.delayed(
Duration.zero,
() {
Provider.of<BookProvider>(context, listen: false)
.setSearchKeyword(value);
Provider.of<BookProvider>(context, listen: false).getBooks();
},
);
}
},
leading: const Icon(Icons.search),
),
......
......@@ -50,7 +50,6 @@ class _AdminLoanList extends State<AdminLoanList> {
var userData = memberData["user"];
var user = User(
userData["id"],
memberData["id"],
userData["username"],
userData["email"],
userData["first_name"],
......
......@@ -32,7 +32,7 @@ class _LoanList extends State<LoanList> {
if (authProvider.memberLoans != null) {
var loans = authProvider.memberLoans!.map(
(loan) {
var book = Book.fromJson(loan["book_detail"]);
var book = Book.fromJson(loan["book"]);
return Loan(
book,
null,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment