Exemplo n.º 1
0
def get_temp_filename(base_name=None):
    """Get temporary file name

    Args:
        base_name - if not Null returning name contains base_name
    """
    boundary = email.generator._make_boundary()
    if base_name:
        return os.path.join(gettempdir(), boundary + "_" + base_name)
    else:
        return os.path.join(gettempdir(), boundary)
Exemplo n.º 2
0
    def process(self, request, queryset=None):
        def format_param_proc(param):
            ret = "%.8f" % float(param * 100)
            return ret + "%"

        def format_param(param):
            ret = "%.8f" % float(param)
            return ret

        config = request.FILES['config_file']
        tmp_dir = gettempdir()

        file_name = os.path.join(tmp_dir, 'temp_config.xlsx')
        with open(file_name, 'wb') as f:
            f.write(config.read())

        workbook = openpyxl.load_workbook(filename=file_name, read_only=True)
        worksheets = workbook.get_sheet_names()
        worksheet = workbook.get_sheet_by_name(worksheets[0])
        for row in worksheet.rows:
            try:
                mag = int(row[0].value)
            except:
                continue
            if not (mag >= 50 and mag <= 99):
                continue

            objects = models.Config.objects.filter(nr_oddz=mag)
            if len(objects) == 1:
                obj = objects[0]
                obj.p1 = format_param_proc(row[1].value)
                obj.p2 = format_param_proc(row[2].value)
                obj.p3 = format_param_proc(row[3].value)
                obj.p4 = format_param_proc(row[4].value)
                obj.p5 = format_param_proc(row[5].value)
                obj.p6 = format_param_proc(row[6].value)
                obj.p7 = format_param_proc(row[7].value)
                obj.p8 = format_param(row[8].value)
                obj.save()
        workbook._archive.close()

        return {'OK': True}
Exemplo n.º 3
0
    def _open_binary_data(self, http_ret, page):
        if "application/vnd.oasis.opendocument" in http_ret.ret_content_type:

            cd = http_ret.response.headers.get("content-disposition")
            if cd:
                name = cd.split("filename=")[1]
            else:
                name = None
            p = http_ret.ptr()

            postfix = name.split("_")[-1][-12:]
            fname = get_temp_filename(postfix)
            with open(fname, "wb") as f:
                f.write(p)

            file_name = fname
            if not name:
                name = file_name
            if not hasattr(wx.GetApp(), "download_files"):
                wx.GetApp().download_files = []
            wx.GetApp().download_files.append(
                (file_name, name, datetime.datetime.now()))

            return self.new_main_page("^standard/odf_view/odf_view.html",
                                      name,
                                      parameters=name)
        elif "application/pdf" in http_ret.ret_content_type:
            p = http_ret.ptr()
            f = NamedTemporaryFile(delete=False)
            f.write(p)
            name = f.name
            f.close()
            href = (
                "http://127.0.0.2/static/vanillajs_plugins/pdfjs/web/viewer.html?file="
                + name)
            return self.new_main_page(href, name, parameters={"schtml": 0})

        elif "zip" in http_ret.ret_content_type:
            p = http_ret.ptr()
            f = NamedTemporaryFile(delete=False)
            f.write(p)
            name = f.name
            f.close()
            return self.new_main_page("^standard/html_print/html_print.html",
                                      name,
                                      parameters=name)
        else:
            cd = http_ret.response.headers.get("content-disposition")
            if cd:
                name = cd.split("filename=")[1].replace('"', "")
            else:
                name = "data.dat"

            p = http_ret.ptr()

            path = gettempdir()

            with open(os.path.join(path, name), "wb") as f:
                f.write(p)

            if platform.system() == "Windows":
                os.startfile(path)
            elif platform.system() == "Darwin":
                subprocess.Popen(["open", path])
            else:
                subprocess.Popen(["xdg-open", path])

        return True
Exemplo n.º 4
0
    def process(self, request, queryset=None):

        object_list = []
        data = request.FILES['import_file']
        tmp_dir = gettempdir()
        file_name = os.path.join(tmp_dir, "employees.xlsx")
        with open(file_name, "wb") as f:
            f.write(data.read())

        workbook = openpyxl.load_workbook(filename=file_name, read_only=True)
        worksheets = workbook.get_sheet_names()
        worksheet = workbook.get_sheet_by_name(worksheets[0])
        lp = 0
        fields = []
        id_type = 0

        for row in worksheet.rows:
            if lp == 0:
                for pos in row:
                    if pos.value:
                        fields.append(str(pos.value).strip())
                    else:
                        fields.append("X")
                if 'email' in fields:
                    id_type = 1
                    lp += 1
                    continue
                else:
                    if 'surname' in fields and 'name' in fields and 'company' in fields:
                        id_type = 2
                        continue
                    else:
                        object_list.append(
                            "Błędna struktura pliku, brak zestawu pól: email lub (name, surname, company)"
                        )
                        break
            else:
                values = []
                for pos in row:
                    if pos.value:
                        values.append(str(pos.value).strip())
                    else:
                        values.append("")

            lp += 1

            obj = {}
            i = 0
            for field in fields:
                obj[field] = values[i]
                i += 1

            if id_type == 1:
                email = obj['email']
            else:
                if obj['name'] and obj['surname'] and obj['company']:
                    email = obj['name'] + "." + obj['surname'] + "@" + obj[
                        'company'] + ".pl"
                    email = email.lower()
                else:
                    email = ""

            if email and '@' in email:
                employees = models.Employee.objects.filter(email=email)
                if employees.count() > 0:
                    e = employees[0]
                else:
                    e = models.Employee()

                for field in fields:
                    if hasattr(e, field):
                        setattr(e, field, obj[field])
                e.email = email
                e.active = True

                e.save()
            else:
                object_list.append("Wiersz nie został wczytany: " +
                                   str(values))

        workbook._archive.close()

        return {"object_list": object_list}
Exemplo n.º 5
0
    def process(self, request, queryset=None):

        LIN_LIMIT = 10
        proc_id = int(request.POST.get('proc_id', '0'))

        tmp_dir = gettempdir()

        if proc_id == 0:
            #try:
            odfdata = request.FILES['ods_wzr']
            stawki = request.FILES['stawki']

            stream = io.BytesIO(odfdata.read())
            zfile = zipfile.ZipFile(stream)

            for m in zfile.infolist():
                data = zfile.read(m)
                disk_file_name = os.path.join(tmp_dir,
                                              m.filename[:2] + '.xlsx')
                with open(disk_file_name, 'wb') as fd:
                    fd.write(data)

            file_name = os.path.join(tmp_dir, 'temp_stawki.xlsx')
            with open(file_name, 'wb') as f:
                f.write(stawki.read())

            return {'status': 'start', 'OK': True}
        #except:
        #    return { 'status':  'start', 'OK': False, 'message': sys.exc_info() }

        elif proc_id == 1000:
            try:
                file_list = os.listdir(path=tmp_dir)
                for pos in file_list:
                    if len(pos) > 3 and pos[0] >= '0' and pos[
                            0] <= '9' and pos[1] >= '0' and pos[
                                1] <= '9' and pos.lower().endswith('.xlsx'):
                        file_name = os.path.join(tmp_dir, pos)
                        #os.unlink(file_name)
                file_name = os.path.join(tmp_dir, 'temp_stawki.xlsx')
                os.unlink(file_name)
                return {'status': 'end', 'OK': True}
            except:
                return {
                    'status': 'end',
                    'OK': False,
                    'message': sys.exc_info()
                }

        elif proc_id > 0 and proc_id < 1000:
            print(proc_id)

            rok = self.cleaned_data['rok']
            mies = self.cleaned_data['mies']

            if int(mies) == 1:
                data_start = "%04d%02d28" % (int(rok) - 1, 12)
                data_stop = "%04d%02d28" % (int(rok), 1)
                data_start_str = "%04d-%02d-28" % (int(rok) - 1, 12)
                data_stop_str = "%04d-%02d-27" % (int(rok), 1)
            else:
                data_start = "%04d%02d28" % (int(rok), int(mies) - 1)
                data_stop = "%04d%02d28" % (int(rok), int(mies))
                data_start_str = "%04d-%02d-28" % (int(rok), int(mies) - 1)
                data_stop_str = "%04d-%02d-27" % (int(rok), int(mies))

            test = self.cleaned_data['test']

            softlab = {}

            file_list = os.listdir(path=tmp_dir)
            data_path = None
            for pos in file_list:
                if len(pos) > 3 and pos[0] >= '0' and pos[0] <= '9' and pos[
                        1] >= '0' and pos[1] <= '9' and pos.lower().endswith(
                            '.xlsx'):
                    x = int(pos[:2])
                    if x == proc_id:
                        #data_path = pos
                        data_path = os.path.join(tmp_dir, pos)

            #data_path = os.path.join(tmp_dir, "Dane_prem_%02d.xlsx" % proc_id)
            #print(data_path)
            if not data_path or not os.path.exists(data_path):
                return {
                    'status': 'etap',
                    'proc_id': proc_id,
                    'OK': False,
                    'message': 'Brak danych'
                }

            workbook = openpyxl.load_workbook(filename=data_path,
                                              read_only=True)
            worksheets = workbook.get_sheet_names()
            worksheet = workbook.get_sheet_by_name(worksheets[0])
            i = 0

            data = DataOddz()

            for row in worksheet.rows:
                if i == 1:
                    data.godz_obce = read_int(row[1].value)
                elif i == 2:
                    data.naj_wyn = read_int(row[1].value)
                elif i == 3:
                    data.il_rbg = read_int(row[1].value)
                elif i < 8:
                    pass
                else:
                    try:
                        print("LP:", row[1].value)
                        no = int(row[1].value)
                    except:
                        no = -1
                    if no > 1000 and no < 100000:
                        try:
                            r = []
                            for i in range(2, 9):
                                r.append(read_str(row[i].value))
                                #if row[i].value:
                                #    r.append(row[i].value)
                                #else:
                                #   r.append(0)
                            data.prac[int(row[1].value)] = r
                        except:
                            pass
                i += 1

            workbook._archive.close()
            #print(data.prac)
            maile = {}
            with settings.DB as db:
                db.execute(select7)
                for pos in db.fetchall():
                    maile[int(pos[0])] = (
                        pos[1],
                        pos[2],
                        pos[3],
                    )

                #db.execute(select4)
                #for pos in db.fetchall():
                #    try:
                #        nr = int(pos[0])
                #        oddz = pos[1][-2:]
                #        opis = pos[2]
                #        softlab[nr] = (oddz, opis)
                #    except:
                #        continue

                cuw = {}
                file_name = os.path.join(tmp_dir, "temp_stawki.xlsx")
                print(file_name)
                workbook = openpyxl.load_workbook(filename=file_name,
                                                  read_only=True)
                worksheets = workbook.get_sheet_names()
                print(worksheets)
                worksheet = workbook.get_sheet_by_name(worksheets[0])
                print(worksheet)
                for row in worksheet.rows:
                    try:
                        sap_id = int(row[0].value)
                    except:
                        continue
                    if sap_id <= 0:
                        continue
                    prac = (get_oddz_from_name(row[7].value), row[1].value)
                    softlab[sap_id] = prac
                    if not int(prac[0]) in cuw:
                        cuw[int(prac[0])] = {}
                    cuw[int(prac[0])][sap_id] = Prac(row)

                workbook._archive.close()

                nag = {}
                db.execute(select1 % (data_start, data_stop))
                for pos in db.fetchall():
                    nag[pos[0]] = pos[1:]

                lin = {}
                db.execute(select2 % (data_start, data_stop))
                for pos in db.fetchall():
                    if pos[0] in lin:
                        lin[pos[0]].append(pos[1:])
                    else:
                        lin[pos[0]] = [
                            pos[1:],
                        ]

                for key, tab in lin.items():
                    if len(tab) > LIN_LIMIT:
                        i = len(tab)
                        row = None
                        while i > LIN_LIMIT:
                            if row:
                                for j in range(len(tab[i - 1])):
                                    if j == 0 or j == 3:
                                        pass
                                    else:
                                        row[j] += tab[i - 1][j]
                            else:
                                row = list(tab[i - 1])
                                row[0] = 'POZOSTALE:'
                                row[3] = row[4] / row[2]
                            i -= 1
                        del tab[LIN_LIMIT:]
                        tab.append(row)

                pw = {}
                db.execute(select3 % (data_start, data_stop))
                for pos in db.fetchall():
                    pw[str(pos[0]) + "_" + str(pos[1])] = pos[2]

                awarie = {}
                db.execute(select5 % (data_start, data_stop))
                for pos in db.fetchall():
                    gniazdo = str(pos[0])
                    if not gniazdo in awarie:
                        awarie[gniazdo] = []
                    awarie[gniazdo].append(pos)

                godziny = {}
                db.execute(select6 %
                           (data_start, data_stop, data_start, data_stop))
                for pos in db.fetchall():
                    gniazdo = str(pos[0])
                    godziny[gniazdo] = pos

            doc_type = 'odf'
            prod = Prod(nag, lin, cuw, pw, awarie, godziny, data, proc_id)

            dfile = os.path.join(settings.DATA_PATH, settings.APPSET_NAME)
            kalkulacja = os.path.join(dfile, "kalkulacja premii.ods")
            file_out, file_in = render_odf(
                kalkulacja,
                Context({
                    'prod': prod,
                    'data_start': data_start_str,
                    'data_stop': data_stop_str,
                }))

            new_name = os.path.join(tmp_dir, "%02d - premia.ods" % proc_id)
            os.rename(file_out, new_name)

            if True:
                with open(new_name, "rb") as f:
                    with open(data_path, "rb") as f2:
                        if test:
                            mail_to = [
                                '*****@*****.**',
                                '*****@*****.**',
                            ]
                            #mail_to = [ '*****@*****.**', ]
                        else:
                            mail_to = [
                                "*****@*****.**",
                                maile[proc_id][1] + "@polbruk.pl",
                                maile[proc_id][0] + "@polbruk.pl",
                                '*****@*****.**',
                                '*****@*****.**'
                            ]

                        mail = EmailMessage("Plik premiowy dla oddziału: " +
                                            prod.settings.nazwa,
                                            MAIL_CONTENT,
                                            to=mail_to)
                        mail.attach(
                            prod.settings.nazwa + "_" +
                            data_stop.replace('-', '').replace(' ', '') +
                            ".ods", f.read(),
                            "application/vnd.oasis.opendocument.spreadsheet")
                        mail.attach(("%02d_" % proc_id) + prod.settings.nazwa +
                                    ".xlsx", f2.read(),
                                    "application/vnd.ms-excel")
                        mail.send()
                os.unlink(new_name)
                os.unlink(data_path)
            return {
                'status': 'etap',
                'proc_id': proc_id,
                'OK': True,
                'file_name': file_out
            }
        else:
            return {}