Skip to content

Commit

Permalink
add:websocket import trans
Browse files Browse the repository at this point in the history
  • Loading branch information
小滋润 committed Sep 27, 2024
1 parent 7ab930b commit 6530b3d
Show file tree
Hide file tree
Showing 27 changed files with 739 additions and 244 deletions.
36 changes: 19 additions & 17 deletions lib/api/api_server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import 'dart:async';
import 'dart:collection';
import 'dart:core';
import 'dart:io';
import 'package:dio_cache_interceptor/dio_cache_interceptor.dart';
import 'package:dio_cache_interceptor_hive_store/dio_cache_interceptor_hive_store.dart';
import 'package:leap_ledger_app/model/common/model.dart';
import 'package:uuid/uuid.dart';

Expand All @@ -10,12 +12,11 @@ import 'package:dio/dio.dart'
BaseOptions,
Dio,
DioException,
FormData,
InterceptorsWrapper,
LogInterceptor,
MultipartFile,
Options,
QueuedInterceptor,
RequestOptions,
Response;

import 'package:leap_ledger_app/api/model/model.dart';
Expand All @@ -30,6 +31,7 @@ import 'package:leap_ledger_app/model/user/model.dart';
import 'package:leap_ledger_app/routes/routes.dart';
import 'package:leap_ledger_app/util/enter.dart';
import 'package:leap_ledger_app/widget/toast.dart';
import 'package:web_socket_channel/io.dart';

part 'common.dart';
part 'user.dart';
Expand All @@ -50,7 +52,7 @@ const String pubilcBaseUrl = '/public';
class ApiServer {
static const _uuid = Uuid();
static Dio dio = Dio(BaseOptions(
baseUrl: Global.config.server.network.address,
baseUrl: Global.config.server.network.httpAddress,
headers: {'Content-Type': 'application/json', 'User-Agent': Current.peratingSystem},
))
..interceptors.add(InterceptorsWrapper(
Expand All @@ -59,18 +61,18 @@ class ApiServer {
return handler.next(options);
},
))
// ..interceptors.add(
// DioCacheInterceptor(
// options: CacheOptions(
// maxStale: const Duration(days: 7),
// keyBuilder: (RequestOptions request) {
// return _uuid.v5(Namespace.url.value, request.uri.toString() + request.data.toString());
// },
// store: HiveCacheStore(Global.tempDirectory.path),
// policy: CachePolicy.request,
// ),
// ),
// )
..interceptors.add(
DioCacheInterceptor(
options: CacheOptions(
maxStale: const Duration(days: 7),
keyBuilder: (RequestOptions request) {
return _uuid.v5(Namespace.url.value, request.uri.toString() + request.data.toString());
},
store: HiveCacheStore(Global.tempDirectory.path),
policy: CachePolicy.request,
),
),
)
..interceptors.add(QueuedInterceptor())
..interceptors.add(LogInterceptor(
request: true,
Expand Down Expand Up @@ -124,12 +126,12 @@ class ApiServer {
Global.hideOverlayLoader();
}
if (!logining.isCompleted) {
return getResponseBody(response);
return ResponseBody({'Msg': '请重新登录'}, isSuccess: false);
} else if (response.requestOptions.headers[HttpHeaders.authorizationHeader]
.toString()
.compareTo(UserBloc.token) !=
0) {
return getResponseBody(response);
return ResponseBody({'Msg': '请重新登录'}, isSuccess: false);
} else {
logining = Completer<bool>();
return await Global.navigatorKey.currentState!.pushNamed(UserRoutes.login).then((value) {
Expand Down
8 changes: 4 additions & 4 deletions lib/api/product.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ class ProductApi {
return response;
}

static Future<ResponseBody> uploadBill(String productKey, String filePath, {required int accountId}) async {
ResponseBody response = await ApiServer.request(Method.post, '/account/$accountId/product/$productKey/bill/import',
data: FormData.fromMap({'File': await MultipartFile.fromFile(filePath)}));
return response;
static Future<IOWebSocketChannel> wsUploadBill(String productKey, {required int accountId}) async {
var url = Uri.parse(
Global.config.server.network.websocketAddress + "/account/$accountId/product/$productKey/bill/import");
return await IOWebSocketChannel.connect(url, headers: {HttpHeaders.authorizationHeader: UserBloc.token});
}
}
27 changes: 6 additions & 21 deletions lib/bloc/transaction/transaction_bloc.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import 'package:bloc/bloc.dart';
import 'package:leap_ledger_app/api/api_server.dart';
import 'package:leap_ledger_app/bloc/user/config/user_config_bloc.dart';
import 'package:leap_ledger_app/common/global.dart';
import 'package:leap_ledger_app/model/account/model.dart';
import 'package:leap_ledger_app/model/transaction/model.dart';
import 'package:leap_ledger_app/widget/common/common.dart';
Expand Down Expand Up @@ -75,28 +74,14 @@ class TransactionBloc extends Bloc<TransactionEvent, TransactionState> {
}

bool _verificationData(TransactionEditModel data, emit) {
if (data.categoryId == 0) {
emit(TransactionDataVerificationFails("请选择交易类型"));
return false;
}
if (data.accountId == 0) {
emit(TransactionDataVerificationFails("请选择账本"));
return false;
}
if (data.amount <= 0) {
emit(TransactionDataVerificationFails("金额需大于0"));
return false;
}
if (data.amount > Constant.maxAmount) {
emit(TransactionDataVerificationFails("金额过大"));
return false;
}
if (data.tradeTime.year > Constant.maxYear || data.tradeTime.year < Constant.minYear) {
emit(TransactionDataVerificationFails("时间超过范围"));
var tip = data.check();
if (tip != null) {
emit(TransactionDataVerificationFails(tip));
return false;
} else {
emit(TransactionDataVerificationSuccess());
return true;
}
emit(TransactionDataVerificationSuccess());
return true;
}

_handleShare(TransactionShare event, emit) async {
Expand Down
2 changes: 2 additions & 0 deletions lib/common/global.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ class Global {
}

enum IncomeExpense {
@JsonValue("income")
income(label: "收入"),
@JsonValue("expense")
expense(label: "支出");

final String label;
Expand Down
8 changes: 5 additions & 3 deletions lib/config/server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ class Server {
class Network {
late final String host;
late final String port;
late final String address;
late final String httpAddress;
late final String websocketAddress;
Network() {
host = const String.fromEnvironment("config.server.network.host", defaultValue: 'http://10.0.2.2');
host = const String.fromEnvironment("config.server.network.host", defaultValue: '10.0.2.2');
port = const String.fromEnvironment("config.server.network.port", defaultValue: '8080');
address = "$host:$port";
httpAddress = "http://$host:$port";
websocketAddress = "ws://$host:$port";
}
Network.fromJson(dynamic data) {
if (data.runtimeType == Map<String, dynamic>) {
Expand Down
1 change: 0 additions & 1 deletion lib/model/transaction/model.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
Expand Down
10 changes: 7 additions & 3 deletions lib/model/transaction/model.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 23 additions & 3 deletions lib/model/transaction/transaction.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class TransactionEditModel {
late int accountId;
@JsonKey(defaultValue: 0)
late int categoryId;
@JsonKey(unknownEnumValue: IncomeExpense.expense)
late IncomeExpense incomeExpense;
@JsonKey(defaultValue: 0)
late int amount;
Expand Down Expand Up @@ -59,6 +60,25 @@ class TransactionEditModel {
setLocation(Location l) {
tradeTime = TZDateTime.from(tradeTime, l);
}

String? check() {
if (categoryId == 0) {
return "请选择交易类型";
}
if (accountId == 0) {
return "请选择账本";
}
if (amount <= 0) {
return "金额需大于0";
}
if (amount > Constant.maxAmount) {
return "金额过大";
}
if (tradeTime.year > Constant.maxYear || tradeTime.year < Constant.minYear) {
return "时间超过范围";
}
return null;
}
}

/// 交易信息模型
Expand Down Expand Up @@ -93,6 +113,9 @@ class TransactionInfoModel extends TransactionEditModel {
factory TransactionInfoModel.fromJson(Map<String, dynamic> json) => _$TransactionInfoModelFromJson(json);
Map<String, dynamic> toJson() => _$TransactionInfoModelToJson(this);

TransactionCategoryBaseModel get categoryBaseModel => TransactionCategoryBaseModel(
id: categoryId, name: categoryName, icon: categoryIcon, incomeExpense: incomeExpense);

TransactionInfoModel.prototypeData() : this(tradeTime: DateTime.now().toLocal());
setAccount(AccountModel account) {
accountId = account.id;
Expand Down Expand Up @@ -165,9 +188,6 @@ class TransactionModel extends TransactionInfoModel {
TransactionModel.prototypeData()
: this(tradeTime: DateTime.now(), createTime: DateTime.now(), updateTime: DateTime.now());

TransactionCategoryBaseModel get categoryBaseModel =>
TransactionCategoryBaseModel(id: id, name: categoryName, icon: categoryIcon, incomeExpense: incomeExpense);

TransactionShareModel getShareModelByConfig(UserTransactionShareConfigModel config) {
TransactionShareModel model = TransactionShareModel(
id: id,
Expand Down
2 changes: 2 additions & 0 deletions lib/util/enter.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'dart:typed_data';
import 'dart:io';
import 'dart:convert';
import 'dart:async';

import 'package:file_picker/file_picker.dart';
import 'package:json_annotation/json_annotation.dart';
Expand All @@ -18,3 +19,4 @@ part 'toast.dart';
part 'shared_preferences_cache.dart';
part 'time.dart';
part 'data.dart';
part 'throttle.dart';
23 changes: 23 additions & 0 deletions lib/util/throttle.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
part of 'enter.dart';

class Throttle {
static Map<String, Timer?> timerMap = {};
late final Duration duration;
Timer? _timer;

Throttle({Duration? duration}) {
this.duration = duration ?? Duration(seconds: 2);
}

void call(String key, void Function() action) {
if (timerMap[key]?.isActive ?? false) return;
timerMap[key] = Timer(duration, () {
_timer = null;
});
action();
}

void dispose() {
_timer?.cancel();
}
}
Loading

0 comments on commit 6530b3d

Please sign in to comment.