cdb_ui/lib/api.dart
2024-09-21 01:37:11 +02:00

480 lines
12 KiB
Dart

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
class API {
late SharedPreferences pref;
static final API _instance = API._internal();
factory API() {
return _instance;
}
API._internal();
Future<void> init() async {
pref = await SharedPreferences.getInstance();
instance = pref.getString("instance") ?? "";
}
bool isInit() {
return pref.containsKey("token") && pref.containsKey("instance");
}
void save(String instance, String token) {
pref.setString("instance", instance);
pref.setString("token", token);
this.instance = instance;
}
String instance = "";
Future<String> getRequest(String url) async {
var resp = await http.get(Uri.parse(url), headers: <String, String>{
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json; charset=UTF-8',
'Token': pref.getString("token")!
});
return utf8.decode(resp.bodyBytes);
}
Future<String> postRequest(String url, Map<String, dynamic> data) async {
var resp = await http.post(Uri.parse(url),
headers: <String, String>{
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json; charset=UTF-8',
'Token': pref.getString("token")!
},
body: jsonEncode(data));
return utf8.decode(resp.bodyBytes);
}
// /items
Future<List<dynamic>> getItems() async {
var resp = jsonDecode(await getRequest("$instance/items"));
var lst = resp["items"];
return lst as List<dynamic>;
}
Future<GlobalItemStat> getGlobalItemStat() async {
var resp = jsonDecode(await getRequest("$instance/items/stat"));
return GlobalItemStat(resp);
}
// /item/<item>/<variant>/unique?<field>
Future<List<String>> getUniqueField(
String item, String variant, String field) async {
var resp = jsonDecode(
await getRequest("$instance/item/$item/$variant/unique?field=$field"));
List<String> ret = [];
for (var e in resp as List<dynamic>) {
ret.add(e);
}
return ret;
}
Future<Map<String, Location>> getLocations() async {
var resp = jsonDecode(await getRequest("$instance/locations"))
as Map<String, dynamic>;
return resp.map((key, value) => MapEntry(key, Location(value)));
}
Future<Item> getItem(String item) async {
return Item(jsonDecode(await getRequest("$instance/item/$item")));
}
Future<Transaction> getTransaction(String id) async {
return Transaction(
jsonDecode(await getRequest("$instance/transaction/$id")));
}
Future<List<Transaction>> getTransactionsOfLocation(String location,
{bool recursive = true}) async {
var url = "$instance/location/$location/inventory";
if (recursive) {
url += "?recursive=true";
}
var resp = jsonDecode(await getRequest(url)) as List<dynamic>;
return resp.map((x) => Transaction(x)).toList();
}
Future<List<Transaction>> getConsumedItems(String item, String variant,
{String? destination}) async {
var url = "$instance/item/$item/$variant/demand";
if (destination != null) {
url += "?destination=$destination";
}
var resp = jsonDecode(await getRequest(url)) as List<dynamic>;
return resp.map((x) => Transaction(x)).toList();
}
// /item/<item_id>/inventory?<origin>
Future<List<Transaction>> getInventory(String item, {String? origin}) async {
var url = "$instance/item/$item/inventory";
if (origin != null) {
url += "?origin=$origin";
}
var resp = jsonDecode(await getRequest(url)) as List<dynamic>;
return resp.map((x) => Transaction(x)).toList();
}
// /item/<item_id>/<variant_id>/inventory
Future<List<Transaction>> getInventoryOfVariant(
String item, String variant) async {
var resp =
jsonDecode(await getRequest("$instance/item/$item/$variant/inventory"))
as List<dynamic>;
return resp.map((x) => Transaction(x)).toList();
}
// /supply
Future<String> supplyItem(String item, String variant, String price,
String? origin, String? location, String? note) async {
if (origin!.isEmpty) {
origin = null;
}
if (location!.isEmpty) {
location = null;
}
if (note!.isEmpty) {
note = null;
}
var req = await postRequest("$instance/supply", {
"item": item,
"variant": variant,
"price": price,
"origin": origin,
"location": location,
"note": note
});
var resp = jsonDecode(req);
return resp["uuid"];
}
// /demand
Future<void> consumeItem(
String transaction, String destination, String price) async {
await postRequest("$instance/demand",
{"uuid": transaction, "destination": destination, "price": price});
}
// /item/<item_id>/<variant_id>/stat
Future<ItemVariantStat> getStat(String item, String variant) async {
return ItemVariantStat(
jsonDecode(await getRequest("$instance/item/$item/$variant/stat")));
}
String getImageURL(String item) {
return "$instance/$item/image";
}
// /item/<item_id>/<variant_id>/price_history?<origin>
Future<List<Price>> getPriceHistory(String item, String variant,
{String? origin}) async {
var url = "$instance/item/$item/$variant/price_history";
if (origin != null) {
url += "?origin=$origin";
}
var resp = jsonDecode(await getRequest(url)) as List<dynamic>;
return resp.map((x) => Price(x)).toList();
}
Future<Price> getLatestPrice(String item, String variant,
{String? origin}) async {
var url = "$instance/item/$item/$variant/price_latest";
if (origin != null) {
url += "?origin=$origin";
}
var resp = jsonDecode(await getRequest(url)) as Map<String, dynamic>;
return Price(resp);
}
// Flows
// /flows
Future<Map<String, FlowInfo>> getFlows() async {
var resp =
jsonDecode(await getRequest("$instance/flows")) as Map<String, dynamic>;
return resp.map((key, value) => MapEntry(key, FlowInfo(value)));
}
// /flow/<id>/info
Future<FlowInfo> getFlowInfo(String id) async {
return FlowInfo(jsonDecode(await getRequest("$instance/flow/$id/info")));
}
Future<List<Flow>> getActiveFlowsOf(String id) async {
var res = jsonDecode(await getRequest("$instance/flow/$id/active"))
as List<dynamic>;
return res.map((x) => Flow(x)).toList();
}
// /flow/<id>
Future<String> startFlow(String id, {List<String>? input}) async {
var resp =
jsonDecode(await postRequest("$instance/flow/$id", {"input": input}));
return resp["uuid"];
}
// /flow/<id>/end
Future<List<String>?> endFlow(String id, {Map<String, int>? produced}) async {
var resp = jsonDecode(
await postRequest("$instance/$id/end", {"produced": produced}));
if (produced != null) {
return resp["produced"] as List<String>;
}
return null;
}
// /flow/<id>/continue
Future<String> continueFlow(String id, {List<String>? input}) async {
var resp = jsonDecode(
await postRequest("$instance/flow/$id/continue", {"input": input}));
return resp["uuid"];
}
Future<List<Transaction>> getExpiredItems() async {
var resp = jsonDecode(await getRequest("$instance/items/expired"))
as List<dynamic>;
return resp.map((x) => Transaction(x)).toList();
}
Future<List<MinItem>> getItemsUnderMin() async {
var resp =
jsonDecode(await getRequest("$instance/items/min")) as List<dynamic>;
return resp.map((x) => MinItem(x)).toList();
}
Future<void> moveTransaction(String id, String newLocation) async {
jsonDecode(await postRequest(
"$instance/transaction/$id/move", {"to": newLocation}));
}
Future<Location> getLocation(String id) async {
var resp = jsonDecode(await getRequest("$instance/location/$id"));
return Location(resp);
}
}
class FlowInfo {
late String id;
late String name;
late List<String> depends;
late String? next;
late List<String>? produces;
FlowInfo(Map<String, dynamic> json) {
id = json["id"];
name = json["name"];
depends = json["depends"] as List<String>;
next = json["next"];
produces = json["produces"];
}
}
class Item {
late String id;
late String name;
late String category;
late Map<String, ItemVariant> variants;
Item(Map<String, dynamic> json) {
id = json["uuid"];
name = json["name"];
category = json["category"];
variants = <String, ItemVariant>{};
json["variants"].forEach((key, value) {
variants[key] = ItemVariant(value);
});
}
}
class ItemVariant {
late String item;
late String variant;
late String name;
int? min;
int? expiry;
ItemVariant(Map<String, dynamic> json) {
item = json["item"];
variant = json["variant"];
name = json["name"];
min = json["min"];
expiry = json["expiry"];
}
}
class Price {
late double value;
late String currency;
Price(Map<String, dynamic> json) {
value = json["value"];
currency = json["currency"];
}
}
class Transaction {
late String uuid;
late String item;
late String variant;
late Price price;
late String? origin;
late int timestamp;
late ConsumeInfo? consumed;
late bool expired;
late String? note;
Transaction(Map<String, dynamic> json) {
uuid = json["uuid"];
item = json["item"];
variant = json["variant"];
price = Price(json["price"]);
origin = json["origin"];
timestamp = json["timestamp"];
expired = json["expired"];
note = json["note"];
consumed = json["consumed"] != null ? ConsumeInfo(json["consumed"]) : null;
}
}
class ConsumeInfo {
late String destination;
late Price price;
late int timestamp;
ConsumeInfo(Map<String, dynamic> json) {
destination = json["destination"];
price = Price(json["price"]);
timestamp = json["timestamp"];
}
}
class ItemVariantStat {
late int amount;
late double totalPrice;
ItemVariantStat(Map<String, dynamic> json) {
amount = json["amount"];
totalPrice = json["total_price"];
}
}
class Location {
late String id;
late String name;
late String? parent;
late LocationCondition? conditions;
Location.zero() {
id = "";
name = "";
parent = null;
conditions = null;
}
Location(Map<String, dynamic> json) {
id = json["id"];
name = json["name"];
parent = json["parent"];
conditions = json["conditions"] != null ? (json["conditions"]) : null;
}
String fullNamePath(Map<String, Location> locations) {
var name = this.name;
if (parent != null) {
name = "${locations[parent!]!.fullNamePath(locations)} / $name";
}
return name;
}
}
class LocationCondition {
late String temperature;
LocationCondition(Map<String, dynamic> json) {
temperature = json["temperature"];
}
}
class MinItem {
late String itemVariant;
late int need;
MinItem(Map<String, dynamic> json) {
itemVariant = json["item_variant"];
need = json["need"];
}
}
class Flow {
late String id;
late int started;
late String kind;
late List<String>? input;
late FlowDone? done;
Flow(Map<String, dynamic> json) {
id = json["id"];
started = json["started"];
kind = json["kind"];
input = json["input"];
done = (json["done"] != null) ? FlowDone(json["done"]) : null;
}
}
class FlowDone {
late int ended;
late String? next;
late List<String>? produced;
FlowDone(Map<String, dynamic> json) {
ended = json["ended"];
next = json["next"];
produced = json["produced"];
}
}
class GlobalItemStat {
late int item_count;
late int total_transactions;
late double total_price;
GlobalItemStat(Map<String, dynamic> json) {
item_count = json["item_count"];
total_transactions = json["total_transactions"];
total_price = json["total_price"];
}
}