Ejemplo n.º 1
0
def main():
    # Initialize the parser with a welcome message
    welcome = "A command line interface for displaying supported currencies for Cheap Stocks, Inc"
    parser = argparse.ArgumentParser(description=welcome)

    # Add a required flag for providing currency code
    parser.add_argument('-c',
                        '--code',
                        required=False,
                        help="Three digit currency code ")
    parser.add_argument('-i',
                        '--item',
                        required=False,
                        help="Display price of a stock item")
    parser.add_argument(
        '-l',
        '--language',
        required=False,
        default="en",
        help="A two digit language code to display information")
    parser.add_argument('-s',
                        '--supported_languages',
                        action="store_true",
                        required=False,
                        help="List all supported languages")
    parser.add_argument('-k',
                        '--supported_currencies',
                        action="store_true",
                        required=False,
                        help="List all supported currencies")
    args = parser.parse_args()

    # Switch to the provided currency
    _lang = args.language.lower()
    lang = language.switch(_lang)
    # List supported currencies
    supported_currencies = args.supported_currencies
    if supported_currencies:
        currency.supported_currencies(lang)
    # Ensure the provided code is 3 letters long
    supported_languages = args.supported_languages
    if supported_languages:
        language.supported_languages(lang)
    # Get currency code provided
    code = args.code
    # Get stock item provided
    item = args.item
    if item is not None:
        stock.check_item(item, code, lang)
    # Verify support of a currency
    if code is not None:
        currency.verify_support(code, lang)
    # If not flag was passed, show help message
    parser.parse_args(['-h'])
Ejemplo n.º 2
0
def updateform_view(request, dtype):
    eid = request.POST.get('doc_id')
    data, doc, baseform, template = get_basics(request, doctype)
    append_key = check_append(data)

    if append_key:
        context = add_compoundfield_doc(doc, baseform, data, append_key, eid)
    else:
        context = update_doc(doc, baseform, data)
    if not context:
        raise Http404

    context.update({
        'type' : dtype,
        'doc' : json.dumps(doc),
        'doc_id': eid,
        "description" : doc.get("description").capitalize(),
        'languages' : supported_languages(),
        'tab_ids'     : prepare_tabs(context['form']),
        'skip_js': True,
        'request': request
    })
    s = template_render(template, context)

    return HttpResponse(s)
Ejemplo n.º 3
0
def add_linkdata_view(request, doctype, exdoctype, linkfield):
    """
    Function adds given given exdoc_id's to given target field and
    sets given linkfield with the modeldocs eid

    TODO: reliable way to find where to put the eid of linked doc in form
          reasonable way to loop the model docs with their id's

    building the form is ever so slightly different when one wants to
    update it with some values and replace with others (linkfield and modeldoc)
    """
    #append_data = conn.get(settings.INDEX_NAME, doctype, exdoc_id)
    exdoc_ids = request.GET.getlist('exdoc_id')
    if not exdoc_ids:
        raise Http404
    append_key = request.GET.get('target')
    if not append_key:
        raise Http404
    template = None
    if doctype == 'organisation':
        template = env.get_template('organisation_form.html')

    eid = request.POST.get('doc_id')
    data, doc, baseform, template = get_basics(request, doctype, template=template)
    example_data = searcher.get_docs(exdoctype, exdoc_ids)
    #if is_compoundfield(doc, append_key):
    #    append_data = example_data
    #else:
    #    append_data = create_exampledoc(doc, append_key, example_data[0])
    #TODO: plz fix.. doclist and eid list are in same order, but not pretty
    for eid_num, modeldoc in enumerate(example_data):
        #TODO: plz fix.. linkfield might not be at first level of subdoc
        modeldoc[linkfield] = exdoc_ids[eid_num]
    context = add_linkdata_doc(doc, baseform, data, append_key, example_data)
    if not context:
        raise Http404

    path = request.path_info + '?doc_id={0}'.format(eid)

    context.update({
        'type' : doctype,
        'doc' : json.dumps(doc),
        'user': request.user,
        'doc_id' : eid,
        'title': data.get('name_fi'),
        "description" : doc.get("description").capitalize(),
        'reload_path': '/add/{dt}/?doc_id={eid}'.format(dt=doctype, eid=eid),
        'languages' : supported_languages(),
        'tab_ids'     : prepare_tabs(context['form']),
        'skip_js': True,
        'request': request
    })
    s = template_render(template, context)
    sr = re.sub(r'\s+', ' ', s)
    return HttpResponse(sr)
Ejemplo n.º 4
0
def add_exampledata_view(request, doctype, exdoctype, append_key):
    #append_data = conn.get(settings.INDEX_NAME, doctype, exdoc_id)
    exdoc_ids = request.GET.getlist('exdoc_id')

    if not exdoc_ids:
        raise Http404

    template = None

    eid = request.POST.get('doc_id')

    if doctype == 'organisation':
        template = env.get_template('organisation_form.html')
    data, doc, baseform, template = get_basics(request, doctype, template=template)
    example_data = searcher.get_docs(exdoctype, exdoc_ids)
    if is_compoundfield(doc, append_key):
        append_data = example_data
    else:
        append_data = create_exampledoc(doc, append_key, example_data[0])
    context = add_fielddata_doc(doc, baseform, data, append_key, append_data)
    if not context:
        raise Http404

    path = request.path_info + '?doc_id={0}'.format(eid)

    context.update({
        'type' : doctype,
        'doc' : json.dumps(doc),
        'user': request.user,
        'doc_id' : eid,
        'title': data.get('name_fi'),
        "description" : doc.get("description").capitalize(),
        'reload_path': '/add/{dt}/?doc_id={eid}'.format(dt=doctype,
                                                                    eid=eid),
        'languages' : supported_languages(),
        'tab_ids'     : prepare_tabs(context['form']),
        'skip_js': True,
        'request': request})
    s = template_render(template, context)
    return HttpResponse(s)
def build_form(data, meta, skip_validation=False):
    """
    Builds a WTForm instance using fields and meta information
    from (JSON) doctype dictionary.

    Uses OrderedDictionary to maintain field definition order
    as per doctype (which should be Ordered too).

    Form class is thus created dynamically with the type-function.

    skip_validation enables making subforms optional when saving the parent form

    """
    based = OD()

    for name, fdata in data.items():
        label = fdata.get("label")
        if label:
            label = label.capitalize()

        if label is None:
            label = ''

        if not skip_validation and name in meta.get('required', []):
            _validators = [validators.Required(message = _('required field'))]
        else:
            _validators = None

        if fdata['type'] == 'multilingualfield':
            # one multilingual field in basedocs maps
            # into several fields in form & document

            for lang in supported_languages():
                if  not lang['required']:
                    _validators = None

                # any primitive field can be a field with a language
                # the translatable version is constructed
                # on the fly
                classname = fdata['field']
                typename = str('Ling' + classname)
                superclass = globals()[classname]
                myclass = type(typename, (LingField, superclass), {})

                suffix = u' <span class="language-label">{0}</span>'.format(lang['label_suffix'])
                llabel = (label + suffix)
                field = myclass(lang=lang['lid'], label=llabel,
                                validators=_validators,
                                description=tr_descr(fdata))

                field_key = name + '_' + lang['lid']
                based[field_key] = field

        else: # single-language fields
            if fdata['type'] == 'choicefield':
                #pre-configured choices
                class_name = SelectMultipleField if fdata['field'] == 'SelectMultipleField' else SelectField

                choices = sort_choices(fdata['choices'])

                #print(fdata['choices'])

                _validators = []

                based[name] = class_name(
                    label, choices = choices, validators=_validators,
                    description=tr_descr(fdata))

            elif fdata['type'] == 'periodfield':
                #repeating sub-fields
                based[name] = FieldList(
                    FormField(build_form(
                            fdata['field']['fields'], fdata['field']['meta'],
                            skip_validation = True), widget=PeriodWidget()),
                    min_entries=1, label=label, widget=AccordionListWidget(
                        has_sample_documents=True))

            elif fdata['type'] == 'compoundfield':
                #print(fdata['field']['fields'])
                #print('')
                #repeating sub-fields
                based[name] = FieldList(
                    FormField(build_form(
                            fdata['field']['fields'], fdata['field']['meta'],
                            skip_validation = True), widget=KirListWidget()),
                    min_entries=1, label=label, widget=AccordionListWidget())

            elif fdata['type'] == 'subfield':
                #sub-fields
                based[name] = FormField(
                    build_form(
                        fdata['field']['fields'], fdata['field']['meta']),
                    label=label, widget=KirListWidget())

            elif fdata['type'] == 'linkfield':
                if name == 'parent_organisation':
                    if _validators is None:
                        _validators = []

                    _validators.append(kir_validators.test_cyclic_hierarchy)

                based[name] = HiddenField(
                    label, widget=LinkWidget(field_data=fdata),
                    validators=_validators, description=tr_descr(fdata))

            elif fdata['type'] == 'extlinkfield':
                choices = get_choices_from_es(fdata['field']['choicefields'],
                                              fdata['field']['query'])
                based[name] = wtforms.SelectMultipleField(
                    label, choices = choices, validators=_validators,
                    description=tr_descr(fdata))

            elif fdata['type'] in ['field', 'geofield']:
                #other regular field types like text
                if skip_validation or fdata['field'] == 'BooleanField':
                    _validators = [validators.Optional()]

                if fdata['field'] == 'KirTimeField':
                    _validators = [validators.Optional()]

                try:
                    based[name] = getattr(wtfields, fdata['field'])(
                        label, validators=_validators,
                        description=tr_descr(fdata))
                except AttributeError:
                    _validators.append(validators.Required())
                    based[name] = kirfields.KirPeriodEndDateField(label,
                        validators=_validators,
                        description=tr_descr(fdata),
                        format='%Y-%m-%d')

    return type('GeneratedForm', (ODForm,), based)
Ejemplo n.º 6
0
def add_view(request, dtype, entity_id=None):
    data, doc, baseform, template = get_basics(request, dtype)
    remove_key = check_remove(data)
    append_key = check_append(data)
    eid = entity_id

    if remove_key:
        context = remove_field_doc(doc, baseform, data, remove_key)
        context['doc_id'] = eid
    elif append_key:
        context = add_compoundfield_doc(doc, baseform, data, append_key, eid)
    else:
        if eid and not data:
            context = open_doc(doc, baseform, request.user, eid)
        elif data:
            context = save_doc(doc, baseform, data, request.user, eid)
            eid = context['doc_id']

            if context['saved'] and context['errors'] == None:
                store_context(context, request.session)
                return redirect('kir.views.add_view', dtype, eid)
        else:
            context = new_doc(doc, baseform)

    if not context:
        raise Http404

    context = restore_context(context, request.session)
    context = process_metafields(context)

    if 'doc_id' in context:
        path = request.path_info
    else:
        path = None

    context.update({
        'type'        : dtype,
        'doc'         : json.dumps(doc),
        'request'     : request,
        'time_separator' : time_separator,
        'image_url'   : settings.MEDIA_URL + settings.UPLOADED_IMAGES_FOLDER + 'medium/',
        'description' : doc.get('description'),
        'languages'   : supported_languages(),
        'tab_ids'     : prepare_tabs(context['form']),
        'title'       : doc_presentation(context['form'].data,
                                         basedoc = doc),
        'reload_path' : path,
        'user': request.user,
    })

    if context['type'] != 'organisation':
        if type(context['title']) == str:
            context['title'] = context['title'].decode('utf-8')

    if dtype == 'period': # todo: generalize as hook?
        context.update(PeriodWidget.template_params(form = context['form']))

    #print(context)

    context['parents'] = parent_chain(doc, context['form'].data, request.user)
    response = HttpResponse(template_render(template, context))
    response['Cache-Control'] = 'no-store'

    print(context.keys())

    return response