Example #1
0
def post_complete(request, username, post_id):

    try:
        post = Post.objects.select_related(
            "blog", "blog__owner",
            "blog__owner__profile").prefetch_related("categories").get(
                id=post_id)

        format = "%Y%m%d%H%M%S"
        if post.blog.owner.username != username or (
                username != request.user.username
                and not request.user.is_superuser
                and strftime(post.date_pub, format) >= strftime(
                    datetime.datetime.now(), format)):
            return render(request, '404.html', {}, status=404)
        else:
            context = {
                'post': post,
                'categories': post.categories.all(),
                'responsiveness': settings.WEB_RESPONSIVE,
            }

            return render(request, 'blogs/post.html', context)

    except Post.DoesNotExist as err:
        return render(request, '404.html', {}, status=404)
Example #2
0
def smart_time(date):
    """
    Cover for ru_strftime from pytils. Don't show needless part of time string
    """
    now = timezone.now()
    today = now.replace(hour=0, minute=0, second=0)
    if date > now - datetime.timedelta(hours=2) and is_language('ru'):
        # from 2 hours ago to now
        return dt.distance_of_time_in_words(date, 1, now)
    elif date > today:
        # from start of today to 2 hours ago
        format = u'%H:%M'
    elif date > today - datetime.timedelta(days=1):
        # yesterday
        format = _('yesterday') + u', %H:%M'
    elif date > today - datetime.timedelta(days=2):
        # the day before yesterday
        format = _('day before yesterday') + u', %H:%M'
    elif date > today.replace(day=1, month=1):
        # this year
        format = u'%d %B, %H:%M'
    else:
        format = u'%d %B %Y, %H:%M'

    if is_language('ru'):
        return ru_strftime(date, format)
    else:
        return strftime(date, format)
Example #3
0
 def editor_info(self, history):
     if history:
         date = strftime(history.action_time, "%b %d, %H:%M")
         user = history.user
     else:
         date = None
         user = None
     return date, user        
Example #4
0
def all_messages(request):
    thisMessage = FooMessage(
        message_text='Test Message created on ' +
        strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S"))
    thisMessage.save()
    messages = FooMessage.objects.all()
    return render_to_response('robertsTest/messages.html',
                              {'messages': messages})
Example #5
0
 def editor_info(self, history):
     if history:
         date = strftime(history.action_time, "%b %d, %H:%M")
         user = history.user
     else:
         date = None
         user = None
     return date, user
 def __log(msg, tag):
     if hasattr(settings,
                "DJANGO_PAYU_LOG_FILE") and settings.DJANGO_PAYU_LOG_FILE:
         log_file = open(settings.DJANGO_PAYU_LOG_FILE, "a")
         log_msg = "{}\t{}\t{}\n".format(
             strftime(now(), "%Y-%m-%d %H:%M:%S"),
             tag,
             msg,
         )
         log_file.write(log_msg)
         log_file.close()
Example #7
0
    def __log(msg, tag):
        if hasattr(settings, "DJANGO_PAYU_LOG_FILE") and settings.DJANGO_PAYU_LOG_FILE:
            log_file = open(settings.DJANGO_PAYU_LOG_FILE, "a")
            log_msg = "{}\t{}\t{}\n".format(
                strftime(now(), "%Y-%m-%d %H:%M:%S"),
                tag,
                msg,

            )
            log_file.write(log_msg)
            log_file.close()
Example #8
0
def index(request):
    """
    parameteres: start, end expect the format yyyy-mm-dd, range_label - 30d, 7d, MTD etc
    """
    res = request.GET.get('res')
    if res is None: res = "day"
    
    today = datetime.now()  
    t = loader.get_template('db/index.html')
    if request.GET.get('start'): 
        start_date = convert_to_date(request.GET.get('start'))
    else:
        start_date = today + timedelta(days=-30) #30 days 
    if request.GET.get('end'):
        end_date=convert_to_date(request.GET.get('end'))
    else:
        end_date = today

    orders = SalesFlatOrder.objects.filter(created_at__gte = start_date).filter(created_at__lte = end_date).order_by('created_at')
    order_stats = {'count':len(orders), 'sum': orders.aggregate(Sum('grand_total'))['grand_total__sum']}
    today_orders = SalesFlatOrder.objects.filter(created_at__gte = datetime(today.year, today.month, today.day))
    today_revenues = today_orders.aggregate(Sum('grand_total'))['grand_total__sum']
    orders_by_date = []
    
    for day, order_group in groupby(orders,lambda o: strftime(o.created_at, date_format(res))):
        orders_by_date.append ({'day':day, 'display_date': day.replace('-','.')[:-5],  'orders': list(order_group)})
        
    for row in orders_by_date:
        
        row['revenues']= sum([x.grand_total for x  in row['orders']])
        row['count'] = len(row['orders'])
    
    #TODO insert to the list all the dates in which there were no orders
    orders_by_date_reverse = orders_by_date[:]
    orders_by_date_reverse.reverse()
    c = Context({
        'orders': orders,
        'order_stats':order_stats,
        'orders_by_date':orders_by_date,  
        'orders_by_date_reverse':orders_by_date_reverse,            
        'start_date':start_date,
        'end_date':end_date,
        'date_range_links':date_range_links(request.GET.get('range_label')),
        'res':res,
        'resolutions':['day','week','month'],
        'range_label':request.GET.get('range_label'),
        'today_orders':{'count':len(today_orders),'sum':today_revenues}
        
    })
    
    
    
    return HttpResponse(t.render(c))
Example #9
0
def generate_valid_path(filename,
                        path,
                        create_it=True,
                        root_base=settings.MEDIA_ROOT,
                        permissions=settings.FILE_UPLOAD_PERMISSIONS):
    """
    Génére le chemin prévu pour un fichier et créé le chemin si besoin

    :type filename: string
    :param filename: Nom du fichier cible

    :type path: string
    :param path: Chemin relatif (au répertoire des médias,
                 ``settings.MEDIA_ROOT``) du répertoire contenant le fichier,
                 peut contenir les paramètres de substitution possibles avec la
                 méthode ``django.utils.datetime_safe.strftime``.

    :type create_it: bool
    :param create_it: (optional) Déclenche la création du répertoire si il
                      n'existe pas déja

    :type root_base: string
    :param root_base: (optional) Chemin de base ou créer le fichier, par défaut
                      dans le ``MEDIA_ROOT`` du projet.

    :type permissions: int
    :param permissions: (optional) Permission chmod sur le chemin à créer, par
                        défaut utilise le ``FILE_UPLOAD_PERMISSIONS`` des
                        settings du projet. Et si cette variable n'est pas
                        renseigné dans vos settings, alors un mask 0744 sera
                        utilisé.

    :rtype: tuple
    :return: * Chemin relatif du fichier
             * Chemin absolu du fichier
    """
    if not permissions:
        permissions = 0744
    # Forme le chemin absolu vers le nouvo fichier créé
    relative_path = strftime(real_datetime.now(), path)
    absolute_path = join(root_base, relative_path)
    # Création du répertoire
    if create_it:
        if not exists(absolute_path):
            makedirs(absolute_path, permissions)
        elif not isdir(absolute_path):
            # Le chemin existe et n'est pas un répertoire
            raise IOError("'%s' exists and is not a directory." %
                          absolute_path)

    return join(relative_path, filename), join(absolute_path, filename)
Example #10
0
def generate_valid_path(
    filename, path, create_it=True, root_base=settings.MEDIA_ROOT, permissions=settings.FILE_UPLOAD_PERMISSIONS
):
    """
    Génére le chemin prévu pour un fichier et créé le chemin si besoin
    
    :type filename: string
    :param filename: Nom du fichier cible
    
    :type path: string
    :param path: Chemin relatif (au répertoire des médias, ``settings.MEDIA_ROOT``) du 
                 répertoire contenant le fichier, peut contenir les paramètres de 
                 substitution possibles avec la méthode 
                 ``django.utils.datetime_safe.strftime``.
    
    :type create_it: bool
    :param create_it: (optional) Déclenche la création du répertoire si il n'existe pas déja
    
    :type root_base: string
    :param root_base: (optional) Chemin de base ou créer le fichier, par défaut dans 
                      le ``MEDIA_ROOT`` du projet.
    
    :type permissions: int
    :param permissions: (optional) Permission chmod sur le chemin à créer, par 
                             défaut utilise le ``FILE_UPLOAD_PERMISSIONS`` des settings 
                             du projet. Et si cette variable n'est pas renseigné dans vos 
                             settings, alors un mask 0744 sera utilisé.
    
    :rtype: tuple
    :return: * Chemin relatif du fichier
             * Chemin absolu du fichier
    """
    if not permissions:
        permissions = 0744
    # Forme le chemin absolu vers le nouvo fichier créé
    relative_path = strftime(real_datetime.now(), path)
    absolute_path = join(root_base, relative_path)
    # Création du répertoire
    if create_it:
        if not exists(absolute_path):
            makedirs(absolute_path, permissions)
        elif not isdir(absolute_path):
            # Le chemin existe et n'est pas un répertoire
            raise IOError("'%s' exists and is not a directory." % absolute_path)

    return join(relative_path, filename), join(absolute_path, filename)
Example #11
0
 def test_clone(self):
     minimum_initialization()
     scenario = FutureScenario.objects.all()[0]
     key = strftime(now(), '%Y_%m_%d_%H_%M_%S')
     future_scenario = FutureScenario(
         parent_config_entity=scenario.project(),
         origin_config_entity=scenario,
         year=scenario.year,
         name=key,
         description='Clone of %s' % scenario.name,
         bounds=scenario.bounds,
         key=key
     )
     future_scenario.save()
     assert_equal(len(scenario.computed_built_form_sets()), len(future_scenario.computed_built_form_sets()))
     assert_equal(len(scenario.computed_policy_sets()), len(future_scenario.computed_policy_sets()))
     assert_equal(len(scenario.computed_db_entity_interests()), len(future_scenario.computed_db_entity_interests()))
     assert_equal(len(Presentation.objects.filter(config_entity=scenario)), len(Presentation.objects.filter(config_entity=future_scenario)))
Example #12
0
    def get_default_pipe_data(self, request, akey, user_id):
        """
        Get a default action data dict
        """
        pipe_data = copy.deepcopy(self.pipe_data_model)

        pipe_data['pipe'] = self.pipe_name

        pipe_data['akey'] = akey
        pipe_data['user_id'] = user_id

        pipe_data['origin_url'] = self.get_referer_path(request)
        pipe_data['pipe_start_time'] = strftime(now(),
                                                '%Y-%m-%d-%H-%M')

        # start new pipe
        pipe_data['pipe_data'] = {}
        return pipe_data
Example #13
0
    def process_reset(self, request, user_profile, input_data, template_args, **kwargs):
        '''
        call this method to be redirected to the previous pipe view
        '''
        user_data = kwargs.get('pipe')
        
        # clean action data if we are finishing the actual pipe
        #if user_data['pipe'] == self.pipe_name:
            # markup end action time
        user_data['action_end_time'] = strftime(now(),
                                                '%Y-%m-%d-%H-%M')

        user_data = self.update_actionpipe_data(request, user_data)
        user_data = self.save_actionpipe_data(request, user_data)
        
        # rotate session akey
        request.session['akey'] = self.get_new_session_user_key()
        self.save_actionpipe_data(request, self.get_default_pipe_data(request, request.session['akey'], 'guest'))
        # removing current akey cookie will rotate the key
        return HttpResponseRedirect(self.get_reversed_action(self.view_name, self.default_action, kwargs))
Example #14
0
    def get_actionpipe_data(self, request):
        """
        Get the request/session associated current actionpipe data
        Get the action pipe data from cache, dynamodb or default
        This is mainly a shortcut to the pipe util
        """
        akey, user_id = self.get_session_user_keys(request)
        
        # init default data dict
        pipe_data = self.get_default_pipe_data(request, akey, user_id)
        
        # check for data in memcached
        cache_data = action_cache.get(self.get_action_cache_key(akey, user_id))
        if cache_data is None:
            # check for data on dynamodb
            cache_data = self.pipe_table.get_latest(akey, user_id)
            # save to cache
            if cache_data is None:
                action_cache.set(self.get_action_cache_key(akey, user_id),
                                 pipe_data)
                
        if cache_data and 'pipe' in cache_data and cache_data['pipe'] == self.pipe_name:
            pipe_data.update(cache_data)
        
        pipe_data['pipe_activity_time'] = strftime(now(), '%s')
        
        pipe_data['akey'] = akey
        pipe_data['user_id'] = user_id
        
        # decompress contained action data
        if isinstance(pipe_data['pipe_data'], str):
            pipe_data['pipe_data'] = json.loads(pipe_data['pipe_data'])

        # clean empty fields
        fields = list(pipe_data['pipe_data'].keys())
        for field in fields:
            if not pipe_data['pipe_data'][field]:
                del pipe_data['pipe_data'][field]

        return pipe_data
Example #15
0
def getcomments(request):
    if request.method == 'POST':
        project_id = request.POST['project_id']
        project = Project.objects.get(pk=project_id)

        comment_list = []

        if project is not None:
            for comment in project.comment_set.all().order_by('-date_added'):
                single_comment = {
                    'comment_id': comment.id,
                    'comment_author': comment.user.username,
                    'comment_text': comment.text,
                    'comment_date': strftime(comment.date_added, '%Y-%m-%d %H:%M:%S'),
                }
                comment_list.append(single_comment)

            return JsonResponse(comment_list, safe=False)
        else:
            return JsonResponse("")
    else:
        return JsonResponse("")
Example #16
0
 def as_json(self, make_string=True):
     _json = {
         "version": 8,
         "flows": [
             {
                 "version": self.version,
                 "flow_type": self.flow_type,
                 "entry": unicode(self.action_sets.order_by("created_on").first().uuid),
                 "rule_sets": [rule_set.as_json(False) for rule_set in self.rule_sets.all()],
                 "action_sets": [_set.as_json(False) for _set in self.action_sets.all()],
                 "base_language": "eng",
             }
         ],
         "metadata": {
             "expires": 0,
             "revision": self.revision,
             "id": self.pk,
             "name": self.name,
             "saved_on": strftime(self.saved_on, "%Y-%m-%dT%H:%M:%S.%fZ"),
         },
         "triggers": [],
     }
     return json.dumps(_json) if make_string else _json
Example #17
0
def PlantAlertSimple(request):
    body = ''
    alerts = PlantAlert.objects.filter(active=True)[:10]
    for alert in alerts:
        color = 'black'
        icon = ''
        if alert.state == 'N':
            color = 'green'
            icon = 'fa-check-circle'
        elif alert.state == 'W':
            color = 'orange'
            icon = 'fa-exclamation-circle'
        elif alert.state == 'S':
            color = 'red'
            icon = 'fa-times-circle'
        body += '''
        <li>
            <a href="#" onclick="notif_go(%s,'%s')">
                <div style="color:%s;">
                    <i class="fa %s fa-fw"></i> %s
                    <span class="pull-right text-muted small">%s</span>
                </div>
            </a>
        </li>
        <li class="divider"></li>
        ''' % (alert.id, alert.url, color, icon, alert.note,
               strftime(alert.dt, '%d/%b/%y %H:%M'))
    foot = '''
    <li>
        <a class="text-center" href="%s">
            <strong>Lihat Semua Berita</strong>
            <i class="fa fa-angle-right"></i>
        </a>
    </li>
    ''' % (reverse_lazy('plantalert_list'))
    return HttpResponse('%s%s' % (body, foot), content_type='text/plain')
Example #18
0
 def _get_display_joined(self):
     return strftime(self.date_joined, '%y/%m/%d %H:%M')
 def rejected_at(self, obj):
     return strftime(
         timezone.localtime(obj.rejected),
         "%d-%m-%Y %H:%M:%S",
     )
 def cancelled_at(self, obj):
     return strftime(
         timezone.localtime(obj.cancelled_at),
         "%d-%m-%Y %H:%M:%S",
     )
 def paid_at(self, obj):
     return strftime(
         timezone.localtime(obj.paid_at),
         "%d-%m-%Y %H:%M:%S",
     )
Example #22
0
    def __unicode__(self):
        if self.action == 'join':
            return self.retailer.name + " joined the re:punch network on " + strftime(self.date, "%m-%d-%y")

        if self.action == 'bonus':
            return self.retailer.name + " is offering (blank) for (blank) punches on (blank)"
Example #23
0
 def get_fecha_hora(self):
     return strftime(self.fecha_hora, "%d-%m-%Y %H:%M")
Example #24
0
def index(request):
    """
    parameteres: start, end expect the format yyyy-mm-dd, range_label - 30d, 7d, MTD etc
    """
    res = request.GET.get('res')
    if res is None: res = "day"

    today = datetime.now()
    t = loader.get_template('db/index.html')
    if request.GET.get('start'):
        start_date = convert_to_date(request.GET.get('start'))
    else:
        start_date = today + timedelta(days=-30)  #30 days
    if request.GET.get('end'):
        end_date = convert_to_date(request.GET.get('end'))
    else:
        end_date = today

    orders = SalesFlatOrder.objects.filter(created_at__gte=start_date).filter(
        created_at__lte=end_date).order_by('created_at')
    order_stats = {
        'count': len(orders),
        'sum': orders.aggregate(Sum('grand_total'))['grand_total__sum']
    }
    today_orders = SalesFlatOrder.objects.filter(
        created_at__gte=datetime(today.year, today.month, today.day))
    today_revenues = today_orders.aggregate(
        Sum('grand_total'))['grand_total__sum']
    orders_by_date = []

    for day, order_group in groupby(
            orders, lambda o: strftime(o.created_at, date_format(res))):
        orders_by_date.append({
            'day': day,
            'display_date': day.replace('-', '.')[:-5],
            'orders': list(order_group)
        })

    for row in orders_by_date:

        row['revenues'] = sum([x.grand_total for x in row['orders']])
        row['count'] = len(row['orders'])

    #TODO insert to the list all the dates in which there were no orders
    orders_by_date_reverse = orders_by_date[:]
    orders_by_date_reverse.reverse()
    c = Context({
        'orders':
        orders,
        'order_stats':
        order_stats,
        'orders_by_date':
        orders_by_date,
        'orders_by_date_reverse':
        orders_by_date_reverse,
        'start_date':
        start_date,
        'end_date':
        end_date,
        'date_range_links':
        date_range_links(request.GET.get('range_label')),
        'res':
        res,
        'resolutions': ['day', 'week', 'month'],
        'range_label':
        request.GET.get('range_label'),
        'today_orders': {
            'count': len(today_orders),
            'sum': today_revenues
        }
    })

    return HttpResponse(t.render(c))
Example #25
0
def convert_to_string(p_date):
    return strftime(p_date, "%Y-%m-%d")
Example #26
0
 def last_edited_at(obj, field):
     history = list(AttributeLogEntry.get_history(obj, field)[:1])
     if not history:
         return None
     else:
         return strftime(history[0].action_time, "%Y-%m-%d %H:%M")
Example #27
0
 def last_edited_at(obj, field):
     history = list(AttributeLogEntry.get_history(obj, field)[:1])
     if not history:
         return None
     else:
         return strftime(history[0].action_time, "%Y-%m-%d %H:%M")
Example #28
0
def tracking_fetch(scan_infos, cn_customs_code=None):
    if not cn_customs_code:cn_customs_code = 'default'    
    try:
        gss = Gss.objects.get(cn_customs_code=cn_customs_code)
    except:
        gss = Gss.objects.get(cn_customs_code='default')
    
    results = []
    if not scan_infos:
        return results
        
    req_data = u"<scan_infos>"
    for scan_info in scan_infos:
        req_data += u"<scan_info>"
        if 'mail_no' in scan_info:
            req_data += u"<mailno>%s</mailno>" % scan_info['mail_no']
            req_data += u"<mailno_type>2</mailno_type>"
        elif 'mail_oth_no' in scan_info:
            req_data += u"<mailno>%s</mailno>" % scan_info['mail_oth_no']
            req_data += u"<mailno_type>1</mailno_type>"
                    
        req_data += u"</scan_info>"
    req_data += u"</scan_infos>"
    req_data = base64.b64encode(req_data.encode('utf-8'))
    
    sign_infor = req_data + gss.tracking_passwd
    sign_infor = hashlib.md5(sign_infor).hexdigest()

    all_infor = {
               'account':gss.tracking_username,
               'version':gss.tracking_version,
               'validation':sign_infor,
               'data':req_data,
               }
    try:
        r = requests.post(gss.get_tracking_api_url, data=all_infor)
        
        text = r.text.encode('ascii', 'xmlcharrefreplace')
        tree = ET.fromstring(text)
           
        for response in tree:
            status = response.find('status').text
            msg = response.find('msg').text
            scan_infos = []
            if status == '1':                    
                for scan_info in response.find('scan_infos'):
                    scan_infos.append({
                        'time':scan_info.find('time').text,
                        'remark':scan_info.find('remark').text,
                                       })
                
            else:
                scan_infos.append({
                        'time': strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'),
                        'remark':msg,
                                       })
            results.append({
                                'tracking_number':response.find('mail_no').text,
                                'scan_infos':scan_infos,
                                })
        return results
    except Exception as e:
        logger.error(e)
        # send mail
        send_mail(u"Error when fetch tracking records bei GOS",
              "",
              u'韵达德国 <*****@*****.**>',
              ['*****@*****.**'],
              fail_silently=False,
              html_message=e)
        return []
Example #29
0
 def __str__(self):
     return '{subject} - {date}'.format(date=strftime(
         self.date_created, '%Y-%m-%d'),
                                        subject=self.subject)
Example #30
0
def depositPaypal(request):
    user = request.user
    paymentId = request.data.get('paymentId')
    payerId = request.data.get('payerId')
    # print(payerId)
    try:
        profile = Profile.objects.get(user=user)
        wallet = Wallet.objects.get(profile=profile)
        previousCredit = wallet.credit

        authUrl = settings.PAYPAL_GET_AUTH_TOKEN_ENDPOINT
        headers = {
            'Accept': 'application/json',
        }
        authResponse = requests.post(authUrl,
                                     headers=headers,
                                     data={
                                         'grant_type': 'client_credentials'
                                     },
                                     auth=HTTPBasicAuth(
                                         settings.PAYPAL_MERCHANT_ID,
                                         settings.PAYPAL_SECRET)).json()

        print(authResponse['access_token'])

        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer %s' % authResponse['access_token']
        }
        paymentUrl = settings.PAYPAL_PAYMENT_DETAILS_ENDPOINT % paymentId
        paymentResponse = requests.get(paymentUrl, headers=headers).json()

        # print(paymentResponse)
        if 'error' in paymentResponse.keys():
            return Response({
                'success': False,
                'error': paymentResponse['error_description']
            })

        if 'state' in paymentResponse.keys(
        ) and paymentResponse['state'] == 'approved':
            paypalTransaction = paymentResponse['transactions'][0]
            amount = float(paypalTransaction['amount']['total'])
            currency = paypalTransaction['amount']['currency']
            transaction = TransactionPaypal()
            transaction.hash = paymentResponse['id']
            transaction.date = paymentResponse['create_time']
            transaction.type = 'deposit'
            transaction.currency = currency
            transaction.amount = amount
            transaction.wallet = wallet
            feePercentage = Configuration().getConfiguration(
                "paypal_deposit_percentage")
            freezedCurrency = Currency().getCurrency('PPBC')
            if currency == 'USD':
                pass
            elif currency == 'EUR':
                amount = (amount / freezedCurrency.eur)
            else:
                return Response({
                    'success':
                    False,
                    'error':
                    'currency.notavailable',
                    'message':
                    'deposit of %s in %s not available' % (amount, currency)
                })
            transaction.paymentId = paymentId
            transaction.save()
            wallet.depositIn(
                freezedCurrency,
                transaction,
                amount,
                'Paypal transaction found ID: %s with positive amount: %s (USD)'
                % (paymentId, amount),
                feePercentage,
            )
            #all good
            # create transactions info for paypal
            transactionInfo = TransactionInfo()
            transactionInfo.transaction = transaction
            transactionInfo.description = 'Currency Rate Date: %s' % strftime(
                freezedCurrency.dateUpdated, '%Y-%m-%d %H:%M:%S')
            transactionInfo.save()

            transactionInfo = TransactionInfo()
            transactionInfo.transaction = transaction
            transactionInfo.description = 'BC -> USD'
            transactionInfo.cost = freezedCurrency.usd
            transactionInfo.save()

            transactionInfo = TransactionInfo()
            transactionInfo.transaction = transaction
            transactionInfo.description = 'BC -> EUR'
            transactionInfo.cost = freezedCurrency.eur
            transactionInfo.save()

            transactionInfo = TransactionInfo()
            transactionInfo.transaction = transaction
            transactionInfo.description = 'Previous Credit'
            transactionInfo.cost = previousCredit
            transactionInfo.save()

            transactionInfo = TransactionInfo()
            profile = Profile.objects.get(user=user)
            wallet = Wallet.objects.get(profile=profile)
            transactionInfo.transaction = transaction
            transactionInfo.description = 'Current Credit'
            transactionInfo.cost = wallet.credit
            transactionInfo.save()

            return Response({'success': True})

        return Response({'success': False})
    except Profile.DoesNotExist:
        return Response({'success': False, 'error': 'profile.notfound'})
    except Wallet.DoesNotExist:
        return Response({'success': False, 'error': 'wallet.notfound'})
Example #31
0
def summernote_upload_filepath(instance, filename):
    return os.path.join(strftime(now(), "i/%Y/%m/%d"),
                        get_valid_filename(filename))
Example #32
0
def emails(request):
    previous_day = datetime.now()-timedelta(days=1)
    query = "after:%s" % strftime(previous_day, "%Y/%m/%d", )
    return render(request, "zaps/emails.html", {'query': query})
Example #33
0
def convert_to_string(p_date):
    return strftime(p_date, "%Y-%m-%d")
Example #34
0
def _upload_to_prefix(webplayer, original_filename, prefix):
    basename = os.path.basename(original_filename)
    name, ext = os.path.splitext(basename)
    uuid = shortuuid.uuid()
    datepart = strftime(now(), "%Y-%m-%d")
    return "%s/%s-%s-%s%s" % (prefix, name, datepart, uuid, ext)
Example #35
0
def processBtcTransactions(FreezedCurrency):
    r = {
        "processed_addresses": 0,
        "created_transactions": [],
        "errors_transactions": [],
        "errors_addresses": []
    }

    allWallets = Wallet.objects.filter()

    for wallet in allWallets:

        for btcAddress in wallet.getWalletToCcAddresses(currency='BTC'):
            r['processed_addresses'] += 1
            atm = AtmBtc(btcAddress.address.address)
            btcAddress.address.address = atm.clean(btcAddress.address.address)
            try:
                addressRemoteTransactions = atm.getTransactions()
            except Exception, ex:
                addressRemoteTransactions = []
                r['errors_addresses'].append("%s" % (traceback.format_exc()))

            if len(addressRemoteTransactions) > 0:
                for art in addressRemoteTransactions:
                    if art.get("error"):
                        r['errors_addresses'].append(
                            "failed get data for address: %s" %
                            (btcAddress.address.address))
                    else:
                        if art['positive'] and art['confirmations'] > 0:

                            try:
                                new = False
                                try:
                                    transaction = Transaction.objects.get(
                                        hash=art['hash'],
                                        currency="BTC",
                                        address=btcAddress.address)
                                except Transaction.DoesNotExist:
                                    previousCredit = wallet.credit
                                    transaction = Transaction()
                                    transaction.hash = art['hash']
                                    transaction.date = art['date']
                                    transaction.type = 'deposit'
                                    transaction.currency = 'BTC'
                                    transaction.freezedUsd = FreezedCurrency.usd
                                    transaction.freezedEur = FreezedCurrency.eur
                                    transaction.amount = art['value']
                                    transaction.wallet = wallet
                                    transaction.address = btcAddress.address
                                    transaction.save()

                                    # update wallet credit
                                    feePercentage = Configuration(
                                    ).getConfiguration(
                                        "btc_deposit_percentage")
                                    wallet.depositIn(
                                        FreezedCurrency, transaction,
                                        art['value'],
                                        'by AtmBtc found new tx: %s with positive amount: %s (BTC)'
                                        % (art['hash'], art['value']),
                                        feePercentage)
                                    new = True

                                    #all good
                                    # create transactions info btc
                                    transactionInfo = TransactionInfo()
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'Currency Rate Date: %s' % strftime(
                                        FreezedCurrency.dateUpdated,
                                        '%Y-%m-%d %H:%M:%S')
                                    transactionInfo.save()

                                    transactionInfo = TransactionInfo()
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'BTC -> USD'
                                    transactionInfo.cost = FreezedCurrency.usd
                                    transactionInfo.save()

                                    transactionInfo = TransactionInfo()
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'BTC -> EUR'
                                    transactionInfo.cost = FreezedCurrency.eur
                                    transactionInfo.save()

                                    transactionInfo = TransactionInfo()
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'Previous Credit'
                                    transactionInfo.cost = previousCredit
                                    transactionInfo.save()

                                    transactionInfo = TransactionInfo()
                                    wallet = Wallet.objects.get(id=wallet.id)
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'Current Credit'
                                    transactionInfo.cost = wallet.credit
                                    transactionInfo.save()

                            except Exception, ex:
                                transaction = None

                                r['errors_transactions'].append(
                                    "failed insert for transaction: %s" %
                                    (art['hash']))

                            if new:
                                if transaction:
                                    if not any(x.hash == art['hash'] for x in
                                               r['created_transactions']):
                                        r['created_transactions'].append(
                                            transaction)
                                        # Admin Notification
                                        adminNotification = Notification()
                                        adminNotification.email = True
                                        adminNotification.user = User.objects.get(
                                            username="******")
                                        adminNotification.setEmailData(
                                            "New BTC deposit transaction confirmed",
                                            "notifications/email/admin_email_new_deposit_transaction_confirmed.html",
                                            {
                                                'transaction': transaction,
                                            })
Example #36
0
 def last_edited_at(self):
     story = list(self.get_history()[:1])
     if not story:
         return datetime.datetime(2000, 1, 1, 0, 0, 0)
     else:
         return strftime(story[0].action_time, "%Y-%m-%d %H:%M")
Example #37
0
 def last_edited_at(self):
     story = list(self.get_history()[:1])
     if not story:
         return datetime.datetime(2000, 1, 1, 0, 0, 0)
     else:
         return strftime(story[0].action_time, "%Y-%m-%d %H:%M")
Example #38
0
def _upload_to_prefix(webplayer, original_filename, prefix):
    basename = os.path.basename(original_filename)
    name, ext = os.path.splitext(basename)
    uuid = shortuuid.uuid()
    datepart = strftime(now(), "%Y-%m-%d")
    return "%s/%s-%s-%s%s" % (prefix, name, datepart, uuid, ext)