Skip to content

Instantly share code, notes, and snippets.

@iyusa
Created October 13, 2019 15:31
Show Gist options
  • Save iyusa/2520b160234f9e6b88f5db5a2470e637 to your computer and use it in GitHub Desktop.
Save iyusa/2520b160234f9e6b88f5db5a2470e637 to your computer and use it in GitHub Desktop.
import 'package:grpc/grpc.dart';
import 'package:mikropay/const.dart';
import 'package:mikropay/util.dart';
import 'package:mikropay/models/transaction.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'client/api.pb.dart';
import 'client/client.dart';
Workspace workspace ;
class Workspace extends ChangeNotifier {
// data section
String msg;
var loginResponse = LoginResponse();
var parameter = ParameterResponse();
var customer = Customer();
Transaction transaction;
// properties
String _token = "";
bool get activated => _token.isNotEmpty;
bool get isEmpty => parameter.version == 0;
bool get isNotEmpty => parameter.version > 0;
String get token => _token;
set token(String value) {
save("token", value).then((String val) => _token = val);
}
/// load token from shared preferences, on production: change to secure storeage
Future<String> loadToken() async {
_token = await load("token");
return _token;
}
// update and save token to shared preference
Future<void> updateToken(String value) async {
await save("token", value);
_token = value;
notifyListeners();
}
Future<void> saveCustomer() async {
var raw = this.customer.writeToJson();
await save("customer", raw);
}
Future<bool> loadCustomer() async {
var x = await load("customer");
if (x == "")
return false;
try{
this.customer = Customer.fromJson(x);
return true;
} catch(e) {
return false;
}
}
void refresh() {
print("Will notify listener with token $token");
notifyListeners();
}
// digunakan untuk load token
CallOptions callOptions({bool useToken}) {
final tok = this.token;
final duration = new Duration(seconds: DEFAULT_TIMEOUT);
if (useToken) {
assert(tok.isNotEmpty);
return CallOptions(metadata: {'token': tok}, timeout: duration);
}
else
return CallOptions(timeout: duration);
}
CallOptions callOptionsWithToken() {
return callOptions(useToken: true);
}
/// helper for catchError(err)
void logError(err) {
print("error@workspace: $err");
}
/// download parameter from backend
/// input: None
/// output: ParameterResponse parameter
Future<bool> downloadParameter(bool force) async {
this.parameter = await client.getParameter();
this.msg = client.message;
return client.valid;
}
// Future<bool> downloadParameterX(bool force) async {
// this.msg = "";
// try {
// var options = callOptions(useToken: true);
// // execute GetParameter from grpc
// this.parameter = await stub.getParameter(Empty(), options: options);
// if (!this.parameter.valid) {
// this.msg = this.parameter.message;
// return false;
// }
// } catch (e) {
// this.msg = e is GrpcError ? e.message : e.toString();
// if (this.msg.isEmpty) this.msg = "Kesalahan dari biller tidak terdefinisi.";
// return false;
// }
// return true;
// }
// Future<void> logout() async {
// try {
// await stub.logout(Empty());
// } catch (e) {
// var msg = e is GrpcError ? e.message : e.toString();
// if (msg.isEmpty)
// msg = "Kesalahan logout tidak terdefinisi.";
// print("Gagal logout: $msg");
// }
// await this.updateToken("");
// }
List<Product> findProducts({String prefix, bool isDataPackage}) {
String voucher = isDataPackage ? GROUP_DATA : GROUP_PULSA;
for (var pg in parameter.productGroups)
if (pg.group == voucher)
for (var cats in pg.productCategories)
for (var prefixes in cats.prefixes)
if (prefixes.prefix == prefix) return cats.products;
return [];
}
Product findProduct({String code}) {
for (var pg in parameter.productGroups)
for (var cats in pg.productCategories)
for (var product in cats.products)
if (product.code == code) return product;
return null;
}
List<Product> findPlnPrepaidProducts() {
const PLN_GROUP = 3;
const PLN_PREPAID = 11;
for (var pg in parameter.productGroups)
if (pg.id == PLN_GROUP)
for (var cats in pg.productCategories)
if (cats.id == PLN_PREPAID) return cats.products;
return [];
}
List<ProductCategory> getPdamCategories() {
for (var pg in parameter.productGroups)
if (pg.group == GROUP_PDAM) return pg.productCategories;
return [];
}
@Deprecated('diganti getPdamCategories')
List<dynamic> getPdamList() {
const PDAM_GROUP = 7;
var list = [];
for (var pg in parameter.productGroups)
if (pg.id == PDAM_GROUP)
for (var cats in pg.productCategories) {
var pdams = [];
for (var product in cats.products) {
pdams.add(product.title);
}
list.add({cats.name: pdams});
}
return list;
}
@Deprecated('diganti getPdamCategories')
List<dynamic> getPdamListA() {
const PDAM_GROUP = 7;
var list = [];
for (var pg in parameter.productGroups)
if (pg.id == PDAM_GROUP)
for (var cats in pg.productCategories) {
var pdams = [];
for (var product in cats.products) {
pdams.add(CodeTitle(product.code, product.title));
}
list.add({CodeTitle(cats.name, cats.name): pdams});
// list.add({cats.name: pdams});
}
return list;
}
List<dynamic> getPdamAdapter() {
var list = [];
for (var pg in parameter.productGroups)
if (pg.group == GROUP_PDAM)
for (var cats in pg.productCategories) {
var pdams = [];
for (var product in cats.products)
pdams.add(CodeTitle(product.code, product.title));
list.add({CodeTitle(cats.name, cats.name): pdams});
}
return list;
}
/// used by: CustomerServiceDialog for DropDownButton.items
List<DropdownMenuItem<String>> get productGroupMenu {
List<DropdownMenuItem<String>> menus = [];
for (var pg in this.parameter.productGroups)
menus.add(DropdownMenuItem(child: Text(pg.icon), value: pg.caption));
return menus;
}
/// used by HistoryFindPage for transaction type
@Deprecated("Dipindah ke HistoryFindPage")
List<DropdownMenuItem<String>> get productGroupMenuOpt {
List<DropdownMenuItem<String>> menus = [];
menus.add(DropdownMenuItem(child: Text("Semua transaksi"), value: ""));
for (var pg in this.parameter.productGroups)
menus.add(DropdownMenuItem(child: Text(pg.icon), value: pg.caption));
return menus;
}
/// used by HistoryFindPage fot transaction type
@Deprecated("Dipindah ke HistoryFindPage")
List<DropdownMenuItem<String>> get transactionStatusOpt {
// return [
// DropdownMenuItem(child: Text("Semua status"), value: "all"),
// DropdownMenuItem(child: Text("Transaksi sukses"), value: "success"),
// DropdownMenuItem(child: Text("Transaksi gagal"), value: "fail"),
// DropdownMenuItem(child: Text("Transaksi tertunda"), value: "pending")
// ];
List<DropdownMenuItem<String>> menus = [];
menus.add(DropdownMenuItem(child: Text("Semua status"), value: "all"));
menus.add(DropdownMenuItem(child: Text("Transaksi sukses"), value: "success"));
menus.add(DropdownMenuItem(child: Text("Transaksi gagal"), value: "fail"));
menus.add(DropdownMenuItem(child: Text("Transaksi tertunda"), value: "pending"));
return menus;
}
String findPlnPostpaidProduct() {
return "PLNPOSTPAID";
}
/// Download transaction histories
/// for used in HistoryFindPage
// Future<List<TransactionHistory>> downloadTransactionHistories(HistoryRequest request, bool force) async {
// try {
// LocalDb db = LocalDb.shared();
// String raw = await db.read("HISTORIES");
// if (raw == null || force) {
// // download from server
// var options = this.callOptions(useToken: true);
// // HistoryRequest request = HistoryRequest();
// HistoryResponse response =
// await stub.getHistory(request, options: options);
// if (response.valid) {
// var raw = response.writeToJson();
// await db.save("HISTORIES", raw);
// return response.transactions;
// }
// } else {
// // load from cache
// HistoryResponse response = HistoryResponse.fromJson(raw);
// return response.transactions;
// }
// } catch (e) {
// print("Exception @ Histories.download(): ${e.toString()}");
// }
// return [];
// }
/// get receipt based on uuid
/// return null if fail and workspace.msg is set error message
// Future<Receipt> getReceipt(String uuid) async {
// try {
// print ("Will download receipt with uuid $uuid");
// var request = ReceiptRequest();
// request.uuid = uuid;
// var options = callOptions(useToken: false);
// return await stub.getReceipt(request, options: options);
// } catch(e) {
// this.msg = e is GrpcError ? e.message : e.toString();
// return null;
// }
// }
}
/// Simple class for code title pair
class CodeTitle {
final String code;
final String title;
CodeTitle(this.code, this.title);
@override
String toString() {
return this.title;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment