Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mfr api prod #115

Closed
wants to merge 14 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions .github/workflows/ci-prod.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
name: CI-Prod

on:
push:
branches: [ mfr-api-prod ]


jobs:

deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Deploy to VPS
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.SERVER_HOST }}
port: ${{ secrets.SERVER_PORT }}
username: ${{ secrets.SERVER_USER }}
password: ${{ secrets.SERVER_KEY }}
script: |
set -e
cd /opt/mfl_api
if ! [[ -d './.git' ]]; then git init; fi
if ! [[ `git remote -v | awk '{print $1}' | head -n 1` =~ 'origin' ]]; then git remote add origin ${{ github.server_url }}${{ github.username }}/${{ github.repository }}.git; fi
git stash
git pull origin mfr-api-prod
echo ${{ secrets.SERVER_KEY }} | sudo -S service supervisor restart







8 changes: 7 additions & 1 deletion chul/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,15 @@ def buffer_updates(
services=None):

try:
update = ChuUpdateBuffer.objects.get(
chu_updates = ChuUpdateBuffer.objects.filter(
health_unit=chu_instance,
is_approved=False, is_rejected=False)

update = chu_updates[chu_updates.__len__() - 1] if chu_updates.__len__() > 0 else None

if update is None:
raise ChuUpdateBuffer.DoesNotExist

except ChuUpdateBuffer.DoesNotExist:
update = ChuUpdateBuffer.objects.create(
health_unit=chu_instance,
Expand Down
119 changes: 83 additions & 36 deletions facilities/models/facility_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def get_org_unit_id(self, code):
}
)
print("Get Org Unit ID Response", r.text, str(code))
if len(r.json()["organisationUnits"]) is 1:
if len(r.json()["organisationUnits"]) is 1 and "id" in r.json()["organisationUnits"][0]:
# raise ValidationError(
# {
# "Error!": ["This facility is already available in DHIS2. Please ensure details are correct"]
Expand All @@ -161,7 +161,9 @@ def get_org_unit_id(self, code):
# )

def get_parent_id(self, ward_id):

# print self.session_store[self.oauth2_token_variable_name]

r = requests.get(
settings.DHIS_ENDPOINT+"api/organisationUnits.json",
auth=(settings.DHIS_USERNAME, settings.DHIS_PASSWORD),
Expand All @@ -182,7 +184,7 @@ def get_parent_id(self, ward_id):
if dhis2_facility[0]["id"] is None:
raise ValidationError(
{
"Error!": ["Unable to resolve exact parent of the new facility in DHIS2"]
"Error!": ["Unable to resolve exact parent of the facility in DHIS2"]
}
)
else:
Expand All @@ -200,7 +202,17 @@ def push_facility_to_dhis2(self, new_facility_payload, new_facility=True):
},
json=new_facility_payload
)
LOGGER.info("Create Facility Response: %s" % r.text)

if r.json()["status"] != "OK":

raise ValidationError(
{
"Error!": [
"An error occured while creating the facility in KHIS Aggregate. This is may be caused by the "
"existance of an organisation unit with as similar name as to the one you are creating. KHIS Error: {}".format(r.text)
]
}
)
else:
facility = requests.get(
settings.DHIS_ENDPOINT + "api/organisationUnits/" + new_facility_payload.pop('id'),
Expand All @@ -221,16 +233,16 @@ def push_facility_to_dhis2(self, new_facility_payload, new_facility=True):
},
json=new_facility_payload
)
LOGGER.info("Update Facility Response: %s" % r.text)
if r.json()["status"] != "OK":
LOGGER.error('Facility feedback: %s' % r.text)
raise ValidationError(
{
"Error!": ["An error occured while pushing facility to DHIS2. This is may be caused by the "
"existance of an organisation unit with as similar name as to the one you are creating. "
"Or some specific information like codes are not unique"]
}
)


if r.json()["status"] != "OK":
raise ValidationError(
{
"Error!": ["An error occured while updating this facility in KHIS Aggregate. KHIS Error {}".format(r.text)]
}
)


def push_facility_metadata(self, metadata_payload, facility_uid):
# Keph Level
Expand Down Expand Up @@ -278,32 +290,39 @@ def push_facility_metadata(self, metadata_payload, facility_uid):

def push_facility_updates_to_dhis2(self, org_unit_id, facility_updates_payload):
r = requests.put(
settings.DHIS_ENDPOINT + "api/organisationUnits/"+org_unit_id[0],

settings.DHIS_ENDPOINT + "api/organisationUnits/" + org_unit_id,

auth=(settings.DHIS_USERNAME, settings.DHIS_PASSWORD),
headers={
"Accept": "application/json"
},
json=facility_updates_payload
)


print("Update Facility Response", r.url, r.status_code, r.json())
LOGGER.info('[>>>>>>>>>>>>>] Org_unit_id: {} \n payload: {} \n response: {}'.format(org_unit_id, facility_updates_payload, r.json()))
LOGGER.info('[DEBUG]: parent_id: {} \n [DEBUG]: payload: {} \n [DEBUG]: response: {}'.format(org_unit_id, facility_updates_payload, r.json()))


if r.json()["status"] != "OK":
r = requests.post(
settings.DHIS_ENDPOINT + "api/organisationUnits/",
auth=(settings.DHIS_USERNAME, settings.DHIS_PASSWORD),
headers={
"Accept": "application/json"
},
json=facility_updates_payload
)
# raise ValidationError(
# {
# "Error!": ["Unable to push facility updates to DHIS2"]
# }
# )
# r = requests.post(
# settings.DHIS_ENDPOINT + "api/organisationUnits/",
# auth=(settings.DHIS_USERNAME, settings.DHIS_PASSWORD),
# headers={
# "Accept": "application/json"
# },
# json=facility_updates_payload
# )

raise ValidationError(
{
"Error!": ["Unable to push facility updates to KHIS. Created a new facility {}".format(r)]
}
)
else:
return r.json()


def format_coordinates(self, str_coordinates):
coordinates_str_list = str_coordinates.split(" ")
Expand Down Expand Up @@ -700,7 +719,7 @@ def _ensure_a_user_is_linked_to_just_one_regulator(self):
else:
msg = "The user {0} was successfully linked to the regulator {1}"\
"".format(self.user.id, self.regulatory_body.id)
LOGGER.info(msg)
LOGGER.info("[DEBUG]: {}".format(msg))

def make_user_national_user(self):
self.user.is_national = True
Expand Down Expand Up @@ -1029,7 +1048,12 @@ class FacilityExportExcelMaterialView(models.Model):
long = models.CharField(max_length=30, null=True, blank=True)
lat = models.CharField(max_length=30, null=True, blank=True)
approved_national_level = models.BooleanField(default=False)

# number_of_minor_theatres = models.PositiveIntegerField(
# default=0)
# number_of_eye_theatres = models.PositiveIntegerField(
# default=0)
# new_born_unit = models.BooleanField(default=False)
# out_reach_services = models.BooleanField(default=False)
class Meta(object):
managed = False
ordering = ('-created', )
Expand Down Expand Up @@ -1109,6 +1133,7 @@ class Facility(SequenceMixin, AbstractBase):
default=0,
help_text="The number of maternity theatres "
" that a facility has e.g 0")

number_of_minor_theatres = models.PositiveIntegerField(
default=0,
help_text="The number of minor theatres "
Expand All @@ -1118,7 +1143,9 @@ class Facility(SequenceMixin, AbstractBase):
help_text="The number of eye theatres "
" that a facility has e.g 0")
new_born_unit = models.BooleanField(default=False)

out_reach_services = models.BooleanField(default=False)

open_whole_day = models.BooleanField(
default=False,
help_text="Does the facility operate 24 hours a day")
Expand Down Expand Up @@ -1270,6 +1297,7 @@ class Facility(SequenceMixin, AbstractBase):
dhis2_api_auth = DhisAuth()

def push_new_facility(self, code=None):
# If is approved national level and operational status is opertaional and is reporting to dhis and SETTINGS.PUSH_TO_DHIS is True; then push faciliti DHIS
if self.approved_national_level and str(self.operation_status.id) == 'ae75777e-5ce3-4ac9-a17e-63823c34b55e' \
and self.reporting_in_dhis is True and settings.PUSH_TO_DHIS:
from mfl_gis.models import FacilityCoordinates
Expand All @@ -1282,7 +1310,9 @@ def push_new_facility(self, code=None):
"20b86171-0c16-47e1-9277-5e773d485c33": "YQK9pleIoeB",
"5eb392ac-d10a-40c9-b525-53dac866ef6c": "lTrpyOiOcM6",
"8949eeb0-40b1-43d4-a38d-5d4933dc209f": "lTrpyOiOcM6",

"0b7f9699-6024-4813-8801-38f188c834f5": "lTrpyOiOcM6",

"ccc1600e-9a24-499f-889f-bd9f0bdc4b95": "YQK9pleIoeB",
"d8d741b1-21c5-45c8-86d0-a2094bf9bda6": "YQK9pleIoeB",
"85f2099b-a2f8-49f4-9798-0cb48c0875ff": "YQK9pleIoeB",
Expand All @@ -1308,8 +1338,10 @@ def push_new_facility(self, code=None):
"87626d3d-fd19-49d9-98da-daca4afe85bf": "mVrepdLAqSD",
"79158397-0d87-4d0e-8694-ad680a907a79": "YQK9pleIoeB",
"031293d9-fd8a-4682-a91e-a4390d57b0cf": "YQK9pleIoeB",

"4369eec8-0416-4e16-b013-e635ce46a02f": "YQK9pleIoeB",
"9ad22615-48f2-47b3-8241-4355bb7db835" : "rhKJPLo27x7",

}
kmhfl_dhis2_ownership_mapping = {
"d45541f8-3b3d-475b-94f4-17741d468135": "aRxa6o8GqZN",
Expand All @@ -1335,6 +1367,7 @@ def push_new_facility(self, code=None):
"2e651780-2ed4-4f8c-9061-6e5acf95d581": "AaAF5EmS1fk",
"30af7e3f-cd52-4ca0-b5dc-d8b1040a9808": "AaAF5EmS1fk",
"d64bbd8a-4013-463b-a238-c346cee66a92": "AaAF5EmS1fk",

}
kmhfl_dhis2_keph_mapping = {
"ed23da85-4c92-45af-80fa-9b2123769f49": "FpY8vg4gh46",
Expand Down Expand Up @@ -1376,7 +1409,6 @@ def push_new_facility(self, code=None):
else:
pass



def validate_facility_name(self):
if self.pk:
Expand Down Expand Up @@ -1577,6 +1609,7 @@ def latest_approval_or_rejection(self):
def get_facility_services(self):
"""Digests the facility_services for the sake of frontend."""
services = self.facility_services.all()

return [
{
"id": service.id,
Expand All @@ -1599,7 +1632,9 @@ def get_facility_services(self):
@property
def get_facility_contacts(self):
"""For the same purpose as the get_facility_services above"""

contacts = self.facility_contacts.all()

return [
{
"id": contact.id,
Expand Down Expand Up @@ -1658,6 +1693,7 @@ def get_facility_specialities(self):
# for h_r in hr
# ]


@property
def average_rating(self):
avg_service_rating = [
Expand Down Expand Up @@ -1825,7 +1861,7 @@ def _dump_updates(self, origi_model):
return json.dumps(data)
else:
message = "The facility was not scheduled for update"
LOGGER.info(message)
LOGGER.info("[DEBUG]: {}".format(message))

def index_facility_material_view(self):
"""
Expand Down Expand Up @@ -2101,16 +2137,19 @@ def update_facility(self):
new_date = datetime.date(year=value.year, month=value.month, day=value.day)
value = new_date
elif field_name == 'sub_county_id':

print('field_name error', field_changed.get('display_value'))

value = SubCounty.objects.get(id=field_changed.get('actual_value')).id
else:
value = field_changed.get("actual_value")

setattr(self.facility, field_name, value)
self.facility.save(allow_save=True)
#if self.facility.code and self.facility.is_complete and self.facility.approved_national_level:
# self.facility.push_new_facility(self.facility.code)
self.push_facility_updates()

if self.facility.code and self.facility.is_complete and self.facility.approved_national_level:
#self.facility.push_new_facility(self.facility.code)
self.push_facility_updates()


def update_facility_services(self):
Expand Down Expand Up @@ -2237,6 +2276,7 @@ def validate_only_one_update_at_a_time(self):
raise ValidationError(error)

def push_facility_updates(self):

# Don't push facility updates to KHIS if facility not validated , approved nationally and reporting to KHIS
if self.facility.is_approved and self.facility.approved_national_level and self.facility.reporting_in_dhis:
from mfl_gis.models import FacilityCoordinates
Expand All @@ -2252,6 +2292,7 @@ def push_facility_updates(self):

LOGGER.error('[>>>>>Info] coordinates: {}, FacilityCoordinatesObj: {}'.format(coordinates, FacilityCoordinates.objects.values('coordinates')
.get(facility_id=self.facility.id)['coordinates']))

new_facility_updates_payload = {
"code": str(self.facility.code),
"name": str(self.facility.name),
Expand All @@ -2267,7 +2308,9 @@ def push_facility_updates(self):
# print("Names;", "Official Name:", self.facility.official_name, "Name:", self.facility.name)
#
print("New Facility Push Payload => ", new_facility_updates_payload)
self.dhis2_api_auth.push_facility_updates_to_dhis2(dhis2_org_unit_id, new_facility_updates_payload)
new_facility = False if dhis2_org_unit_id[1] == 'retrived' else True

self.dhis2_api_auth.push_facility_to_dhis2(new_facility_updates_payload, new_facility)

def clean(self, *args, **kwargs):
self.validate_only_one_update_at_a_time()
Expand Down Expand Up @@ -2940,8 +2983,10 @@ class FacilitySpecialist(AbstractBase):
Facility, related_name='facility_specialists',
on_delete=models.PROTECT)


speciality = models.ForeignKey(Speciality, related_name='speciality', on_delete=models.PROTECT)


count = models.IntegerField(
default=0,
blank=True,
Expand Down Expand Up @@ -3060,9 +3105,11 @@ class FacilityInfrastructure(AbstractBase):

infrastructure = models.ForeignKey(
Infrastructure,

related_name='infrastructure',
on_delete=models.PROTECT)


count = models.IntegerField(
default=0,
blank=True,
Expand Down
Loading
Loading