Exemplo n.º 1
0
def json_ext_manufactureitem_working_time_detail(request, mig_id):
    mig = ManufactureItemGroup.objects.get(id=mig_id)
    mis_id = [mi.id for mi in mig.manufacture_items.all()]
    mrs_id = [
        mr.id for mr in ManufactureRecord.objects.filter(
            manufacture_item_id__in=mis_id)
    ]
    timesheets = Timesheet.objects.filter(
        object_id__in=mrs_id, content_type__model='manufacturerecord')

    json = {}
    data = []
    total = timesheets.count()
    json['totalCount'] = total

    func = request.GET.get("func", None)
    page = request.GET.get("page", None)
    limit = request.GET.get("limit", None)
    if func and func == '2':
        i_timesheets = timesheets
        for i in range(12):
            aaa = {'month': _("%d month") % (i + 1)}
            ies_timesheets = timesheets.filter(start__month=i +
                                               1).order_by('-start')
            i_timesheets = i_timesheets.exclude(start__month=i +
                                                1).order_by('-start')
            worked_hours = sum([t.difference_hours for t in ies_timesheets],
                               timedelta())
            aaa['cNum'] = worked_hours.seconds
            data.append(aaa)
        response = HttpResponse(content=JSONEncoder().encode(data),
                                mimetype='text/javascript')
    else:
        if page and limit:
            paginator = Paginator(timesheets, int(limit))
            try:
                timesheets = paginator.page(int(page))
            except PageNotAnInteger:
                # If page is not an integer, deliver first page.
                timesheets = paginator.page(int(page))
            except EmptyPage:
                # If page is out of range (e.g. 9999), deliver last page of results.
                timesheets = paginator.page(paginator.num_pages)

        for ts in timesheets:
            aaa = {'mi': ts.content_object.manufacture_item.__unicode__()}
            aaa['start'] = ts.start.strftime(DATETIMEFORMAT)
            aaa['end'] = ts.end.strftime(DATETIMEFORMAT)
            aaa['df'] = str(timedelta(seconds=ts.difference_hours.seconds))
            aaa['type'] = ts.get_type_display()
            data.append(aaa)

        json['data'] = data
        response = HttpResponse(content=JSONEncoder().encode(json),
                                mimetype='text/javascript')
    response['Content-Length'] = len(response.content)
    return response
Exemplo n.º 2
0
def json_ext_knife_scraped_detail(request, item_id):
    item = Item.objects.get(id=item_id)
    list_category = 3  #TODO
    transport_category = 3  #Scrap
    tdrs = TransportDetailRecord.objects.filter(
        inventory_item_entry__item=item,
        transport_list_detail__transport_list__list_category=list_category,
        transport_list_detail__transport_list__transport_category=
        transport_category).order_by('-created_at')

    json = {}
    data = []
    total = tdrs.count()
    json['totalCount'] = total

    func = request.GET.get("func", None)
    page = request.GET.get("page", None)
    limit = request.GET.get("limit", None)

    if func and func == '2':
        i_tdrs = tdrs
        for i in range(12):
            aaa = {'month': _("%d month") % (i + 1)}
            ies_tdrs = i_tdrs.filter(created_at__month=i +
                                     1).order_by('-created_at')
            i_tdrs = i_tdrs.exclude(created_at__month=i +
                                    1).order_by('-created_at')
            aaa['cNum'] = ies_tdrs[0].scrap_qty if ies_tdrs else 0
            data.append(aaa)
        response = HttpResponse(content=JSONEncoder().encode(data),
                                mimetype='text/javascript')
    else:
        if page and limit:
            paginator = Paginator(tdrs, int(limit))
            try:
                tdrs = paginator.page(int(page))
            except PageNotAnInteger:
                # If page is not an integer, deliver first page.
                tdrs = paginator.page(int(page))
            except EmptyPage:
                # If page is out of range (e.g. 9999), deliver last page of results.
                tdrs = paginator.page(paginator.num_pages)

        for tdr in tdrs:
            aaa = {'c': tdr.created_at.strftime(DATETIMEFORMAT)}
            aaa['s'] = tdr.scrap_qty
            data.append(aaa)

        json['data'] = data
        response = HttpResponse(content=JSONEncoder().encode(json),
                                mimetype='text/javascript')
    response['Content-Length'] = len(response.content)
    return response
Exemplo n.º 3
0
def del_device(request):
    json = []
    if not request.user.is_authenticated():
        return HttpResponse(JSONEncoder().encode(json),
                            mimetype='application/json')
    else:
        if request.method == 'POST' and request.is_ajax():
            # TODO del functional
            return HttpResponse(JSONEncoder().encode(json),
                                mimetype='application/json')
        else:
            return HttpResponse(JSONEncoder().encode(json),
                                mimetype='application/json')
Exemplo n.º 4
0
def json_ext_employee_worked_manufactureitem(request, year):
    now = datetime.now()
    employees = Employee.objects.filter(department_id=2)
    timesheets = Timesheet.objects.filter(
        start__year=year, content_type__model='manufacturerecord')

    json = {}
    data = []
    total = employees.count()
    json['totalCount'] = total

    func = request.GET.get("func", None)
    page = request.GET.get("page", None)
    limit = request.GET.get("limit", None)
    if page and limit:
        paginator = Paginator(employees, int(limit))
        try:
            employees = paginator.page(int(page))
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            employees = paginator.page(int(page))
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            employees = paginator.page(paginator.num_pages)

    for e in employees:
        e_name = e.name if func and func == '2' else '<a href="' + reverse(
            'ext_employee_worked_detail', args=[e.id]) + '">' + e.name + '</>'
        aaa = {0: e_name}
        ts = timesheets.filter(person=e)
        for i in range(12):
            if datetime(int(year), i + 1, 1) > now:
                aaa[i + 1] = 0 if func and func == '2' else '-'
            else:
                e_ts = ts.filter(start__month=i + 1)
                ts = ts.exclude(start__month=i + 1)
                mrs_id = [e.object_id for e in e_ts]
                mrs = ManufactureRecord.objects.filter(id__in=mrs_id)
                mi_count = mrs.values('manufacture_item').annotate(
                    Count('manufacture_item')).count()
                aaa[i + 1] = mi_count
        data.append(aaa)
    if func and func == '2':
        response = HttpResponse(content=JSONEncoder().encode(data),
                                mimetype='text/javascript')
    else:
        json['data'] = data
        response = HttpResponse(content=JSONEncoder().encode(json),
                                mimetype='text/javascript')
    response['Content-Length'] = len(response.content)
    return response
Exemplo n.º 5
0
    def merge_json_capabilities(self, merge):
        d = JSONDecoder()
        e = JSONEncoder()

        capabilities = d.decode(self.json_capabilities)
        capabilities_merge = d.decode(merge)

        for (group, props) in capabilities_merge.items():
            if capabilities.has_key(group):
                capabilities[group].update(props)
            else:
                capabilities[group] = props

        self.json_capabilities = e.encode(capabilities)
Exemplo n.º 6
0
def set_metadata(id_item, param):
    """
    Allows to set metadata of an item
    parameters:
        id_item: id of item
        param: dict with key 'metadata'
    return:
        empty string
    """

    json_enc = JSONEncoder()
    param['metadata'] = json_enc.encode(param['metadata'])
    #set_metadata
    i._item_set_metadata(id_item, param)

    return ''
Exemplo n.º 7
0
def get_active_users(request):
    """
    Retrieves a list of active users which is returned as plain JSON for
    easier manipulation with JavaScript.
    """
    if request.is_ajax():
        active = VisitorTracked.objects.active().reverse()
        now = datetime.now()

        # we don't put the session key or IP address here for security reasons
        data = {'users': [{
                'id': v.id,
                #'user': uc(v.user),
                'user_agent': uc(v.user_agent),
                'referrer': uc(v.referrer),
                'url': uc(v.url),
                'page_views': v.page_views,
                'geoip': v.geoip_data_json,
                'last_update': (now - v.last_update).seconds,
                'friendly_time': ', '.join(friendly_time((now - v.last_update).seconds)),
            } for v in active]}
        #print data

        response = HttpResponse(content=JSONEncoder().encode(data),
                                mimetype='text/javascript')
        response['Content-Length'] = len(response.content)

        return response

    # if the request was not made via AJAX, raise a 404
    raise Http404
Exemplo n.º 8
0
def set_metadata(id_item,param):
    """
    Allows to set metadata of an item
    parameters:
        id_item: id of item
        param: dict with key 'metadata'
    return:
        empty string
    """
    
    json_enc = JSONEncoder()
    param['metadata'] = json_enc.encode(param['metadata'])
    #set_metadata
    i._item_set_metadata(id_item,param)
    
    return ''
Exemplo n.º 9
0
def wishlist_remove_ajax(request, template="shop/json.html"):
    success, msg = _wishlist_remove(request)

    data = {'success': success, 'wishlist_message': msg}
    encoded = JSONEncoder().encode(data)
    encoded = mark_safe(encoded)

    return render_to_response(template, {'json': encoded})
Exemplo n.º 10
0
def add_keywords(i,
                 data,
                 ws_origTows_new,
                 id_orig_itemToid_new_item,
                 keyColl_origTokeyColl_new,
                 returnkeywords=None):
    """
    Allows to create keywords into a workspace.
    parameters:
        i: class instance Importer logged at DAM
        data:data to insert new keyword
        ws_origTows_new:  dict with key 'id' ws read to file workspace.json end value 'id' workspace create .
        id_orig_itemToid_new_item: dict with key 'id' item read to file item.json end value 'id' item create .
        keyColl_origTokeyColl_new: dict with key 'id' read to file collections.json end value 'id' create for equivalent collection.
        returnkeywords: None if keyword haven't parent, else data of father 
    return:
    """

    logger.debug("-----ADD KEYWORD ID OLD WS %s" % data['workspace'])
    data['workspace_id'] = ws_origTows_new[str(data['workspace'])]
    logger.debug("-----new ID WS %s" % data['workspace_id'])
    items_flag = True
    data_app = dict(data)
    try:
        if data["parent_id"] == None:
            del data["parent_id"]
        else:
            del data["workspace_id"]
            data["parent_id"] = returnkeywords['id']

        if data["associate_ancestors"] == False:
            del data["associate_ancestors"]
        if (len(data["items"]) == 0):
            del data["items"]
            items_flag = False
        else:
            del data["items"]

        if len(data["metadata_schema"]) == 0:
            del data["metadata_schema"]
        else:
            json_enc = JSONEncoder()
            data["metadata_schema"] = json_enc.encode(data["metadata_schema"])
    except Exception, ex:
        logger.exception(ex)
Exemplo n.º 11
0
def add_smartfolders(i, data, ws_origTows_new, keyColl_origTokeyColl_new):
    """
    Allows to create smartfolders into a workspace.
    parameters:
        i: class instance Importer logged at DAM
        data:
        ws_origTows_new: dict with key 'id' ws read to file workspace.json end value 'id' workspace create.
        keyColl_origTokeyColl_new: dict with key 'id' read to file collections.json end value 'id' create for equivalent collection.
    returns:
        empty string
    """
    json_enc = JSONEncoder()
    for q in data['queries']:
        q['id'] = keyColl_origTokeyColl_new[q['id']]
    data['queries'] = json_enc.encode(data['queries'])
    i._smartfolders_add(data)

    return ''
Exemplo n.º 12
0
def add_smartfolders(i,data,ws_origTows_new, keyColl_origTokeyColl_new):
    """
    Allows to create smartfolders into a workspace.
    parameters:
        i: class instance Importer logged at DAM
        data:
        ws_origTows_new: dict with key 'id' ws read to file workspace.json end value 'id' workspace create.
        keyColl_origTokeyColl_new: dict with key 'id' read to file collections.json end value 'id' create for equivalent collection.
    returns:
        empty string
    """
    json_enc = JSONEncoder()
    for q in data['queries']:
        q['id'] = keyColl_origTokeyColl_new[q['id']]
    data['queries'] = json_enc.encode(data['queries'])
    i._smartfolders_add(data)
    
    return ''
Exemplo n.º 13
0
    def default(self, c):
        # Handles generators and iterators
        if hasattr(c, '__iter__'):
            return [i for i in c]

        # Handles closures and functors
        if hasattr(c, '__call__'):
            return c()

        return JSONEncoder.default(self, c)
Exemplo n.º 14
0
    def default(self, c):
        # Handles generators and iterators
        if hasattr(c, '__iter__'):
            return [i for i in c]

        # Handles closures and functors
        if hasattr(c, '__call__'):
            return c()

        return JSONEncoder.default(self, c)
Exemplo n.º 15
0
def json_companys_request(request):
    companys = Company.objects.all().order_by('id')

    root_comps = [c for c in companys if c.parent_id == None]
    c_data = [comp_serializable_object(root_comp) for root_comp in root_comps]

    response = HttpResponse(content=JSONEncoder().encode(c_data),
                            mimetype='text/javascript')
    response['Content-Length'] = len(response.content)
    return response
Exemplo n.º 16
0
 def default(self, obj):
     if isinstance(obj, QuerySet) \
     and obj.model == Candidate:
         result = [];
         for c in obj:
             result.append(self.__construct_simple_candidate(c))
         return result
     elif isinstance(obj, Candidate):
         return self.__construct_simple_candidate(obj)
     else: 
         return JSONEncoder.default(self,obj)
Exemplo n.º 17
0
def current_geos(request):
    json = createResponseTmp('currentgeos', True)
    if not request.user.is_authenticated():
        return HttpResponse(JSONEncoder().encode(json),
                            mimetype='application/json')
    else:
        if request.method == 'POST' and request.is_ajax():
            for d in Device.objects.filter(user_id=request.user.id):
                cg = d.current_geo
                json['currentgeos'].append({
                    'device_id': cg.id,
                    'lat': str(cg.lat),
                    'lng': str(cg.lng)
                })
            json['success'] = True
            return HttpResponse(JSONEncoder().encode(json),
                                mimetype='application/json')
        else:
            return HttpResponse(JSONEncoder().encode(json),
                                mimetype='application/json')
Exemplo n.º 18
0
 def __init__(self, device_class=None, merge=False):
     # Initialized flag
     self.initialized = False
     # Parsing version flag
     self.parse_version = False
     # JSON encoder
     self.e = JSONEncoder()
     # Device class
     self.device_class = device_class
     # are we merging?
     self.merge = merge
Exemplo n.º 19
0
def list_markersimg(request):
    json = createResponseTmp('markersimg', True)
    if not request.user.is_authenticated():
        return HttpResponse(JSONEncoder().encode(json),
                            mimetype='application/json')
    else:
        if request.method == 'POST' and request.is_ajax():
            for m in MapMarker.objects.all():
                json['markersimg'].append({
                    'marker_id': m.marker_id,
                    'width': m.width,
                    'height': m.height,
                    'url': m.url,
                    'name': m.name
                })
                json['success'] = True
            return HttpResponse(JSONEncoder().encode(json),
                                mimetype='application/json')
        else:
            return HttpResponse(JSONEncoder().encode(json),
                                mimetype='application/json')
Exemplo n.º 20
0
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        value = smart_unicode(value)
        final_attrs = self.build_attrs(attrs, name=name)

        self.mce_settings['elements'] = "id_%s" % name
        mce_json = JSONEncoder().encode(self.mce_settings)

        return mark_safe(
            u'<textarea%s>%s</textarea> <script type="text/javascript">\
                tinyMCE.init(%s)</script>' %
            (flatatt(final_attrs), escape(value), mce_json))
Exemplo n.º 21
0
def add_keywords(i,data, ws_origTows_new, id_orig_itemToid_new_item,keyColl_origTokeyColl_new, returnkeywords = None):
    """
    Allows to create keywords into a workspace.
    parameters:
        i: class instance Importer logged at DAM
        data:data to insert new keyword
        ws_origTows_new:  dict with key 'id' ws read to file workspace.json end value 'id' workspace create .
        id_orig_itemToid_new_item: dict with key 'id' item read to file item.json end value 'id' item create .
        keyColl_origTokeyColl_new: dict with key 'id' read to file collections.json end value 'id' create for equivalent collection.
        returnkeywords: None if keyword haven't parent, else data of father 
    return:
    """
   
    logger.debug("-----ADD KEYWORD ID OLD WS %s" %data['workspace'])
    data['workspace_id'] = ws_origTows_new[str(data['workspace'])]
    logger.debug("-----new ID WS %s" %data['workspace_id'])
    items_flag = True
    data_app = dict(data)
    try:
        if data["parent_id"] == None:
            del data["parent_id"]
        else:
            del data["workspace_id"]
            data["parent_id"] = returnkeywords['id']
            
        if data["associate_ancestors"] == False:
            del data["associate_ancestors"]
        if (len(data["items"]) == 0):
            del data["items"]
            items_flag = False
        else:
            del data["items"]
            
        if len(data["metadata_schema"]) == 0:
                del data["metadata_schema"]
        else:
            json_enc = JSONEncoder()
            data["metadata_schema"] = json_enc.encode(data["metadata_schema"])
    except Exception, ex:
        logger.exception(ex)
Exemplo n.º 22
0
def add_device(request):
    json = createResponseTmp('devices', True)
    if not request.user.is_authenticated():
        return HttpResponse(JSONEncoder().encode(json),
                            mimetype='application/json')
    else:
        if request.method == 'POST' and request.is_ajax():
            json_request = simplejson.loads(request.raw_post_data)
            for element in json_request['devices']:
                if 'marker_id' in element:
                    marker = MapMarker.objects.filter(
                        marker_id=element['marker_id'])[0]
                else:
                    marker = None
                if len(Device.objects.filter(imei=element['imei'])) > 0:
                    json['success'] = False
                    json['errors'] = {}
                    json['errors'][
                        'reason'] = 'Device with this IMEI already exist.'
                else:
                    device = Device(imei=element['imei'],
                                    name=element['name'],
                                    text=element['text'],
                                    marker_id=marker,
                                    user_id=request.user)
                    device.save()
                    json['success'] = True
                    json['devices'].append({
                        'device_id': device.device_id,
                        'marker_id': device.marker_id_id,
                        'imei': element['imei'],
                        'name': element['name'],
                        'text': element['text']
                    })
            return HttpResponse(JSONEncoder().encode(json),
                                mimetype='application/json')
        else:
            return HttpResponse(JSONEncoder().encode(json),
                                mimetype='application/json')
Exemplo n.º 23
0
def index(request):
    """
    Main page. If request not AJAX open index page
    """
    c = {}
    # TODO csrf
    #c.update(csrf(request))
    if request.method == 'POST':
        if request.is_ajax():
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            json = createResponseTmp('errors')
            user = auth.authenticate(username=username, password=password)
            if user is not None and user.is_active:
                auth.login(request, user)
                json['success'] = True
                return HttpResponse(JSONEncoder().encode(json),
                                    mimetype='application/json')
            else:
                json['errors']['reason'] = 'Login failed. Try again.'
                return HttpResponse(JSONEncoder().encode(json),
                                    mimetype='application/json')
    return render_to_response('index.html', c)
Exemplo n.º 24
0
def edit_device(request):
    if not request.user.is_authenticated():
        return HttpResponse(JSONEncoder().encode(json),
                            mimetype='application/json')
    else:
        if request.method == 'POST' and request.is_ajax():
            json_request = simplejson.loads(request.raw_post_data)
            json = createResponseTmp('devices', True)
            for element in json_request['devices']:
                device = Device.objects.get(device_id=element['device_id'],
                                            user_id=request.user)
                device.name = element['name']
                device.text = element['text']
                if 'marker_id' in element:
                    marker = MapMarker.objects.get(
                        marker_id=element['marker_id'])
                    device.marker_id = marker
                    try:
                        # Save device in DB
                        device.save()
                        json['success'] = True
                        json['devices'].append({
                            'device_id': device.device_id,
                            'marker_id': device.marker_id_id,
                            'imei': element['imei'],
                            'name': element['name'],
                            'text': element['text']
                        })
                    except:
                        json['errors'] = {}
                        json['errors']['reason'] = 'Error'
            return HttpResponse(JSONEncoder().encode(json),
                                mimetype='application/json')
        else:
            return HttpResponse(JSONEncoder().encode(json),
                                mimetype='application/json')
Exemplo n.º 25
0
def list_devices(request):
    # TODO change True in success
    json = createResponseTmp('devices', True)
    json['success'] = True
    if not request.user.is_authenticated():
        return HttpResponse(JSONEncoder().encode(json),
                            mimetype='application/json')
    else:
        if request.method == 'POST' and request.is_ajax():
            for d in Device.objects.filter(user_id=request.user.id):
                #json['devices'].append({'device_id': d.device_id, 'marker_id': d.marker_id_id, 'imei': d.imei, 'name': d.name,
                #             'text': d.text, 'long': str(d.long), 'lat': str(d.lat), 'ts_time': str(d.ts_time)})
                json['devices'].append({
                    'device_id': d.device_id,
                    'marker_id': d.marker_id_id,
                    'imei': d.imei,
                    'name': d.name,
                    'text': d.text
                })
            return HttpResponse(JSONEncoder().encode(json),
                                mimetype='application/json')
        else:
            return HttpResponse(JSONEncoder().encode(json),
                                mimetype='application/json')
Exemplo n.º 26
0
def add_ajax(request, id=0, template="json.html"):
    data = {'errors': []}
    product = None
    productname = request.POST['productname']
    log.debug('CART_AJAX: slug=%s', productname)
    try:
        product = Product.objects.get(slug=request.POST['productname'])
        if 'ConfigurableProduct' in product.get_subtypes():
            log.debug('Got a configurable product, trying by option')
            # This happens when productname cannot be updated by javascript.
            cp = product.configurableproduct
            chosenOptions = optionset_from_post(cp, request.POST)
            product = cp.get_product_from_options(chosenOptions)
    except Product.DoesNotExist:
        log.warn("Could not find product: %s", productname)
        product = None

    if not product:
        data['errors'].append(
            ('product', _('The product you have requested does not exist.')))

    else:
        data['id'] = product.id
        data['name'] = product.name

        try:
            quantity = int(request.POST['quantity'])
            if quantity < 0:
                data['errors'].append(('quantity', _('Choose a quantity.')))

        except ValueError:
            data['errors'].append(('quantity', _('Choose a whole number.')))

    tempCart = Cart.get_session_cart(request, create=True)

    if not data['errors']:
        tempCart.add_item(product, number_added=quantity)
        request.session['cart'] = tempCart.id
        data['results'] = _('Success')
    else:
        data['results'] = _('Error')

    data['cart_count'] = tempCart.numItems

    encoded = JSONEncoder().encode(data)
    log.debug('CART AJAX: %s', data)

    return render_to_response(template, {'json': encoded})
Exemplo n.º 27
0
	def render(self, name, value, attrs=None):
		if value is None: 
			value = ''

		if self.is_new:
			from settings.tinymce import new_MCE as MCE
		else:
			from settings.tinymce import MCE

		value = smart_unicode(value)
		final_attrs = self.build_attrs(attrs, name=name)

		MCE['elements'] = "id_%s" % name
		mce_json = JSONEncoder().encode(MCE)
		return mark_safe(u'<textarea%s>%s</textarea> <script type="text/javascript">\
			tinyMCE.init(%s)</script>' % (flatatt(final_attrs), escape(value), mce_json))
Exemplo n.º 28
0
def json_departments_request(request, company_id):
    company = get_object_or_404(Company, id=company_id)
    c_depts = Department.objects.filter(belong_to=company).order_by('id')

    root_depts = [d for d in c_depts if d.parent_id == None]
    d_data = [dep_serializable_object(root_dept) for root_dept in root_depts]

    # test_data = [{"name": "w1","description": "e1","children": []},{"name": "w2","description": "e2","children": [{"name": "t2","description": "y2",'leaf': True}]},{"name": "w3","description": "e3","children": [{"name": "t3","description": "y3",'leaf': True}]},{"name": "w4","description": "e4","children": [{"name": "t4","description": "y4",'leaf': True}]},]

    # # test for lxy phonegap
    # import json
    # data = {'result':0,'msg':'error'}
    # return HttpResponse('yuankong(' + json.dumps(data) + ');', content_type="application/json")

    response = HttpResponse(content=JSONEncoder().encode(d_data),
                            mimetype='text/javascript')
    response['Content-Length'] = len(response.content)
    return response
Exemplo n.º 29
0
def wishlist_add_ajax(request, template="shop/json.html"):
    data = {'errors': []}
    product = None
    contact = None
    formdata = request.POST.copy()
    productslug = formdata['productname']

    log.debug('WISHLIST AJAX: slug=%s', productslug)
    try:
        product, details = product_from_post(productslug, formdata)

    except (Product.DoesNotExist, MultiValueDictKeyError):
        log.warn("Could not find product: %s", productslug)
        product = None

    if not product:
        data['errors'].append(
            ('product', _('The product you have requested does not exist.')))
    else:
        data['id'] = product.id
        data['name'] = product.translated_name()

    try:
        contact = Contact.objects.from_request(request)
    except Contact.DoesNotExist:
        log.warn("Could not find contact")

    if not contact:
        data['errors'].append(
            ('contact',
             _('The contact associated with this request does not exist.')))

    if not data['errors']:
        wish = ProductWish.objects.create_if_new(product, contact, details)
        data['results'] = _('Success')
    else:
        data['results'] = _('Error')

    encoded = JSONEncoder().encode(data)
    encoded = mark_safe(encoded)
    log.debug('WISHLIST AJAX: %s', data)

    return render_to_response(template, {'json': encoded})
Exemplo n.º 30
0
def remove_ajax(request, template="json.html"):
    """Remove an item from the cart. Returning JSON formatted results."""
    data = {}
    if not request.POST:
        data['results'] = False
        data['errors'] = _('Internal error: please submit as a POST')

    else:
        success, cart, cartitem, errors = _set_quantity(request,
                                                        force_delete=True)

        data['results'] = success
        data['errors'] = errors

        # note we have to convert Decimals to strings, since simplejson doesn't know about Decimals
        if cart and cartitem:
            data['cart_total'] = str(cart.total)
            data['cart_count'] = cart.numItems
            data['item_id'] = cartitem.id

        return render_to_response(template,
                                  {'json': JSONEncoder().encode(data)})
Exemplo n.º 31
0
def set_quantity_ajax(request, template="json.html"):
    """Set the quantity for a cart item, returning results formatted for handling by script.
    """
    data = {}
    if not request.POST:
        data['results'] = False
        data['errors'] = _('Internal error: please submit as a POST')

    else:
        success, cart, cartitem, errors = _set_quantity(request)

        data['results'] = success
        data['errors'] = errors

        # note we have to convert Decimals to strings, since simplejson doesn't know about Decimals
        if cart and cartitem:
            data['cart_total'] = str(cart.total)
            data['cart_count'] = cart.numItems
            data['item_id'] = cartitem.id
            data['item_qty'] = cartitem.quantity
            data['item_price'] = str(cartitem.line_total)

    return render_to_response(template, {'json': JSONEncoder().encode(data)})
Exemplo n.º 32
0
def update_active_users(request):
    """
    Returns a list of all active users
    """
    if request.is_ajax():
        active = VisitorTracked.objects.active()
        user = getattr(request, 'user', None)

        info = {
            'active': active,
            'registered': active.filter(user__isnull=False),
            'guests': active.filter(user__isnull=True),
            'user': user
        }

        # render the list of active users
        t = loader.get_template('tracking/_active_users.html')
        c = Context(info)
        users = {'users': t.render(c)}

        return HttpResponse(content=JSONEncoder().encode(users))

    # if the request was not made via AJAX, raise a 404
    raise Http404
Exemplo n.º 33
0
        'dump',
        'dumps',
        'load',
        'loads',
        'JSONDecoder',
        'JSONEncoder',
    ]

    from django.utils.simplejson.decoder import JSONDecoder
    from django.utils.simplejson.encoder import JSONEncoder

    _default_encoder = JSONEncoder(
        skipkeys=False,
        ensure_ascii=True,
        check_circular=True,
        allow_nan=True,
        indent=None,
        separators=None,
        encoding='utf-8',
        default=None,
    )

    def dump(obj,
             fp,
             skipkeys=False,
             ensure_ascii=True,
             check_circular=True,
             allow_nan=True,
             cls=None,
             indent=None,
             separators=None,
             encoding='utf-8',
Exemplo n.º 34
0
Arquivo: site.py Projeto: fossabot/noc
        def inner(request, *args, **kwargs):
            def nq(s):
                """
                Convert var[]=xxxx to var=xxxx
                """
                if s.endswith("[]"):
                    return s[:-2]
                else:
                    return s

            try:
                v = view_map[request.method]
            except KeyError:
                logger.info("No handler for '%s' method", request.method)
                return HttpResponseNotFound("No handler for '%s' method" %
                                            request.method)
            if not request.user or not v.access.check(app, request.user):
                return HttpResponseForbidden()
            to_log_api_call = (self.log_api_calls and hasattr(v, "api")
                               and v.api)
            app_logger = v.im_self.logger
            try:
                # Validate requests
                if (hasattr(v, "validate") and v.validate):
                    # Additional validation
                    errors = None
                    if isinstance(v.validate, DictParameter):
                        # Validate via NOC interfaces
                        if request.method == "GET":
                            g = dict((nq(k), v[0] if len(v) == 1 else v)
                                     for k, v in request.GET.lists()
                                     if k != "_dc")
                        else:
                            ct = request.META.get("CONTENT_TYPE")
                            if ct and ("text/json" in ct
                                       or "application/json" in ct):
                                g = json_decode(request.raw_post_data)
                            else:
                                g = dict((k, v[0] if len(v) == 1 else v)
                                         for k, v in request.POST.lists())
                        try:
                            kwargs.update(v.validate.clean(g))
                        except InterfaceTypeError, why:
                            errors = str(why)
                    elif issubclass(v.validate, Form):
                        # Validate via django forms
                        f = v.validate(request.GET)  # @todo: Post
                        if f.is_valid():
                            kwargs.update(f.cleaned_data)
                        else:
                            errors = dict([(f, "; ".join(e))
                                           for f, e in f.errors.items()])
                    if errors:
                        #
                        if to_log_api_call:
                            app_logger.error("ERROR: %s", errors)
                        # Return error response
                        ext_format = (
                            "__format=ext"
                            in request.META["QUERY_STRING"].split("&"))
                        r = JSONEncoder(ensure_ascii=False).encode({
                            "status":
                            False,
                            "errors":
                            errors
                        })
                        status = 200 if ext_format else 400  # OK or BAD_REQUEST
                        return HttpResponse(
                            r,
                            status=status,
                            mimetype="text/json; charset=utf-8")
                # Log API call
                if to_log_api_call:
                    a = {}
                    if request.method in ("POST", "PUT"):
                        ct = request.META.get("CONTENT_TYPE")
                        if ct and ("text/json" in ct
                                   or "application/json" in ct):
                            a = json_decode(request.raw_post_data)
                        else:
                            a = dict((k, v[0] if len(v) == 1 else v)
                                     for k, v in request.POST.lists())
                    elif request.method == "GET":
                        a = dict((k, v[0] if len(v) == 1 else v)
                                 for k, v in request.GET.lists())
                    app_logger.debug("API %s %s %s", request.method,
                                     request.path, a)
                # Call handler
                v.__dict__["hits_metric"] += 1
                with v.__dict__["time_metric"].timer():
                    r = v(request, *args, **kwargs)
                # Dump SQL statements
                if self.log_sql_statements:
                    from django.db import connections
                    tsc = 0
                    sc = defaultdict(int)
                    for conn in connections.all():
                        for q in conn.queries:
                            stmt = q["sql"].strip().split(" ", 1)[0].upper()
                            sc[stmt] += 1
                            tsc += 1
                            app_logger.debug("SQL %(sql)s %(time)ss" % q)
                    x = ", ".join(
                        ["%s: %d" % (k, v) for k, v in sc.iteritems()])
                    if x:
                        x = " (%s)" % x
                    app_logger.debug("SQL statements: %d%s" % (tsc, x))
Exemplo n.º 35
0
def json_ext_device_working_time(request, year):
    now = datetime.now()
    device_entries = DeviceEntry.objects.filter(
        internal_code__icontains="KCSK").order_by("id")
    timesheets = Timesheet.objects.filter(
        start__year=year, content_type__model='manufacturerecord')

    json = {}
    data = []
    total = device_entries.count()
    json['totalCount'] = total

    func = request.GET.get("func", None)
    page = request.GET.get("page", None)
    limit = request.GET.get("limit", None)
    if func and func == '1':
        for de in device_entries:
            aaa = {'name': de.internal_code}
            mrs_id = [
                mr.id
                for mr in ManufactureRecord.objects.filter(device_entry=de)
            ]
            ts = timesheets.filter(object_id__in=mrs_id)
            aaa['cNum'] = sum([t.difference_hours for t in ts],
                              timedelta()).seconds
            data.append(aaa)
        response = HttpResponse(content=JSONEncoder().encode(data),
                                mimetype='text/javascript')
    elif func and func == '2':
        for de in device_entries:
            de_name = de.internal_code
            aaa = {0: de_name}
            mrs_id = [
                mr.id
                for mr in ManufactureRecord.objects.filter(device_entry=de)
            ]
            ts = timesheets.filter(object_id__in=mrs_id)
            for i in range(12):
                if datetime(int(year), i + 1, 1) > now:
                    aaa[i + 1] = 0
                else:
                    worked_hours = timedelta(0, 0, 0)
                    e_ts = ts.filter(start__month=i + 1)
                    ts = ts.exclude(start__month=i + 1)
                    worked_hours = sum([t.difference_hours for t in e_ts],
                                       timedelta())
                    aaa[i + 1] = worked_hours.seconds
            data.append(aaa)
        response = HttpResponse(content=JSONEncoder().encode(data),
                                mimetype='text/javascript')
    else:
        if page and limit:
            paginator = Paginator(device_entries, int(limit))
            try:
                device_entries = paginator.page(int(page))
            except PageNotAnInteger:
                # If page is not an integer, deliver first page.
                device_entries = paginator.page(int(page))
            except EmptyPage:
                # If page is out of range (e.g. 9999), deliver last page of results.
                device_entries = paginator.page(paginator.num_pages)

        for de in device_entries:
            de_name = '<a href="' + reverse(
                'ext_device_working_time_detail',
                args=[de.id]) + '">' + de.internal_code + '</>'
            aaa = {0: de_name}
            mrs_id = [
                mr.id
                for mr in ManufactureRecord.objects.filter(device_entry=de)
            ]
            ts = timesheets.filter(object_id__in=mrs_id)
            for i in range(12):
                if datetime(int(year), i + 1, 1) > now:
                    aaa[i + 1] = '-'
                else:
                    worked_hours = timedelta(0, 0, 0)
                    e_ts = ts.filter(start__month=i + 1)
                    ts = ts.exclude(start__month=i + 1)
                    worked_hours = sum([t.difference_hours for t in e_ts],
                                       timedelta())
                    aaa[i + 1] = str(timedelta(seconds=worked_hours.seconds))
            data.append(aaa)
        json['data'] = data
        response = HttpResponse(content=JSONEncoder().encode(json),
                                mimetype='text/javascript')

    response['Content-Length'] = len(response.content)
    return response
Exemplo n.º 36
0
def json_ext_manufactureitem_working_time(request):
    manu_item_groups = ManufactureItemGroup.objects.filter(
        productionline__isnull=False).order_by('manufactureplan')
    manufacture_items = ManufactureItem.objects.all()

    json = {}
    data = []
    total = manu_item_groups.count()
    json['totalCount'] = total

    func = request.GET.get("func", None)
    page = request.GET.get("page", None)
    limit = request.GET.get("limit", None)
    if func and func == '2':
        timesheets = Timesheet.objects.filter(
            content_type__model='manufacturerecord')
        for i in range(12):
            aaa = {'month': _("%d month") % (i + 1)}
            ies_timesheets = timesheets.filter(start__month=i +
                                               1).order_by('-start')
            timesheets = timesheets.exclude(start__month=i +
                                            1).order_by('-start')
            worked_hours = sum([t.difference_hours for t in ies_timesheets],
                               timedelta())
            aaa['cNum'] = worked_hours.seconds
            data.append(aaa)
        response = HttpResponse(content=JSONEncoder().encode(data),
                                mimetype='text/javascript')
    else:
        if page and limit:
            paginator = Paginator(manu_item_groups, int(limit))
            try:
                manu_item_groups = paginator.page(int(page))
            except PageNotAnInteger:
                # If page is not an integer, deliver first page.
                manu_item_groups = paginator.page(int(page))
            except EmptyPage:
                # If page is out of range (e.g. 9999), deliver last page of results.
                manu_item_groups = paginator.page(paginator.num_pages)
        i = 1
        for mig in manu_item_groups:
            aaa = {'i': i}
            aaa['cc'] = mig.manufactureplan.order.contract_code
            aaa['mc'] = mig.id
            aaa['pn'] = '<a href="' + reverse(
                'ext_manufactureitem_working_time_detail',
                args=[mig.id]) + '">' + mig.product.name + '</>'
            aaa['qty'] = mig.quantity
            aaa['pcc'] = mig.product.cad_code
            aaa['s'] = mig.productionline.get_state_display()
            aaa['wh'] = str(
                timedelta(seconds=sum(
                    [mi.worked_hours for mi in mig.manufacture_items.all()],
                    timedelta()).seconds))
            data.append(aaa)
            i += 1

        json['data'] = data
        response = HttpResponse(content=JSONEncoder().encode(json),
                                mimetype='text/javascript')
    response['Content-Length'] = len(response.content)
    return response
Exemplo n.º 37
0
def json_ext_knife_scraped(request, year):
    list_category = 3  #kinfe
    transport_category = 3  #Scrap
    now = datetime.now()
    tdrs = TransportDetailRecord.objects.filter(
        created_at__year=year,
        transport_list_detail__transport_list__list_category=list_category,
        transport_list_detail__transport_list__transport_category=
        transport_category)
    items_id = list(
        set([
            tdr.scrap_item_entry.item.id for tdr in tdrs
            if tdr.scrap_item_entry
        ]))
    items = Item.objects.filter(id__in=items_id)

    json = {}
    data = []
    total = items.count()
    json['totalCount'] = total

    func = request.GET.get("func", None)
    page = request.GET.get("page", None)
    limit = request.GET.get("limit", None)

    if func and func == '2':
        i_tdrs = tdrs
        for i in range(12):
            aaa = {'month': _("%d month") % (i + 1)}
            ies_tdrs = i_tdrs.filter(created_at__month=i +
                                     1).order_by('-created_at')
            i_tdrs = i_tdrs.exclude(created_at__month=i +
                                    1).order_by('-created_at')
            count = 0
            for ie in items:
                ie_i_tdrs = ies_tdrs.filter(inventory_item_entry__item=ie)
                count += ie_i_tdrs[0].scrap_qty if ie_i_tdrs else 0
            aaa['cNum'] = count
            data.append(aaa)
        response = HttpResponse(content=JSONEncoder().encode(data),
                                mimetype='text/javascript')
    else:
        if page and limit:
            paginator = Paginator(items, int(limit))
            try:
                items = paginator.page(int(page))
            except PageNotAnInteger:
                # If page is not an integer, deliver first page.
                items = paginator.page(int(page))
            except EmptyPage:
                # If page is out of range (e.g. 9999), deliver last page of results.
                items = paginator.page(paginator.num_pages)

        for ie in items:
            aaa = {
                0:
                '<a href="' +
                reverse('ext_knife_scraped_detail', args=[ie.id]) + '">' +
                ie.code + '</>'
            }
            # aaa = {0:ie.code}
            ie_tdrs = tdrs.filter(inventory_item_entry__item=ie)
            for i in range(12):
                if datetime(int(year), i + 1, 1) > now:
                    aaa[i + 1] = '-'
                else:
                    i_ie_tdrs = ie_tdrs.filter(created_at__month=i +
                                               1).order_by('-created_at')
                    if i_ie_tdrs:
                        aaa[i + 1] = sum([t.scrap_qty for t in i_ie_tdrs])
                    elif i != 0 and aaa[i]:
                        aaa[i + 1] = aaa[i]
                    else:
                        aaa[i + 1] = '0'
            data.append(aaa)

        json['data'] = data
        response = HttpResponse(content=JSONEncoder().encode(json),
                                mimetype='text/javascript')
    response['Content-Length'] = len(response.content)
    return response
Exemplo n.º 38
0
    (options, args) = op.parse_args()

    return options
        
if __name__ == '__main__':

    options = main()
    
    archive_name = options.filename + '.tar'    
    backup_file = os.path.join(options.path,archive_name)
    
    basedir = tempfile.mkdtemp()
    try:
        e = Exporter(options.host, options.port, options.api_key, options.user, options.password)
        e.login()
        json_enc = JSONEncoder()    
    
        #backup degli utenti
        f = file(os.path.join(basedir, 'users.json'), 'w')
        f.write(json_enc.encode(e._api_get_users()))
        f.close()
        
        
        for w in e._workspace_get_list():
            #Backup workspace
            logger.info("Export workspace %s" % w['id'])
            workspacedir = os.path.join(basedir,'w_' + str(w['id']))
            os.mkdir(workspacedir)
            items = e._workspace_get_items(w['id'])
    
            logger.info("workspace.json")
Exemplo n.º 39
0
class _Handler(sax.ContentHandler):
    def __init__(self, device_class=None, merge=False):
        # Initialized flag
        self.initialized = False
        # Parsing version flag
        self.parse_version = False
        # JSON encoder
        self.e = JSONEncoder()
        # Device class
        self.device_class = device_class
        # are we merging?
        self.merge = merge
        
    def startElement(self, name, attrs):
        if name in ('wurfl', 'wurfl_patch'):
            self.initialized = True
            self.start_time = time()
            self.stats = {'nb_devices':0, 'errors':[], 'nb_merges':0}
        else:
            if not self.initialized:
                raise ParseError("Invalid XML format")

            if name == 'ver':
                self.stats['version'] = ''
                self.parse_version = True
            elif name == 'device':
                self.device = {}
                self.device['id'] = attrs.get('id', '')
                self.device['user_agent'] = attrs.get('user_agent', '')
                self.device['fall_back'] = attrs.get('fall_back', '')
                self.device['actual_device_root'] = attrs.get('actual_device_root', False) and True
                # Prepare the capabilities
                self.capabilities = {}
            elif name == 'group':
                self.current_group = attrs.get('id','')
                self.capabilities[self.current_group] = {}
            elif name == 'capability':
                value = attrs.get('value', '')
                if value == 'true' or value == 'false':
                    value = (value == 'true')
                elif value.isdigit():
                    value = int(value)
                    
                self.capabilities[self.current_group][attrs.get('name','')] = value
        
    def endElement(self, name):
        if name == 'device':
            # Process the capabilities
            self.device['json_capabilities'] = self.e.encode(self.capabilities)
            
            # Save the device model
            if self.device_class:
                try:
                    try:
                        self.device_class.objects.create(**self.device)
                        self.stats['nb_devices'] += 1
                    except IntegrityError:
                        if self.merge:
                            device = self.device_class.objects.get(id=self.device['id'])
                            device.merge_json_capabilities(self.device['json_capabilities'])
                            device.save()
                            self.stats['nb_merges'] += 1
                        else:
                            raise
                except Exception, err:
                    self.stats['errors'].append(str(err))

        elif name in ('wurfl', 'wurfl_patch'):
            # End of the update
            self.stats['time_for_update'] = time() - self.start_time