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

akvo / iwsims-demo / #72

28 Apr 2025 03:28AM UTC coverage: 86.134% (+1.1%) from 85.024%
#72

push

coveralls-python

web-flow
Merge pull request #20 from akvo/feature/19-eng-1231-dynamic-level-approval

Feature/19 eng 1231 dynamic level approval

2646 of 3188 branches covered (83.0%)

Branch coverage included in aggregate %.

5995 of 6844 relevant lines covered (87.59%)

0.88 hits per line

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

94.67
backend/utils/custom_generator.py
1
import os
1✔
2
import sqlite3
1✔
3
import pandas as pd
1✔
4
import logging
1✔
5
from iwsims.settings import MASTER_DATA, STORAGE_PATH, COUNTRY_NAME
1✔
6
from api.v1.v1_profile.models import Administration
1✔
7

8
logger = logging.getLogger(__name__)
1✔
9

10

11
def generate_sqlite(model, test: bool = False):
1✔
12
    table_name = model._meta.db_table
1✔
13
    field_names = [f.name for f in model._meta.fields]
1✔
14
    objects = model.objects.all()
1✔
15
    file_name = "{0}/{1}{2}.sqlite".format(
1✔
16
        MASTER_DATA,
17
        "test_" if test else "",
18
        table_name,
19
    )
20
    if os.path.exists(file_name):
1✔
21
        os.remove(file_name)
1✔
22
    data = pd.DataFrame(list(objects.values(*field_names)))
1✔
23
    no_rows = data.shape[0]
1✔
24
    if no_rows < 1:
1✔
25
        return
1✔
26
    if "parent" in field_names:
1✔
27
        data["parent"] = data["parent"].apply(
1✔
28
            lambda x: int(x) if x == x else 0
29
        )
30
    elif "administration" in field_names:
1✔
31
        data["parent"] = data["administration"].apply(
1✔
32
            lambda x: int(x) if x == x else 0
33
        )
34
    else:
35
        data["parent"] = 0
1✔
36
    conn = sqlite3.connect(file_name)
1✔
37
    data.to_sql("nodes", conn, if_exists="replace", index=False)
1✔
38
    conn.close()
1✔
39
    return file_name
1✔
40

41

42
def update_sqlite(model, data, id=None, test: bool = False):
1✔
43
    table_name = model._meta.db_table
1✔
44
    fields = data.keys()
1✔
45
    field_names = ", ".join([f for f in fields])
1✔
46
    placeholders = ", ".join(["?" for _ in range(len(fields))])
1✔
47
    update_placeholders = ", ".join([f"{f} = ?" for f in fields])
1✔
48
    params = list(data.values())
1✔
49
    if id:
1✔
50
        params += [id]
1✔
51
    file_name = "{0}/{1}{2}.sqlite".format(
1✔
52
        MASTER_DATA,
53
        "test_" if test else "",
54
        table_name,
55
    )
56
    conn = sqlite3.connect(file_name)
1✔
57
    try:
1✔
58
        with conn:
1✔
59
            c = conn.cursor()
1✔
60
            if id:
1✔
61
                c.execute("SELECT * FROM nodes WHERE id = ?", (id,))
1✔
62
                if c.fetchone():
1✔
63
                    query = f"UPDATE nodes \
1✔
64
                        SET {update_placeholders} WHERE id = ?"
65
                    c.execute(query, params)
1✔
66
            if not id:
1✔
67
                query = f"INSERT INTO nodes({field_names}) \
1✔
68
                    VALUES ({placeholders})"
69
                c.execute(query, params)
1✔
70
    except sqlite3.OperationalError:
1!
71
        generate_sqlite(model=model, test=test)
1✔
72
    except Exception as error:
×
73
        logger.error(
×
74
            {
75
                "context": "update_sqlite",
76
                "error": error,
77
                "table_name": table_name,
78
                "data": data,
79
                "id": id,
80
            }
81
        )
82
        conn.rollback()
×
83
    finally:
84
        conn.close()
1✔
85

86

87
def administration_csv_add(data: dict, test: bool = False):
1✔
88
    filename = "{0}-administration.csv".format(
1✔
89
        "test" if test else COUNTRY_NAME
90
    )
91
    filepath = f"{STORAGE_PATH}/master_data/{filename}"
1✔
92
    if os.path.exists(filepath):
1✔
93
        df = pd.read_csv(filepath)
1✔
94
        new_data = {}
1✔
95
        if data.path:
1!
96
            parent_ids = list(filter(lambda path: path, data.path.split(".")))
1✔
97
            parents = Administration.objects.filter(
1✔
98
                pk__in=parent_ids, level__id__gt=1
99
            ).all()
100
            for p in parents:
1✔
101
                new_data[p.level.name.lower()] = p.name
1✔
102
                new_data[f"{p.level.name.lower()}_id"] = p.id
1✔
103
        new_data[data.level.name.lower()] = data.name
1✔
104
        new_data[f"{data.level.name.lower()}_id"] = data.id
1✔
105
        new_df = pd.DataFrame([new_data])
1✔
106
        df = pd.concat([df, new_df], ignore_index=True)
1✔
107
        df.to_csv(filepath, index=False)
1✔
108
        return filepath
1✔
109
    else:
110
        logger.error(
1✔
111
            {
112
                "context": "insert_administration_row_csv",
113
                "message": (
114
                    f"{('test' if test else COUNTRY_NAME)}-administration.csv"
115
                    " doesn't exist"
116
                ),
117
            }
118
        )
119
    return None
1✔
120

121

122
def find_index_by_id(df, id):
1✔
123
    for idx, row in df.iterrows():
1✔
124
        last_non_null_col = row.last_valid_index()
1✔
125
        last_non_null_value = row[last_non_null_col]
1✔
126
        if last_non_null_value == id:
1✔
127
            return idx
1✔
128
    return None
1✔
129

130

131
def administration_csv_update(data: dict, test: bool = False):
1✔
132
    filename = "{0}-administration.csv".format(
1✔
133
        "test" if test else COUNTRY_NAME
134
    )
135
    filepath = f"{STORAGE_PATH}/master_data/{filename}"
1✔
136
    if os.path.exists(filepath):
1✔
137
        df = pd.read_csv(filepath)
1✔
138
        index = find_index_by_id(df=df, id=data.pk)
1✔
139
        if index is not None:
1✔
140
            if data.path:
1!
141
                parent_ids = list(
1✔
142
                    filter(lambda path: path, data.path.split("."))
143
                )
144
                parents = Administration.objects.filter(
1✔
145
                    pk__in=parent_ids, level__id__gt=1
146
                ).all()
147
                for p in parents:
1✔
148
                    df.loc[index, p.level.name.lower()] = p.name
1✔
149
                    df.loc[index, f"{p.level.name.lower()}_id"] = p.id
1✔
150
            df.loc[index, data.level.name.lower()] = data.name
1✔
151
            df.loc[index, f"{data.level.name.lower()}_id"] = data.id
1✔
152
        df.to_csv(filepath, index=False)
1✔
153
        return filepath
1✔
154
    else:
155
        logger.error(
1✔
156
            {
157
                "context": "update_administration_row_csv",
158
                "message": f"{filename} doesn't exist",
159
            }
160
        )
161
    return None
1✔
162

163

164
def administration_csv_delete(id: int, test: bool = False):
1✔
165
    filename = "{0}-administration.csv".format(
1✔
166
        "test" if test else COUNTRY_NAME
167
    )
168
    filepath = f"{STORAGE_PATH}/master_data/{filename}"
1✔
169
    if os.path.exists(filepath):
1!
170
        df = pd.read_csv(filepath)
1✔
171
        ix = find_index_by_id(df=df, id=id)
1✔
172
        if ix is not None:
1✔
173
            df.drop(index=ix, inplace=True)
1✔
174
        df.to_csv(filepath, index=False)
1✔
175
        return filepath
1✔
176
    else:
177
        logger.error(
×
178
            {
179
                "context": "delete_administration_row_csv",
180
                "message": f"{filename} doesn't exist",
181
            }
182
        )
183
    return None
×
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