예제 #1
0
def bd_hari(sampling=datetime.date.today()):
    sp = datetime.date(2016, 1, 3)
    wds = AgentBd.select(AgentBd.q.AgentType == 3)
    rs = WadukDaily.select(
        AND(WadukDaily.q.waktu >= sp, WadukDaily.q.waktu <= sp)).orderBy(
            ('pos_id, waktu', ))
    for r in rs:
        print r.pos.cname, r.waktu
    return sampling
예제 #2
0
def import_rtow(file_input):
    '''Mengimport data RTOW (setahun) dari file excel
            nop1 | nop2 | des1 | des2 | ...
    tma
    outflow_q
    inflow_q
    bon_a
    bon_b


    '''
    # deteksi pemisah data TAB, ;,','
    seps = '\t_;_,_|'.split('_')
    lines = open(file_input).readlines()
    header = lines[1].strip()
    sep = None
    for s in seps:
        if len(header.split(s)) > 5:
            sep = s
            cols = header.split(s)
            numcol = len(cols)
            break
    if not sep:
        msg = 'Tidak ditemukan pemisah kolom yang valid. (' + '_'.join(seps)
        ret = dict(ok=False, msg=msg)
        return ret

    try:
        nama_bendungan = lines[0].strip().split(sep)[0]
    except IndexError:
        nama_bendungan = lines[0].strip()
    bd_names = dict([(a.table_name, a.AgentId)
                     for a in AgentBd.select(AgentBd.q.AgentType == 3)])
    if nama_bendungan not in bd_names.keys():
        ret = dict(ok=False, msg=','.join(bd_names))
        return ret
    data = []
    for i in range(len(lines) - 2):
        i += 2
        line = lines[i].strip().split(sep)
        waktu = to_date(line[0])
        val = dict(waktu=waktu, posID=bd_names.get(nama_bendungan))
        for j in (1, 2, 3, 4, 5, 6, 7, 8):
            try:
                val[cols[j]] = float(line[j].replace(',', '.'))
            except ValueError:
                val[cols[j]] = None
        data.append(val)
    ret = dict(ok=True,
               pos_id=bd_names.get(nama_bendungan),
               table_name=nama_bendungan,
               object=data)
    return ret
예제 #3
0
 def GET(self):
     inp = web.input()
     if inp.get('sampling'):
         sampling = to_date(inp.sampling)
     else:
         sampling = datetime.date.today()
     tanggal = sampling
     bdgs = AgentBd.select(AgentBd.q.AgentType == 3).orderBy('wilayah')
     poses = dict([(a.table_name, a) for a in bdgs])
     daily_bd = dict([
         (w.pos.table_name, w)
         for w in WadukDaily.select(WadukDaily.q.waktu == tanggal)
     ])
     poses = [(poses.get(p), daily_bd.get(p))
              for p in [p.table_name for p in bdgs]]
     return render.adm.bendungan.index({'poses': poses, 'tanggal': tanggal})
예제 #4
0
 def GET(self, table_name):
     inp = web.input()
     bd = dict([(a.table_name, a.AgentId)
                for a in AgentBd.select(AgentBd.q.AgentType == 3)])
     if table_name not in bd.keys():
         return 'table_name: ' + table_name + ' tidak ditemukan'
     rows = export_rtow(bd.get(table_name))
     web.header('Content-Type', 'application/vnd.ms-excel')
     web.header('Content-Disposition',
                'attachment;filename=' + table_name + '.csv')
     s = table_name + '\n'
     for r in rows:
         s += '\t'.join(
             map(
                 lambda x: type(x) == datetime.datetime and x.strftime(
                     '%Y-%m-%d') or str(x), r)) + '\n'
     return s
예제 #5
0
def import_rtow(file_input):
    '''Mengimport data RTOW (setahun) dari file excel
            nop1 | nop2 | des1 | des2 | ...
    tma
    outflow_q
    inflow_q
    bon_a
    bon_b


    '''
    lines = open(file_input).readlines()
    nama_bendungan = lines[0].strip()
    bd_names = dict([(a.table_name, a.AgentId)
                     for a in AgentBd.select(AgentBd.q.AgentType == 3)])
    if nama_bendungan not in bd_names.keys():
        ret = dict(ok=False, msg=','.join(bd_names))
        return ret
    if len(lines) != 26:
        ret = dict(ok=False, msg='Data harus dari Nop - Okt / 24 baris')
        return ret
    cols = lines[1].strip().split('\t')
    data = []
    for i in range(24):
        i += 2
        line = lines[i].split('\t')
        waktu = datetime.datetime.strptime(line[0], '%Y-%m-%d').date()
        val = dict(waktu=waktu, posID=bd_names.get(nama_bendungan))
        for j in (1, 2, 3, 4, 5, 6, 7, 8):
            try:
                val[cols[j]] = float(line[j].strip())
            except ValueError:
                val[cols[j]] = None
        data.append(val)
    ret = dict(ok=True,
               pos_id=bd_names.get(nama_bendungan),
               table_name=nama_bendungan,
               object=data)
    return ret
예제 #6
0
    def POST(self, table_name):
        try:
            try:
                pos = [
                    a for a in AgentBd.select(AgentBd.q.AgentType == 3)
                    if a.table_name == table_name
                ][0]
            except IndexError:
                return web.notfound()
            inp = web.input()
            fields = 'curahhujan,tma,vol,inflow_q,inflow_v,intake_q,intake_v,spillway_q,spillway_v'.split(
                ',')
            koloms = 'tanggal,jam,tma'.split(',')
            form2_fields = 'tma,vol'.split(',')
            form3_fields = 'vnotch_tin1,vnotch_q1,vnotch_tin2,vnotch_q2,vnotch_tin3,vnotch_q3'.split(
                ',')
            form4_fields = 'a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4,c4,a5,b5,c5'.split(
                ',')
            # memeriksa apakah record pada Pos dan waktu(tgl) sudah ada pada tabel 'waduk_daily'
            try:
                wd = WadukDaily.select(
                    AND(WadukDaily.q.waktu == to_date(inp.waktu),
                        WadukDaily.q.pos == pos))[0]
                is_wd_exist = True
            except IndexError:
                wd = None
                is_wd_exist = False

            # memeriksa apakah table 'tma' telah terisi dari pos dan waktu
            tmas = [
                t for t in TinggiMukaAir.select(
                    AND(TinggiMukaAir.q.agent == pos, TinggiMukaAir.q.waktu ==
                        to_date(inp.waktu)))
            ]

            if inp.tahap == 'pagi':
                obj = {}
                for f in fields:
                    if inp.get(f):
                        nilai = float(inp.get(f))
                    else:
                        nilai = None
                    if f in 'tma,vol'.split(','):
                        obj.update({f + '6': nilai})
                    else:
                        obj.update({f: nilai})
                obj.update({'pos': pos, 'waktu': to_date(inp.waktu)})
                if not is_wd_exist:
                    wd = WadukDaily(**obj)
                else:
                    wd.set(**obj)
                # Mengupdate / Insert data TinggiMukaAir
                try:
                    tma = [t for t in tmas if t.jam == '6'][0]
                    tma.set(**{'jam': '6', 'manual': obj.get('tma6')})
                    tma.syncUpdate()
                except:
                    tma = TinggiMukaAir(
                        **{
                            'agent': pos,
                            'waktu': obj.get('waktu'),
                            'jam': '6',
                            'manual': obj.get('tma6'),
                            'origin': 'web'
                        })
                    tma.syncUpdate()
            elif inp.tahap in ('siang', 'sore'):
                # jika data pagi belum ada, untuk WadukDaily perlu error
                if not is_wd_exist:
                    session[
                        'err'] = "<strong style='margin-right: 10px'>P e r h a t i a n</strong>Data TMA Pagi tidak ditemukan."
                    return web.redirect('/adm/bendungan/' + table_name +
                                        '?sampling=' +
                                        inp.waktu.replace('/', '-'),
                                        absolute=True)
                per = inp.tahap == 'siang' and '12' or '18'
                if per == '12':
                    wd.tma12 = float(inp.get('tma'))
                    wd.vol12 = float(inp.get('vol'))
                elif per == '18':
                    wd.tma18 = float(inp.get('tma'))
                    wd.vol18 = float(inp.get('vol'))

                # Mengupdate / Insert data TinggiMukaAir
                try:
                    tma = [t for t in tmas if t.jam == per][0]
                    tma.set(**{'jam': per, 'manual': float(inp.get('tma'))})
                    tma.syncUpdate()
                except:
                    tma = TinggiMukaAir(
                        **{
                            'agent': pos,
                            'waktu': to_date(inp.waktu),
                            'jam': per,
                            'manual': float(inp.get('tma')),
                            'origin': 'web'
                        })
                    tma.syncUpdate()
            elif inp.tahap == 'vnotch':  # inputan vnotch
                # jika data pagi belum ada, untuk WadukDaily perlu error
                if not is_wd_exist:
                    session[
                        'err'] = "<strong style='margin-right: 10px'>P e r h a t i a n</strong>Data TMA Pagi tidak ditemukan."
                    return web.redirect('/adm/bendungan/' + table_name +
                                        '?sampling=' +
                                        inp.waktu.replace('/', '-'),
                                        absolute=True)
                obj = {}
                for f in form3_fields:
                    if inp.get(f):
                        obj.update({f: float(inp.get(f))})
                wd.set(**obj)
            elif inp.tahap == 'piezometer':
                # jika data pagi belum ada, untuk WadukDaily perlu error
                if not is_wd_exist:
                    session[
                        'err'] = "<strong style='margin-right: 10px'>P e r h a t i a n</strong>Data TMA Pagi tidak ditemukan."
                    return web.redirect('/adm/bendungan/' + table_name +
                                        '?sampling=' +
                                        inp.waktu.replace('/', '-'),
                                        absolute=True)
                obj = {}
                for f in form4_fields:
                    if inp.get(f):
                        obj.update({f: float(inp.get(f))})
                wd.set(**obj)

            return web.redirect('/adm/bendungan/' + table_name, absolute=True)

        except AttributeError:
            try:
                bendungan = [
                    a for a in AgentBd.select(AgentBd.q.AgentType == 3)
                    if a.table_name == table_name
                ][0]
                bendungan_id = bendungan.id
                print bendungan_id
            except IndexError:
                return web.notfound()
            inp = web.input()
            # memeriksa apakah record pada bendungan_id, tanggal dan jam sudah ada pada tabel 'bendung_alert'
            if inp.tahap == 'banjir':
                try:
                    ba = BendungAlert.select(
                        AND(BendungAlert.q.tanggall == to_date(inp.tanggall),
                            BendungAlert.q.bendungan == bendungan_id,
                            BendungAlert.q.jam == inp.jam))[0]
                    print ba
                    is_ba_exist = True
                except IndexError:
                    ba = None
                    is_ba_exist = False

                if inp.tahap == 'banjir':
                    obj = {
                        'bendunganID': bendungan_id,
                        'tanggall': to_date(inp.tanggall),
                        'jam': inp.jam,
                        'tmab': float(inp.tmab),
                        'spillwayb_q': float(inp.spillwayb_q)
                    }
                    if not is_ba_exist:
                        ba = BendungAlert(**obj)
                    else:
                        ba.set(**obj)
                return web.redirect('/adm/bendungan/' + table_name,
                                    absolute=True)

            if inp.tahap == 'chterkini':
                # memeriksa apakah record pada bendungan__id, tanggal dan jam sudah ada pada tabel 'curahhujan_terkini'

                try:
                    chkini = CurahHujanTerkini.select(
                        AND(
                            CurahHujanTerkini.q.tanggall == to_date(
                                inp.tanggall),
                            CurahHujanTerkini.q.bendungan == bendungan_id,
                            CurahHujanTerkini.q.jam == inp.jam))[0]
                    print chkini
                    is_chkini_exist = True
                except IndexError:
                    chkini = None
                    is_chkini_exist = False

                if inp.tahap == 'chterkini':
                    objj = {
                        'bendunganID': bendungan_id,
                        'tanggall': to_date(inp.tanggall),
                        'jam': inp.jam,
                        'ch_terkini': float(inp.ch_terkini)
                    }
                    if not is_chkini_exist:
                        chkini = CurahHujanTerkini(**objj)
                    else:
                        chkini.set(**objj)
                return web.redirect('/adm/bendungan/' + table_name,
                                    absolute=True)
예제 #7
0
 def GET(self):
     bdgs = AgentBd.select(AgentBd.q.AgentType == 3).orderBy('wilayah')
     poses = bdgs
     return render.adm.bendungan.teknis({'poses': poses})
예제 #8
0
    def GET(self):
        inp = web.input()
        try:
            pola_operasi = open('pola_operasi.txt').read()
        except:
            pola_operasi = "Basah"
        if inp.get('periode'):
            periode = to_date(inp.periode)
        else:
            periode = datetime.date.today()
        if periode.month < 11:
            periode = datetime.date(periode.year - 1, 11,
                                    1)  # 1 Nop tahun lalu
        else:
            periode = datetime.date(periode.year, 11, 1)

        tanggal = periode
        if periode.month > 10:
            tanggal = datetime.date(tanggal.year + 1, 11, 1)

        if tanggal.year <= 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=1))
                rr.append(periode.replace(day=16))
                periode += datetime.timedelta(days=jhar[i])
        if tanggal.year > 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=15))
                rr.append(periode.replace(day=jhar[i]))
                periode += datetime.timedelta(days=jhar[i])
        sql = "SELECT pos_id, waktu, po_outflow_q, po_tma, po_outflow_v, id, po_bona, po_bonb, vol_bona, vol_bonb \
                FROM waduk_daily \
                WHERE waktu IN (%s) \
                ORDER BY pos_id, waktu" % ','.join(
            ["'" + str(i) + "'" for i in rr])
        rst = conn.queryAll(sql)
        bdgs = dict([(a.AgentId, a)
                     for a in AgentBd.select(AgentBd.q.AgentType == 3)])
        bids = list(set([r[0] for r in rst]))
        data = []
        bid = 0
        row = []
        for r in rst:
            if bid != r[0]:
                bid = r[0]
                row = [{
                    'id': r[5],
                    'tma': r[3],
                    'q': r[2],
                    'v': r[4],
                    'bona': r[6],
                    'bonb': r[7],
                    'volbona': r[8],
                    'volbonb': r[9]
                }]
                data.append((r[0], row))
                continue
            row.append({
                'id': r[5],
                'tma': r[3],
                'q': r[2],
                'v': r[4],
                'bona': r[6],
                'bonb': r[7],
                'volbona': r[8],
                'volbonb': r[9]
            })
        return render.adm.bendungan.rotw({
            'data': data,
            'bendungan': bdgs,
            'periode': rr,
            'pola_operasi': pola_operasi,
            'tanggal': tanggal
        })