コード例 #1
0
ファイル: stock_input.py プロジェクト: fadiga/mstock
    def save_b(self):
        ''' add operation '''
        # entete de la facture
        if not self.table_in.isvalid:
            return False
        date = str(self.date.text())
        datetime_ = date_to_datetime(date)
        store = self.liste_store[self.box_mag.currentIndex()]
        values_t = self.table_in.get_table_items()

        for ligne in values_t:
            qty, name = ligne
            product = Product.select().where(Product.name == name).get()

            rep = Reports(orders=None, type_=Reports.E, store=store,
                          date=datetime_, product=product,
                          qty_use=int(qty))
            try:
                rep.save()
            except:
                self.parent.Notify(
                    u"Ce mouvement n'a pas pu être enrgistré dans les raports", "error")
                return False

        self.parent.change_context(GReportViewWidget)
        self.parent.Notify(u"L'entrée des articles avec succès", "success")
コード例 #2
0
def add_report():
    pokemon = request.args.get('pokemon')
    latitude = request.args.get('latitude')
    longitude = request.args.get('longitude')
    user_id = request.args.get('user_id')
    if pokemon is not None and latitude is not None and longitude is not None:
        pokemon = float(pokemon)
        latitude = float(latitude)
        longitude = float(longitude)
        report = Reports(latitude, longitude, pokemon, user_id=user_id)
        id = report.insert_into_db()
        block_dim = 0.01
        users_in_radius = User.query.filter(
            User.latitude <= latitude + block_dim).filter(
                User.latitude >= latitude - block_dim).filter(
                    User.longitude >= longitude - block_dim).filter(
                        User.longitude <= longitude + block_dim).all()
        for user in users_in_radius:
            print(str(user.username) + " is in radius.")
            notification = Notifications.query.filter_by(
                user=user.id, pokemon=pokemon).first()
            if notification is not None:
                curr_dir = os.path.dirname(
                    os.path.realpath(__file__)) + "/pushcert.pem"
                send_APN(curr_dir, user.device_token,
                         pokemonList[int(pokemon)] + " was reported near you!")
        return jsonify(success=0, report=report.serialize)
    return jsonify(success=1, error='check request params')
コード例 #3
0
ファイル: stock_output.py プロジェクト: fadiga/mstock
    def save_report(self):
        ''' add operation '''
        # entete de la facture
        self.table_out.changed_value()
        if not self.table_out.isvalid:
            return False
        date_out = str(self.date_out.text())
        datetime_ = date_to_datetime(date_out)
        self.current_store = self.liste_store[self.box_store.currentIndex()]

        values_t = self.table_out.get_table_items()

        for qty, name in values_t:
            rep = Reports(type_=Reports.S, store=self.current_store,
                          date=datetime_, product=Product.get(name=name),
                          qty_use=int(qty))
            try:
                rep.save()
            except:
                self.parent.Notify(
                    u"Ce mouvement n'a pas pu être enrgistré dans les raports", "error")
                return False

        self.parent.change_context(GReportViewWidget)
        self.parent.Notify(u"La sortie des articles avec succès", "success")
コード例 #4
0
def add_report():
    time = request.args.get('time')
    reporter = 3
    latitude = request.args.get('latitude')
    longitude = request.args.get('longitude')
    type_report = request.args.get('type')
    report = Reports(time, reporter, latitude, longitude, type_report)
    return jsonify(report=report.insert_into_db())
コード例 #5
0
ファイル: invoice_show.py プロジェクト: fadiga/mstock
    def annulation(self):
        reply = QMessageBox.question(self, 'Confirmation',
                                    u"<h2 style='color:red;'>Voulez vous vraiment annuler cette"
                                    u" facture?</h2>",
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:
            from ui.dashboard import DashbordViewWidget
            rep = Reports()
            rep.store = 1
            for item in Reports.filter(invoice=self.invoice):
                item.delete_instance()
            self.invoice.delete_instance()
            self.change_main_context(DashbordViewWidget)
コード例 #6
0
ファイル: reports_managers.py プロジェクト: fadiga/mstock
 def set_data_for(self, on, end):
     self.data = [(rap.type_, rap.store.name, rap.product,
                   formatted_number(rap.qty_use),
                   formatted_number(rap.remaining),
                   show_date(rap.date), rap.id)
                  for rap in Reports.filter(deleted=False, date__gte=on, date__lte=end)
                  .order_by(Reports.date.desc())]
コード例 #7
0
ファイル: state_stock.py プロジェクト: fadiga/mstock
    def set_data_for(self, main_date):

        try:
            on, end = main_date.current.current
        except:
            on, end = main_date.current
        on = datetime(on.year, on.month, on.day, 0, 0, 0)
        end = datetime(end.year, end.month, end.day, 23, 59, 59)
        reports = []
        this_periode_rpt = Reports.select().where(Reports.date >= on,
                                                  Reports.date <= end)
        for store in Store.select().order_by(Store.name):
            if ([(i) for i in this_periode_rpt.where(Reports.store << [store, ])] == []):
                continue
            cpt = 0
            for prod in Product.select().order_by(Product.name):
                if ([(i) for i in this_periode_rpt.where(Reports.store == store,
                                                         Reports.product << [prod, ])] == []):
                    continue
                dict_store = {}
                repts = this_periode_rpt.where(
                    Reports.store == store, Reports.product == prod)
                dict_store["store"] = store.name if cpt < 1 else ""
                dict_store["product"] = prod.name
                dict_store["sum_qty_in"] = repts.select(
                    peewee.fn.SUM(Reports.qty_use)).where(Reports.type_ == Reports.E).scalar()
                dict_store["sum_qty_out"] = repts.select(
                    peewee.fn.SUM(Reports.qty_use)).where(Reports.type_ == Reports.S).scalar()
                cpt += 1
                reports.append(dict_store)

        self.data = [(rep.get('store'), rep.get('product'), rep.get('sum_qty_in'),
                      rep.get('sum_qty_out')) for rep in reports]
コード例 #8
0
ファイル: by_product.py プロジェクト: fadiga/mstock
    def set_data_for(self, main_date):

        try:
            on, end = main_date.current.current[0], main_date.current.current[1]
        except:
            on, end = main_date.current[0], main_date.current[1]

        on = datetime(on.year, on.month, on.day, 0, 0, 0)
        end = datetime(end.year, end.month, end.day, 23, 59, 59)
        reports = []
        period_report = Reports.select().filter(product=self.product,
                                                date__gte=on, date__lte=end)

        for rept in period_report.group_by("store").order_by(Reports.date.desc()):
            dict = {}
            reports_stores = period_report.filter(store=rept.store)
            sum_qty_in = reports_stores.filter(type_=Reports.E).aggregate(peewee.Sum('qty_use'))
            sum_qty_out = reports_stores.filter(type_=Reports.S).aggregate(peewee.Sum('qty_use'))

            dict["store"] = rept.store.name
            dict["sum_qty_in"] = sum_qty_in if sum_qty_in else 0
            dict["sum_qty_out"] = sum_qty_out if sum_qty_out else 0
            dict["sum_nbr_part_in"] = rept.product.number_parts_box * dict["sum_qty_in"]
            dict["sum_nbr_part_out"] = rept.product.number_parts_box * dict["sum_qty_out"]
            try:
                dict["remaining"] = reports_stores.order_by(('.date', 'desc')).get().remaining
                reports.append(dict)
            except:
                raise
                # pass
        self.data = [(rep.get('store'), rep.get('sum_qty_in'), rep.get('sum_qty_out'),
                      rep.get('remaining'))
                      for rep in reports]
コード例 #9
0
ファイル: stock_output.py プロジェクト: fadiga/mstock
    def set_data_for(self, value):

        products = [(Product.get(id=rpt.product_id).name) for rpt in
                    Reports.select(fn.Distinct(Reports.product))]
        if value:
            products = [(prod.name) for prod in Product.select().where(Product.name.contains(value))
                        .where(Product.name << products).order_by(Product.name.desc())]
        self.data = [("", rpt, "") for rpt in products]
コード例 #10
0
async def api_create_report(request, *, title):
    # logging.info('func:api_create_report')
    check_admin(request)
    if not title or not title.strip():
        raise APIValueError('title', 'title cannot be empty.')
    report = Reports(title=title.strip())
    await report.save()
    return report
コード例 #11
0
ファイル: dashboard.py プロジェクト: fadiga/mstock
 def set_data_for(self):
     self.data = [(rap.type_, rap.store.name, rap.product,
                   formatted_number(rap.qty_use),
                   formatted_number(rap.remaining),
                   show_date(rap.date))
                  for rap in Reports.select().where(
         Reports.date < date_on_or_end(self.today, on=False),
         Reports.date > date_on_or_end(self.today)
     ).order_by(Reports.id.desc())]
コード例 #12
0
ファイル: data_helper.py プロジェクト: fadiga/mstock
def update_report(report):
    """ Supression  """
    try:
        p = Reports.filter(deleted=False, date__gt=report.date).get()
        p.save()
    except Exception as e:
        print("update_report", e)
        pass

    report.delete_instance()
コード例 #13
0
ファイル: data_helper.py プロジェクト: fadiga/mstock
def lastes_reports():
    list_rep = []
    for store in Store.select():
        for prod in Product.select():
            try:
                list_rep.append(Reports.filter(deleted=False, store=store,
                                               product=prod)
                                       .order_by(Reports.date.desc()).get())
            except Exception as e:
                # print(e)
                pass
    return list_rep
コード例 #14
0
def task_statistics():
    current_time = datetime.now()
    previous_year = datetime(current_time.year - 1, 1, 1)
    current_year = datetime(current_time.year, 1, 1)

    all_task = Reports.objects.count()
    task_by_current_year = Reports.objects(Q(create_date__gte=current_year) & Q(create_date__lt=current_time)).count()

    previous_month = current_time.replace(day=1, hour=0, minute=0, second=0) - timedelta(days=1)
    previous_month = previous_month.replace(day=1)
    current_month = current_time.replace(day=1, hour=0, minute=0, second=0)

    all_task = all_task
    task_by_current_month = Reports.objects(Q(create_date__gte=current_month) & Q(create_date__lt=current_time)).count()

    previous_day = current_time.replace(hour=0, minute=0, second=0) - timedelta(days=1)
    all_task = all_task
    task_by_today = Reports.objects(
        Q(create_date__gte=current_time.replace(hour=0, minute=0, second=0)) & Q(create_date__ne=current_time)).count()

    _users = Users.objects.count()

    response_content = {
        'year': {
            'all_task': all_task,
            'current_year': task_by_current_year
        },
        'month': {
            'all_task': all_task,
            'current_month': task_by_current_month
        },
        'day': {
            'all_task': all_task,
            'today': task_by_today
        },
        'user': _users
    }

    return jsonify(response_content), 200
コード例 #15
0
def revoke_tasks(task_id):
    if task_id != '':
        celery_pipe.AsyncResult(task_id).revoke(terminate=True, wait=True, timeout=10, signal='SIGKILL')
        time.sleep(3)
        celery_pipe.AsyncResult(task_id).forget()
        _reports = Reports.objects(task_id=task_id)
        for _report in _reports:
            _report.delete()
    response_content = {
        'code': '200',
        'message': 'The task has been removed!'
    }
    return jsonify(response_content), 200
コード例 #16
0
ファイル: reports_managers.py プロジェクト: fadiga/mstock
    def popup(self, pos):
        row = self.selectionModel().selection().indexes()[0].row()
        if (len(self.data) - 1) < row:
            return False

        # self.report = Reports.filter(id=self.data[row][6]).get()
        self.report = Reports.select().where(
            Reports.id == self.data[row][6]).get()
        menu = QMenu()
        menu.addAction(QIcon("{}del.png".format(Config.img_cmedia)),
                       u"supprimer", lambda: self.del_report(self.report))

        self.action = menu.exec_(self.mapToGlobal(pos))
コード例 #17
0
ファイル: util.py プロジェクト: qzorg/flaskchan
def add_report(rboard, rdate, rdeleted, rop):
    #newRep = db.session.query(Reports).filter_by(id=id).one()
    print(rboard)
    print(rdate)
    print(rdeleted)
    print(rop)
    newRep = Reports(board   = rboard,
        rdate    = rdate,
        deleted = rdeleted,
        op_id   = rop,
        )
    db.session.add(newRep)
    db.session.commit()
コード例 #18
0
ファイル: stock_output.py プロジェクト: fadiga/mstock
    def changed_value(self, refresh=False):
        """ Calcule les Resultat """
        current_store = self.parent.liste_store[
            self.parent.box_store.currentIndex()]

        for row_num in xrange(0, self.data.__len__()):
            self.isvalid = True
            try:
                last_report = Reports.filter(store=current_store,
                                             product__name=str(self.item(row_num, 1)
                                                               .text())).order_by(Reports.date.desc()).get()
                qtremaining = last_report.remaining

                date_out = str(self.parent.date_out.text())
                if last_report.date > date_on_or_end(date_out, on=False):
                    self.parent.date_out.setStyleSheet("font-size:15px;"
                                                       "color:red")
                    self.parent.date_out.setToolTip(u"Cette date est "
                                                    u"Inférieure à la date "
                                                    u"de la dernière rapport"
                                                    u" (%s) " %
                                                    last_report.date)
                    self.isvalid = False
                    return False

            except Exception as e:
                print(e)
                qtremaining = 0

            qtsaisi = is_int(self.cellWidget(row_num, 0).text())

            self._update_data(row_num, [qtsaisi])
            viderreur_qtsaisi = ""
            stylerreur = "background-color: rgb(255, 235, 235);" + \
                         "border: 3px double SeaGreen"
            if qtsaisi == 0:
                viderreur_qtsaisi = stylerreur
                self.cellWidget(row_num, 0).setToolTip(u"obligatoire")
                self.isvalid = False

            self.cellWidget(row_num, 0).setStyleSheet(viderreur_qtsaisi)

            self.cellWidget(row_num, 0).setToolTip("")
            if qtremaining < qtsaisi:
                self.cellWidget(row_num, 0).setStyleSheet("font-size:20px;"
                                                          " color: red")
                self.cellWidget(row_num, 0).setToolTip(u"%s est > %s (stock"
                                                       u" remaining)" % (qtsaisi,
                                                                         qtremaining))
                self.isvalid = False
                return False
コード例 #19
0
ファイル: reports_managers.py プロジェクト: fadiga/mstock
 def del_report(self, report):
     remaining, nb = report.store.get_remaining_and_nb_parts(report.product)
     remaining -= report.remaining
     if remaining >= 0:
         self.parent.open_dialog(ConfirmDeletionDiag, modal=True,
                                 obj_delete=report,
                                 msg="Magasin : {}\nProduit: {}\nQuantité: {}".format(report.store,
                                                                                      report.product,
                                                                                      report.qty_use),
                                 table_p=self.parent.table_op)
         rep = Reports.select().where(Reports.date <
                                      report.date).order_by(Reports.date.desc()).get()
         rep.save()
     else:
         raise_error(u"Erreur", u"Impossible de supprimer ce rapport car"
                     u" le restant sera : <b>%s</b> qui est < 0"
                     % remaining)
コード例 #20
0
ファイル: export_xls.py プロジェクト: fadiga/mstock
def write_report_xls(file_name, data):
    ''' Export data '''
    # Principe
    # write((nbre ligne - 1), nbre colonne, "contenu", style(optionnel).
    # write_merge((nbre ligne - 1), (nbre ligne - 1) + nbre de ligne
    # à merger, (nbre de colonne - 1), (nbre de colonne - 1) + nbre
    # de colonne à merger, u"contenu", style(optionnel)).
    book = xlwt.Workbook(encoding='ascii')
    sheet = book.add_sheet(u"Rapports")
    rowx = 0
    sheet.write_merge(rowx, rowx + 1, 0, 3,
                      u"Rapports de gestion de stock %s" % Config.NAME_ORGA, style_title)
    rowx += 3
    sheet.write_merge(rowx, rowx, 1, 2, u"Date du rapport: ", style)
    date_com = "Bko le %s" % date.today().strftime(u"%d/%m/%Y")
    sheet.write_merge(rowx, rowx, 3, 3, date_com)

    sheet.col(1).width = 0x0d00 * 3
    sheet.col(2).width = 0x0d00 * 1.5
    sheet.col(4).width = 0x0d00 * 2
    # title = [u"Type", u"Produit", u"Nbre Carton", u"Restant", u"Date"]

    for rap in Reports.all():
        if int(rowx) % 2 == 0:
            style_row_table = style1
        else:
            style_row_table = style2
        sheet.write(rowx, 0, rap.type_, style_row_table)
        sheet.write(rowx, 1, "%s (%s)" % (rap.product.name,
                                          rap.product.code_prod), style_row_table)
        sheet.write(rowx, 2, rap.nbr_carton, style_row_table)
        sheet.write(rowx, 3, rap.remaining, style_row_table)
        sheet.write(
            rowx, 4, rap.date.strftime(u'%x %Hh:%Mmn'), style_row_table)
        rowx += 1
    book.save(file_name)

    openFile(file_name)
コード例 #21
0
def insert():
    form = WordForm()
    if form.validate_on_submit():
        name = form.name.data
        lat = form.lat.data
        lon = form.lon.data
        desc = form.description.data
    else:
        return render_template('submit.html', form=form)
    print(name)
    print(lat)
    print(lon)
    print(desc)
    # Nuke database
    # db.session.execute('DELETE FROM reports WHERE true')
    rows = db.session.execute('SELECT * FROM reports')
    id = len(rows.fetchall()) + 1
    print(id)
    #insert = 'INSERT INTO reports (id, name, lon, lat, description) VALUE ({}, \'{}\', \'{}\', \'{}\', \'{}\')'.format(id, name, lat, lon, desc)
    #print(insert)
    r = Reports(id, name, lat, lon, desc)
    db.session.add(r)
    db.session.commit()
    return render_template('successful.html')
コード例 #22
0
def submit_report():
    print('sub')
    linked_reqs = request.form.getlist('linked_reqs')
    consumers = request.form.get('consumers')
    #form_data = request.form
    summary=request.form.get('summary','')
    summary=unmark_indicators(summary)
    #getting rid of pesky dashes
    for i in range(8210, 8214):
        summary=summary.replace(chr(i),'-')
    
    if request.form.get('is_edited'):
        tlp = request.form.get('tlp')
        report= Reports.query.filter_by(id=request.form.get('id')).first()
        report.title=request.form.get('title')
        report.content=summary
        report.friendly_id=request.form.get('friendly_id')
        #report.tags=request.form.get('tags')
        report.is_archived=request.form.get('is_archived')
        if report.is_archived:
            report.is_archived = 1
        else:
            report.is_archived = 0
        report.tlp=tlp
        db.session.commit()
        db.session.flush()
        goto=url_for('view_report', report_id=report.id)
        
    else:
        title = request.form.get('title')
        friendly_id = request.form.get('friendly_id')
        #tags = request.form.get('tags')
        tlp = request.form.get('tlp')
        report = Reports(title=title, content=summary,creator=current_user.name,friendly_id=friendly_id,is_archived=False,tlp=tlp)
        add_db_entry(report)
        goto=url_for('active_reports')
        
        #send a webhook
        hooks=Organization.query.filter(Organization.slack_webhook_on_report_create.is_(True)).all()
        hooks=[hook.slack_webhook for hook in hooks if hook.slack_webhook]
        
        message='A new report, {},  has been created. To view the report, go to: {}{}'.format(report.title,request.host_url[0:-1], url_for('view_report', report_id=report.id))
        wh_data = {
            "attachments":[
                {
                    "fallback":message,
                    "pretext":message,
                    "color":"#6658EA",
                    "fields":[
                        {
                        "title":"Writer",
                        "value":report.creator,
                        "short":'true'
                        },
                        {
                        "title":"ID",
                        "value":report.friendly_id,
                        "short":'true'
                        },
                        {
                        "title":"Title",
                        "value":report.title,
                        }
                    ]
                }
            ]
            }
        
        send_webhook(wh_data, hooks)

        
    ReportTags.query.filter(ReportTags.report == report.id).delete()

    if request.form.get('tags'):
        tag_list=json.loads(request.form.get('tags'))
        for tag in tag_list:
            rt=ReportTags(report=report.id, tag=tag['value'])
            add_db_entry(rt)
            
    parse_indicators(summary,report.id, queue)
    delete_report_requirement_links(report_id=report.id)
    add_report_requirement_links(report_ids=[report.id], req_ids=linked_reqs)
    
    return redirect(goto)
コード例 #23
0
def tasks():
    scantypes = ['-sT', '-sT', '-sS', '-sA', '-sW', '-sM', '-sN', '-sF', '-sX', '-sU']

    if request.method == 'GET':
        skip = int(request.args['skip'])
        limit = int(request.args['limit'])
        sort_by = request.args['sort_by']
        sort_context = int(request.args['sort_context'])
        search = request.args['search']

        if sort_context == -1:
            sort_by = '-' + sort_by

        query = Reports.objects(user_id=session['current_user']).all().order_by(sort_by)
        if search != '':
            query = Reports.objects(user_id=session['current_user']).filter(targets__contains=search).all().order_by(
                sort_by)

        _nmap_tasks = []
        paginator = Pagination(query, skip / limit + 1, 10)
        _dbreports = paginator.items
        for _dbreport in _dbreports:
            _nmap_task = celery_pipe.AsyncResult(_dbreport['task_id'])
            _report = {
                'id': _nmap_task.id,
                'targets': _dbreport['targets'],
                'options': _dbreport['options'],
                'create_date': _dbreport['create_date'],
                'status': _nmap_task.status,
                'ready': 0
            }
            if _nmap_task.result and 'done' in _nmap_task.result:
                _report.update({'progress': float(_nmap_task.result['done'])})
            elif _nmap_task.result and 'report' in _nmap_task.result:
                _report.update({'progress': 100})
            else:
                _report.update({'progress': 0})
            if _nmap_task.status in READY_STATES:
                _report.update({'ready': 1})
            _nmap_tasks.append(_report)

        response_content = {
            'recordsTotal': Reports.objects.count(),
            'recordsFiltered': paginator.total,
            'data': _nmap_tasks
        }
        return jsonify(response_content), 200

    elif request.method == 'POST':
        data = request.get_json()

        if data['targets'] == '':
            response_content = {
                'code': '403',
                'message': 'The targets is not correct!'
            }
            return jsonify(response_content), 200

        scani = int(data.get('scanTechniques', 0))
        if data.get('ports', '') != '':
            portlist = '-p ' + data.get('ports')
        else:
            portlist = ''
        noping = '-Pn' if data.get('noping', False) else ''
        osdetect = '-O' if data.get('osDetection', False) else ''
        bannerdetect = '-sV' if data.get('bannerDetection', False) else ''
        nse_script = ''
        if data.get('scripts', '') != '':
            nse_script = '--script={0}'.format(data.get('scripts'))
        options = '{0} {1} {2} {3} {4} {5}'.format(scantypes[scani],
                                                   portlist,
                                                   noping,
                                                   osdetect,
                                                   bannerdetect,
                                                   nse_script)
        _celery_task = celery_nmap_scan.delay(targets=str(data['targets']), options=str(options))
        report = Reports(user_id=session['current_user'], task_id=_celery_task.id, targets=data['targets'],
                         options=options)
        report.save()

        response_content = {
            'code': '200',
            'message': 'Successful!'
        }
        return jsonify(response_content), 200