about summary refs log tree commit diff
path: root/universe/ac_types/ac_types.py
blob: 8a3513c597980df2696f7d9e5938d5a1e8d343ac (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
from itertools import product
import string
from pretty import pretty_print
import csv
import parse
import serialize
import dict
import scrape
import fs
import f
import log
import regex
import input_constant
from test_utils import simple_assert

################################################################################
# Main
################################################################################
enable_tests = True


# parse_csv :: Path -> [RowAsDict]
def parse_csv(path):
    parser = {
        "Name": parse.required("Name", parse.identity),
        "Type": parse.required("Type", parse.as_type),
        # TODO: Are we sure we want to default to False here?
        "Optional": parse.if_empty(False, parse.as_yes_no),
        # We'd like to skip rows where "Data Source Type" is empty.
        "Data Source Type": parse.nullable(parse.as_data_source_type),
        "Data Source/Value": parse.nullable(parse.identity),
    }
    result = []
    # Below are only the column in which we're interested:
    columns = [
        'Name',
        'Type',
        'Optional',
        'Data Source Type',
        'Data Source/Value',
    ]
    assert set(columns) == set(parser.keys())
    with open(path, 'r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            try:
                parsed = parse.apply_parser(parser, row)
                result.append(dict.take(columns, parsed))
            except Exception as e:
                pretty_print(row)
                raise Exception('Failed parsing the following row: {}'.format(
                    ','.join(row.values())))
                return

    return result


def serialize_id_value(xs):
    return string.indent('\n'.join([
        'id: {}'.format(serialize.literal(xs['id'])),
        'value: {}'.format(serialize.literal(xs['value'])),
    ]))


# serialize_parent_routing_frd :: RowAsDict -> [String]
def serialize_parent_routing_frd(row):
    # All parent_routing_frds should be set as Hard-Code
    assert row['Data Source Type'] == 'Hard-Code'

    frds = {
        'Consult Type': '^88149',
        'neoenum.program': '^87379',
        'form.country': '^16296',
        'Form.ad_language': "^3906"
    }
    name, value = row['Name'], parse.as_union_type(row['Data Source/Value'])

    result = []
    for x in value:
        header = 'parent_lookup_frds {'
        fields = serialize_id_value({'id': frds[name], 'value': x})
        footer = '}'
        result.append('\n'.join([header, fields, footer]))

    return result


actual = serialize_parent_routing_frd({
    'Name':
    'neoenum.program',
    'Data Source Type':
    'Hard-Code',
    'Data Source/Value':
    '"olympus" or "olympus_plus"',
})
expected = [
    """parent_lookup_frds {
  id: "^87379"
  value: "olympus"
}""",
    """parent_lookup_frds {
  id: "^87379"
  value: "olympus_plus"
}""",
]
simple_assert(actual, expected, name='serialize_parent_routing_frd')

actual = serialize_parent_routing_frd({
    'Name':
    'Consult Type',
    'Type':
    'Parent Routing FRD',
    'AIV':
    False,
    'Optional':
    False,
    'Data Source Type':
    'Hard-Code',
    'Data Source/Value':
    'ads_accountappeals_autoconsult'
})
expected = [
    """parent_lookup_frds {
  id: "^88149"
  value: "ads_accountappeals_autoconsult"
}"""
]
simple_assert(actual, expected, name='serialize_parent_routing_frd')


def serialize_return_routing_frd(row):
    header = 'parent_return_routing_frds {'
    fields = serialize_id_value({
        'id': row['Name'],
        'value': row['Data Source/Value'],
    })
    footer = '}'
    return '\n'.join([header, fields, footer])


def serialize_consult_routing_frd(row):
    header = 'consult_routing_frds {'
    fields = serialize_id_value({
        'id': row['Name'],
        'value': row['Data Source/Value'],
    })
    footer = '}'
    return '\n'.join([header, fields, footer])


# TODO: Reconcile this definition with serialize.input.
# serialize_inputs :: RowAsDict -> [String]
def serialize_input(row):
    value_type = row['Data Source Type']
    name, value = string.trim_prefix('IDENTIFIER_',
                                     row['Name']), row['Data Source/Value']

    if ' or ' in value and value_type != 'Hard-Code':
        log.warn('Found a union type in a non-"Hard-Code" row: {}'.format(row))

    # TODO: We need to resolve row['Name'] into "^<id-number>". But only
    # Sometimes... so... when is that sometimes?
    if value_type == 'Hard-Code':
        return serialize.input(
            input_type='CONSTANT',
            fields={
                'consult_frd_id': name,
                'is_optional': row['Optional'],
                # TODO: Call resolution function.
                'constant_value': input_constant.to_rule_id(value),
            })
    elif value_type == 'Atlas':
        # We need to remove the trailing parens if they exist. See the CSVs for more
        # context.
        value = regex.remove(r'\s\([\w\s]+\)$', value)
        return serialize.input(input_type='SIGNAL',
                               fields={
                                   'consult_frd_id': name,
                                   'is_optional': row['Optional'],
                               })
    elif value_type == 'Form':
        # TODO: Prefer a generic serialize.dictionary
        # We need to remove the trailing parens if they exist. See the CSVs for more
        # context.
        value = regex.remove(r'\s\([\w\s]+\)$', value)
        return serialize.input(input_type='PARENT_FRD',
                               fields={
                                   'consult_frd_id':
                                   name,
                                   'is_optional':
                                   row['Optional'],
                                   'parent_frd_id':
                                   scrape.attribute_id_for(
                                       value, error_when_absent=False),
                               })
    else:
        raise Exception("This should not have occurred.")


# csv_to_proto :: Path -> [Protobuf]
def csv_to_proto(path):
    """Maps the CSV located at `path` into a textproto that Auto Consult will consume."""
    # ORGANIZATION, which is currently a 'Consult Routing FRD' should become a
    # 'Consult Parameter' as "neo_organization".
    consult_routing_frds_blacklist = {'ORGANIZATION'}
    index = {
        'Parent Routing FRD': [],
        'Consult Parameter': [],
        'Return Routing FRD': [],
        'Consult Routing FRD': [],
        'Input': []
    }

    # Index each row according to its "Type" column.
    for row in parse_csv(path):
        name, rtype, dst = row['Name'], row['Type'], row['Data Source Type']
        # Here we need to mutate the spreadsheet because the curators encoded a
        # 'Consult Parameter', "ORGANIZATION", as a 'Consult Routing FRD'.
        if name == 'ORGANIZATION' and rtype == 'Consult Routing FRD':
            row['Type'] = 'Consult Parameter'
            index['Consult Parameter'].append(row)
            continue
        if dst is None:
            log.warn('Column "Data Source Type" is None. Skipping this row.')
            continue
        if dst == 'N/A':
            continue
        index[row['Type']].append(row)

    return serialize_index(index)


def serialize_consult_parameters(xs):
    result = []
    transforms = {
        'Taxonomy ID': 'taxonomy_id',
        'View ID': 'view_id',
        'Timeout': 'max_wait_time_for_consult_secs',
        'Re-Route if Customer Responds': 'reroute_on_customer_interaction',
        'ORGANIZATION': 'neo_organization'
    }
    parsers = {
        'Taxonomy ID':
        parse.identity,
        'View ID':
        parse.identity,
        'Timeout':
        lambda x: parse.as_hours(x) * 60 * 60,
        'Re-Route if Customer Responds':
        parse.as_mapping({
            'TRUE': True,
            'FALSE': False
        }),
        'ORGANIZATION':
        parse.identity
    }
    for row in xs:
        name = row['Name']
        parser = parsers[name]
        key, value = transforms[name], parser(row['Data Source/Value'])
        result.append('  {}: {}'.format(key, serialize.literal(value)))

    return '\n'.join(result)


def serialize_index(index):
    header = 'consult_settings {'

    consult_parameters = serialize_consult_parameters(
        index['Consult Parameter'])

    product_xs = []
    parent_lookup_frds = []
    for row in index['Parent Routing FRD']:
        product_xs.append(serialize_parent_routing_frd(row))
    for frds in product(*product_xs):
        parent_lookup_frds.append('\n'.join(frds))

    # TODO: Cover with tests.
    parent_return_routing_frds = string.indent('\n'.join([
        serialize_return_routing_frd(row)
        for row in index['Return Routing FRD']
    ]))

    # TODO: Cover with tests.
    consult_routing_frds = string.indent('\n'.join([
        serialize_consult_routing_frd(row)
        for row in index['Consult Routing FRD']
    ]))

    inputs = string.indent('\n'.join(
        [serialize_input(row) for row in index['Input']]))

    footer = '}'

    result = []
    for parent_frd in parent_lookup_frds:
        result.append('\n'.join([
            header, consult_parameters,
            string.indent(parent_frd), parent_return_routing_frds,
            consult_routing_frds, inputs, footer
        ]))

    return '\n'.join(result)


csv_directory = f.ensure_absolute("~/auto-consult-csv")
# TODO: Add missing files.
csvs = [
    'Non-Sensitive Ads Review (Olympus).csv',
    'Ads Review (Olympus).csv',
    'Ad Review (Non-Olympus).csv',
    'Review Account Under Review (Olympus).csv',
    'Accounts Review Requests (Non-Olympus).csv',
    'Review Suspended Account (Olympus).csv',
    'Review Suspended Account (Non-Olympus).csv',
    'Suspended Long Form (Olympus).csv',
    'Suspended Long Form (Non-Olympus).csv',
    'Copyright (Olympus).csv',
    'Copyright (Non-Olympus).csv',
    'EU Election Certification (Olympus).csv',
    'EU Election Certification #2 (Olympus).csv',
    'EU Election Certification (Non-Olympus).csv',
    'EU Election Certification #2 (Non-Olympus).csv',
    'US Election Certification (Olympus).csv',
    'US Election Certification (Non-Olympus).csv',
    'IN Election Certification (Olympus).csv',
    'IN Election Certification (Non-Olympus).csv',
    'NY Election Certification (Olympus).csv',
    'NY Election Certification (Non-Olympus).csv',
    'Ticket Seller Certification (Olympus).csv',
    'Ticket Seller Certification (Non-Olympus).csv',
    'Pharma Certification EMEA (Olympus).csv',
    'Pharma Certification EMEA (Non-Olympus).csv',
    'CSFP Certification (Olympus).csv',
    'CSFP Certification (Non-Olympus).csv',
    'Social Casino Games Certification (Olympus).csv',
    'Social Casino Games Certification (NonOlympus).csv',
    'Gambling Certification (Olympus).csv',
    'Gambling Certification (Non-Olympus).csv',
    'Addiction Services Certification (Olympus).csv',
    'Addiction Services Certification (Non-Olympus).csv',
    'HTML5 Application (Olympus).csv',
    'HTML5 Application (Non-Olympus).csv',
    # TODO: Support this once Jason unblocks.
    # 'Account Take Over (Olympus).csv',
    # TODO: Support this once Jason unblocks.
    # 'Account Take Over (Non-Olympus).csv',
    'Free Desktop Software Policy (Olympus).csv',
    'Free Desktop Software Policy (Non-Olympus).csv',
    'Untrustworthy Promotions (Olympus).csv',
    'Untrustworthy Promotions (Non-Olympus).csv',
]

# TODO: Dump these CSVs into SQL to run basic queries on the " or " count, etc.
# Only 'Hard-Code' fields seem to have " or "s in them; SQL can help me verify
# this claim.

for x in csvs:
    print('# File: "{}"'.format(f.strip_extension(x)))
    print(csv_to_proto(f.join(csv_directory, x)))

################################################################################
# Tests
################################################################################
if enable_tests:
    tests = [
        # 'EU Election Certification (Olympus).csv',
        'EU Election Certification (Non-Olympus).csv',
        # 'Non-Sensitive Ads Review (Olympus).csv',
    ]
    for csv_file in tests:
        textproto_file = f.join('expected',
                                f.change_extension('.textproto', csv_file))
        actual = csv_to_proto(
            f.ensure_absolute(f.join(csv_directory, csv_file)))
        expected = open(textproto_file, 'r').read()
        simple_assert(actual, expected, name='csv_to_proto')