• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

OpenSRP / opensrp-client-immunization / #901

pending completion
#901

push

github-actions

web-flow
Merge pull request #191 from opensrp/issue189-2

Migrate core dependencies

5141 of 6670 relevant lines covered (77.08%)

0.77 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

75.12
opensrp-immunization/src/main/java/org/smartregister/immunization/util/VaccinateActionUtils.java
1
package org.smartregister.immunization.util;
2

3
import static org.smartregister.util.Utils.convertDateFormat;
4

5
import android.content.Context;
6
import android.graphics.Color;
7
import android.view.View;
8
import android.widget.Button;
9
import android.widget.TableLayout;
10
import android.widget.TableRow;
11
import android.widget.TextView;
12

13
import androidx.fragment.app.Fragment;
14
import androidx.fragment.app.FragmentActivity;
15
import androidx.fragment.app.FragmentTransaction;
16

17
import org.apache.commons.lang3.StringUtils;
18
import org.joda.time.DateTime;
19
import org.json.JSONException;
20
import org.json.JSONObject;
21
import org.smartregister.clientandeventmodel.DateUtil;
22
import org.smartregister.domain.Alert;
23
import org.smartregister.domain.AlertStatus;
24
import org.smartregister.immunization.R;
25
import org.smartregister.immunization.db.VaccineRepo;
26
import org.smartregister.immunization.domain.ServiceRecord;
27
import org.smartregister.immunization.domain.ServiceType;
28
import org.smartregister.immunization.domain.VaccinateFormSubmissionWrapper;
29
import org.smartregister.immunization.domain.Vaccine;
30
import org.smartregister.immunization.domain.VaccineWrapper;
31
import org.smartregister.immunization.domain.jsonmapping.VaccineGroup;
32
import org.smartregister.immunization.fragment.VaccinationDialogFragment;
33
import org.smartregister.service.AlertService;
34
import org.smartregister.util.FormUtils;
35

36
import java.util.ArrayList;
37
import java.util.Arrays;
38
import java.util.Calendar;
39
import java.util.Collection;
40
import java.util.Date;
41
import java.util.List;
42
import java.util.Set;
43
import java.util.concurrent.TimeUnit;
44

45
import timber.log.Timber;
46

47
/**
48
 * Created by keyman on 17/11/2016.
49
 */
50
public class VaccinateActionUtils {
1✔
51

52
    public static String formData(Context context, String entityId, String formName, String metaData) {
53
        try {
54
            return FormUtils.getInstance(context).generateXMLInputForFormWithEntityId(entityId, formName, metaData);
1✔
55
        } catch (Exception e) {
1✔
56
            Timber.e(e);
1✔
57
            return null;
1✔
58
        }
59
    }
60

61
    public static void updateJson(JSONObject jsonObject, String field, String value) {
62
        try {
63
            if (jsonObject.has(field)) {
1✔
64
                JSONObject fieldJson = jsonObject.getJSONObject(field);
1✔
65
                fieldJson.put("content", value);
1✔
66
            }
67
        } catch (JSONException e) {
1✔
68
            Timber.e(e);
1✔
69
        }
1✔
70
    }
1✔
71

72
    public static JSONObject find(JSONObject jsonObject, String field) {
73
        try {
74
            if (jsonObject.has(field)) {
1✔
75
                return jsonObject.getJSONObject(field);
1✔
76

77
            }
78
        } catch (JSONException e) {
1✔
79
            Timber.e(e);
1✔
80
        }
1✔
81

82
        return null;
1✔
83
    }
84

85

86
    public static TableRow findRow(Set<TableLayout> tables, String tag) {
87
        for (TableLayout table : tables) {
1✔
88
            View view = table.findViewWithTag(tag);
1✔
89
            if (view != null && view instanceof TableRow) {
1✔
90
                return (TableRow) view;
1✔
91
            }
92
        }
1✔
93
        return null;
1✔
94
    }
95

96
    public static TableRow findRow(TableLayout table, String tag) {
97
        View view = table.findViewWithTag(tag);
1✔
98
        if (view != null && view instanceof TableRow) {
1✔
99
            return (TableRow) view;
1✔
100
        }
101
        return null;
1✔
102
    }
103

104
    public static void vaccinateToday(TableRow tableRow, VaccineWrapper tag) {
105
        TextView textView = tableRow.findViewById(R.id.date);
×
106
        textView.setText(R.string.done_today);
×
107

108
        Button button = tableRow.findViewById(R.id.undo);
×
109
        button.setVisibility(View.VISIBLE);
×
110

111
        String color = "#31B404";
×
112
        Button status = tableRow.findViewById(R.id.status);
×
113
        status.setBackgroundColor(Color.parseColor(color));
×
114

115
        tableRow.setOnClickListener(null);
×
116
    }
×
117

118
    public static void vaccinateEarlier(TableRow tableRow, VaccineWrapper tag) {
119
        String vaccineDate = convertDateFormat(tag.getUpdatedVaccineDateAsString(), true);
×
120

121
        TextView textView = tableRow.findViewById(R.id.date);
×
122
        textView.setText(vaccineDate);
×
123

124
        Button button = tableRow.findViewById(R.id.undo);
×
125
        button.setVisibility(View.VISIBLE);
×
126

127
        String color = "#31B404";
×
128
        Button status = tableRow.findViewById(R.id.status);
×
129
        status.setBackgroundColor(Color.parseColor(color));
×
130

131
        tableRow.setOnClickListener(null);
×
132
    }
×
133

134
    public static void undoVaccination(final Context context, TableRow tableRow, final VaccineWrapper tag) {
135
        Button button = tableRow.findViewById(R.id.undo);
×
136
        button.setVisibility(View.GONE);
×
137

138
        String color = tag.getColor();
×
139
        Button status = tableRow.findViewById(R.id.status);
×
140
        status.setBackgroundColor(Color.parseColor(color));
×
141

142
        TextView v = tableRow.findViewById(R.id.date);
×
143
        v.setText(tag.getFormattedVaccineDate());
×
144

145
        if ("due".equalsIgnoreCase(tag.getStatus())) {
×
146
            tableRow.setOnClickListener(new TableRow.OnClickListener() {
×
147
                @Override
148
                public void onClick(View view) {
149
                    FragmentTransaction ft = ((FragmentActivity) context).getSupportFragmentManager().beginTransaction();
×
150
                    Fragment prev =
×
151
                            ((FragmentActivity) context).getSupportFragmentManager()
×
152
                                    .findFragmentByTag(VaccinationDialogFragment.DIALOG_TAG);
×
153
                    if (prev != null) {
×
154
                        ft.remove(prev);
×
155
                    }
156
                    ft.addToBackStack(null);
×
157
                    ArrayList<VaccineWrapper> list = new ArrayList<VaccineWrapper>();
×
158
                    list.add(tag);
×
159
                    VaccinationDialogFragment vaccinationDialogFragment = VaccinationDialogFragment
×
160
                            .newInstance(null, null, list);
×
161
                    vaccinationDialogFragment.show(ft, VaccinationDialogFragment.DIALOG_TAG);
×
162

163
                }
×
164
            });
165
        }
166

167
    }
×
168

169
    public static JSONObject retrieveFieldOverides(String overrides) {
170
        try {
171
            //get the field overrides map
172
            if (overrides != null) {
1✔
173
                JSONObject json = new JSONObject(overrides);
1✔
174
                String overridesStr = json.getString("fieldOverrides");
1✔
175
                return new JSONObject(overridesStr);
1✔
176
            }
177
        } catch (Exception e) {
1✔
178
            Timber.e(e);
1✔
179
        }
1✔
180
        return new JSONObject();
1✔
181

182
    }
183

184
    public static String retrieveExistingAge(VaccinateFormSubmissionWrapper vaccinateFormSubmissionWrapper) {
185
        try {
186
            if (vaccinateFormSubmissionWrapper != null) {
×
187
                JSONObject fieldOverrides = vaccinateFormSubmissionWrapper.getOverrides();
×
188
                if (fieldOverrides.has("existing_age")) {
×
189
                    return fieldOverrides.getString("existing_age");
×
190
                }
191
            }
192
        } catch (JSONException e) {
×
193
            Timber.e(e);
×
194
        }
×
195
        return null;
×
196
    }
197

198
    public static boolean addDialogHookCustomFilter(VaccineWrapper tag) {
199
        boolean addHook = false;
1✔
200

201
        int age = 0;
1✔
202
        String existingAge = tag.getExistingAge();
1✔
203
        if (StringUtils.isNumeric(existingAge)) {
1✔
204
            age = Integer.valueOf(existingAge);
1✔
205
        }
206

207
        VaccineRepo.Vaccine vaccine = tag.getVaccine();
1✔
208
        switch (vaccine) {
1✔
209
            case penta1:
210
            case pcv1:
211
            case opv1:
212
                if (age > 35)
1✔
213
                    addHook = true;
1✔
214
                break;
215
            case penta2:
216
            case pcv2:
217
            case opv2:
218
                if (age > 63)
1✔
219
                    addHook = true;
1✔
220
                break;
221
            case penta3:
222
            case pcv3:
223
            case opv3:
224
            case ipv:
225
                if (age > 91)
1✔
226
                    addHook = true;
1✔
227
                break;
228
            case measles1:
229
                if (age > 250)
1✔
230
                    addHook = true;
1✔
231
                break;
232
            case measles2:
233
                if (age > 340)
1✔
234
                    addHook = true;
1✔
235
                break;
236
            default:
237
                addHook = true;
1✔
238
                break;
239
        }
240

241
        return addHook;
1✔
242

243
    }
244

245
    public static String[] allAlertNames(String category) {
246
        if (category == null) {
1✔
247
            return null;
1✔
248
        }
249

250
        List<VaccineRepo.Vaccine> vaccines = VaccineRepo.getVaccines(category);
1✔
251
        List<String> names = new ArrayList<>();
1✔
252

253
        for (VaccineRepo.Vaccine vaccine : vaccines) {
1✔
254
            names.add(vaccine.display());
1✔
255
            names.add(vaccine.name());
1✔
256
        }
1✔
257

258
        return names.toArray(new String[names.size()]);
1✔
259

260
    }
261

262
    public static String[] allAlertNames(Collection<List<ServiceType>> typeList) {
263
        if (typeList == null) {
1✔
264
            return null;
×
265
        }
266

267
        List<String> names = new ArrayList<>();
1✔
268

269
        for (List<ServiceType> serviceTypes : typeList) {
1✔
270
            if (serviceTypes != null) {
1✔
271
                String[] array = allAlertNames(serviceTypes);
1✔
272
                if (array != null) {
1✔
273
                    names.addAll(Arrays.asList(array));
1✔
274
                }
275
            }
276
        }
1✔
277

278
        return names.toArray(new String[names.size()]);
1✔
279
    }
280

281
    public static String[] allAlertNames(List<ServiceType> list) {
282
        if (list == null) {
1✔
283
            return null;
×
284
        }
285

286
        List<String> names = new ArrayList<>();
1✔
287

288
        for (ServiceType serviceType : list) {
1✔
289
            names.add(serviceType.getName().toLowerCase().replaceAll("\\s+", ""));
1✔
290
            names.add(serviceType.getName());
1✔
291
        }
1✔
292
        return names.toArray(new String[names.size()]);
1✔
293
    }
294

295
    public static String addHyphen(String s) {
296
        if (StringUtils.isNotBlank(s)) {
1✔
297
            return s.replace(" ", "_");
1✔
298
        }
299
        return s;
1✔
300
    }
301

302
    public static String removeHyphen(String s) {
303
        if (StringUtils.isNotBlank(s)) {
1✔
304
            return s.replace("_", " ");
1✔
305
        }
306
        return s;
1✔
307
    }
308

309
    public static void populateDefaultAlerts(AlertService alertService, List<Vaccine> vaccineList,
310
                                             List<Alert> alertList, String entityId,
311
                                             DateTime birthDateTime, VaccineRepo.Vaccine[] vList) {
312

313
        if (vList == null || vList.length == 0) {
1✔
314
            return;
1✔
315
        }
316

317
        List<Alert> defaultAlerts = new ArrayList<Alert>();
1✔
318
        for (VaccineRepo.Vaccine v : vList) {
1✔
319
            if ((!VaccinateActionUtils.hasVaccine(vaccineList, v)) && (!VaccinateActionUtils.hasAlert(alertList, v))) {
1✔
320
                defaultAlerts.add(VaccinateActionUtils.createDefaultAlert(v, entityId, birthDateTime));
1✔
321
            }
322
        }
323

324
        for (Alert alert : defaultAlerts) {
1✔
325
            alertService.create(alert);
1✔
326
            alertService.updateFtsSearch(alert, true);
1✔
327
        }
1✔
328
    }
1✔
329

330
    public static boolean hasVaccine(List<Vaccine> vaccineList, VaccineRepo.Vaccine v) {
331
        if (vaccineList == null || vaccineList.isEmpty() || v == null) {
1✔
332
            return false;
1✔
333
        }
334

335
        for (Vaccine vaccine : vaccineList) {
1✔
336
            if (vaccine.getName().equalsIgnoreCase(v.display().toLowerCase())) {
1✔
337
                return true;
1✔
338
            }
339
        }
1✔
340
        return false;
1✔
341
    }
342

343
    public static boolean hasAlert(List<Alert> alerts, VaccineRepo.Vaccine vaccine) {
344
        if (alerts == null || alerts.isEmpty() || vaccine == null) {
1✔
345
            return false;
1✔
346
        }
347

348
        for (Alert alert : alerts) {
1✔
349
            if (alert.scheduleName().replaceAll(" ", "").equalsIgnoreCase(vaccine.name())
1✔
350
                    || alert.visitCode().replaceAll(" ", "").equalsIgnoreCase(vaccine.name())) {
1✔
351
                return true;
1✔
352
            }
353
        }
1✔
354
        return false;
1✔
355
    }
356

357
    public static Alert createDefaultAlert(VaccineRepo.Vaccine vaccine, String entityId, DateTime birthDateTime) {
358

359

360
        AlertStatus alertStatus = AlertStatus.upcoming;
1✔
361
        Calendar today = Calendar.getInstance();
1✔
362
        today.set(Calendar.HOUR_OF_DAY, 0);
1✔
363
        today.set(Calendar.MINUTE, 0);
1✔
364
        today.set(Calendar.SECOND, 0);
1✔
365
        today.set(Calendar.MILLISECOND, 0);
1✔
366
        Date birthDate = birthDateTime.toDate();
1✔
367
        if (birthDateTime != null && birthDateTime.plusDays(vaccine.expiryDays()).isBefore(DateTime.now())) {
1✔
368
            alertStatus = AlertStatus.expired;
1✔
369
        } else if (birthDate.getTime() > (today.getTimeInMillis() + TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS))) {
1✔
370
            // Vaccination due more than one day from today
371
            alertStatus = AlertStatus.upcoming;
1✔
372
        } else if (birthDate.getTime() < (today.getTimeInMillis() - TimeUnit.MILLISECONDS.convert(10, TimeUnit.DAYS))) {
1✔
373
            // Vaccination overdue
374
            alertStatus = AlertStatus.urgent;
1✔
375
        } else {
376
            alertStatus = AlertStatus.normal;
1✔
377
        }
378

379
        return new Alert(entityId, vaccine.display(), vaccine.name(), alertStatus, DateUtil.yyyyMMdd.format(birthDate),
1✔
380
                null);
381

382
    }
383

384
    public static Alert getAlert(List<Alert> alerts, VaccineRepo.Vaccine vaccine) {
385
        if (alerts == null || alerts.isEmpty() || vaccine == null) {
1✔
386
            return null;
1✔
387
        }
388

389
        for (Alert alert : alerts) {
1✔
390
            if (alert.scheduleName().replaceAll(" ", "").equalsIgnoreCase(vaccine.name())
1✔
391
                    || alert.visitCode().replaceAll(" ", "").equalsIgnoreCase(vaccine.name())) {
1✔
392
                return alert;
1✔
393
            }
394
        }
1✔
395
        return null;
1✔
396
    }
397

398
    public static Vaccine getVaccine(List<Vaccine> vaccineList, VaccineRepo.Vaccine v) {
399
        if (vaccineList == null || vaccineList.isEmpty() || v == null) {
1✔
400
            return null;
1✔
401
        }
402

403
        for (Vaccine vaccine : vaccineList) {
1✔
404
            if (vaccine.getName().equalsIgnoreCase(v.display().toLowerCase())) {
1✔
405
                return vaccine;
1✔
406
            }
407
        }
1✔
408
        return null;
1✔
409
    }
410

411
    /**
412
     * Picks the BCG 2 special vaccine from the loaded list of special_vaccines and adds it to the birth group
413
     *
414
     * @param context
415
     * @param vaccineGroupObject
416
     * @param vaccineList
417
     * @return
418
     */
419
    public static boolean addBcg2SpecialVaccine(Context context, VaccineGroup vaccineGroupObject, List<Vaccine> vaccineList) {
420
        //Add BCG2 special vaccine to birth vaccine group
421
        if (VaccinateActionUtils.hasVaccine(vaccineList, VaccineRepo.Vaccine.bcg2)
1✔
422
                && vaccineGroupObject.days_after_birth_due != null
423
                && vaccineGroupObject.vaccines != null
424
                && "Birth".equalsIgnoreCase(vaccineGroupObject.name)
1✔
425
                && "0".equalsIgnoreCase(vaccineGroupObject.days_after_birth_due.toString())) {
1✔
426

427
            List<org.smartregister.immunization.domain.jsonmapping.Vaccine> specialVaccines = VaccinatorUtils
1✔
428
                    .getSpecialVaccines(context);
1✔
429

430
            if (specialVaccines != null && !specialVaccines.isEmpty()) {
1✔
431
                for (org.smartregister.immunization.domain.jsonmapping.Vaccine vaccine : specialVaccines) {
1✔
432
                    if (vaccine.name != null
1✔
433
                            && vaccine.type != null
434
                            && vaccine.name.equalsIgnoreCase(VaccineRepo.Vaccine.bcg2.display())
1✔
435
                            && vaccine.type.equalsIgnoreCase(VaccineRepo.Vaccine.bcg.display())) {
1✔
436
                        vaccineGroupObject.vaccines.add(vaccine);
1✔
437
                        return true;
1✔
438
                    }
439
                }
×
440
            }
441
        }
442

443
        return false;
1✔
444
    }
445

446
    public static boolean moreThanThreeMonths(Date createdAt) {
447
        return createdAt != null && org.smartregister.util.DateUtil.checkIfDateThreeMonthsOlder(createdAt);
1✔
448
    }
449

450
    public static boolean lessThanThreeMonths(Vaccine vaccine) {
451
        ////////////////////////check 3 months///////////////////////////////
452
        return vaccine == null || vaccine.getCreatedAt() == null || !org.smartregister.util.DateUtil
1✔
453
                .checkIfDateThreeMonthsOlder(vaccine.getCreatedAt());
1✔
454
        ///////////////////////////////////////////////////////////////////////
455
    }
456

457

458
    public static boolean lessThanThreeMonths(ServiceRecord serviceRecord) {
459
        ////////////////////////check 3 months///////////////////////////////
460
        return serviceRecord == null || serviceRecord.getCreatedAt() == null || !org.smartregister.util.DateUtil
1✔
461
                .checkIfDateThreeMonthsOlder(serviceRecord.getCreatedAt());
1✔
462
        ///////////////////////////////////////////////////////////////////////
463
    }
464

465
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc