Items workflow done
This commit is contained in:
parent
d973954a75
commit
6ba57612fa
5 changed files with 565 additions and 5 deletions
|
|
@ -1,5 +1,6 @@
|
|||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:tuuli_app/api/model/access_token_model.dart';
|
||||
import 'package:http/browser_client.dart';
|
||||
import 'package:http/http.dart';
|
||||
|
|
@ -23,6 +24,8 @@ class ErrorOrData<T> {
|
|||
}
|
||||
|
||||
typedef FutureErrorOrData<T> = Future<ErrorOrData<T>>;
|
||||
typedef TableItemsData = Map<String, dynamic>;
|
||||
typedef TableItemsDataList = List<TableItemsData>;
|
||||
|
||||
class ApiClient {
|
||||
final BrowserClient _client = BrowserClient();
|
||||
|
|
@ -142,6 +145,155 @@ class ApiClient {
|
|||
return ErrorOrData(ignored, error);
|
||||
}
|
||||
|
||||
FutureErrorOrData<TableItemsDataList> getTableItems(TableModel table) async {
|
||||
TableItemsDataList? data;
|
||||
Exception? error;
|
||||
|
||||
final response = await post(
|
||||
'/items/${Uri.encodeComponent(table.tableName)}',
|
||||
body: {
|
||||
"fields": ["*"]
|
||||
},
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
);
|
||||
if (response.statusCode == 200) {
|
||||
final body = json.decode(await response.stream.bytesToString())
|
||||
as Map<String, dynamic>;
|
||||
if (body['error'] != null) {
|
||||
error = Exception(body['error']);
|
||||
} else if (body['items'] == null) {
|
||||
error = Exception('Server error');
|
||||
} else {
|
||||
data = (body['items'] as List)
|
||||
.map((e) => e as TableItemsData)
|
||||
.toList(growable: false);
|
||||
}
|
||||
} else if (response.statusCode == 422) {
|
||||
error = Exception('Invalid request parameters');
|
||||
} else {
|
||||
error = Exception('HTTP ${response.statusCode}');
|
||||
}
|
||||
|
||||
return ErrorOrData(data, error);
|
||||
}
|
||||
|
||||
FutureErrorOrData<bool> insertItem(
|
||||
TableModel table, TableItemsData newItem) async {
|
||||
bool? ignored;
|
||||
Exception? error;
|
||||
|
||||
final response = await post(
|
||||
'/items/${Uri.encodeComponent(table.tableName)}/+',
|
||||
body: newItem.map((key, value) =>
|
||||
MapEntry(key, value is DateTime ? value.toIso8601String() : value)),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
);
|
||||
if (response.statusCode == 200) {
|
||||
final body = json.decode(await response.stream.bytesToString());
|
||||
if (body['error'] != null) {
|
||||
error = Exception(body['error']);
|
||||
} else {
|
||||
ignored = true;
|
||||
}
|
||||
} else if (response.statusCode == 422) {
|
||||
error = Exception('Invalid request parameters');
|
||||
} else {
|
||||
error = Exception('HTTP ${response.statusCode}');
|
||||
}
|
||||
|
||||
return ErrorOrData(ignored, error);
|
||||
}
|
||||
|
||||
FutureErrorOrData<bool> updateItem(
|
||||
TableModel table, TableItemsData newItem, TableItemsData oldItem) async {
|
||||
bool? ignored;
|
||||
Exception? error;
|
||||
|
||||
final response = await post(
|
||||
'/items/${Uri.encodeComponent(table.tableName)}/*',
|
||||
body: {
|
||||
"item": newItem.map((key, value) =>
|
||||
MapEntry(key, value is DateTime ? value.toIso8601String() : value)),
|
||||
"oldItem": oldItem.map((key, value) =>
|
||||
MapEntry(key, value is DateTime ? value.toIso8601String() : value)),
|
||||
},
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
);
|
||||
if (response.statusCode == 200) {
|
||||
final body = json.decode(await response.stream.bytesToString());
|
||||
if (body['error'] != null) {
|
||||
error = Exception(body['error']);
|
||||
} else {
|
||||
ignored = true;
|
||||
}
|
||||
} else if (response.statusCode == 422) {
|
||||
error = Exception('Invalid request parameters');
|
||||
} else {
|
||||
error = Exception('HTTP ${response.statusCode}');
|
||||
}
|
||||
|
||||
return ErrorOrData(ignored, error);
|
||||
}
|
||||
|
||||
FutureErrorOrData<bool> deleteItem(TableModel table, TableItemsData e) async {
|
||||
bool? ignored;
|
||||
Exception? error;
|
||||
|
||||
TableField? primaryField =
|
||||
table.columns.firstWhereOrNull((el) => el.isPrimary);
|
||||
TableField? uniqueField =
|
||||
table.columns.firstWhereOrNull((el) => el.isUnique);
|
||||
|
||||
final response = await post(
|
||||
'/items/${Uri.encodeComponent(table.tableName)}/-',
|
||||
body: {
|
||||
"defs": [
|
||||
if (primaryField != null)
|
||||
{
|
||||
"name": primaryField.fieldName,
|
||||
"value": e[primaryField.fieldName],
|
||||
}
|
||||
else if (uniqueField != null)
|
||||
{
|
||||
"name": uniqueField.fieldName,
|
||||
"value": e[uniqueField.fieldName],
|
||||
}
|
||||
else
|
||||
for (final field in table.columns)
|
||||
{
|
||||
"name": field.fieldName,
|
||||
"value": e[field.fieldName],
|
||||
}
|
||||
],
|
||||
},
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
);
|
||||
if (response.statusCode == 200) {
|
||||
final body = json.decode(await response.stream.bytesToString());
|
||||
if (body['error'] != null) {
|
||||
error = Exception(body['error']);
|
||||
} else {
|
||||
ignored = true;
|
||||
}
|
||||
} else if (response.statusCode == 422) {
|
||||
error = Exception('Invalid request parameters');
|
||||
} else {
|
||||
error = Exception('HTTP ${response.statusCode}');
|
||||
}
|
||||
|
||||
return ErrorOrData(ignored, error);
|
||||
}
|
||||
|
||||
// REGION: HTTP Methods implementation
|
||||
|
||||
Future<StreamedResponse> get(
|
||||
String path, {
|
||||
Map<String, String>? headers,
|
||||
|
|
|
|||
198
lib/pages/bottomsheets/create_table_item_bottomsheet.dart
Normal file
198
lib/pages/bottomsheets/create_table_item_bottomsheet.dart
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_fast_forms/flutter_fast_forms.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:tuuli_app/api/api_client.dart';
|
||||
import 'package:tuuli_app/api/model/table_field_model.dart';
|
||||
import 'package:tuuli_app/api/model/tables_list_model.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import 'package:uuid/uuid_util.dart';
|
||||
|
||||
class CreateTableItemBottomSheet extends StatefulWidget {
|
||||
final TableModel table;
|
||||
final TableItemsData? existingItem;
|
||||
|
||||
const CreateTableItemBottomSheet({
|
||||
super.key,
|
||||
required this.table,
|
||||
this.existingItem,
|
||||
});
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() => _CreateTableItemBottomSheetState();
|
||||
}
|
||||
|
||||
class _CreateTableItemBottomSheetState
|
||||
extends State<CreateTableItemBottomSheet> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
final _values = <String, dynamic>{};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
for (final field in widget.table.columns.where((e) => !e.isPrimary)) {
|
||||
_values[field.fieldName] = null;
|
||||
}
|
||||
widget.existingItem?.forEach((key, value) {
|
||||
_values[key] = value;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: FastForm(
|
||||
formKey: _formKey,
|
||||
children: [
|
||||
Text(
|
||||
"Create new item",
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
for (final field in widget.table.columns.where((e) => !e.isPrimary))
|
||||
Card(
|
||||
margin: const EdgeInsets.all(8),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: _createFormField(field),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text("Cancel"),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
Navigator.of(context).pop(_values);
|
||||
return;
|
||||
}
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text("Please fill in all fields"),
|
||||
),
|
||||
);
|
||||
},
|
||||
child:
|
||||
Text(widget.existingItem == null ? "Create" : "Update"),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _createFormField(TableField field) {
|
||||
switch (field.fieldType) {
|
||||
case "serial":
|
||||
case "bigint":
|
||||
// ignore: no_duplicate_case_values
|
||||
case "int":
|
||||
return FastTextField(
|
||||
name: field.fieldName,
|
||||
labelText: field.fieldName,
|
||||
validator: (value) {
|
||||
if (value == null ||
|
||||
value.isEmpty ||
|
||||
double.tryParse(value) is! double) {
|
||||
return "Please enter a value";
|
||||
}
|
||||
return null;
|
||||
},
|
||||
initialValue: (_values[field.fieldName] ?? "").toString(),
|
||||
onChanged: (value) {
|
||||
_values[field.fieldName] = int.tryParse(value ?? "");
|
||||
},
|
||||
);
|
||||
case "uuid":
|
||||
return FastTextField(
|
||||
name: field.fieldName,
|
||||
labelText: field.fieldName,
|
||||
validator: (value) {
|
||||
if (value == null ||
|
||||
value.isEmpty ||
|
||||
!Uuid.isValidUUID(fromString: value)) {
|
||||
return "Please enter a value";
|
||||
}
|
||||
return null;
|
||||
},
|
||||
initialValue: (_values[field.fieldName] ?? "").toString(),
|
||||
onChanged: (value) {
|
||||
_values[field.fieldName] =
|
||||
Uuid.isValidUUID(fromString: value ?? "") ? value : null;
|
||||
},
|
||||
);
|
||||
case "str":
|
||||
return FastTextField(
|
||||
name: field.fieldName,
|
||||
labelText: field.fieldName,
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return "Please enter a value";
|
||||
}
|
||||
return null;
|
||||
},
|
||||
initialValue: _values[field.fieldName],
|
||||
onChanged: (value) {
|
||||
_values[field.fieldName] = value;
|
||||
},
|
||||
);
|
||||
case "bool":
|
||||
return FastCheckbox(
|
||||
name: field.fieldName,
|
||||
labelText: field.fieldName,
|
||||
titleText: field.fieldName,
|
||||
initialValue: _values[field.fieldName],
|
||||
onChanged: (value) {
|
||||
_values[field.fieldName] = value;
|
||||
},
|
||||
);
|
||||
case "date":
|
||||
// ignore: no_duplicate_case_values
|
||||
case "datetime":
|
||||
return FastCalendar(
|
||||
name: field.fieldName,
|
||||
firstDate: DateTime.now().subtract(const Duration(days: 365 * 200)),
|
||||
lastDate: DateTime.now().add(const Duration(days: 365 * 200)),
|
||||
initialValue: DateTime.tryParse(_values[field.fieldName] ?? ""),
|
||||
validator: (value) {
|
||||
if (value == null) {
|
||||
return "Please enter a value";
|
||||
}
|
||||
return null;
|
||||
},
|
||||
onChanged: (value) {
|
||||
_values[field.fieldName] = value;
|
||||
},
|
||||
);
|
||||
case "float":
|
||||
return FastTextField(
|
||||
name: field.fieldName,
|
||||
labelText: field.fieldName,
|
||||
validator: (value) {
|
||||
if (value == null ||
|
||||
value.isEmpty ||
|
||||
double.tryParse(value) is! double) {
|
||||
return "Please enter a value";
|
||||
}
|
||||
return null;
|
||||
},
|
||||
initialValue: (_values[field.fieldName] ?? "").toString(),
|
||||
onChanged: (value) {
|
||||
_values[field.fieldName] = double.tryParse(value ?? "");
|
||||
},
|
||||
);
|
||||
default:
|
||||
return const Text("Unknown field type");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,11 @@
|
|||
import 'package:bottom_sheet/bottom_sheet.dart';
|
||||
import 'package:data_table_2/data_table_2.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:recase/recase.dart';
|
||||
import 'package:tuuli_app/api/api_client.dart';
|
||||
import 'package:tuuli_app/api/model/tables_list_model.dart';
|
||||
import 'package:tuuli_app/pages/bottomsheets/create_table_item_bottomsheet.dart';
|
||||
|
||||
class OpenTableBottomSheet extends StatefulWidget {
|
||||
final TableModel table;
|
||||
|
|
@ -15,14 +18,23 @@ class OpenTableBottomSheet extends StatefulWidget {
|
|||
|
||||
class _OpenTableBottomSheetState extends State<OpenTableBottomSheet> {
|
||||
final apiClient = Get.find<ApiClient>();
|
||||
final tableItems = TableItemsDataList.empty(growable: true);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
_refreshTableData();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
|
|
@ -31,6 +43,14 @@ class _OpenTableBottomSheetState extends State<OpenTableBottomSheet> {
|
|||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
onPressed: _addNewItem,
|
||||
icon: const Icon(Icons.add),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: _refreshTableData,
|
||||
icon: const Icon(Icons.refresh),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: _dropTable,
|
||||
icon: const Icon(Icons.delete),
|
||||
|
|
@ -42,6 +62,45 @@ class _OpenTableBottomSheetState extends State<OpenTableBottomSheet> {
|
|||
],
|
||||
),
|
||||
const Divider(),
|
||||
Expanded(
|
||||
child: DataTable2(
|
||||
columnSpacing: 12,
|
||||
horizontalMargin: 12,
|
||||
headingRowColor:
|
||||
MaterialStateColor.resolveWith((states) => Colors.black),
|
||||
columns: [
|
||||
...widget.table.columns.map((e) => DataColumn(
|
||||
label: Text(e.fieldName),
|
||||
)),
|
||||
const DataColumn(label: Text("Actions")),
|
||||
],
|
||||
rows: tableItems
|
||||
.map((e) => DataRow(cells: [
|
||||
for (int i = 0; i < widget.table.columns.length; i++)
|
||||
DataCell(
|
||||
Text(e[widget.table.columns[i].fieldName]
|
||||
?.toString() ??
|
||||
"null"),
|
||||
),
|
||||
DataCell(
|
||||
Row(
|
||||
children: [
|
||||
IconButton(
|
||||
onPressed: () => _deleteItem(e),
|
||||
icon: const Icon(Icons.delete),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: () => _updateExistingItem(e),
|
||||
icon: const Icon(Icons.edit),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
]))
|
||||
.toList(growable: false),
|
||||
empty: const Center(child: Text("No data")),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
|
@ -55,7 +114,7 @@ class _OpenTableBottomSheetState extends State<OpenTableBottomSheet> {
|
|||
"Are you sure you want to drop this table \"${widget.table.tableName}\"?",
|
||||
textConfirm: "Drop",
|
||||
onConfirm: () => Get.back(result: true),
|
||||
onCancel: () => Get.back(result: false),
|
||||
onCancel: () {},
|
||||
barrierDismissible: false,
|
||||
);
|
||||
|
||||
|
|
@ -70,4 +129,129 @@ class _OpenTableBottomSheetState extends State<OpenTableBottomSheet> {
|
|||
Get.snackbar("Error", error.toString());
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _refreshTableData() async {
|
||||
final result = await apiClient.getTableItems(widget.table);
|
||||
result.unfold((data) {
|
||||
setState(() {
|
||||
tableItems.clear();
|
||||
tableItems.addAll(data);
|
||||
});
|
||||
}, (error) {
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text("Error: $error"),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _addNewItem() async {
|
||||
final newItem = await showFlexibleBottomSheet<Map<String, dynamic>>(
|
||||
minHeight: 1,
|
||||
initHeight: 1,
|
||||
maxHeight: 1,
|
||||
context: context,
|
||||
builder: (_, __, ___) => CreateTableItemBottomSheet(table: widget.table),
|
||||
anchors: [0, 0.5, 1],
|
||||
isSafeArea: true,
|
||||
isDismissible: false,
|
||||
);
|
||||
|
||||
if (newItem == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final result = await apiClient.insertItem(widget.table, newItem);
|
||||
result.unfold((data) {
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text("Item added"),
|
||||
),
|
||||
);
|
||||
_refreshTableData();
|
||||
}, (error) {
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text("Error: $error"),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _updateExistingItem(TableItemsData oldItem) async {
|
||||
final newItem = await showFlexibleBottomSheet<Map<String, dynamic>>(
|
||||
minHeight: 1,
|
||||
initHeight: 1,
|
||||
maxHeight: 1,
|
||||
context: context,
|
||||
builder: (_, __, ___) => CreateTableItemBottomSheet(
|
||||
table: widget.table,
|
||||
existingItem: Map.fromEntries(widget.table.columns
|
||||
.where((el) => !el.isPrimary)
|
||||
.map((el) => MapEntry(el.fieldName, oldItem[el.fieldName]))),
|
||||
),
|
||||
anchors: [0, 0.5, 1],
|
||||
isSafeArea: true,
|
||||
isDismissible: false,
|
||||
);
|
||||
|
||||
if (newItem == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final result = await apiClient.updateItem(widget.table, newItem, oldItem);
|
||||
result.unfold((data) {
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text("Item added"),
|
||||
),
|
||||
);
|
||||
_refreshTableData();
|
||||
}, (error) {
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text("Error: $error"),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _deleteItem(TableItemsData e) async {
|
||||
final really = await Get.defaultDialog<bool>(
|
||||
title: "Delete item",
|
||||
middleText: "Are you sure you want to delete this item?",
|
||||
textConfirm: "Delete",
|
||||
onConfirm: () => Get.back(result: true),
|
||||
onCancel: () {},
|
||||
barrierDismissible: false,
|
||||
);
|
||||
|
||||
if (really != true) {
|
||||
return;
|
||||
}
|
||||
|
||||
final result = await apiClient.deleteItem(widget.table, e);
|
||||
result.unfold((data) {
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text("Item deleted"),
|
||||
),
|
||||
);
|
||||
_refreshTableData();
|
||||
}, (error) {
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text("Error: $error"),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue