Skip to content

Commit

Permalink
Merge branch 'develop' of github.com:udsm-dhis2-lab/d2-touch into dev…
Browse files Browse the repository at this point in the history
…elop
  • Loading branch information
waltervfaustine committed Dec 6, 2022
2 parents 6013013 + 17e81b0 commit c0a5548
Show file tree
Hide file tree
Showing 24 changed files with 136 additions and 112 deletions.
5 changes: 3 additions & 2 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ jobs:
with:
java-version: "12.x"
- uses: subosito/flutter-action@v1
with:
with:
channel: "stable"
- run: flutter pub get
- run: flutter analyze
- run: flutter test
- run: sh database_builder.sh
- run: flutter test
9 changes: 9 additions & 0 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# include: package:lints/recommended.yaml

analyzer:
exclude:
- "test/*"
- "sample/*"
# linter:
# rules:
# use_key_in_widget_constructors: false
23 changes: 2 additions & 21 deletions lib/core/utilities/repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ class Repository<T extends BaseEntity> extends BaseRepository<T> {
.sanitizeIncomingData(entity: entity.toJson(), columns: this.columns);
final Database db = database != null ? database : await this.database;

final saveDataResponse = db.insert(this.entity.tableName, data);
final saveDataResponse = await db.insert(this.entity.tableName, data);

if (this.oneToManyColumns.isEmpty) {
return saveDataResponse;
Expand Down Expand Up @@ -476,12 +476,8 @@ class Repository<T extends BaseEntity> extends BaseRepository<T> {
{required List<T> entities,
Database? database,
int? chunk,
// <<<<<<< HEAD
// required MergeMode mergeMode}) async {
// =======
required MergeMode mergeMode,
SaveOptions? saveOptions}) async {
// >>>>>>> 63e83b144c34e5b66cf32be8d6fd2509d57c558a
final Database db = database != null ? database : await this.database;

if (entities.isEmpty) {
Expand All @@ -491,16 +487,11 @@ class Repository<T extends BaseEntity> extends BaseRepository<T> {
final queue = Queue(parallel: chunk ?? 500);

entities.forEach((T entity) {
// <<<<<<< HEAD
// queue.add(
// () => saveOne(entity: entity, database: db, mergeMode: mergeMode));
// =======
queue.add(() => saveOne(
entity: entity,
database: db,
mergeMode: mergeMode,
saveOptions: saveOptions));
// >>>>>>> 63e83b144c34e5b66cf32be8d6fd2509d57c558a
});

await queue.onComplete;
Expand All @@ -512,12 +503,8 @@ class Repository<T extends BaseEntity> extends BaseRepository<T> {
Future<int> saveOne(
{required T entity,
Database? database,
// <<<<<<< HEAD
// required MergeMode mergeMode}) async {
// =======
required MergeMode mergeMode,
SaveOptions? saveOptions}) async {
// >>>>>>> 63e83b144c34e5b66cf32be8d6fd2509d57c558a
final Database db = database != null ? database : await this.database;

var result = await this.findById(id: entity.id as String, database: db);
Expand All @@ -538,14 +525,8 @@ class Repository<T extends BaseEntity> extends BaseRepository<T> {
Map<String, dynamic> localData = result.toJson();
Map<String, dynamic> entityMap = entity.toJson();


// if (!localData['synced']) {



if (saveOptions?.skipLocalSyncStatus == null ||
saveOptions?.skipLocalSyncStatus == false) {

entityMap['synced'] = localData['synced'];
}

Expand Down Expand Up @@ -599,7 +580,7 @@ class Repository<T extends BaseEntity> extends BaseRepository<T> {
Map<String, dynamic> data = this
.sanitizeIncomingData(entity: entity.toJson(), columns: this.columns);
final Database db = database != null ? database : await this.database;
final saveDataResponse = db.update(
final saveDataResponse = await db.update(
this.entity.tableName,
data,
where: "id = ?",
Expand Down
86 changes: 50 additions & 36 deletions lib/d2_touch.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,9 @@ import 'modules/metadata/dashboard/dashboard.module.dart';
import 'modules/metadata/data_element/data_element.module.dart';

class D2Touch {
static Future<void> initialize(
{String? databaseName,
bool? inMemory,
DatabaseFactory? databaseFactory}) async {
static Future<void> initialize({String? databaseName,
bool? inMemory,
DatabaseFactory? databaseFactory}) async {
final newDatabaseName = databaseName ?? await D2Touch.getDatabaseName();
if (newDatabaseName != null) {
DatabaseManager(
Expand All @@ -53,8 +52,8 @@ class D2Touch {

static Future<bool> isAuthenticated(
{Future<SharedPreferences>? sharedPreferenceInstance,
bool? inMemory,
DatabaseFactory? databaseFactory}) async {
bool? inMemory,
DatabaseFactory? databaseFactory}) async {
WidgetsFlutterBinding.ensureInitialized();
final databaseName = await D2Touch.getDatabaseName(
sharedPreferenceInstance: sharedPreferenceInstance);
Expand All @@ -77,27 +76,25 @@ class D2Touch {
{Future<SharedPreferences>? sharedPreferenceInstance}) async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs =
await (sharedPreferenceInstance ?? SharedPreferences.getInstance());
await (sharedPreferenceInstance ?? SharedPreferences.getInstance());
return prefs.getString('databaseName');
}

static Future<bool> setDatabaseName(
{required String databaseName,
Future<SharedPreferences>? sharedPreferenceInstance}) async {
static Future<bool> setDatabaseName({required String databaseName,
Future<SharedPreferences>? sharedPreferenceInstance}) async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs =
await (sharedPreferenceInstance ?? SharedPreferences.getInstance());
await (sharedPreferenceInstance ?? SharedPreferences.getInstance());
return prefs.setString('databaseName', databaseName);
}

static Future<LoginResponseStatus> logIn(
{required String username,
required String password,
required String url,
Future<SharedPreferences>? sharedPreferenceInstance,
bool? inMemory,
DatabaseFactory? databaseFactory,
Dio? dioTestClient}) async {
static Future<LoginResponseStatus> logIn({required String username,
required String password,
required String url,
Future<SharedPreferences>? sharedPreferenceInstance,
bool? inMemory,
DatabaseFactory? databaseFactory,
Dio? dioTestClient}) async {
WidgetsFlutterBinding.ensureInitialized();
HttpResponse userResponse = await HttpClient.get(
'me.json?fields=id,name,created,lastUpdated,birthday,gender,displayName,jobTitle,surname,employer,email,firstName,phoneNumber,nationality,userCredentials[code,id,name,lastLogin,displayName,username,userRoles[id,name,code]],organisationUnits[id,code,name],dataViewOrganisationUnits[id,code,name],userGroups[id,name],authorities,programs,dataSets',
Expand All @@ -114,7 +111,9 @@ class D2Touch {
return LoginResponseStatus.SERVER_ERROR;
}

final uri = Uri.parse(url).host;
final uri = Uri
.parse(url)
.host;
final String databaseName = '${username}_$uri';

await D2Touch.initialize(
Expand All @@ -125,7 +124,7 @@ class D2Touch {
await D2Touch.setDatabaseName(
databaseName: databaseName,
sharedPreferenceInstance:
sharedPreferenceInstance ?? SharedPreferences.getInstance());
sharedPreferenceInstance ?? SharedPreferences.getInstance());

UserQuery userQuery = UserQuery();

Expand Down Expand Up @@ -161,17 +160,17 @@ class D2Touch {
return logOutSuccess;
}

static Future<LoginResponseStatus> setToken(
{required String instanceUrl,
required Map<String, dynamic> userObject,
required Map<String, dynamic> tokenObject,
Future<SharedPreferences>? sharedPreferenceInstance,
bool? inMemory,
DatabaseFactory? databaseFactory,
Dio? dioTestClient}) async {
final uri = Uri.parse(instanceUrl).host;
static Future<LoginResponseStatus> setToken({required String instanceUrl,
required Map<String, dynamic> userObject,
required Map<String, dynamic> tokenObject,
Future<SharedPreferences>? sharedPreferenceInstance,
bool? inMemory,
DatabaseFactory? databaseFactory,
Dio? dioTestClient}) async {
final uri = Uri
.parse(instanceUrl)
.host;
final String databaseName = '$uri';

await D2Touch.initialize(
databaseName: databaseName,
inMemory: inMemory,
Expand All @@ -180,16 +179,30 @@ class D2Touch {
await D2Touch.setDatabaseName(
databaseName: databaseName,
sharedPreferenceInstance:
sharedPreferenceInstance ?? SharedPreferences.getInstance());
sharedPreferenceInstance ?? SharedPreferences.getInstance());

AuthToken token = AuthToken.fromJson(tokenObject);

List<dynamic> authorities = [];

userObject['userCredentials']['userRoles'].forEach((role) {

List<dynamic> authoritiesToAdd = role["authorities"].map((auth) {
return auth as String;
}).toList();

authorities.addAll(authoritiesToAdd);
});

userObject['token'] = token.accessToken;
userObject['tokenType'] = token.tokenType;
userObject['tokenExpiry'] = token.expiresIn;
userObject['refreshToken'] = token.refreshToken;
userObject['isLoggedIn'] = true;
userObject['dirty'] = true;
userObject['baseUrl'] = instanceUrl;
userObject['authType'] = "token";
userObject['authorities'] = authorities;

final user = User.fromApi(userObject);
await UserQuery().setData(user).save();
Expand All @@ -199,18 +212,19 @@ class D2Touch {
return LoginResponseStatus.ONLINE_LOGIN_SUCCESS;
}

static Future<List<Map>> rawQuery({required String query}) async {
static Future<List<Map>> rawQuery(
{required String query, required List args}) async {
final Database db = await DatabaseManager.instance.database;

final List<Map> queryResult = await db.rawQuery(query.toString());
final List<Map> queryResult = await db.rawQuery(query.toString(), args);

return queryResult;
}

static UserModule userModule = UserModule();

static OrganisationUnitModule organisationUnitModule =
OrganisationUnitModule();
OrganisationUnitModule();

static DataElementModule dataElementModule = DataElementModule();

Expand All @@ -221,7 +235,7 @@ class D2Touch {
static DashboardModule dashboardModule = DashboardModule();

static TrackedEntityInstanceModule trackerModule =
TrackedEntityInstanceModule();
TrackedEntityInstanceModule();

static AggregateModule aggregateModule = AggregateModule();

Expand Down
8 changes: 6 additions & 2 deletions lib/modules/auth/user/entities/user.entity.dart
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,12 @@ class User extends IdentifiableEntity {
dirty: jsonData['dirty'] ?? true))
.toList(),
dataViewOrganisationUnits: jsonData['dataViewOrganisationUnits'],
programs: jsonData['programs'].toString(),
dataSets: jsonData['datasets'].toString(),
programs: jsonData['programs'] != null
? jsonData['programs'].toString()
: null,
dataSets: jsonData['datasets'] != null
? jsonData['datasets'].toString()
: null,
isLoggedIn: jsonData['isLoggedIn'],
dirty: jsonData['dirty'] ?? false);
}
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/data/aggregate/entities/data_value.entity.dart
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class DataValue extends IdentifiableEntity {

factory DataValue.fromJson(Map<String, dynamic> json) {
final id = json['id'] ??
'${json['dataElement']}_${json['categoryOptionCombo']}_${json['dataValueSet']}}';
'${json['dataElement']}_${json['categoryOptionCombo']}_${json['dataValueSet']}';
return DataValue(
id: id,
name: json['name'] ?? id,
Expand Down
8 changes: 1 addition & 7 deletions lib/modules/data/tracker/entities/enrollment.entity.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class Enrollment extends IdentifiableEntity {

@Column()
String orgUnit;

@Column()
String program;

Expand Down Expand Up @@ -90,13 +91,6 @@ class Enrollment extends IdentifiableEntity {
? EnrollmentImportSummary.fromJson(jsonDecode(json['lastSyncSummary']))
: null;

// print(json['lastSyncSummary']);
// print("888888888888888888888888888888888888");

// print(json["geometry"].runtimeType);
// print(json["geometry"]);
// print(json["geometry"].runtimeType == String);

final Geometry? geometry = json["geometry"] != null
? Geometry.fromJson(json["geometry"].runtimeType == String
? jsonDecode(json["geometry"])
Expand Down
3 changes: 0 additions & 3 deletions lib/modules/data/tracker/queries/event.query.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import 'dart:convert';

import 'package:d2_touch/core/annotations/index.dart';
import 'package:d2_touch/core/utilities/repository.dart';
import 'package:d2_touch/modules/data/tracker/entities/event.entity.dart';
Expand Down Expand Up @@ -156,7 +154,6 @@ class EventQuery extends BaseQuery<Event> {
this.apiResourceName as String, {'events': eventUploadPayload},
database: this.database, dioTestClient: dioTestClient);


callback(
RequestProgress(
resourceName: this.apiResourceName as String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,6 @@ class TrackedEntityInstanceQuery extends BaseQuery<TrackedEntityInstance> {
trackedEntityInstance, eventUploadPayload);
}).toList();


final response = await HttpClient.post(this.apiResourceName as String,
{'trackedEntityInstances': trackedEntityInstanceUploadPayload},
database: this.database, dioTestClient: dioTestClient);
Expand All @@ -394,7 +393,7 @@ class TrackedEntityInstanceQuery extends BaseQuery<TrackedEntityInstance> {
dioTestClient: dioTestClient))
.toList();

final results = await Future.wait(transferApis);
await Future.wait(transferApis);

callback(
RequestProgress(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,7 @@ class ValidationRuleEngine {
Expression leftSideExpression =
Expression.parse(leftSideConditionForEvaluation);
final leftSideEvaluator = const ExpressionEvaluator();
var leftSideEvaluationResult = leftSideEvaluator.eval(
leftSideExpression, nonTotalEvaluationContext);
leftSideEvaluator.eval(leftSideExpression, nonTotalEvaluationContext);
} catch (e) {
skipLeftSideExpression =
leftSide['missingValueStrategy'] == 'SKIP_IF_ANY_VALUE_MISSING';
Expand All @@ -98,8 +97,7 @@ class ValidationRuleEngine {
Expression rightSideExpression =
Expression.parse(rightSideConditionForEvaluation);
final rightSideEvaluator = const ExpressionEvaluator();
var rightSideEvaluationResult = rightSideEvaluator.eval(
rightSideExpression, nonTotalEvaluationContext);
rightSideEvaluator.eval(rightSideExpression, nonTotalEvaluationContext);
} catch (e) {
skipRightSideExpression =
rightSide['missingValueStrategy'] == 'SKIP_IF_ANY_VALUE_MISSING';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import 'package:d2_touch/modules/metadata/program/entities/program_section.entity.dart';
import 'package:d2_touch/modules/metadata/program/entities/tracked_entity_attribute.entity.dart';
import 'package:d2_touch/shared/queries/base.query.dart';
import 'package:sqflite/sqlite_api.dart';
Expand Down
1 change: 0 additions & 1 deletion lib/modules/sync/utilities/query-resource.util.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import 'package:d2_touch/modules/auth/user/entities/user.entity.dart';
import 'package:d2_touch/modules/metadata/organisation_unit/queries/organisation_unit.query.dart';
import 'package:sqflite/sqflite.dart';

class QueryResource {
Expand Down
2 changes: 1 addition & 1 deletion lib/shared/utilities/http_client.util.dart
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class HttpClient {
}
}

static Future<HttpResponse> put(String resourceUrl, dynamic? data,
static Future<HttpResponse> put(String resourceUrl, dynamic data,
{String? baseUrl,
String? username,
String? password,
Expand Down
Loading

0 comments on commit c0a5548

Please sign in to comment.