def get_all(election_id=None, area_name=None, associated_area_id=None, area_type=None):
    election = Election.get_by_id(electionId=election_id)

    if associated_area_id is not None and area_type is not None:
        associated_area = get_by_id(areaId=associated_area_id)
        query = get_associated_areas_query(areas=[associated_area], areaType=area_type, electionId=election_id)
    else:
        query = Model.query

    if area_name is not None:
        query = query.filter(Model.areaName.like(area_name))

    if election is not None:
        query = query.filter(
            or_(
                Model.electionId.in_(election.mappedElectionIds),
                Model.electionId.in_(election.subElectionIds)
            )
        )

    if area_type is not None:
        query = query.filter(Model.areaType == area_type)

    query = query.order_by(Model.areaId)

    return query
示例#2
0
def get_all(electionId=None, areaId=None, tallySheetCode=None, voteType=None):
    # Filter by authorized areas
    user_access_area_ids: Set[int] = get_user_access_area_ids()

    query_args = [Model]
    query_filters = [
        Submission.Model.areaId.in_(user_access_area_ids),
        Template.Model.templateId == Model.templateId,
        Submission.Model.submissionId == Model.tallySheetId,
        Election.Model.electionId == Submission.Model.electionId
    ]
    query_group_by = [Model.tallySheetId]

    if areaId is not None:
        query_filters.append(Submission.Model.areaId == areaId)

    if electionId is not None:
        election = Election.get_by_id(electionId=electionId)
        query_filters.append(
            Election.Model.electionId.in_(
                election.get_this_and_below_election_ids()))

    if tallySheetCode is not None:
        query_filters.append(Template.Model.templateName == tallySheetCode)

    if voteType is not None:
        query_filters.append(Election.Model.voteType == voteType)

    return db.session.query(*query_args).filter(*query_filters).group_by(
        *query_group_by)
示例#3
0
def get_all(electionId=None, areaId=None, tallySheetCode=None):
    election = Election.get_by_id(electionId=electionId)

    query = Model.query.join(
        Submission.Model,
        Submission.Model.submissionId == Model.tallySheetId
    ).join(
        Election.Model,
        Election.Model.electionId == Submission.Model.electionId
    )

    if electionId is not None:
        query = query.filter(
            Election.Model.electionId.in_(election.mappedElectionIds)
        )

    if areaId is not None:
        query = query.filter(Submission.Model.areaId == areaId)

    if tallySheetCode is not None:
        query = query.filter(Model.tallySheetCode == get_tally_sheet_code(tallySheetCode))

    # Filter by authorized areas
    user_access_area_ids: Set[int] = get_user_access_area_ids()
    query = query.filter(Submission.Model.areaId.in_(user_access_area_ids))

    return query
示例#4
0
    def create_test_election(mock_stamp_create):
        mock_stamp = Stamp()
        mock_stamp.ip = "0.0.0.0"
        mock_stamp.createdBy = "TestAdmin"
        mock_stamp.createdAt = datetime.now()
        db.session.add(mock_stamp)
        db.session.flush()
        mock_stamp_create.return_value = mock_stamp

        from orm.entities.Election.election_helper import build_presidential_election
        election = Election.create(electionName="Test Election")

        basedir = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                               "..", "sample-data", "test")
        party_candidate_dataset_file = os.path.join(basedir,
                                                    "party-candidate.csv")
        polling_station_dataset_file = os.path.join(basedir, "data.csv")
        postal_counting_centers_dataset_file = os.path.join(
            basedir, "postal-data.csv")
        invalid_vote_categories_dataset_file = os.path.join(
            basedir, "invalid-vote-categories.csv")

        build_presidential_election(
            root_election=election,
            party_candidate_dataset_file=party_candidate_dataset_file,
            polling_station_dataset_file=polling_station_dataset_file,
            postal_counting_centers_dataset_file=
            postal_counting_centers_dataset_file,
            invalid_vote_categories_dataset_file=
            invalid_vote_categories_dataset_file)
        return election
示例#5
0
def create(body):
    request_body = RequestBody(body)
    election_name = request_body.get("electionName")
    election_template_name = request_body.get("electionTemplateName")

    files = connexion.request.files
    polling_stations_dataset = files.get("pollingStationsDataset")
    postal_counting_centres_dataset = files.get("postalCountingCentresDataset")
    party_candidates_dataset = files.get("partyCandidatesDataset")
    invalid_vote_categories_dataset = files.get("invalidVoteCategoriesDataset")
    number_of_seats_dataset_file = files.get("numberOfSeatsDataset")

    election = Election.create(
        electionTemplateName=election_template_name,
        electionName=election_name,
        isListed=True,
        party_candidate_dataset_file=party_candidates_dataset,
        polling_station_dataset_file=polling_stations_dataset,
        postal_counting_centers_dataset_file=postal_counting_centres_dataset,
        invalid_vote_categories_dataset_file=invalid_vote_categories_dataset,
        number_of_seats_dataset_file=number_of_seats_dataset_file)

    db.session.commit()

    return Schema().dump(election).data
def get_by_id(electionId):
    result = Election.get_by_id(electionId=electionId)
    if result is None:
        raise NotFoundException(message="Election not found (electionId=%d)" %
                                electionId,
                                code=MESSAGE_CODE_ELECTION_NOT_FOUND)

    return Schema().dump(result).data
示例#7
0
def get_all(electionId=None,
            areaId=None,
            tallySheetCode=None,
            voteType=None,
            partyId=None,
            limit=None,
            offset=None):
    # Filter by authorized areas
    user_access_area_ids: Set[int] = get_user_access_area_ids()

    query_args = [Model]
    query_filters = [
        Submission.Model.areaId.in_(user_access_area_ids),
        Template.Model.templateId == Model.templateId,
        Submission.Model.submissionId == Model.tallySheetId,
        Election.Model.electionId == Submission.Model.electionId
    ]
    query_group_by = [Model.tallySheetId]

    if areaId is not None:
        query_filters.append(Submission.Model.areaId == areaId)

    if electionId is not None:
        election = Election.get_by_id(electionId=electionId)
        query_filters.append(
            Election.Model.electionId.in_(
                election.get_this_and_below_election_ids()))

    if tallySheetCode is not None:
        query_filters.append(Template.Model.templateName == tallySheetCode)

    if voteType is not None:
        query_filters.append(Election.Model.voteType == voteType)

    if partyId is not None:
        query_filters += [
            MetaData.Model.metaId == Model.metaId,
            MetaData.Model.metaDataKey == "partyId",
            MetaData.Model.metaDataValue == partyId
        ]

    tally_sheet_list = db.session.query(*query_args).filter(
        *query_filters).group_by(*query_group_by).order_by(Model.tallySheetId)

    tally_sheet_list = get_paginated_query(query=tally_sheet_list,
                                           limit=limit,
                                           offset=offset)

    authorized_tally_sheet_list = []
    for tally_sheet in tally_sheet_list:
        if has_role_based_access(election=tally_sheet.submission.election,
                                 tally_sheet_code=tally_sheet.tallySheetCode,
                                 access_type=WORKFLOW_ACTION_TYPE_VIEW):
            authorized_tally_sheet_list.append(tally_sheet)

    return authorized_tally_sheet_list
示例#8
0
def _cache_get_area_map(user_access_area_ids, electionId):
    election = Election.get_by_id(electionId=electionId)
    if election is None:
        raise NotFoundException(message="Election not found (electionId=%d)" %
                                electionId,
                                code=MESSAGE_CODE_ELECTION_NOT_FOUND)

    extended_election = election.get_extended_election()
    area_map = extended_election.get_area_map()

    return AreaMapSchema(many=True).dump(area_map).data
示例#9
0
def get_mapped_area(electionId=None, areaIds=None, requestedAreaType=None):
    election = Election.get_by_id(electionId=electionId)
    if election is None:
        raise NotFoundException(message="Election not found (electionId=%d)" %
                                electionId,
                                code=MESSAGE_CODE_ELECTION_NOT_FOUND)

    extended_election = election.get_extended_election()
    mapped_area = extended_election.get_mapped_area(areaIds, requestedAreaType)

    return MappedAreaSchema(many=True).dump(mapped_area).data
示例#10
0
def _cache_get_all(user_access_area_ids,
                   parentElectionId=None,
                   rootElectionId=None,
                   isListed=None):
    if isListed == "false":
        isListed = False
    elif isListed == "true":
        isListed = True

    result = Election.get_all(parentElectionId=parentElectionId,
                              rootElectionId=rootElectionId,
                              isListed=isListed)

    return Schema(many=True).dump(result).data
def create(body):
    request_body = RequestBody(body)
    election_name = request_body.get("electionName")

    files = connexion.request.files
    polling_stations_dataset = files.get("pollingStationsDataset")
    postal_counting_centres_dataset = files.get("postalCountingCentresDataset")
    party_candidates_dataset = files.get("partyCandidatesDataset")
    invalid_vote_categories_dataset = files.get("invalidVoteCategoriesDataset")

    election = Election.create(electionName=election_name)
    election.set_polling_stations_dataset(fileSource=polling_stations_dataset)
    election.set_postal_counting_centres_dataset(fileSource=postal_counting_centres_dataset)
    election.set_party_candidates_dataset(fileSource=party_candidates_dataset)
    election.set_invalid_vote_categories_dataset(fileSource=invalid_vote_categories_dataset)

    build_presidential_election(root_election=election)

    db.session.commit()

    return Schema().dump(election).data
def get_all(electionId=None, areaId=None, tallySheetCode=None, voteType=None):
    # Filter by authorized areas
    user_access_area_ids: Set[int] = get_user_access_area_ids()

    query_args = [Model]
    query_filters = [
        Submission.Model.areaId.in_(user_access_area_ids),
        Template.Model.templateId == Model.templateId,
        Submission.Model.submissionId == Model.tallySheetId,
        Election.Model.electionId == Submission.Model.electionId
    ]
    query_group_by = [Model.tallySheetId]

    if areaId is not None:
        query_filters.append(Submission.Model.areaId == areaId)

    if electionId is not None:
        election = Election.get_by_id(electionId=electionId)
        query_filters.append(
            Election.Model.electionId.in_(
                election.get_this_and_below_election_ids()))

    if tallySheetCode is not None:
        query_filters.append(Template.Model.templateName == tallySheetCode)

    if voteType is not None:
        query_filters.append(Election.Model.voteType == voteType)

    tally_sheet_list = db.session.query(*query_args).filter(
        *query_filters).group_by(*query_group_by)

    authorized_tally_sheet_list = []
    for tally_sheet in tally_sheet_list:
        if has_role_based_access(tally_sheet=tally_sheet,
                                 access_type=WORKFLOW_ACTION_TYPE_VIEW):
            authorized_tally_sheet_list.append(tally_sheet)

    return authorized_tally_sheet_list
def get_all():
    result = Election.get_all()

    result = get_paginated_query(result).all()

    return Schema(many=True).dump(result).data
示例#14
0
def build_presidential_election(root_election: Election,
                                party_candidate_dataset_file=None,
                                polling_station_dataset_file=None,
                                postal_counting_centers_dataset_file=None,
                                invalid_vote_categories_dataset_file=None):
    postal_election = root_election.add_sub_election(
        electionName="Postal", voteType=VoteTypeEnum.Postal)
    ordinary_election = root_election.add_sub_election(
        electionName="Ordinary", voteType=VoteTypeEnum.NonPostal)

    if not party_candidate_dataset_file:
        party_candidate_dataset_file = root_election.partyCandidateDataset.get_file_path(
        )

    if not polling_station_dataset_file:
        polling_station_dataset_file = root_election.pollingStationsDataset.get_file_path(
        )

    if not postal_counting_centers_dataset_file:
        postal_counting_centers_dataset_file = root_election.postalCountingCentresDataset.get_file_path(
        )

    if not invalid_vote_categories_dataset_file:
        invalid_vote_categories_dataset_file = root_election.invalidVoteCategoriesDataset.get_file_path(
        )

    data_stores = {}

    def get_data_store(data_store_key):
        if data_store_key not in data_stores:
            data_stores[data_store_key] = {}

        return data_stores[data_store_key]

    def get_object_from_data_store(data_key, data_store_key):
        data_store = get_data_store(data_store_key)
        if data_key in data_store:
            return data_store[data_key]
        else:
            return None

    def set_object_to_data_store(data_key, data_store_key, obj):
        data_store = get_data_store(data_store_key)
        data_store[data_key] = obj

    def get_object(election, row, row_key, data_key=None):
        if data_key is None:
            cell = row[row_key].strip()
            data_key = cell
        else:
            cell = row[data_key].strip()
            data_key = cell

        data_store_key = row_key

        if data_store_key == "TallySheet":
            data_key = "%s-%s" % (row["TallySheet"], row["Counting Centre"])
        elif data_store_key == "Polling District":
            data_key = "%s-%s-%s" % (row["Electoral District"],
                                     row["Polling Division"],
                                     row["Polling District"])
        elif data_store_key == "Counting Centre":
            data_key = "%s-%s" % (row["Electoral District"],
                                  row["Counting Centre"])
        elif data_store_key == "Polling Station":
            data_key = "%s-%s-%s-%s" % (
                row["Electoral District"], row["Polling Division"],
                row["Polling District"], row["Polling Station"])

        obj = get_object_from_data_store(data_key, data_store_key)

        # To identify the duplicated polling stations.
        if data_store_key == "Polling Station" and obj is not None:
            raise Exception("Duplicated polling station %s" % data_key)

        # To identify the duplicated counting centres.
        # if data_store_key == "Counting Centre" and obj is not None:
        #     print("[Error] Duplicated counting centre %s" % data_key)

        if obj is None:
            if data_store_key == "Ballot":
                obj = Ballot.create(ballotId=cell,
                                    electionId=election.electionId)
            elif data_store_key == "Tendered Ballot":
                obj = Ballot.create(ballotId=cell,
                                    electionId=election.electionId,
                                    ballotType=BallotTypeEnum.Tendered)
            elif data_store_key == "Ballot Box":
                obj = BallotBox.create(ballotBoxId=cell,
                                       electionId=election.electionId)

            elif data_store_key == "Party":
                obj = Party.create(partyName=cell,
                                   partySymbol=row["Party Symbol"],
                                   partyAbbreviation=row["Party Abbreviation"])
            elif data_store_key == "Candidate":
                obj = Candidate.create(candidateName=cell)

            elif data_store_key == "Country":
                obj = Country.create(cell, electionId=election.electionId)

                TallySheet.create(
                    tallySheetCode=TallySheetCodeEnum.PRE_ALL_ISLAND_RESULTS,
                    electionId=election.electionId,
                    areaId=obj.areaId)
                TallySheet.create(
                    tallySheetCode=TallySheetCodeEnum.
                    PRE_ALL_ISLAND_RESULTS_BY_ELECTORAL_DISTRICTS,
                    electionId=election.electionId,
                    areaId=obj.areaId)
                TallySheet.create(tallySheetCode=TallySheetCodeEnum.PRE_34_AI,
                                  electionId=election.electionId,
                                  areaId=obj.areaId)

            elif data_store_key == "Electoral District":
                obj = ElectoralDistrict.create(cell,
                                               electionId=election.electionId)

                TallySheet.create(tallySheetCode=TallySheetCodeEnum.PRE_30_ED,
                                  electionId=election.electionId,
                                  areaId=obj.areaId)
                TallySheet.create(tallySheetCode=TallySheetCodeEnum.PRE_34_ED,
                                  electionId=election.electionId,
                                  areaId=obj.areaId)
                TallySheet.create(tallySheetCode=TallySheetCodeEnum.PRE_30_PD,
                                  electionId=postal_election.electionId,
                                  areaId=obj.areaId)
                TallySheet.create(tallySheetCode=TallySheetCodeEnum.PRE_34_PD,
                                  electionId=postal_election.electionId,
                                  areaId=obj.areaId)
                TallySheet.create(
                    tallySheetCode=TallySheetCodeEnum.PRE_34_I_RO,
                    electionId=postal_election.electionId,
                    areaId=obj.areaId)
                TallySheet.create(
                    tallySheetCode=TallySheetCodeEnum.PRE_34_II_RO,
                    electionId=election.electionId,
                    areaId=obj.areaId)
                TallySheet.create(tallySheetCode=TallySheetCodeEnum.PRE_34,
                                  electionId=election.electionId,
                                  areaId=obj.areaId)

            elif data_store_key == "Polling Division":
                obj = PollingDivision.create(cell,
                                             electionId=election.electionId)

                TallySheet.create(tallySheetCode=TallySheetCodeEnum.PRE_30_PD,
                                  electionId=ordinary_election.electionId,
                                  areaId=obj.areaId)
                TallySheet.create(tallySheetCode=TallySheetCodeEnum.PRE_34_PD,
                                  electionId=ordinary_election.electionId,
                                  areaId=obj.areaId)
                TallySheet.create(
                    tallySheetCode=TallySheetCodeEnum.PRE_34_I_RO,
                    electionId=ordinary_election.electionId,
                    areaId=obj.areaId)

            elif data_store_key == "Polling District":
                obj = PollingDistrict.create(cell,
                                             electionId=election.electionId)

            elif data_store_key == "Election Commission":
                obj = ElectionCommission.create(cell,
                                                electionId=election.electionId)

            elif data_store_key == "District Centre":
                obj = DistrictCentre.create(cell,
                                            electionId=election.electionId)

            elif data_store_key == "Counting Centre":
                if election.voteType is VoteTypeEnum.NonPostal:
                    obj = CountingCentre.create(cell,
                                                electionId=election.electionId)
                    TallySheet.create(tallySheetCode=TallySheetCodeEnum.PRE_41,
                                      electionId=election.electionId,
                                      areaId=obj.areaId)
                    TallySheet.create(tallySheetCode=TallySheetCodeEnum.CE_201,
                                      electionId=election.electionId,
                                      areaId=obj.areaId)
                    TallySheet.create(
                        tallySheetCode=TallySheetCodeEnum.PRE_34_CO,
                        electionId=election.electionId,
                        areaId=obj.areaId)
                elif election.voteType is VoteTypeEnum.Postal:
                    obj = CountingCentre.create(
                        cell,
                        electionId=election.electionId,
                        registeredVotersCount=row["Registered Voters"])
                    TallySheet.create(tallySheetCode=TallySheetCodeEnum.PRE_41,
                                      electionId=election.electionId,
                                      areaId=obj.areaId)
                    TallySheet.create(
                        tallySheetCode=TallySheetCodeEnum.CE_201_PV,
                        electionId=election.electionId,
                        areaId=obj.areaId)
                    TallySheet.create(
                        tallySheetCode=TallySheetCodeEnum.PRE_34_CO,
                        electionId=election.electionId,
                        areaId=obj.areaId)

            elif data_store_key == "Polling Station":
                obj = PollingStation.create(
                    cell,
                    electionId=election.electionId,
                    registeredVotersCount=row["Registered Voters"])

            else:
                print("-------------  Not supported yet : *%s*" %
                      data_store_key)

            set_object_to_data_store(data_key, data_store_key, obj)

        return obj

    def get_rows_from_csv(csv_path):
        csv_file_path = csv_path
        if os.path.exists(csv_file_path) is True:
            with open(csv_file_path, 'r') as f:
                reader = csv.DictReader(f, delimiter=',')
                rows = list(reader)
        else:
            rows = []

        # for row in rows:
        #     for cell_key in row:
        #         row[cell_key] = row[cell_key].encode('unicode_escape')

        return rows

    for row in get_rows_from_csv(party_candidate_dataset_file):
        party = get_object(root_election, row, "Party")
        root_election.add_party(partyId=party.partyId)

        candidate = get_object(root_election, row, "Candidate")
        root_election.add_candidate(candidateId=candidate.candidateId,
                                    partyId=party.partyId)

    for row in get_rows_from_csv(invalid_vote_categories_dataset_file):
        root_election.add_invalid_vote_category(
            row["Invalid Vote Category Description"])

    for row in get_rows_from_csv(polling_station_dataset_file):
        print("[ROW] ========= ", row)
        country = get_object(root_election, {"Country": "Sri Lanka"},
                             "Country")
        electoralDistrict = get_object(root_election, row,
                                       "Electoral District")
        pollingDivision = get_object(root_election, row, "Polling Division")
        pollingDistrict = get_object(root_election, row, "Polling District")
        electionCommission = get_object(
            root_election,
            {"Election Commission": "Sri Lanka Election Commission"},
            "Election Commission")
        districtCentre = get_object(root_election, row, "District Centre")
        countingCentre = get_object(ordinary_election, row, "Counting Centre")

        registered_voters = row["Registered Voters"]

        pollingStation = get_object(
            ordinary_election, {
                "Electoral District": row["Electoral District"],
                "Polling Division": row["Polling Division"],
                "Polling District": row["Polling District"],
                "Polling Station": row["Polling Station (English)"],
                "Registered Voters": registered_voters
            }, "Polling Station")

        country.add_child(electoralDistrict.areaId)
        electoralDistrict.add_child(pollingDivision.areaId)
        pollingDivision.add_child(pollingDistrict.areaId)
        pollingDistrict.add_child(pollingStation.areaId)
        electionCommission.add_child(districtCentre.areaId)
        districtCentre.add_child(countingCentre.areaId)
        countingCentre.add_child(pollingStation.areaId)

        AreaMap.create(electionId=root_election.electionId,
                       voteType=VoteTypeEnum.NonPostal,
                       pollingStationId=pollingStation.areaId,
                       countingCentreId=countingCentre.areaId,
                       districtCentreId=districtCentre.areaId,
                       electionCommissionId=electionCommission.areaId,
                       pollingDistrictId=pollingDistrict.areaId,
                       pollingDivisionId=pollingDivision.areaId,
                       electoralDistrictId=electoralDistrict.areaId,
                       countryId=country.areaId)

        # stationaryItems = []
        #
        # for i in range(1, 4):
        #     box_key = "Ballot Box %d" % i
        #     if box_key in row and row[box_key] is not None and len(row[box_key]) > 0:
        #         if row[box_key] is not None and len(row[box_key]) > 0:
        #             ballotBox = BallotBox.Model(ballotBoxId=row[box_key], electionId=root_election.electionId)
        #             db.session.add(ballotBox)
        #             stationaryItems.append(ballotBox)
        #             # ballotBox = get_object({"Ballot Box": row[box_key]}, "Ballot Box")
        #
        # if len(row["Ballot - start"]) is not 0 and len(row["Ballot - end"]) is not 0:
        #     for ballotId in range(int(row["Ballot - start"]), int(row["Ballot - end"]) + 1):
        #         ballot = Ballot.Model(ballotId=ballotId, electionId=root_election.electionId)
        #         db.session.add(ballot)
        #         stationaryItems.append(ballot)
        #         # ballot = get_object({"Ballot": str(ballotId)}, "Ballot")
        #         # invoice.add_stationary_item(ballot.stationaryItemId)
        #
        # if len(row["Tendered Ballot - start"]) is not 0 and len(row["Tendered Ballot - end"]) is not 0:
        #     for ballotId in range(int(row["Tendered Ballot - start"]), int(row["Tendered Ballot - end"]) + 1):
        #         ballot = Ballot.Model(ballotId=ballotId, ballotType=BallotTypeEnum.Tendered,
        #                               electionId=root_election.electionId)
        #         db.session.add(ballot)
        #         stationaryItems.append(ballot)
        #         # ballot = get_object({"Tendered Ballot": str(ballotId)}, "Tendered Ballot")
        #         # invoice.add_stationary_item(ballot.stationaryItemId)
        #
        # invoice = Invoice.create(
        #     electionId=root_election.electionId,
        #     issuingOfficeId=countingCentre.areaId,
        #     receivingOfficeId=pollingStation.areaId,
        #     issuedTo=1
        # )
        #
        # invoice.add_stationary_items([stationaryItem.stationaryItemId for stationaryItem in stationaryItems])
        #
        # invoice.set_confirmed()

        print("[ROW END] ========= ")

    for row in get_rows_from_csv(postal_counting_centers_dataset_file):
        print("[POSTAL ROW] ========= ", row)
        country = get_object(root_election, {"Country": "Sri Lanka"},
                             "Country")
        electoralDistrict = get_object(root_election, row,
                                       "Electoral District")
        electionCommission = get_object(
            root_election,
            {"Election Commission": "Sri Lanka Election Commission"},
            "Election Commission")
        districtCentre = get_object(root_election, row, "District Centre")

        registered_voters = row["Registered Voters"]

        countingCentre = get_object(
            postal_election, {
                "Counting Centre": row["Postal Vote Counting Centre"],
                "Registered Voters": registered_voters,
                "Electoral District": row["Electoral District"]
            }, "Counting Centre")

        country.add_child(electoralDistrict.areaId)
        electoralDistrict.add_child(countingCentre.areaId)
        districtCentre.add_child(countingCentre.areaId)
        electionCommission.add_child(districtCentre.areaId)

        print("[POSTAL ROW END] ========= ")

        AreaMap.create(electionId=root_election.electionId,
                       voteType=VoteTypeEnum.Postal,
                       countingCentreId=countingCentre.areaId,
                       districtCentreId=districtCentre.areaId,
                       electionCommissionId=electionCommission.areaId,
                       electoralDistrictId=electoralDistrict.areaId,
                       countryId=country.areaId)

    db.session.commit()

    update_dashboard_tables()

    return root_election
def get_associated_areas_query(areas, areaType, electionId=None):
    presidential_area_map_sub_query = get_presidential_area_map_query().subquery()
    election = Election.get_by_id(electionId=electionId)

    query = db.session.query(
        AreaModel
    ).join(
        Election.Model,
        Election.Model.electionId == AreaModel.electionId
    )

    if areaType is AreaTypeEnum.PollingStation:
        query = query.join(
            presidential_area_map_sub_query,
            presidential_area_map_sub_query.c.pollingStationId == AreaModel.areaId
        )
    elif areaType is AreaTypeEnum.CountingCentre:
        query = query.join(
            presidential_area_map_sub_query,
            presidential_area_map_sub_query.c.countingCentreId == AreaModel.areaId
        )
    elif areaType is AreaTypeEnum.DistrictCentre:
        query = query.join(
            presidential_area_map_sub_query,
            presidential_area_map_sub_query.c.districtCentreId == AreaModel.areaId
        )
    elif areaType is AreaTypeEnum.ElectionCommission:
        query = query.join(
            presidential_area_map_sub_query,
            presidential_area_map_sub_query.c.electionCommissionId == AreaModel.areaId
        )
    elif areaType is AreaTypeEnum.PollingDistrict:
        query = query.join(
            presidential_area_map_sub_query,
            presidential_area_map_sub_query.c.pollingDistrictId == AreaModel.areaId
        )
    elif areaType is AreaTypeEnum.PollingDivision:
        query = query.join(
            presidential_area_map_sub_query,
            presidential_area_map_sub_query.c.pollingDivisionId == AreaModel.areaId
        )
    elif areaType is AreaTypeEnum.ElectoralDistrict:
        query = query.join(
            presidential_area_map_sub_query,
            presidential_area_map_sub_query.c.electoralDistrictId == AreaModel.areaId
        )
    elif areaType is AreaTypeEnum.Country:
        query = query.join(
            presidential_area_map_sub_query,
            presidential_area_map_sub_query.c.countryId == AreaModel.areaId
        )
    elif areaType is AreaTypeEnum.PostalVoteCountingCentre:
        query = query.join(
            presidential_area_map_sub_query,
            presidential_area_map_sub_query.c.postalVoteCountingCentreId == AreaModel.areaId
        )

    query = query.group_by(AreaModel.areaId)

    filtered_polling_stations = [area.areaId for area in areas if area.areaType == AreaTypeEnum.PollingStation]
    filtered_counting_centres = [area.areaId for area in areas if area.areaType == AreaTypeEnum.CountingCentre]
    filtered_district_centres = [area.areaId for area in areas if area.areaType == AreaTypeEnum.DistrictCentre]
    filtered_election_commissions = [area.areaId for area in areas if area.areaType == AreaTypeEnum.ElectionCommission]
    filtered_polling_districts = [area.areaId for area in areas if area.areaType == AreaTypeEnum.PollingDistrict]
    filtered_polling_divisions = [area.areaId for area in areas if area.areaType == AreaTypeEnum.PollingDivision]
    filtered_electoral_districts = [area.areaId for area in areas if area.areaType == AreaTypeEnum.ElectoralDistrict]
    filtered_countries = [area.areaId for area in areas if area.areaType == AreaTypeEnum.Country]

    if len(filtered_polling_stations) > 0:
        query = query.filter(
            presidential_area_map_sub_query.c.pollingStationId.in_(filtered_polling_stations)
        )
    elif len(filtered_counting_centres) > 0:
        query = query.filter(
            presidential_area_map_sub_query.c.countingCentreId.in_(filtered_counting_centres)
        )
    elif len(filtered_district_centres) > 0:
        query = query.filter(
            presidential_area_map_sub_query.c.districtCentreId.in_(filtered_district_centres)
        )
    elif len(filtered_election_commissions) > 0:
        query = query.filter(
            presidential_area_map_sub_query.c.electionCommissionId.in_(filtered_election_commissions)
        )
    elif len(filtered_polling_districts) > 0:
        query = query.filter(
            presidential_area_map_sub_query.c.pollingDistrictId.in_(filtered_polling_districts)
        )
    elif len(filtered_polling_divisions) > 0:
        query = query.filter(
            presidential_area_map_sub_query.c.pollingDivisionId.in_(filtered_polling_divisions)
        )
    elif len(filtered_electoral_districts) > 0:
        query = query.filter(
            presidential_area_map_sub_query.c.electoralDistrictId.in_(filtered_electoral_districts)
        )
    elif len(filtered_countries) > 0:
        query = query.filter(
            presidential_area_map_sub_query.c.countryId.in_(filtered_countries)
        )

    if electionId is not None:
        query = query.filter(
            or_(
                Model.electionId.in_(election.mappedElectionIds),
                Model.electionId.in_(election.subElectionIds)
            )
        )

    query = query.filter(
        AreaModel.areaType == areaType
    )

    return query
def get_all():
    result = Election.get_all()

    return Schema(many=True).dump(result).data
def get_all(parentElectionId=None, rootElectionId=None):
    result = Election.get_all(parentElectionId=parentElectionId, rootElectionId=rootElectionId)

    result = get_paginated_query(result).all()

    return Schema(many=True).dump(result).data