def _convert_consinco_to_plataform(self): res = apps.result_dict() pk_charge = 0 try: self.carrier_list = [] self.product_list = [] self.product_similar_list = [] self.carrier_product_list = [] data = None fk_carriers = '' for index, row in self.df.iterrows(): # insert a charge if pk_charge != row['nrocarga']: pk_charge, fk_carriers = self._get_carrier_to_list(row) # check if products already registered and if it is updated self._get_product_to_list(row) self._get_product_similar_to_list(row) self._get_carrier_product_to_list(row, fk_carriers) self.save_bulk_data(self.carrier_list, Carriers) self.save_bulk_data(self.product_list, Products) self.save_bulk_data(self.product_similar_list, ProductsSimilar) self.save_bulk_data(self.carrier_product_list, CarriersProducts) self.df = None except Exception as e: res = apps.result_dict() res['status']['sttCode'] = 500 res['status']['sttMsgs'] = f'Erro ao gravar os cargas da plataforma! - ({e})' if res['status']['sttCode'] != 200: return res return res
def check_changes(self, request, *args, **kwargs): """ check Changes to display boxes stored on databses """ self.result = apps.result_dict() car_id = request.query_params.get('car_id') display_id = request.query_params.get('display_id') fk_display = display_id.replace('e', '') date_hour = datetime.now(tz=timezone.utc) - timedelta( hours=0, minutes=1, seconds=0) try: for msg in CarBoxesMessage.objects.filter( fk_cars=car_id, fk_car_boxes=int(fk_display), flag_captured=0, capture_date__gt=date_hour): self.result['data'].append(self._get_message_dictionary(msg)) msg.flag_captured = 1 msg.capture_date = datetime.now(tz=timezone.utc) msg.save() except Exception as e: self.result['status']['sttCode'] = 500 self.result['status'][ 'sttMsgs'] = f'Erro ao buscar as mensagens: {e}' # HOw to return this message? return Response(self.result, self.result['status']['sttCode'])
def _save_charge_products(self) -> dict: res = apps.result_dict() res['result_to'] = self.df.shape[0] try: data = None list_of_data = [] last_data = None for index, row in self.df.iterrows(): data = CargasProdutos(**row) list_of_data.append(data) if len(list_of_data) > 15: self.save_bulk_data(list_of_data, CargasProdutos) last_data = list_of_data[-1] list_of_data = [] # data.save() if len(list_of_data) > 0: self.save_bulk_data(list_of_data, CargasProdutos) last_data = list_of_data[-1] if last_data is not None: last_data.save() reg = LastCharge( pk_last_charge=last_data.nrocarga, fk_cargas_produtos_id=last_data.pk_cargas_produtos, fk_company=last_data.nroempresa, num_lot=last_data.seqlote, fk_product=last_data.seqproduto, fk_customer=last_data.seqpessoa, date_last_charge=timezone.now() ) reg.save() except Exception as e: res['status']['sttCode'] = 500 res['status']['sttMsgs'] = f'Erro: ao salvar o Data Frame - {e}' return res
def get(self, request, *args, **kwargs): type_test = kwargs.get('type') apps.CAR_ID = kwargs.get('car_id') base_dir = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) header = os.path.join(base_dir, 'templates/home/http_header.html') footer = os.path.join(base_dir, 'templates/home/http_footer.html') with open(header, "r") as fd: header = fd.read() fd.close() with open(footer, "r") as fd: footer = fd.read() fd.close() apps.CAR_PREPARED = 1 apps.CAR_COLLECT_PRODUCTS = 1 apps.USER_NAME = request.user.username res = apps.result_dict() if type_test not in ['load_boxes', 'get_charges', 'generate_boxes']: res['status']['sttCode'] = 404 res['status'][ 'sttMsg'] = 'Type param must be "load_boxes" or "get_charges"' res_str = str(res) html = f'{header}\n<pre>\n{res_str}\n</pre>\n{footer}' return HttpResponse(html) pdc = ProductDataControl() df = None if type_test == 'generate_boxes': res, df = pdc.load_boxes_from_operator() elif type_test == 'load_boxes': if pdc.get_allocation_boxes(): res['status']['sttCode'] = 200 res['status']['sttMsgs'] = 'Ok... Caçambas Alocadas!' else: res['status']['sttCode'] = 404 res['status'][ 'sttMsgs'] = 'Caçambas ainda não foram alocadasAlocadas!' css_classes = 'table table-striped' res_str = str(res) if df is None: html = f'{header}\n<pre>\n{res_str}\n</pre>\n{footer}' return HttpResponse(html) else: header += f'<pre>{res_str}</pre>\n' # return HttpResponse(header + df.to_html(classes=css_classes, float_format='%.4f', decimal=',') + footer) return HttpResponse(header + df.to_html(classes=css_classes, decimal=',') + footer)
def load_boxes_from_operator(self): def dictfetchall(qry_cursor): """ Return all rows from a cursor as a dict """ columns = [col[0] for col in qry_cursor.description] return [ dict(zip(columns, qry_row)) for qry_row in qry_cursor.fetchall() ] products_query = """ select icr.flag_type_line, icr.charge, icr.lot, icr.fk_customer, ipr.pk_products, ipr.dsc_prod, icp.street, icp.tower, icp.side, icp.qtd_packing , icp.qtd_order, icp.qtd_collected, icp.unity, icp.stock, icp.weight_prod, icp.volume_prod, icr.flag_status, icp.level, icp.position, icr.volume_charge, icr.weight_charge, icr.flag_ready, icr.flag_conference from icity_carriers icr, icity_carriers_products icp, icity_products ipr where icr.flag_status = 'L' and icr.flag_ready = 0 and icr.flag_conference = 0 and icp.fk_carriers_id = icr.pk_carriers and ipr.pk_products = icp.fk_products_id order by icr.flag_type_line, icr.charge, icr.lot, icr.fk_customer, ipr.pk_products """ res = apps.result_dict() try: cursor = connection.cursor() cursor.execute(products_query) result = dictfetchall(cursor) self.df = pd.DataFrame(result) except Exception as e: res['status']['sttCode'] = 500 res['status']['sttMsgs'] = f'Erro ao ler o banco de dados: {e}' finally: cursor.close() if res['status']['sttCode'] != 200: return res, None # res = self._filter_user_product() self.CAR_BOXES = self._load_boxes() if len(self.CAR_BOXES) > 0: self._set_boxes_charge() self.df = self.df[self.df['box_id'] != ''] self.df.reset_index(inplace=True) self.df = self.df.groupby(Cmp.SEPARATION_SORT).first().copy() return res, self.df
def authenticate_user(self, username=None, password=None): self.flag_ins = False res = apps.result_dict() username = username if username else self.username password = password if password else self.password user = authenticate(username=username, password=password) if not user: try: api.set_end_points({'login': f'/{self.HTTP_API_GET_OPERATOR}/{username}'}) res = api.get_data('login') if res['status']['sttCode'] == 200: res = res['data'] if len(res['records']) > 0 and str(res['records'][0]['codprodutivo']) == password: self.flag_ins = True except Exception as e: res['status']['sttCode'] = 500 res['status']['sttMsgs'] = f'Erro ao ler os dados do usuário no E.R.P. - {e}' return res res['user'] = user return res
def get_data(self, api_name: str, **params) -> dict: def check_params(api_url: str): for param in params: if api_url.find('{' + param + '}') < 0: return False return True result = result_dict() if api_name not in self.END_POINTS: result['status']['sttCode'] = 404 result['status'][ 'sttMsgs'] = f'Error: Entry point for api {api_name} not found!' return result check = CheckHost() host = check.check_hosts() if not host: result['status']['sttCode'] = 404 result['status']['sttMsgs'] = 'Error: Host(s) not found!' return result end_point = self.END_POINTS[api_name].format(**params) \ if len(params) > 0 and check_params(self.END_POINTS[api_name]) \ else self.END_POINTS[api_name] url = f'{self.proto}://{host}:{self.port}{end_point}' # mount URL result['url'] = url headers = {'Content-Type': 'application/json'} try: response = requests.get(url, headers=headers) result['status']['sttCode'] = response.status_code result['data'] = json.loads(response.content.decode('utf-8')) except Exception as e: result['status']['sttCode'] = 500 result['status']['sttMsgs'] = \ f'Error on API {api_name} ({url}) to load products from ERP: [{e}]' return result
def _filter_user_product(self): res = apps.result_dict() # Get all users permissions permissions = UsersOperatorsPermissions.objects.filter( pk__startswith=apps.USER_NAME ) for perm in permissions: if perm.flag_status == 'A': apps.USER_PERMISSIONS.append(perm.type_line) if len(apps.USER_PERMISSIONS) == 0: res['status']['sttCode'] = 404 res['status']['sttMsgs'] = 'Usuário não possui atividades!' return res # Filter users permissions from data self.df = self.df[self.df['flag_type_line'].isin(apps.USER_PERMISSIONS)] sp = self.df.shape if sp[0] < 1: res['status']['sttCode'] = 404 res['status']['sttMsgs'] = 'Usuário não possui atividades nas cargas selecionadas' return res return res