Exemplo n.º 1
0
def parse_opstock_content(content, drop_if=lambda row: False):
	soup = BeautifulSoup(content, 'html.parser')
	recs = RecordParser(
		records = [OrderedDict((child.name, child.text) for child in table.children) for table in soup.find_all('table1')],
		drop_if = drop_if
	)
	recs.format([('stock_qty', 0.0)])
	recs.update([('drug_nm', get_std_name), ('drug_cd', code_with_count)])
	recs.group_by(
		columns = ['drug_nm'], 
		aggset = [('stock_qty', sum, 'stock')], 
		selects = ['drug_cd', 'drug_nm', 'stock', 'stock_unit']
	)
	recs.update([('stock', lambda row: row['stock'] if int(row['stock'])!=row['stock'] else int(row['stock']) )])
	return recs.records
Exemplo n.º 2
0
def report_excel_response(invset_slugs):
	records = []
	invests = Invest.objects.filter(slug__in=invset_slugs)
	for invest in invests:
		for item in invest.investitem_set.all():
			records.append({
						'EDI코드': item.drug.edi, '판매사': item.drug.firm, '약품명': item.drug.name_as, '실사량': item.total, '규격단위': item.drug.standard_unit,
						 '재고단가': item.price, '재고구분': item.drug.invest_class, '유효기한': item.expire
					})
	recs = RecordParser(records)
	recs = recs.select(['EDI코드', '판매사', '약품명', '실사량', '규격단위', '재고단가', '재고구분', '유효기한'])
	output = recs.to_excel()
	filename = '{}.xlsx'.format(' '.join(invset_slugs))
	response = HttpResponse(output, content_type='application/vnd.ms-excel')
	response['Content-Disposition'] = 'attachment; filename='+ filename
	return response
Exemplo n.º 3
0
	def save_queryset(self, agg, detail, ord_tp, form_data):
		today = date.today().strftime('%Y-%m-%d')
		seq_list = [row['seq'] for row in self.label_history_list if row['date'] == today and row['ord_tp'] == ord_types[ord_tp]]
		seq = max(seq_list) + 1 if seq_list else 0
		queryset = []
		recs = RecordParser(detail)

		today_queryset = [history for history in self.label_history_list if history['date'] == today]
		today_subqueryset = []

		for rec in today_queryset:
			collect_seq = rec['seq'] + 1
			for row in rec['records']:
				today_subqueryset.append((collect_seq, row['sub_object_list']))

		for item in agg:
			item['sub_object_list'] = recs.select('*', where = lambda row: row['ord_cd'] == item['ord_cd'], inplace=False).order_by(['ord_ymd', 'rcpt_dt']).records
			item['duplicated'] = False
			for sub in item['sub_object_list']:
				sub['duplicated'] = 0
				for cseq, today_sub_list in today_subqueryset:

					for today_sub in today_sub_list:
						sub_dup_save = sub.pop('duplicated')
						today_sub_save = today_sub.pop('duplicated')
						if sub == today_sub:
							sub['duplicated'] = cseq
							item['duplicated'] = True
						else:	
							sub['duplicated'] = sub_dup_save
						today_sub['duplicated'] = today_sub_save

			queryset.append(item)

		log = {
			'date' : today,
			'seq': seq,
			'ord_tp': ord_types[ord_tp],
			'form_data': form_data,
			'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
			'records': queryset
		}
		self.label_history_list.append(log)
		with open(self.json_path, 'w') as fp:
			fp.write(json.dumps(self.label_history_list[-MAX_COLLECT_LENGTH:]))

		return log['records']
Exemplo n.º 4
0
    def save_drug_list(self,
                       page_start,
                       page_end,
                       categorys,
                       market_status,
                       excel=None,
                       csv=None,
                       append=False,
                       set_detail=False):
        '''	present_code = {'Y':'급여', 'N': '비급여'}
			categorys = {'E': '전문', 'O': '일반', 'Q': '의약외품'}
			market_status = {'AS': '유통/생산 중', 'AE': '유통/생산 미확인', 'AD': '유통/생산 중단'}
		'''
        if append:
            recs = read_excel(excel) if excel else read_csv(csv,
                                                            encoding='cp949')
        else:
            recs = RecordParser()

        for ctg in categorys:
            for mks in market_status:
                for npage in range(page_start, page_end):
                    try:
                        record = RecordParser(
                            self.get_all(category=ctg,
                                         market_status=mks,
                                         page=npage,
                                         set_detail=set_detail))
                    except Exception as e:
                        print("Except on", ctg, mks, npage, e)
                        break
                    if not record:
                        break
                    recs += record
                    print('{}-{}-{}'.format(ctg, mks, npage))

        recs.distinct(['drug_id'])
        if excel:
            recs.to_excel(excel)
        elif csv:
            recs.to_csv(csv)
Exemplo n.º 5
0
def get_object_list_test(start_dtime, end_dtime, kind):
    req = LabelCollectingApiRequest(API_REQ['collecting'][kind], start_dtime,
                                    end_dtime)
    req.set_test_response('response_samples/LabelCollecting.sample.rsp')
    records = req.get_records('table1')
    recs = RecordParser(records=records)

    recs.format([('tot_qty', 0)])
    recs.group_by(['drug_nm'], [('tot_qty', sum, 'agg_qty')],
                  ['drug_nm', 'drug_cd', 'agg_qty'])

    return recs.records
Exemplo n.º 6
0
def get_object_list(start_dtime, end_dtime, kind):
    req = LabelCollectingApiRequest(API_REQ['collecting'][kind], start_dtime,
                                    end_dtime)
    req.api_call()
    records = req.get_records('table1')
    recs = RecordParser(records=records)
    for row in recs:
        print(row)

    recs.format([('tot_qty', 0)])
    recs.group_by(['drug_nm'], [('tot_qty', sum, 'agg_qty'),
                                ('drug_nm', len, 'ord_cnt')],
                  ['drug_nm', 'drug_cd', 'agg_qty', 'ord_cnt'])
    return recs
Exemplo n.º 7
0
def parse_narc_content(content, n=0):
    soup = BeautifulSoup(content, 'html.parser')
    recs = RecordParser(records=[
        OrderedDict((child.name, child.text) for child in table.children)
        for table in soup.find_all('table1')
    ],
                        drop_if=lambda row: not row.get('narct_owarh_ymd') or
                        row['drug_cd'] not in drugDB or not row.get('ptnt_no'))
    recs.select([
        'narct_owarh_ymd', 'ward', 'ori_ord_ymd', 'ord_no', 'ptnt_no',
        'ptnt_nm', 'drug_cd', 'drug_nm', 'ord_qty_std', 'tot_qty'
    ],
                where=lambda row: row['ret_gb'] not in ['D/C', '반납', '수납취소'])
    recs.vlookup(drugDB.values(), 'drug_cd', 'code', [('amount', 0),
                                                      ('amount_unit', ''),
                                                      ('name', ""),
                                                      ('std_unit', "")])
    recs.format([('tot_qty', 0.0), ('ord_qty_std', 0.0)])
    recs.add_column([('잔량', lambda row: row['tot_qty'] - row['ord_qty_std']),
                     ('폐기량', lambda row: row['잔량'] * row['amount'])])
    recs.select('*', where=lambda row: row['잔량'] > 0).order_by(
        ['name', 'narct_owarh_ymd', 'ward'])
    recs.rename([('narct_owarh_ymd', '불출일자'), ('ori_ord_ymd', '원처방일자'),
                 ('ord_no', '처방번호[묶음]'), ('tot_qty', '집계량'), ('name', '폐기약품명'),
                 ('drug_cd', '약품코드'), ('amount', '집계량'),
                 ('ord_qty_std', '처방량(규격단위)'), ('drug_nm', '약품명'),
                 ('amount_unit', '폐기단위'), ('ptnt_nm', '환자명'),
                 ('ptnt_no', '환자번호'), ('std_unit', '규격단위'), ('ward', '병동')])
    table = recs.select([
        '불출일자', '병동', '환자번호', '환자명', '폐기약품명', '처방량(규격단위)', 'GET_DEPT_NM', '잔량',
        '규격단위', '폐기량', '폐기단위'
    ]).to2darry()
    grp = recs.group_by(
        columns=['폐기약품명'],
        aggset=[('폐기량', sum, '폐기량__sum'), ('폐기약품명', len, '폐기약품명__len')],
        selects=['폐기약품명', '폐기약품명__len', '규격단위', '폐기량__sum', '폐기단위'],
        inplace=False)
    for row in grp:
        row['폐기량'] = round(row['폐기량1'], 2)

    return table[n:], grp
Exemplo n.º 8
0
    def get_all(self,
                category="E",
                market_status='AS',
                page=1,
                set_detail=False):
        '''	present_code = {'Y':'급여', 'N': '비급여'}
			prodtype_code = {'E': '전문', 'O': '일반', 'Q': '의약외품'}
			market_status_code = {'AS': '유통/생산 중', 'AE': '유통/생산 미확인', 'AD': '유통/생산 중단'}
		'''

        params = {
            "Page": page,
            "prodtype": category,
            "MktStatus": market_status
        }
        r = requests.get(self.get_all_url,
                         params=params,
                         headers=self.api_headers)
        soup = BeautifulSoup(r.text, 'html.parser')
        table = soup.find('div', {'class': 'search_result_list'})

        tab_as = soup.find(id='tabAS')
        tab_ae = soup.find(id='tabAE')
        tab_ad = soup.find(id='tabAD')

        as_count = tab_as.text
        ret = []
        for row in table('li'):
            img = row.find(
                'img', {'src': re.compile(r'^/Data/DrugPictures_Small/.+$')})
            img_src = img['src'] if img else ''

            subject = row.find(class_='subject_kr')

            if not subject:
                return ret

            href = subject.a['href'] if subject.a else ''
            name = subject.a.text if subject.a else ''
            pow_yesno = '불가' if row.find(
                'span', {'class': re.compile('.*icon_crs')}) else '가능'

            cmpnt = row.find(class_='subject_eng')
            component = cmpnt.text if cmpnt else ''

            info_area = row.find(class_='info_area')
            price = info_area.find(class_='price')
            edi = info_area.find(class_='type')
            company = info_area.find(class_='company')
            present_val = info_area.find(
                'span', {'class': re.compile('.+[YNX]')})['class'][1][-1]

            present_code = {'Y': '급여', 'N': '비급여'}
            prodtype_code = {'E': '전문', 'O': '일반', 'Q': '의약외품'}
            market_status_code = {
                'AS': '유통/생산 중',
                'AE': '유통/생산 미확인',
                'AD': '유통/생산 중단'
            }

            ret.append({
                'market_status':
                market_status,
                'prod_type':
                prodtype_code.get(category),
                'img_src':
                urljoin(self.host, img_src) if img_src else '',
                'href':
                urljoin(self.host, href),
                'name':
                name,
                'component_summary':
                component,
                'company':
                company.text if company else '',
                'edi':
                edi.text if edi else '',
                'price':
                price.text.replace(',', '').replace('원', '') if price else '',
                'drug_id':
                os.path.basename(href),
                'powder_yesno':
                pow_yesno,
                'present_yesno':
                present_code.get(present_val, '산정불가')
            })

        if set_detail:
            recs_list = RecordParser(ret)
            id_list = recs_list.select(['drug_id'],
                                       inplace=False).to2darry(headers=False)
            id_list = [e[0] for e in id_list]

            with ThreadPoolExecutor(min(MAX_WORKER, len(ret))) as executor:
                details = executor.map(self.detail, id_list)

            recs_detail = RecordParser(list(details))
            recs_list.vlookup(recs_detail, 'drug_id', 'drug_id',
                              [('manufacture', ''), ('celler', ''),
                               ('pkg_info', ''), ('official_sort', ''),
                               ('components', ''), ('component_code', '')])
            print('Detail: ', len(recs_detail))
            return recs_list.records

        return ret
Exemplo n.º 9
0
def get_chemo_label_object(wards, ord_start_date, ord_end_date, start_dt,
                           end_dt):
    from recordlib import RecordParser, read_excel
    drugs_recs = read_excel(DRUG_DB_PATH)
    odr = OrderSelectApiRequest(ord_start_date, ord_end_date, wards)
    odr.api_calls()
    records = odr.get_records()
    ord_recs = RecordParser(records=records,
                            drop_if=lambda row: row.get('rcpt_dt', "") == "")

    # if real
    ord_recs.select('*', where=lambda row: start_dt <= row['rcpt_dt'] < end_dt)

    ord_recs.vlookup(drugs_recs, 'ord_cd',
                     '약품코드', [('항암제구분', '0'), ('함량1', 0.0), ('함량단위1', ''),
                              ('함량2', 0.0), ('함량단위2', '')])
    ord_recs.format([('ord_qty', 0.0), ('함량1', 0.0), ('함량2', 0.0)])
    ord_recs.add_column([('amt_vol', lambda row: row['ord_qty'] * row['함량1']),
                         ('amt_wgt', lambda row: row['ord_qty'] * row['함량2'])])

    chemo_index = ord_recs.select(['ord_ymd', 'rcpt_seq', 'medi_no', 'ord_no'],
                                  where=lambda row: row['항암제구분'] == '1',
                                  inplace=False).to2darry(headers=False)
    ord_recs.select('*',
                    where=lambda r: [
                        r['ord_ymd'], r['rcpt_seq'], r['medi_no'], r['ord_no']
                    ] in chemo_index)
    detail = ord_recs.records.copy()
    f, l = ord_recs.min('rcpt_dt'), ord_recs.max('rcpt_dt')
    ord_recs.group_by(columns=['ord_ymd', 'rcpt_seq', 'medi_no', 'ord_cd'],
                      aggset=[('amt_vol', sum, 'amt_vol_sum'),
                              ('amt_wgt', sum, 'amt_wgt_sum'),
                              ('ord_qty', sum, 'ord_qty_sum'),
                              ('drug_nm', len, 'drug_nm_count')],
                      selects=[
                          'ord_cd', 'drug_nm', 'ord_unit_nm', 'amt_vol_sum',
                          'amt_wgt_sum', 'ord_qty_sum', '함량단위1', '함량단위2',
                          'drug_nm_count'
                      ],
                      inplace=True)
    ord_recs.add_column([('rcpt_dt_min', lambda x: f),
                         ('rcpt_dt_max', lambda x: l)])
    return ord_recs.records, detail


# path  = 'C:\\Users\\user\\Desktop\\집계표.xlsx'
# ret = get_label_object(['P', 'S'], ['51', '52', '61', '71', '81', '92', 'IC'], '2017-04-09','2017-04-10', '2017-04-08 00:00:00', '2017-04-08 23:23:00')
# ret.to_excel(path)
# os.startfile(path)

# get_label_object_test(['P', 'S'], ['51', '52', '61', '71', '81', '92', 'IC'], '2017-04-09','2017-04-10', '2017-04-08 00:00:00', '2017-04-08 23:23:00')
Exemplo n.º 10
0
def get_chemo_label_object_test(wards, ord_start_date, ord_end_date, start_dt,
                                end_dt):
    from recordlib import RecordParser, read_excel
    drugs_recs = read_excel(DRUG_DB_PATH)
    odr = OrderSelectApiRequest(ord_start_date, ord_end_date, wards)
    odr.set_test_response('response_samples/ordSelect51.sample.rsp')
    records = odr.get_records()
    ord_recs = RecordParser(records=records,
                            drop_if=lambda row: row.get('rcpt_dt', "") == "")

    # if real
    # ord_recs.select('*', where= lambda row: start_dt <= row['rcpt_dt'] < end_dt)

    ord_recs.vlookup(drugs_recs, 'ord_cd',
                     '약품코드', [('항암제구분', '0'), ('함량1', 0.0), ('함량단위1', ''),
                              ('함량2', 0.0), ('함량단위2', '')])
    ord_recs.format([('ord_qty', 0.0), ('함량1', 0.0), ('함량2', 0.0)])
    ord_recs.add_column([('amt_vol', lambda row: row['ord_qty'] * row['함량1']),
                         ('amt_wgt', lambda row: row['ord_qty'] * row['함량2'])])

    chemo_index = ord_recs.select(['ord_ymd', 'rcpt_seq', 'medi_no', 'ord_no'],
                                  where=lambda row: row['항암제구분'] == '1',
                                  inplace=False).to2darry(headers=False)
    ord_recs.select('*',
                    where=lambda r: [
                        r['ord_ymd'], r['rcpt_seq'], r['medi_no'], r['ord_no']
                    ] in chemo_index)
    detail = ord_recs.records.copy()
    f, l = ord_recs.min('rcpt_dt'), ord_recs.max('rcpt_dt')
    ord_recs.group_by(columns=['ord_ymd', 'rcpt_seq', 'medi_no', 'ord_cd'],
                      aggset=[('amt_vol', sum, 'amt_vol_sum'),
                              ('amt_wgt', sum, 'amt_wgt_sum'),
                              ('ord_qty', sum, 'ord_qty_sum'),
                              ('drug_nm', len, 'drug_nm_count')],
                      selects=[
                          'ord_cd', 'drug_nm', 'ord_unit_nm', 'amt_vol_sum',
                          'amt_wgt_sum', 'ord_qty_sum', '함량단위1', '함량단위2',
                          'drug_nm_count'
                      ],
                      inplace=True)
    ord_recs.add_column([('rcpt_dt_min', lambda x: f),
                         ('rcpt_dt_max', lambda x: l)])
    return ord_recs.records, detail
Exemplo n.º 11
0
def get_inj_object(types,
                   wards,
                   ord_start_date,
                   ord_end_date,
                   start_dt,
                   end_dt,
                   test=False):
    from recordlib import RecordParser, read_excel
    drug_db_recs = read_excel(
        DRUG_DB_PATH,
        drop_if=lambda row: row['투여경로'] != '3' or row['효능코드명'] in
        ['혈액대용제', '당류제'] or row['항암제구분'] == '1' or row['약품법적구분'] in ['1', '2'])
    pk_set = drug_db_recs.unique('약품코드')
    odr = OrderSelectApiRequest(ord_start_date, ord_end_date, wards)

    if test:
        odr.set_test_response('response_samples/ordSelect51.sample.rsp')
    else:
        odr.api_calls()

    ord_recs = RecordParser(
        records=odr.get_records(),
        drop_if=lambda row: row.get('ord_cd') not in pk_set or row.get(
            'rcpt_dt', "") == "" or row.get('rcpt_ord_tp_nm') not in types)
    ord_recs.format([('ord_qty', 0.0), ('ord_frq', 0), ('ord_day', 0)])
    if not test:
        ord_recs.select('*',
                        where=lambda row: start_dt <= row['rcpt_dt'] < end_dt)

    ord_recs.add_column([
        ('once_amt', lambda row: round(row['ord_qty'] / row['ord_frq'], 2)),
        ('total_amt', lambda row: row['ord_qty'] * row['ord_day'])
    ])

    detail = ord_recs.records.copy()
    f, l = ord_recs.min('rcpt_dt'), ord_recs.max('rcpt_dt')
    ord_recs.group_by(columns=['ord_cd'],
                      aggset=[('ord_qty', sum, 'ord_qty_sum'),
                              ('drug_nm', len, 'drug_nm_count'),
                              ('total_amt', sum, 'total_amt_sum')],
                      selects=[
                          'ord_cd', 'drug_nm', 'ord_qty_sum', 'ord_unit_nm',
                          'drug_nm_count', 'total_amt_sum'
                      ])
    ord_recs.add_column([('rcpt_dt_min', lambda x: f),
                         ('rcpt_dt_max', lambda x: l)])
    return ord_recs.records, detail
Exemplo n.º 12
0
def get_label_object(kinds, types, wards, ord_start_date, ord_end_date,
                     start_dt, end_dt):
    from recordlib import RecordParser, read_excel
    try:
        drug_db_recs = get_label_list()
        drug_db_recs = RecordParser(
            drug_db_recs, drop_if=lambda row: row['단일포장구분'] not in ['S', 'P'])
    except:
        drug_db_recs = read_excel(
            DRUG_DB_PATH, drop_if=lambda row: row['단일포장구분'] not in ['S', 'P'])

    pk_set = drug_db_recs.unique('약품코드')
    odr = OrderSelectApiRequest(ord_start_date, ord_end_date, wards)
    odr.api_calls()
    records = odr.get_records()
    ord_recs = RecordParser(
        records=records,
        drop_if=lambda row: row.get('ord_cd') not in pk_set or row.get(
            'rcpt_dt', "") == "" or row.get('rcpt_ord_tp_nm') not in types)

    ord_recs.vlookup(drug_db_recs, 'ord_cd', '약품코드', [('단일포장구분', 'S')])
    ord_recs.format([('ord_qty', 0.0), ('ord_frq', 0), ('ord_day', 0)])

    ord_recs.select('*', where=lambda row: start_dt <= row['rcpt_dt'] < end_dt)
    ord_recs.add_column([
        ('once_amt', lambda row: round(row['ord_qty'] / row['ord_frq'], 2)),
        ('total_amt', lambda row: row['ord_qty'] * row['ord_day'])
    ])
    detail = ord_recs.records.copy()
    f, l = ord_recs.min('rcpt_dt'), ord_recs.max('rcpt_dt')

    ord_recs.group_by(columns=['단일포장구분', 'drug_nm'],
                      aggset=[('ord_qty', sum, 'ord_qty_sum'),
                              ('drug_nm', len, 'drug_nm_count'),
                              ('total_amt', sum, 'total_amt_sum')],
                      selects=[
                          '단일포장구분', 'ord_cd', 'drug_nm', 'ord_qty_sum',
                          'ord_unit_nm', 'drug_nm_count', 'total_amt_sum'
                      ])
    ord_recs.add_column([('rcpt_dt_min', lambda x: f),
                         ('rcpt_dt_max', lambda x: l)])
    ord_recs.value_map([('단일포장구분', {'S': '작은라벨', 'P': '큰라벨'}, '')])
    return ord_recs.records, detail