Skip to content

Commit

Permalink
generate tasks after adding or updating stock item (#632)
Browse files Browse the repository at this point in the history
* Bump up version
* generate tasks after adding or updating stock item
* Fix obtaining operational area
* Ensure we can get region
* Regenerate tasks in operational area when service point is created
  • Loading branch information
hilpitome authored Jan 31, 2024
1 parent af08fc2 commit 157a72a
Show file tree
Hide file tree
Showing 11 changed files with 179 additions and 8 deletions.
42 changes: 42 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# This workflow will build a Java project with Gradle
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle

name: Snapshot Release

on:
push:
tags:
- v[0-9]+.[0-9]+.[0-9]+-SNAPSHOT
- v[0-9]+.[0-9]+.[0-9]+-[0-9a-zA-Z]+-SNAPSHOT
- v[0-9]+.[0-9]+.[0-9]+-[0-9a-zA-Z]+-[0-9a-zA-Z]+-SNAPSHOT

jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Cancel previous workflow runs
uses: styfle/[email protected]
with:
access_token: ${{ github.token }}

- uses: actions/checkout@v2
with:
submodules: recursive

- name: Set up JDK 11
uses: actions/setup-java@v1
with:
java-version: 11

- name: Decode & Generate Settings.xml file
run: echo $SETTINGS_FILE | base64 -di > ~/.m2/settings.xml
env:
SETTINGS_FILE: ${{ secrets.SETTINGS_XML }}

- name: Generate & upload library snapshot artifact JAR (Java Archive) file
run: mvn clean deploy -Dmaven.test.skip=true --no-transfer-progress

- name: Github Release
uses: softprops/action-gh-release@v1
with:
prerelease: ${{ contains(github.ref, '-alpha') || contains(github.ref, '-beta') }}
2 changes: 1 addition & 1 deletion configs
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<artifactId>opensrp-server-core</artifactId>
<packaging>jar</packaging>
<version>2.14.8-SNAPSHOT</version>
<version>2.14.9-SNAPSHOT</version>
<name>opensrp-server-core</name>
<description>OpenSRP Server Core module</description>
<url>https://github.com/OpenSRP/opensrp-server-core</url>
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/org/opensrp/repository/PlanRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
public interface PlanRepository extends BaseRepository<PlanDefinition>, PlanDao {

List<PlanDefinition> getPlansByServerVersionAndOperationalAreas(Long serverVersion, List<String> operationalAreaIds, boolean experimental);
List<PlanDefinition> getPlansByServerVersionAndOperationalAreasAndStatus(Long serverVersion, List<String> operationalAreaIds,
boolean experimental, PlanDefinition.PlanStatus status);

/**
* This method searches for plans using a list of provided
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package org.opensrp.repository;

import org.opensrp.domain.postgres.Structure;
import org.springframework.context.ApplicationEvent;

public class StructureCreateOrUpdateEvent extends ApplicationEvent {
public StructureCreateOrUpdateEvent(Structure source) {
super(source);
}
}


Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.opensrp.domain.postgres.StructureMetadata;
import org.opensrp.domain.postgres.StructureMetadataExample;
import org.opensrp.repository.LocationRepository;
import org.opensrp.repository.StructureCreateOrUpdateEvent;
import org.opensrp.repository.postgres.mapper.custom.CustomLocationMapper;
import org.opensrp.repository.postgres.mapper.custom.CustomLocationMetadataMapper;
import org.opensrp.repository.postgres.mapper.custom.CustomStructureMapper;
Expand All @@ -46,6 +47,7 @@
import org.smartregister.domain.PhysicalLocation;
import org.smartregister.domain.PhysicalLocationAndStocks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -67,6 +69,8 @@ public class LocationRepositoryImpl extends BaseRepositoryImpl<PhysicalLocation>
@Autowired
private LocationTagService locationTagService;

@Autowired
private ApplicationEventPublisher applicationEventPublisher;
@Override
public PhysicalLocation get(String id) {
return convert(locationMetadataMapper.findById(id, true, false));
Expand Down Expand Up @@ -161,7 +165,8 @@ private void addStructure(PhysicalLocation entity) {
StructureMetadata structureMetadata = createStructureMetadata(entity, pgStructure.getId());

structureMetadataMapper.insertSelective(structureMetadata);

StructureCreateOrUpdateEvent structureEvent = new StructureCreateOrUpdateEvent(pgStructure);
applicationEventPublisher.publishEvent(structureEvent);
}

@Override
Expand Down Expand Up @@ -230,6 +235,8 @@ private void updateStructure(PhysicalLocation entity, Long id) {
structureMetadata.setId(metadata.getId());
structureMetadata.setDateCreated(metadata.getDateCreated());
structureMetadataMapper.updateByPrimaryKey(structureMetadata);
StructureCreateOrUpdateEvent structureEvent = new StructureCreateOrUpdateEvent(pgStructure);
applicationEventPublisher.publishEvent(structureEvent);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,16 @@ public List<PlanDefinition> getPlansByServerVersionAndOperationalAreas(Long serv
PlanExample planExample = new PlanExample();
planExample.createCriteria().andServerVersionGreaterThanOrEqualTo(serverVersion).andDateDeletedIsNull().andExperimentalEqualTo(experimental);
List<Plan> plans = planMetadataMapper.selectMany(planExample, operationalAreaIds, 0, DEFAULT_FETCH_SIZE);

return convert(plans);
}

public List<PlanDefinition> getPlansByServerVersionAndOperationalAreasAndStatus(Long serverVersion, List<String> operationalAreaIds, boolean experimental,
PlanDefinition.PlanStatus status) {
PlanExample planExample = new PlanExample();
planExample.createCriteria().andServerVersionGreaterThanOrEqualTo(serverVersion).andDateDeletedIsNull()
.andExperimentalEqualTo(experimental);
List<Plan> plans = planMetadataMapper.selectManyByStatus(planExample, operationalAreaIds, 0, DEFAULT_FETCH_SIZE, status.value());

return convert(plans);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@
public interface CustomPlanMetadataMapper extends PlanMetadataMapper {
List<Plan> selectMany(@Param("example") PlanExample planExample, @Param("operationalAreaIds") List<String> operationalAreaIds, @Param("offset") int offset,
@Param("limit") int limit);

List<Plan> selectManyByStatus(@Param("example") PlanExample planExample, @Param("operationalAreaIds") List<String> operationalAreaIds, @Param("offset") int offset,
@Param("limit") int limit, @Param("status") String status);

}
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,30 @@
LIMIT #{limit} OFFSET #{offset}
</select>

</mapper>
<select id="selectManyByStatus"
resultMap="org.opensrp.repository.postgres.mapper.PlanMapper.BaseResultMap">
select
<include refid="Base_Column_List" />
from core.plan p
<where>
<trim prefixOverrides="and">
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="operationalAreaIds != null">
and p.id in ( select plan_id from core.plan_metadata where
operational_area_id IN <foreach item="operationalAreaId" collection="operationalAreaIds" open="(" separator="," close=")">#{operationalAreaId}</foreach>
)
</if>
<if test="status != null">
and p.json->>'status' = #{status,jdbcType=VARCHAR}
</if>
</trim>
</where>
<if test="example.orderByClause != null">
order by pm.${example.orderByClause}
</if>
LIMIT #{limit} OFFSET #{offset}
</select>

</mapper>
46 changes: 45 additions & 1 deletion src/main/java/org/opensrp/service/PhysicalLocationService.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.Collections;

import javax.transaction.Transactional;

Expand All @@ -25,13 +26,19 @@
import org.opensrp.domain.LocationDetail;
import org.opensrp.domain.StructureCount;
import org.opensrp.domain.StructureDetails;
import org.opensrp.domain.postgres.Structure;
import org.opensrp.repository.LocationRepository;
import org.opensrp.repository.PlanRepository;
import org.opensrp.repository.postgres.PlanRepositoryImpl;
import org.opensrp.search.LocationSearchBean;
import org.smartregister.domain.LocationProperty;
import org.smartregister.domain.PhysicalLocation;
import org.smartregister.domain.PlanDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import com.google.gson.JsonElement;
Expand All @@ -40,6 +47,13 @@
@Service
public class PhysicalLocationService {

@Autowired
TaskGenerator taskGenerator;

@Autowired
private ApplicationContext applicationContext;
@Value("#{opensrp['operational.area.levels.from.structure'] ?: 3}")
private int iterationsToOperationalArea;
private static Logger logger = LogManager.getLogger(PhysicalLocationService.class.toString());

private LocationRepository locationRepository;
Expand All @@ -50,7 +64,7 @@ public class PhysicalLocationService {
public void setLocationRepository(LocationRepository locationRepository) {
this.locationRepository = locationRepository;
}

public PhysicalLocation getLocation(String id, boolean returnGeometry, boolean includeInactive) {
return locationRepository.get(id, returnGeometry, includeInactive);
}
Expand Down Expand Up @@ -588,4 +602,34 @@ long countStructuresByProperties(List<String> parentIds, Map<String, String> pro
public List<String> findStructureIdsByProperties(List<String> parentIds, Map<String, String> properties, int limit){
return locationRepository.findStructureIdsByProperties(parentIds,properties,limit);
}

public void regenerateTasksForOperationalArea(Structure structure){
/*
Go up the location tree to get the operational area.
TODO Make process configurable
*/
assert structure != null;
PhysicalLocation servicePoint = (PhysicalLocation) structure.getJson();
logger.info("Fetching parent location for service point "+servicePoint.getProperties().getParentId());
String currentLevelLocationId = servicePoint.getProperties().getParentId();
// get username from service point
String username = servicePoint.getProperties().getUsername();
PhysicalLocation operationalArea = null;
for (int i = 0; i < iterationsToOperationalArea ; i++) {
operationalArea = getLocation(currentLevelLocationId, false, false);
logger.info("Current operational area "+operationalArea.getProperties().getName() +" id "+operationalArea.getId());
currentLevelLocationId = operationalArea.getProperties().getParentId();
logger.info("parentId "+currentLevelLocationId);
}

logger.info("Generating tasks for operationalArea "+operationalArea.getProperties().getName() +"with id "+operationalArea.getId());
PlanRepository planRepository = applicationContext.getBean(PlanRepositoryImpl.class);
List<PlanDefinition> plans = planRepository.getPlansByServerVersionAndOperationalAreasAndStatus(0L,
Collections.singletonList(operationalArea.getId()), false, PlanDefinition.PlanStatus.ACTIVE);
for (PlanDefinition plan :
plans) {
logger.info("Processing tasks for planID "+plan.getIdentifier());
taskGenerator.processPlanEvaluation(plan, null,username);
}
}
}
30 changes: 28 additions & 2 deletions src/main/java/org/opensrp/service/StockService.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,18 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joda.time.DateTime;
import org.opensrp.domain.postgres.Structure;
import org.opensrp.domain.postgres.StructureMetadataExample;
import org.opensrp.repository.postgres.mapper.custom.CustomStructureMetadataMapper;
import org.smartregister.domain.Inventory;
import org.smartregister.domain.ProductCatalogue;
import org.smartregister.domain.PhysicalLocation;
import org.smartregister.domain.Stock;
import org.opensrp.dto.CsvBulkImportDataSummary;
import org.opensrp.dto.FailedRecordSummary;
import org.opensrp.repository.StocksRepository;
import org.opensrp.search.StockSearchBean;
import org.opensrp.validator.InventoryDataValidator;
import org.smartregister.domain.PhysicalLocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

Expand Down Expand Up @@ -48,6 +51,14 @@ public class StockService {
private PhysicalLocationService physicalLocationService;

private InventoryDataValidator inventoryDataValidator;

@Autowired
private PlanService planService;
@Autowired
private TaskGenerator taskGenerator;

@Autowired
private CustomStructureMetadataMapper structureMetadataMapper;

private static Logger logger = LogManager.getLogger(StockService.class.toString());

Expand Down Expand Up @@ -177,8 +188,10 @@ public void addInventory(Inventory inventory, String userName) {
return;
}
allStocks.add(stock);
generateTasks(stock);

}

public void updateInventory(Inventory inventory, String userName) {
validateFields(inventory);
if(inventory.getStockId() == null) {
Expand All @@ -193,6 +206,19 @@ public void updateInventory(Inventory inventory, String userName) {
stock.setId(existingStock.getId());
stock.setDateEdited(DateTime.now());
allStocks.update(stock);

logger.info("Init updating tasks after adding stock");
generateTasks(stock);
}

private void generateTasks(Stock stock) {
StructureMetadataExample structureMetadataExample = new StructureMetadataExample();
structureMetadataExample.createCriteria().andGeojsonIdEqualTo(stock.getId());
// null check to keep tests from failing
if(structureMetadataMapper != null) {
Structure structure = structureMetadataMapper.findById(stock.getLocationId(), true);
physicalLocationService.regenerateTasksForOperationalArea(structure);
}
}

public Stock findByIdentifierAndServicePointId(String identifier, String locationId) {
Expand Down

0 comments on commit 157a72a

Please sign in to comment.