у арм3 вечно идет "процесс идет" в статусе и импульсы в sparkline , нужно сделать чтобы импульс был один при запуске arm3 скрипта activationglaz.py
скрипт
import subprocess
import time
import re
import xml.etree.ElementTree as ET
import requests
import logging
import threading
import glob
import os
from datetime import datetime
Paths and constants
ADB_PATH = "/usr/bin/adb"
TELEGRAM_BOT_TOKEN = "7033736801:AAGh-gPCffmyfU5MnxOgTj5JLUGISpmkBM0" # Replace with your bot's token
TELEGRAM_CHAT_ID = "-1007260008005" # Replace with your Telegram chat ID
PACKAGE_NAME = 'com.autel.maxlink'
PATH_GLAZ = "/home/moon/apk640/glaz.apk"
PATH_SUNDOFF = "/home/moon/apk640/SoundOFF.apk"
PATH_PDF = "/home/moon/apk640/Google_PDF_Viewer.apk"
PATH_640T = "/home/moon/apk640/640T.apk"
PATH_INSTRUCTION = "/home/moon/apk640/manual.apk"
def is_connected():
"""Checks if there is a network connection."""
try:
# Attempt to connect to the Flask server
requests.get(FLASK_SERVER_URL, timeout=5)
return True
except requests.ConnectionError:
return False
def update_device_status(processing_status, internet_up):
"""Updates the device status on the server."""
data = {
'worker_name': worker_name,
'processing': processing_status,
'internet_up': internet_up,
}
try:
response = requests.post(
f"{FLASK_SERVER_URL}/register_user",
json=data,
headers={'Content-Type': 'application/json'}
)
if response.status_code == 200:
logger.info(f"Updated device status: processing={processing_status}, internet_up={internet_up}")
else:
logger.error(f"Error updating device status: {response.status_code}")
except Exception as e:
logger.error(f"Exception updating device status: {e}")
def send_heartbeat():
"""Sends periodic updates to the server during processing."""
while processing:
internet_up = is_connected()
update_device_status(True, internet_up=internet_up)
time.sleep(5) # Adjust the interval as needed
Assistant
def run_adb_command(command):
"""Executes an ADB command and returns the output."""
try:
result = subprocess.run([ADB_PATH] + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
return result.stdout
except subprocess.CalledProcessError as e:
logger.error(f"Error executing adb {' '.join(command)}: {e.stderr}")
return None
def get_sn_devices():
"""Returns a list of connected device serial numbers."""
output = run_adb_command(['devices', '-l'])
if not output:
logger.error("No output from 'adb devices -l' command.")
return []
devices = []
lines = output.strip().split('\n')
for line in lines[1:]: # Skip the first line 'List of devices attached'
if line.strip() == '':
continue
parts = line.strip().split()
if 'device' in parts:
SN = parts[0]
if SN != 'XSP12345678':
devices.append(SN)
return devices
def install_apk(SN):
"""Installs the APK on the device."""
logger.info(f"Installing APK on device {SN}...")
output = run_adb_command(['-s', SN, 'install', '-r', PATH_GLAZ])
if output:
logger.info(f"APK successfully installed on device {SN}.")
return True
else:
logger.error(f"Failed to install APK on device {SN}.")
return False
def grant_manage_external_storage_permission(SN, package_name):
"""Grants MANAGE_EXTERNAL_STORAGE permission to the application."""
logger.info(f"Granting MANAGE_EXTERNAL_STORAGE permission to {package_name} on device {SN}...")
output = run_adb_command(['-s', SN, 'shell', 'appops', 'set', package_name, 'MANAGE_EXTERNAL_STORAGE', 'allow'])
if output is not None:
logger.info(f"MANAGE_EXTERNAL_STORAGE permission granted to {package_name} on device {SN}.")
else:
logger.error(f"Failed to grant MANAGE_EXTERNAL_STORAGE permission to {package_name} on device {SN}.")
def get_ui_dump(SN):
"""Gets the UI hierarchy dump and saves it to a file for analysis."""
run_adb_command(['-s', SN, 'shell', 'uiautomator', 'dump', '/sdcard/ui_dump.xml'])
run_adb_command(['-s', SN, 'shell', 'chmod', '666', '/sdcard/ui_dump.xml'])
ui_dump = run_adb_command(['-s', SN, 'shell', 'cat', '/sdcard/ui_dump.xml'])
if ui_dump:
with open(f'ui_dump_{SN}.xml', 'w', encoding='utf-8') as f:
f.write(ui_dump)
logger.info(f"UI dump saved to file 'ui_dump_{SN}.xml' for device {SN}.")
return ui_dump
def parse_device_id(ui_dump):
"""Extracts Device ID from the UI hierarchy dump."""
try:
root = ET.fromstring(ui_dump)
except ET.ParseError as e:
logger.error(f"Error parsing UI dump: {e}")
return None
device_id = None
# Search
for node in root.iter('node'):
text = node.attrib.get('text', '')
for pattern in PATTERNS:
match = pattern.match(text)
if match:
device_id = match.group(1)
logger.info(f"Found Device id: {device_id}")
return device_id
logger.warning("Device id not found in UI dump.")
return device_id
def approve_device(device_id):
"""Sends a request to register the device and returns the API response."""
headers = {
"Content-Type": "application/json",
"token": API_TOKEN
}
data = {
"deviceId": device_id
}
try:
response = requests.post(API_URL, headers=headers, json=data)
logger.info(f"API Response Status Code: {response.status_code}")
logger.info(f"API Response Body: {response.text}")
response.raise_for_status()
try:
return response.json()
except ValueError:
# If response is not JSON, return text as message
logger.warning("API response is not JSON. Handling as text message.")
return {'message': response.text}
except requests.exceptions.HTTPError as errh:
logger.error(f"HTTP Error: {errh}")
except requests.exceptions.ConnectionError as errc:
logger.error(f"Connection Error: {errc}")
except requests.exceptions.Timeout as errt:
logger.error(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
logger.error(f"An error occurred: {err}")
return None
def send_message_via_bot(message):
"""Sends a message to a Telegram group via the bot."""
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
payload = {
'chat_id': TELEGRAM_CHAT_ID,
'text': message
}
try:
response = requests.post(url, json=payload)
response.raise_for_status()
result = response.json()
if result.get("ok"):
logger.info("Message successfully sent via bot.")
else:
logger.error(f"Error sending message: {result}")
logger.error(f"Error description: {result.get('description')}")
except requests.exceptions.HTTPError as errh:
logger.error(f"HTTP Error: {errh}")
try:
error_details = response.json()
logger.error(f"Error description from Telegram: {error_details}")
except:
pass
except requests.exceptions.ConnectionError as errc:
logger.error(f"Connection Error: {errc}")
except requests.exceptions.Timeout as errt:
logger.error(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
logger.error(f"Request error: {err}")
def main_process(SN):
"""Main process for device registration and confirmation."""
global processing # Declare as global to modify the global variable
processing = True # Start processing
try:
internet_up = is_connected()
update_device_status(True, internet_up=internet_up)
if not internet_up:
logger.warning("No network connection. Waiting for network...")
return # Exit if no network
# Start heartbeat thread
heartbeat_thread = threading.Thread(target=send_heartbeat, daemon=True)
heartbeat_thread.start()
# Your existing main process code
run_adb_command(['-s', SN, 'root'])
# Change language
run_adb_command(['-s', SN, 'shell', 'setprop', 'persist.sys.locale', 'ru-RU'])
run_adb_command(['-s', SN, 'shell', 'setprop', 'ctl.restart', 'zygote'])
time.sleep(15)
run_adb_command(['-s', SN, 'wait-for-device'])
# Disable GPS
run_adb_command(['-s', SN, 'shell', 'settings', 'put', 'secure','location_mode','0'])
# Set night mode
run_adb_command(['-s', SN, 'shell', 'su', '0', 'cmd','uimode','night', 'yes'])
# Disable Wi-Fi
run_adb_command(['-s', SN, 'shell', 'svc', 'wifi', 'disable'])
# Sound OFF
run_adb_command(['-s', SN, 'install', '-r', PATH_SUNDOFF])
time.sleep(1)
run_adb_command(['-s', SN, 'shell', 'am', 'start', '-n','com.rannsoft.soundoff/.MainActivity'])
time.sleep(1)
run_adb_command(['-s', SN, 'shell', 'pm', 'uninstall', 'com.rannsoft.soundoff'])
time.sleep(1)
# Install PDF viewer
run_adb_command(['-s', SN, 'install', '-r', PATH_PDF])
# Set screen brightness
run_adb_command(['-s', SN, 'shell', 'settings', 'put', 'system', 'screen_brightness', '20'])
# Remove stock UAV apps
run_adb_command(['-s', SN, 'shell', 'pm', 'clear', 'com.autelrobotics.explorer'])
run_adb_command(['-s', SN, 'shell', 'pm', 'clear', 'com.autelrobotics.explorer.extended'])
run_adb_command(['-s', SN, 'shell', 'pm', 'clear', 'com.autelrobotics.explores'])
run_adb_command(['-s', SN, 'shell', 'pm', 'clear', 'com.autel.maxlink'])
run_adb_command(['-s', SN, 'shell', 'pm', 'uninstall', '--user', '0', 'com.autelrobotics.explorer'])
run_adb_command(['-s', SN, 'shell', 'pm', 'uninstall', '--user', '0', 'com.autelrobotics.explorer.extended'])
run_adb_command(['-s', SN, 'shell', 'pm', 'uninstall', '--user', '0', 'com.autelrobotics.explores'])
run_adb_command(['-s', SN, 'shell', 'pm', 'uninstall', '--user', '0', 'com.autel.maxlink'])
run_adb_command(['-s', SN, 'shell', 'pm', 'disable-user', '--user', '0', 'com.autelrobotics.explorer'])
run_adb_command(['-s', SN, 'shell', 'pm', 'disable-user', '--user', '0', 'com.autelrobotics.explorer.extended'])
run_adb_command(['-s', SN, 'shell', 'pm', 'disable-user', '--user', '0', 'com.autelrobotics.explores'])
run_adb_command(['-s', SN, 'shell', 'pm', 'disable-user', '--user', '0', 'com.autel.maxlink'])
# Install 640T
run_adb_command(['-s', SN, 'install', '-r', PATH_640T])
# Grant permissions to UAV
run_adb_command(['-s', SN, 'shell', 'pm', 'grant', 'com.autelrobotics.explorer.extended', 'android.permission.READ_PHONE_STATE'])
run_adb_command(['-s', SN, 'shell', 'pm', 'grant', 'com.autelrobotics.explorer.extended', 'android.permission.ACCESS_COARSE_LOCATION'])
run_adb_command(['-s', SN, 'shell', 'pm', 'grant', 'com.autelrobotics.explorer.extended', 'android.permission.ACCESS_FINE_LOCATION'])
run_adb_command(['-s', SN, 'shell', 'pm', 'grant', 'com.autelrobotics.explorer.extended', 'android.permission.READ_EXTERNAL_STORAGE'])
run_adb_command(['-s', SN, 'shell', 'pm', 'grant', 'com.autelrobotics.explorer.extended', 'android.permission.WRITE_EXTERNAL_STORAGE'])
run_adb_command(['-s', SN, 'shell', 'pm', 'grant', 'com.autelrobotics.explorer.extended', 'android.permission.RECORD_AUDIO'])
# Install APK on device
installed = install_apk(SN)
if not installed:
send_message_via_bot(f"Ошибка: Не удалось установить APK на устройство {SN}.")
return
# Install instruction
run_adb_command(['-s', SN, 'install', '-r', PATH_INSTRUCTION])
run_adb_command(['-s', SN, 'shell', 'am', 'start', '-a', 'android.intent.action.MAIN','-n', 'com.example.myapplication/.MainActivity'])
time.sleep(3)
run_adb_command(['-s', SN, 'shell', 'input', 'tap', '1140', '840'])
time.sleep(2)
run_adb_command(['-s', SN, 'shell', 'input', 'tap', '670', '1290'])
time.sleep(2)
run_adb_command(['-s', SN, 'shell', 'input', 'tap', '1362', '1373'])
time.sleep(4)
# Animation setup
run_adb_command(['-s', SN, 'root'])
run_adb_command(['-s', SN, 'remount'])
run_adb_command(['-s', SN, 'push', '/home/moon/Desktop/BAT/bootanimation.zip', 'system/media/bootanimation.zip'])
# Grant permissions to com.autel.maxlink
run_adb_command(['-s', SN, 'shell', 'pm', 'grant', 'com.autel.maxlink', 'android.permission.READ_PHONE_STATE'])
run_adb_command(['-s', SN, 'shell', 'pm', 'grant', 'com.autel.maxlink', 'android.permission.ACCESS_COARSE_LOCATION'])
run_adb_command(['-s', SN, 'shell', 'pm', 'grant', 'com.autel.maxlink', 'android.permission.ACCESS_FINE_LOCATION'])
run_adb_command(['-s', SN, 'shell', 'pm', 'grant', 'com.autel.maxlink', 'android.permission.READ_EXTERNAL_STORAGE'])
run_adb_command(['-s', SN, 'shell', 'pm', 'grant', 'com.autel.maxlink', 'android.permission.WRITE_EXTERNAL_STORAGE'])
run_adb_command(['-s', SN, 'shell', 'pm', 'grant', 'com.autel.maxlink', 'android.permission.RECORD_AUDIO'])
# Icon setup
run_adb_command(['-s', SN, 'shell', 'input', 'swipe', '1040', '1519', '1037', '1148', '500'])
run_adb_command(['-s', SN, 'shell', 'input', 'tap', '1027', '1528'])
run_adb_command(['-s', SN, 'shell', 'input', 'swipe', '1045', '620', '950', '258', '50'])
run_adb_command(['-s', SN, 'shell', 'input', 'swipe', '660', '251', '700', '280', '1800'])
run_adb_command(['-s', SN, 'shell', 'input', 'swipe', '1045', '620', '950', '258', '50'])
run_adb_command(['-s', SN, 'shell', 'input', 'swipe', '660', '500', '720', '560', '1800'])
run_adb_command(['-s', SN, 'shell', 'input', 'swipe', '1045', '620', '950', '258', '50'])
run_adb_command(['-s', SN, 'shell', 'input', 'swipe', '1035', '233', '1055', '333', '2500'])
# Grant MANAGE_EXTERNAL_STORAGE permission
grant_manage_external_storage_permission(SN, PACKAGE_NAME)
# Start application on device
logger.info(f"Starting application on device {SN}...")
run_adb_command(['-s', SN, 'shell', 'am', 'start', '-n', f'{PACKAGE_NAME}/.MainActivity'])
time.sleep(5) # Wait for the application to start
# Get UI dump
logger.info(f"Getting UI dump from device {SN}...")
ui_dump = get_ui_dump(SN)
if not ui_dump:
logger.error("Failed to get UI dump.")
send_message_via_bot("Ошибка: Не удалось получить дамп UI-иерархии.")
return
# Parse Device ID
logger.info("Searching for Device ID...")
device_id = parse_device_id(ui_dump)
if not device_id:
logger.error("Failed to find Device ID.")
send_message_via_bot("Ошибка: Не удалось найти Device ID.")
return
# Send Device ID to API for registration
logger.info("Sending Device ID to API for registration...")
api_response = approve_device(device_id)
if api_response:
confirmation_message = api_response.get('message', f"Устройство с ID {device_id} успешно зарегистрировано!")
send_message_via_bot(confirmation_message)
else:
logger.error("An error occurred during device registration via API.")
send_message_via_bot(f"Ошибка: Не удалось зарегистрировать устройство с ID {device_id}.")
finally:
processing = False # Stop the heartbeat thread
internet_up = is_connected()
update_device_status(False, internet_up=internet_up)
# Turn off the screen
logger.info(f"Turning off screen on device {SN}...")
run_adb_command(['-s', SN, 'shell', 'input', 'tap', '977', '740'])
run_adb_command(['-s', SN, 'shell', 'input', 'tap', '927', '1057'])
run_adb_command(['-s', SN, 'shell', 'input', 'tap', '1960', '1035'])
run_adb_command(['-s', SN, 'shell', 'input', 'tap', '1035', '863'])
run_adb_command(['-s', SN, 'shell', 'input', 'keyevent', '26'])
# Prepare data to send to Flask server
arma_type = 'SRC'
string = SN
# Get current date and time
current_datetime = datetime.now()
selected_date = datetime.now().strftime("%Y-%m-%d")
# Send data to Flask server
data = {
'date': selected_date,
'serial': string if string else "Не получен",
'worker_name': worker_name,
'timestamp': current_datetime.strftime("%Y-%m-%d %H:%M:%S"),
'arma_type': arma_type,
}
try:
headers = {
'Content-Type': 'application/json'
}
response = requests.post(
f"{FLASK_SERVER_URL}/update_table",
json=data,
headers=headers
)
if response.status_code == 200:
response_data = response.json()
if response_data.get('status') == 'success':
logger.info(f"Data successfully sent to server for date {selected_date}")
else:
logger.error(f"Server error: {response_data.get('message', 'Unknown error')}")
else:
logger.error(f"Failed to send data to server. Status code: {response.status_code}")
except Exception as e:
logger.error(f"Error sending data to server: {e}")
if name == "main":
logger.info("Getting list of connected devices...")
SN_list = get_sn_devices()
if not SN_list:
logger.error("No connected devices found.")
else:
# Process all devices
threads = []
for SN in SN_list:
logger.info(f"Processing device {SN}...")
thread = threading.Thread(target=main_process, args=(SN,))
thread.start()
threads.append(thread)
logger.info("Waiting for all device processing threads to finish...")
for thread in threads:
thread.join()
logger.info("All device processing completed.")
# Clean up UI dump files
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
pattern = os.path.join(desktop_path, "ui_dump_*")
for file_path in glob.glob(pattern):
try:
os.remove(file_path)
except Exception as e:
logger.error(f"Failed to remove file {file_path}: {e}")
from flask import Flask, render_template, request, redirect, make_response, jsonify, send_file, Response
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
from datetime import datetime, timedelta, date
import pandas as pd
from io import BytesIO
import json
import queue
import logging
from sqlalchemy import cast, Integer, or_
import os
from collections import deque
import random
app = Flask(name)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///table_data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
ACTIVITY_HISTORY_LENGTH = 400 # Количество последних значений для графика
activity_data = {}
class TableRow(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.String(10), nullable=False)
row_number = db.Column(db.String(10))
timestamp = db.Column(db.String(50))
number = db.Column(db.String(50))
serial = db.Column(db.String(50))
dl_number = db.Column(db.String(50))
worker_name = db.Column(db.String(100))
pack_time = db.Column(db.String(50))
arma_type = db.Column(db.String(50))
class DLCounter(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.String(10), unique=True, nullable=False)
counter = db.Column(db.Integer, nullable=False)
Добавьте это в раздел моделей вашего Flask-приложения
class Device(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(10), unique=True, nullable=False) # Имена: ARM1, ARM2 и т.д.
arma_type = db.Column(db.String(10), nullable=False, default='Other') # Тип АРМА
last_active = db.Column(db.DateTime, nullable=True) # Время последней активности
internet_up = db.Column(db.Boolean, nullable=False, default=True) # Статус интернет-соединения
copying = db.Column(db.Boolean, nullable=False, default=False) # Статус копирования
previous_copying = db.Column(db.Boolean, nullable=False, default=False) # Новое поле
sending_number = db.Column(db.Boolean, nullable=False, default=False) # Статус отправки номера
processing = db.Column(db.Boolean, nullable=False, default=False) # Новое поле для активности activationGlaz.py
def to_dict(self, current_time=None):
if current_time is None:
current_time = datetime.utcnow()
if self.copying:
status = 'copying'
elif self.sending_number:
status = 'sending_number'
else:
status = 'offline'
if self.last_active:
delta = current_time - self.last_active
if delta <= timedelta(seconds=60):
if self.internet_up:
status = 'online'
else:
status = 'no_internet'
return {
"id": self.id,
"name": self.name,
"arma_type": self.arma_type,
"last_active": self.last_active.isoformat() if self.last_active else None,
"internet_up": self.internet_up,
"copying": self.copying,
"sending_number": self.sending_number,
"status": status
}
def get_status(self, current_time=None):
if current_time is None:
current_time = datetime.utcnow()
if self.copying:
return 'copying'
elif self.sending_number:
return 'sending_number'
elif self.name == 'ARM3':
# Для ARM3 игнорируем статус 'processing'
if self.last_active:
delta = current_time - self.last_active
threshold = timedelta(seconds=5)
if delta <= threshold:
if self.internet_up:
return 'online'
else:
return 'no_internet'
return 'offline'
elif self.processing:
return 'processing'
else:
if self.last_active:
delta = current_time - self.last_active
threshold = timedelta(seconds=5)
if delta <= threshold:
if self.internet_up:
return 'online'
else:
return 'no_internet'
return 'offline'
@app.route('/get_device_status', methods=['GET'])
def get_device_status():
devices = Device.query.all()
device_statuses = {}
threshold = timedelta(seconds=5) # Уменьшенный порог времени для быстрого определения оффлайн
now = datetime.utcnow()
for device in devices:
name = device.name
if device.sending_number:
status = 'sending_number'
activity_value = random.choice([2, 3, 2, 3, 4, 3, 2])
elif device.copying:
status = 'copying'
activity_value = random.choice([0, 1, 0, 1, 2, 1, 0])
else:
if device.last_active and now - device.last_active <= threshold:
if device.internet_up:
status = 'online'
activity_value = 1
else:
status = 'no_internet'
activity_value = 0
else:
status = 'offline'
activity_value = 0
# Если устройство в процессе обработки, оставляем статус онлайн, но меняем activity_value
if device.processing:
status = 'processing'
activity_value = random.choice([2, 3, 2, 3, 4, 3, 2])
device_statuses[name] = {
'status': status,
'processing': device.processing # Передаем информацию о процессе
}
activity_data[name].append(activity_value)
logging.debug(f"Устройство {name}: статус {status}, активность {activity_value}")
# Преобразуем deque в список для JSON
activity_data_serializable = {name: list(data) for name, data in activity_data.items()}
logging.debug(f"Activity data: {activity_data_serializable}") # Добавьте эту строку для отладки
return jsonify({
'status': 'success',
'devices': device_statuses,
'activity': activity_data_serializable
})
def initialize_activity_data():
device_names = ['ARM1', 'ARM2', 'ARM3', 'ARM4', 'ARM5', 'ARM6']
for name in device_names:
activity_data[name] = deque([0]*ACTIVITY_HISTORY_LENGTH, maxlen=ACTIVITY_HISTORY_LENGTH)
def create_devices():
device_types = {
'ARM1': 'CFA',
'ARM2': 'VND',
'ARM3': 'SRC',
'ARM4': 'SRC',
'ARM5': 'RPA',
'ARM6': 'RPA' # Убедитесь, что ARM6 тоже имеет тип 'RPA'
}
for name, arma_type in device_types.items():
device = Device.query.filter_by(name=name).first()
if not device:
device = Device(name=name, arma_type=arma_type, sending_number=False)
db.session.add(device)
db.session.commit()
initialize_activity_data()
@app.route('/register_user', methods=['POST'])
def register_user():
data = request.json
worker_name = data.get('worker_name')
internet_up = data.get('internet_up', False)
copying = data.get('copying', False)
sending_number = data.get('sending_number', False)
processing = data.get('processing', False) # Новое поле
if not worker_name:
return jsonify({"status": "error", "message": "worker_name is required"}), 400
device = Device.query.filter_by(name=worker_name).first()
if not device:
return jsonify({"status": "error", "message": "Device not found"}), 404
device.last_active = datetime.utcnow()
device.internet_up = internet_up
device.copying = copying
device.sending_number = sending_number
device.processing = processing # Сохраняем новое поле
db.session.commit()
return jsonify({"status": "success"})
@app.route('/get_unpacked_days', methods=['GET'])
def get_unpacked_days():
year = request.args.get('year')
month = request.args.get('month')
if not year or not month:
return jsonify({"status": "error", "message": "Необходимо указать год и месяц"}), 400
try:
year = int(year)
month = int(month)
except ValueError:
return jsonify({"status": "error", "message": "Год и месяц должны быть числами"}), 400
# Формируем формат даты для фильтрации
month_str = f"{month:02d}"
# Запрашиваем уникальные дни, где pack_time отсутствует и arma_type равен 'RPA'
unpacked_dates = TableRow.query.filter(
TableRow.date.like(f"{year}-{month_str}-%"),
TableRow.arma_type == 'RPA',
or_(TableRow.pack_time == None, TableRow.pack_time == '')
).with_entities(TableRow.date).distinct().all()
# Извлекаем дни из дат
unpacked_days = set()
for date_str, in unpacked_dates:
try:
day = int(date_str.split('-')[2])
unpacked_days.add(day)
except (IndexError, ValueError):
continue # Пропускаем некорректные форматы дат
return jsonify({'status': 'success', 'unpacked_days': list(unpacked_days)})
Удален маршрут /ping, так как он использовал ActiveUser
@app.route('/get_table_data')
def get_table_data():
date = request.args.get('date')
filter_arma = request.args.get('filter_arma') # Новый параметр фильтра
app.logger.debug(f"Получен запрос таблицы для даты: {date}, фильтр: {filter_arma}")
# Начинаем построение запроса
query = TableRow.query.filter_by(date=date)
# Если фильтр активирован, добавляем условие
if filter_arma == 'RPA':
query = query.filter_by(arma_type='RPA')
rows = query.all()
app.logger.debug(f"Найдено записей: {len(rows)} для даты {date} с фильтром {filter_arma}")
data = []
numbers = {}
serials = {}
dl_numbers = {}
for row in rows:
data.append({
'id': row.id,
'row_number': row.row_number,
'timestamp': row.timestamp,
'number': row.number,
'serial': row.serial,
'dl_number': row.dl_number,
'worker_name': row.worker_name,
'pack_time': row.pack_time,
'arma_type': row.arma_type,
})
# Собираем информацию о дубликатах
if row.number:
clean_number = ''.join(filter(str.isdigit, row.number))
if clean_number in numbers:
numbers[clean_number].append(len(data) - 1)
else:
numbers[clean_number] = [len(data) - 1]
if row.serial:
clean_serial = ''.join(filter(str.isdigit, row.serial))
if clean_serial in serials:
serials[clean_serial].append(len(data) - 1)
else:
serials[clean_serial] = [len(data) - 1]
if row.dl_number:
clean_dl_number = ''.join(filter(str.isdigit, row.dl_number))
if clean_dl_number in dl_numbers:
dl_numbers[clean_dl_number].append(len(data) - 1)
else:
dl_numbers[clean_dl_number] = [len(data) - 1]
# Фильтруем только реальные дубликаты
duplicate_numbers = {k: v for k, v in numbers.items() if len(v) > 1}
duplicate_serials = {k: v for k, v in serials.items() if len(v) > 1}
duplicate_dl_numbers = {k: v for k, v in dl_numbers.items() if len(v) > 1}
return jsonify({
"data": data,
"duplicates": {
"numbers": duplicate_numbers,
"serials": duplicate_serials,
"dl_numbers": duplicate_dl_numbers
}
})
@app.route('/update_table', methods=['POST'])
def update_table():
data = request.json
print(data)
date = data['date']
worker_name = data['worker_name']
arma_type = data['arma_type']
# Получаем количество существующих записей для этой даты
row_count = TableRow.query.filter_by(date=date).count() + 1
# Создаём новую строку в таблице
if not data.get('number') and not data.get('serial'):
new_row = TableRow(
date=date,
row_number=str(row_count),
timestamp=data['timestamp'],
number='', # Пустое значение для номера
serial='', # Пустое значение для серийного номера
dl_number='', # Пустое значение для графы
worker_name=worker_name,
arma_type=arma_type,
)
elif not data.get('number'):
new_row = TableRow(
date=date,
row_number=str(row_count),
timestamp=data['timestamp'],
number='', # Пустое значение для номера
serial=data['serial'],
dl_number='', # Пустое значение для графы
worker_name=worker_name,
arma_type=arma_type,
)
else:
new_row = TableRow(
date=date,
row_number=str(row_count),
timestamp=data['timestamp'],
number=data['number'],
serial=data['serial'],
dl_number=data.get('dl_number', ''),
worker_name=worker_name,
arma_type=arma_type,
)
# Сохраняем запись в базе данных
db.session.add(new_row)
device = Device.query.filter_by(name=worker_name).first()
if device:
device.last_active = datetime.utcnow()
db.session.commit()
# Отправляем сообщение в очередь для обновления клиентов
update_queue.put(json.dumps({"type": "update", "date": date}))
# Добавляем импульсивное значение для sparkline, если запись отправлена ARM5 или ARM6
if worker_name in ['ARM5', 'ARM6']:
activity_data[worker_name].append(5) # Значение импульса (можно настроить по необходимости)
return jsonify({"status": "success"})
@app.route('/update_graf', methods=['POST'])
def update_graf():
try:
data = request.json
row_id = int(data.get('id'))
new_value = data.get('new_value')
date = data.get('date')
if not row_id or not date:
return jsonify({"status": "error", "message": "Missing 'id' or 'date' in request"}), 400
# Находим запись по id и дате
row = TableRow.query.filter_by(id=row_id, date=date).first()
if row:
row.dl_number = new_value
db.session.commit()
return jsonify({"status": "success"})
else:
return jsonify({"status": "error", "message": "Row not found"}), 404
except (ValueError, TypeError) as e:
return jsonify({"status": "error", "message": f"Invalid input: {str(e)}"}), 400
except Exception as e:
db.session.rollback()
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/update_arma_type', methods=['POST'])
def update_arma_type():
try:
data = request.json
date = data['date']
serial = data['serial']
arma_type = data['arma_type']
row = TableRow.query.filter_by(date=date, serial=serial).first()
if row:
row.arma_type = arma_type
db.session.commit()
return jsonify({"status": "success"})
else:
return jsonify({"status": "error", "message": "Row not found"})
except Exception as e:
return jsonify({"status": "error", "message": str(e)})
@app.route('/update_number', methods=['POST'])
def update_number():
try:
data = request.json
row_id = int(data['id']) # Используем 'id' вместо 'row_index'
new_value = data['new_value']
date = data['date']
# Находим запись по id и дате
row = TableRow.query.filter_by(id=row_id, date=date).first()
if row:
row.number = new_value
db.session.commit()
return jsonify({"status": "success"})
return jsonify({"status": "error", "message": "Row not found"})
except Exception as e:
db.session.rollback()
return jsonify({"status": "error", "message": str(e)})
@app.route('/pack_item', methods=['POST'])
def pack_item():
try:
data = request.json
row_id = data['id']
date = data['date']
rows = TableRow.query.filter_by(id=row_id, date=date).all()
if rows:
row = rows[0]
pack_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
row.pack_time = pack_time
db.session.commit()
# Обновляем статистику упаковки
statistics = Statistics.query.filter_by(date=date).first()
if statistics:
statistics.pack_clicks += 1
else:
statistics = Statistics(date=date, generate_clicks=0, pack_clicks=1) # pack_clicks=1
db.session.add(statistics)
db.session.commit()
# Отправляем сообщение в очередь для обновления клиентов
update_queue.put(json.dumps({"type": "update", "date": date}))
return jsonify({"status": "success", "pack_time": pack_time})
return jsonify({"status": "error", "message": "Строка не найдена"}), 404
except Exception as e:
print(f"Ошибка в pack_item: {str(e)}")
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/set_initial_dl', methods=['POST'])
def set_initial_dl():
try:
data = request.json
if not data:
return jsonify({"status": "error", "message": "No data received"})
date = data.get('date')
initial_number = data.get('initial_number')
if not date or not initial_number:
return jsonify({
"status": "error",
"message": "Missing required fields",
"received": {"date": date, "initial_number": initial_number}
})
try:
initial_number = int(initial_number)
except ValueError:
return jsonify({
"status": "error",
"message": "Initial number must be an integer"
})
print(f"Setting initial DL for date {date}: {initial_number}") # Отладочный вывод
dl_counter = DLCounter.query.filter_by(date=date).first()
if dl_counter:
dl_counter.counter = initial_number
print(f"Updated existing counter for {date}") # Отладочный вывод
else:
dl_counter = DLCounter(date=date, counter=initial_number)
db.session.add(dl_counter)
print(f"Created new counter for {date}") # Отладочный вывод
db.session.commit()
return jsonify({
"status": "success",
"message": f"DL counter set to {initial_number} for date {date}"
})
except Exception as e:
print(f"Error in set_initial_dl: {str(e)}") # Отладочный вывод
db.session.rollback()
return jsonify({
"status": "error",
"message": str(e)
})
@app.route('/generate_dl', methods=['POST'])
def generate_dl():
try:
data = request.json
row_id = data['id']
date = data['date']
# Получаем или создаем счетчик DL для данной даты
dl_counter = DLCounter.query.filter_by(date=date).first()
if not dl_counter:
return jsonify({"status": "error", "message": "DL counter не инициализирован"}), 400
# Генерируем новый DL номер
dl_number = f"DL{dl_counter.counter:06d}"
# Находим и обновляем нужную запись по id
row = TableRow.query.filter_by(id=row_id, date=date).first()
if row:
row.dl_number = dl_number
dl_counter.counter += 1 # Увеличиваем счетчик
# Обновляем статистику генерации
statistics = Statistics.query.filter_by(date=date).first()
if statistics:
statistics.generate_clicks += 1
else:
statistics = Statistics(date=date, generate_clicks=1, pack_clicks=0)
db.session.add(statistics)
db.session.commit()
return jsonify({"status": "success", "dl_number": dl_number, "id": row_id})
return jsonify({"status": "error", "message": "Строка не найдена"}), 404
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
def initialize_table_for_date(date):
# Проверяем, существуют ли уже записи для этой даты
existing = TableRow.query.filter_by(date=date).first()
if not existing:
# Создаем новую запись только в случае отсутствия данных
new_row = TableRow(
date=date,
row_number=str(1),
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
number='',
serial='',
dl_number='',
worker_name='',
arma_type='',
pack_time='',
)
db.session.add(new_row)
# Инициализируем статистику для новой даты
statistics = Statistics(date=date, generate_clicks=0, pack_clicks=0)
db.session.add(statistics)
db.session.commit()
@app.route('/update_serial_arma', methods=['POST'])
def update_serial_arma():
try:
data = request.json
date = data['date']
serial = data['serial']
arma_type = data['arma_type']
# Создаем новую запись в таблице
new_row = TableRow(
date=date,
serial=serial,
arma_type=arma_type,
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
)
db.session.add(new_row)
db.session.commit()
return jsonify({"status": "success"})
except Exception as e:
db.session.rollback()
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/get_statistics')
def get_statistics():
try:
date = request.args.get('date')
app.logger.debug(f"Получен запрос статистики для даты: {date}")
# Получаем статистику генерации и упаковки
statistics = Statistics.query.filter_by(date=date).first()
if not statistics:
generate_clicks = 0
pack_clicks = 0
app.logger.debug(f"Статистика для даты {date} не найдена. Установлено значение 0.")
else:
generate_clicks = statistics.generate_clicks
pack_clicks = statistics.pack_clicks
app.logger.debug(f"Статистика для даты {date}: Генераций = {generate_clicks}, Упаковок = {pack_clicks}")
# Получаем количество записей типа "RPA"
rpa_records = TableRow.query.filter_by(date=date, arma_type='RPA').count()
app.logger.debug(f"Количество записей типа RPA для даты {date}: {rpa_records}")
return jsonify({
"generate_clicks": generate_clicks,
"pack_clicks": pack_clicks,
"rpa_records": rpa_records
})
except Exception as e:
app.logger.error(f"Ошибка в get_statistics: {str(e)}")
return jsonify({
"generate_clicks": 0,
"pack_clicks": 0,
"rpa_records": 0,
"error": str(e)
})
if not row_id:
return jsonify({'status': 'error', 'message': 'ID записи не предоставлен'}), 400
row = TableRow.query.get(row_id)
if not row:
return jsonify({'status': 'error', 'message': 'Запись не найдена'}), 404
date = row.date # Получаем дату записи для обновления статистики
# Получаем запись статистики для этой даты
statistics = Statistics.query.filter_by(date=date).first()
if statistics:
# Если запись имела сгенерированный DL номер, уменьшаем generate_clicks
if row.dl_number:
if statistics.generate_clicks > 0:
statistics.generate_clicks -= 1
else:
app.logger.warning(f"Attempting to decrement generate_clicks below zero for date {date}")
# Если запись была упакована, уменьшаем pack_clicks
if row.pack_time:
if statistics.pack_clicks > 0:
statistics.pack_clicks -= 1
else:
app.logger.warning(f"Attempting to decrement pack_clicks below zero for date {date}")
db.session.commit()
else:
app.logger.warning(f"No Statistics entry found for date {date} when deleting row {row_id}")
# Удаляем запись из таблицы
db.session.delete(row)
db.session.commit()
# Отправляем сообщение в очередь для обновления клиентов
update_queue.put(json.dumps({"type": "delete", "date": date, "id": row.id}))
return jsonify({'status': 'success'})
except Exception as e:
db.session.rollback()
app.logger.error(f"Ошибка в delete_row: {str(e)}")
return jsonify({'status': 'error', 'message': str(e)}), 500
@app.route('/', methods=['GET', 'POST'])
def main():
if request.method == 'POST':
worker = request.form.get('worker')
name = request.form.get('name')
# Сохраняем информацию о входе
user = User.query.filter_by(username=name).first()
if not user:
user = User(username=name)
db.session.add(user)
login_history = LoginHistory(user=user)
db.session.add(login_history)
db.session.commit()
resp = make_response(redirect('/welcome'))
resp.set_cookie('worker', worker)
resp.set_cookie('name', name)
return resp
return render_template('main.html')
@app.route('/get_current_dl', methods=['GET'])
def get_current_dl():
date = request.args.get('date')
if not date:
return jsonify({"status": "error", "message": "Дата обязательна"}), 400
dl_counter = DLCounter.query.filter_by(date=date).first()
if dl_counter:
return jsonify({"status": "success", "current_dl": dl_counter.counter})
else:
return jsonify({"status": "error", "message": "Счетчик DL не инициализирован для этой даты"}), 404
@app.route('/welcome')
def welcome():
worker = request.cookies.get('worker')
name = request.cookies.get('name')
if not worker or not name:
return redirect('/')
current_time = datetime.utcnow()
devices = [device.to_dict(current_time=current_time) for device in Device.query.order_by(Device.name).all()]
current_time_str = current_time.isoformat()
return render_template('welcome.html', name=name, worker=worker, table=table, devices=devices, current_time=current_time_str)
let isEditing = false;
let searchTimeout;
let lastUpdateTime = 0;
const updateInterval = 1000;
let eventSource;
let lastData = null;
let isDeleting = false;
let fpInstance;
let unpackedDaysCache = {}; // Ключи будут в формате 'YYYY-MM', значение - Set дней
const deviceSparklines = {};
// Глобальные переменные для отслеживания сортировки
let globalSortColumn = null;
let globalSortOrder = 'asc';
function getSelectedDate() {
return $('#datepicker').val();
}
// Функция для получения состояния фильтра
function getArmaFilter() {
return $('#armaFilter').is(':checked') ? 'RPA' : '';
}
function updateTable(force = false, highlightNew = false) {
return new Promise((resolve, reject) => {
const now = Date.now();
if (!force && now - lastUpdateTime < updateInterval) {
resolve();
return;
}
if (isEditing) {
resolve();
return;
}
function initializeSparklines(activity) {
for (const [name, data] of Object.entries(activity)) {
const sparklineSpan = (`#{name}-sparkline`);
sparklineSpan.sparkline(data, {
type: 'line',
width: '300px', // Увеличенная ширина
height: '50px', // Также можно увеличить высоту для лучшей видимости
lineColor: 'green',
fillColor: 'transparent',
spotColor: 'red', // Отображение пиков
minSpotColor: 'blue', // Минимальные пики
maxSpotColor: 'orange', // Максимальные пики
highlightSpotColor: 'blue',
highlightLineColor: 'blue'
});
sparklineSpan.data('sparkline-initialized', true);
}
}
function updateSparklines(devices, activity) {
for (const [name, status] of Object.entries(devices)) {
const sparklineSpan = (`#{name}-sparkline`);
const data = activity[name];
// Определяем цвет линии в зависимости от статуса устройства и последнего значения активности
let lineColor = 'green'; // Стандартный цвет
if (status === 'processing') {
lineColor = 'green'; // Цвет для состояния processing
} else if (status === 'copying') {
lineColor = 'orange';
} else if (status === 'sending_number') {
lineColor = 'blue';
} else if (status === 'no_internet') {
lineColor = 'red';
}
// Проверяем, был ли добавлен импульс (например, значение > 4)
const lastValue = data[data.length - 1];
if (lastValue > 4) {
lineColor = 'purple'; // Цвет импульса
}
if (sparklineSpan.data('sparkline-initialized')) {
// Обновляем существующий Sparkline
sparklineSpan.sparkline(data, {
type: 'line',
width: '100%',
height: '20px',
lineColor: lineColor,
fillColor: 'transparent',
spotColor: 'red',
minSpotColor: 'blue',
maxSpotColor: 'orange',
highlightSpotColor: 'blue',
highlightLineColor: 'blue'
});
} else {
// Инициализируем Sparkline, если он ещё не инициализирован
sparklineSpan.sparkline(data, {
type: 'line',
width: '100%',
height: '50px',
lineColor: lineColor,
fillColor: 'transparent',
spotColor: 'red',
minSpotColor: 'blue',
maxSpotColor: 'orange',
highlightSpotColor: 'blue',
highlightLineColor: 'blue'
});
sparklineSpan.data('sparkline-initialized', true);
}
}
function sortTable(column, order) {
const rows = $('#tableBody > tr').get();
rows.sort(function(a, b) {
let A = $(a).children('td').eq(column).text().trim();
let B = $(b).children('td').eq(column).text().trim();
// Обработка пустых значений
if (A === '' && B === '') return 0;
if (A === '') return order === 'asc' ? 1 : -1;
if (B === '') return order === 'asc' ? -1 : 1;
// Специальная обработка для столбца "Графа" (dl_number) с использованием data-value
if (column === 4) { // Индекс столбца "Графа"
let numA = parseInt($(a).children('td').eq(column).attr('data-value')) || 0;
let numB = parseInt($(b).children('td').eq(column).attr('data-value')) || 0;
// Отладочные сообщения
console.log(`Сортировка Графа: numA = ${numA}; numB = ${numB}`);
return order === 'asc' ? numA - numB : numB - numA;
}
// Обработка дат и времени для соответствующих столбцов
if (column === 1 || column === 6) { // Столбцы "Время отправки" и "Время упаковки"
let dateA = Date.parse(A);
let dateB = Date.parse(B);
if (isNaN(dateA)) dateA = 0;
if (isNaN(dateB)) dateB = 0;
return order === 'asc' ? dateA - dateB : dateB - dateA;
}
// Обработка числовых столбцов
if (column === 0 || column === 2) { // Столбцы с числами (№ и Номер)
let numA = parseFloat(A) || 0;
let numB = parseFloat(B) || 0;
return order === 'asc' ? numA - numB : numB - numA;
}
// Обработка строковых столбцов
if (column === 5) { // Столбец с именем отправителя
A = A.toLowerCase();
B = B.toLowerCase();
}
// Строковое сравнение для остальных столбцов
A = A.toUpperCase();
B = B.toUpperCase();
if (A < B) return order === 'asc' ? -1 : 1;
if (A > B) return order === 'asc' ? 1 : -1;
return 0;
});
// Очистка тела таблицы
$('#tableBody').empty();
// Добавление отсортированных строк
$.each(rows, function(index, row) {
$('#tableBody').append(row);
});
checkDuplicates();
bindEventHandlers();
}
function parseDL(dl_number) {
if (typeof dl_number !== 'string') return null;
dl_number = dl_number.trim();
let match = dl_number.match(/^DL[-\s]?(\d+)$/i);
if (match && match[1]) {
return parseInt(match[1], 10);
}
return null;
}
function generateDL(rowId) {
console.log(Generating DL for row ID ${rowId});
const selectedDate = getSelectedDate();
console.log("Selected date:", selectedDate);
$.ajax({
url: '/generate_dl',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
id: rowId,
date: selectedDate
}),
success: function(response) {
if (response.status === 'success') {
console.log('DL успешно сгенерирован:', response.dl_number);
var row = $(`#tableBody tr[data-id='${rowId}']`);
var dlCell = row.find('td:eq(4)');
var packCell = row.find('td:eq(6)'); // Столбец "Время упаковки"
var armaType = row.find('td:eq(7)').text().trim();
dlCell.text(response.dl_number)
.addClass('clickable')
.css('cursor', 'pointer')
.off('click') // Удаляем предыдущие обработчики
.on('click', function() {
copyToClipboard(response.dl_number);
$(this).addClass('copied');
setTimeout(() => {
$(this).removeClass('copied');
}, 200);
});
// Добавляем кнопку упаковки только если arma_type не исключен
const excludedArmaTypes = ["CFA", "VND", "SRC"];
if (!excludedArmaTypes.includes(armaType)) {
packCell.html('<button class="pack-button">Упаковать</button>')
.find('button')
.click(function() {
packItem(rowId);
});
}
// Обновляем поле initial-dl с текущим значением DL
loadCurrentDL();
} else {
alert('Ошибка при генерации DL: ' + response.message);
}
},
error: function(xhr, status, error) {
console.error('Ошибка при генерации DL:', status, error);
alert('Ошибка при генерации DL: ' + error);
}
});
}
function packItem(rowId) {
console.log(Упаковка элемента для строки ID ${rowId});
const selectedDate = getSelectedDate();
console.log("Selected date:", selectedDate);
$.ajax({
url: '/pack_item',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
id: rowId,
date: selectedDate
}),
success: function(response) {
console.log("Ответ сервера:", response);
if (response.status === 'success') {
var row = $(`#tableBody tr[data-id='${rowId}']`);
row.addClass('packed-row');
var cell = row.find('td:eq(6)'); // Столбец "Время упаковки"
cell.text(response.pack_time);
updateStatistics();
// Удаляем кнопку "Упаковать", так как запись уже упакована
cell.find('button.pack-button').remove();
// Определяем год и месяц из `selectedDate`
const [year, month, day] = selectedDate.split('-').map(Number);
// Принудительно обновляем неупакованные дни для этого месяца
markUnpackedDays(year, month, true);
} else {
alert('Ошибка при упаковке: ' + response.message);
}
},
error: function(xhr, status, error) {
console.error("Ошибка AJAX:", xhr, status, error);
alert('Ошибка при упаковке: ' + error);
}
});
}
function areSimilarNumbers(num1, num2) {
// Очищаем строки от нецифровых символов и пробелов
const clean1 = num1.toString().replace(/\D/g, '').trim();
const clean2 = num2.toString().replace(/\D/g, '').trim();
// Если строки пустые или разной длины - не дубликаты
if (!clean1 || !clean2 || clean1.length !== clean2.length) {
return false;
}
// Проверяем на точное совпадение
return clean1 === clean2;
}
function checkDuplicates() {
console.log("Checking for duplicates...");
const rows = $('#tableBody tr');
// Очищаем предыдущие выделения
rows.find('td').removeClass('duplicate-highlight');
// Создаем массивы для хранения номеров и их индексов
const numbers = new Map();
const dl_numbers = new Map();
const serials = new Map();
// Собираем все номера и серийные номера
rows.each(function(index) {
const number = $(this).find('td:nth-child(3)').text().trim();
const serial = $(this).find('td:nth-child(4)').text().trim();
const dl_number = $(this).find('td:nth-child(5)').text().trim();
if (number) {
if (!numbers.has(number)) {
numbers.set(number, []);
}
numbers.get(number).push(index);
}
if (dl_number) {
if (!dl_numbers.has(dl_number)) {
dl_numbers.set(dl_number, []);
}
dl_numbers.get(dl_number).push(index);
}
if (serial) {
if (!serials.has(serial)) {
serials.set(serial, []);
}
serials.get(serial).push(index);
}
});
// Подсвечиваем дубликаты
let duplicatesFound = false;
dl_numbers.forEach((indices, dl_number) => {
if (dl_number.startsWith("DL")) {
if (indices.length > 1) {
indices.forEach(index => {
rows.eq(index).find('td:nth-child(5)').addClass('duplicate-highlight');
});
duplicatesFound = true;
}
}
});
// Проверяем номера
numbers.forEach((indices, number) => {
if (indices.length > 1) {
indices.forEach(index => {
rows.eq(index).find('td:nth-child(3)').addClass('duplicate-highlight');
});
duplicatesFound = true;
}
});
// // Проверяем грайвера
// dl_numbers.forEach((indices, dl_number) => {
// if (indices.length > 1) {
// indices.forEach(index => {
// rows.eq(index).find('td:nth-child(5)').addClass('duplicate-highlight');
// });
// duplicatesFound = true;
// }
// });
// Проверяем серийные номера
serials.forEach((indices, serial) => {
if (indices.length > 1) {
indices.forEach(index => {
rows.eq(index).find('td:nth-child(4)').addClass('duplicate-highlight');
});
duplicatesFound = true;
}
});
return duplicatesFound;
}
function appendNewRow(tableBody, rowData) {
console.log("Добавление новой строки:", rowData);
// Создаем элемент строки и присваиваем уникальный data-id
var tr = $('<tr>').attr('data-id', rowData.id);
// Если есть время упаковки и это не заголовок, добавляем класс 'packed-row'
if (rowData.pack_time && rowData.pack_time !== "Время упаковки") {
tr.addClass('packed-row');
}
// Добавляем ячейки в строку
tr.append($('<td>').text(rowData.row_number));
tr.append($('<td>').text(rowData.timestamp));
// Столбец "Номер" (Третий столбец, индекс 2)
var numberCell = $('<td>')
.text(rowData.number)
.addClass('editable') // Добавляем класс для редактирования
.attr('data-column', '2'); // Указываем индекс столбца
tr.append(numberCell);
tr.append($('<td>').text(rowData.serial));
// Столбец "Графа" (Пятый столбец, индекс 4)
var dlCell = $('<td>')
.text(rowData.dl_number || '')
.addClass('editable') // Добавляем класс для редактирования
.attr('data-column', '4'); // Указываем индекс столбца "Графа"
tr.append(dlCell);
// Добавляем data-value
var numericValue = parseDL(rowData.dl_number) || 0;
dlCell.attr('data-value', numericValue);
// Проверка и добавление кнопок или кликабельного текста для "Графа"
const excludedArmaTypes = ["CFA", "VND", "SRC"];
if (rowData.arma_type === 'RPA' && !excludedArmaTypes.includes(rowData.arma_type)) {
// Для типа АРМА 'RPA', проверяем наличие и формат dl_number
if (!rowData.dl_number || !rowData.dl_number.startsWith('DL')) {
// Если dl_number отсутствует или не начинается с 'DL', отображаем кнопку "Генерировать"
dlCell.html('<button class="generate-button">Генерировать</button>')
.find('button')
.click(function() {
generateDL(rowData.id); // Передаем уникальный ID строки
});
} else {
// Если dl_number присутствует и начинается с 'DL', делаем его кликабельным для копирования
dlCell.text(rowData.dl_number)
.addClass('clickable')
.css('cursor', 'pointer')
.on('click', function() {
copyToClipboard(rowData.dl_number);
$(this).addClass('copied');
setTimeout(() => {
$(this).removeClass('copied');
}, 200);
});
}
} else if (!excludedArmaTypes.includes(rowData.arma_type)) {
// Для других типов АРМА, которые не исключены, отображаем или скрываем кнопку
if (rowData.dl_number && rowData.dl_number.startsWith('DL')) {
dlCell.text(rowData.dl_number)
.addClass('clickable')
.css('cursor', 'pointer')
.on('click', function() {
copyToClipboard(rowData.dl_number);
$(this).addClass('copied');
setTimeout(() => {
$(this).removeClass('copied');
}, 200);
});
} else {
dlCell.text(rowData.dl_number || '');
}
} else {
// Для типов АРМА "CFA", "VND", "SRC" оставляем ячейку пустой или с текущим значением
dlCell.text(rowData.dl_number || '');
}
// Добавляем ячейку с именем отправителя
tr.append($('<td>').text(rowData.worker_name));
/**
* Обработка ячейки "Время упаковки" (pack_time)
*/
var packCell = $('<td>');
if (rowData.dl_number && rowData.dl_number.startsWith('DL') && !rowData.pack_time && !excludedArmaTypes.includes(rowData.arma_type)) {
// Если dl_number с 'DL', pack_time отсутствует и arma_type не исключен, показываем кнопку "Упаковать"
packCell.html('<button class="pack-button">Упаковать</button>')
.find('button')
.click(function() {
packItem(rowData.id); // Передаем уникальный ID строки
});
} else {
// Иначе отображаем время упаковки или оставляем пустым
packCell.text(rowData.pack_time || '');
}
tr.append(packCell);
// Добавляем ячейку с типом АРМА
tr.append($('<td>').text(rowData.arma_type || ''));
/**
* Добавление ячейки "Действие" с кнопкой "Удалить"
*/
var actionTd = $('<td>');
var deleteButton = $('<button>').text('Удалить').addClass('delete-button btn btn-danger btn-sm');
deleteButton.click(function() {
initiateDeleteConfirmation(rowData.id); // Используем новую функцию
});
actionTd.append(deleteButton);
tr.append(actionTd);
// Добавляем строку в тело таблицы
tableBody.append(tr);
/**
* Дополнительная обработка после добавления строки
*/
setTimeout(() => {
const dlValue = dlCell.text().trim();
const packValue = packCell.text().trim();
if (dlValue.startsWith('DL') && !packValue && !excludedArmaTypes.includes(rowData.arma_type)) {
console.log('Добавляем кнопку упаковки для DL:', dlValue);
packCell.html('<button class="pack-button">Упаковать</button>')
.find('button')
.click(function() {
packItem(rowData.id); // Передаем уникальный ID строки
});
}
// Проверяем дубликаты после добавления новой строки
checkDuplicates();
}, 100);
}
function bindEventHandlers() {
// Привязка обработчика для кнопки "Генерировать"
('.generate-button').off('click').on('click', function() {
var rowId = (this).closest('tr').data('id');
generateDL(rowId);
});
// Привязка обработчика для кнопки "Упаковать"
$('.pack-button').off('click').on('click', function() {
var rowId = $(this).closest('tr').data('id');
packItem(rowId);
});
// Привязка обработчика для кнопки "Удалить"
$('.delete-button').off('click').on('click', function() {
var rowId = $(this).closest('tr').data('id');
initiateDeleteConfirmation(rowId);
});
}
function updateTableContent(data, tableBody, highlightNew = false) {
tableBody.empty(); // Очищаем текущее содержимое таблицы
data.forEach(function(rowData, index) {
appendNewRow(tableBody, rowData);
if (highlightNew && index === data.length - 1) {
// Можно добавить подсветку новой строки, если нужно
}
});
checkDuplicates();
bindEventHandlers(); // Проверяем дубликаты после обновления таблицы
}
var td = $(this);
var currentValue = td.text();
var input = $('<input type="text">')
.val(currentValue)
.addClass('edit-input');
td.html(input);
input.focus();
input.on('blur', function() {
var newValue = $(this).val().trim();
var rowId = td.closest('tr').data('id');
var columnIndex = td.attr('data-column');
// Определяем URL для обновления в зависимости от столбца
let url;
let updateData = {
id: rowId,
new_value: newValue,
date: getSelectedDate()
};
if (columnIndex === '2') { // Столбец "Номер"
url = '/update_number';
} else if (columnIndex === '4') { // Столбец "Графа"
url = '/update_graf';
} else {
alert('Неподдерживаемый столбец для редактирования');
td.text(currentValue);
isEditing = false;
return;
}
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(updateData),
success: function(response) {
if (response.status === 'success') {
td.text(newValue);
checkDuplicates();
} else {
alert('Ошибка при обновлении значения: ' + response.message);
td.text(currentValue);
}
isEditing = false;
},
error: function(xhr, status, error) {
alert('Ошибка при отправке данных: ' + error);
td.text(currentValue);
isEditing = false;
}
});
});
input.on('keypress', function(e) {
if (e.which === 13) { // Нажатие Enter
$(this).blur();
}
});
input.on('keydown', function(e) {
if (e.key === 'Escape') { // Нажатие Esc
td.text(currentValue);
isEditing = false;
}
});
});
function searchNumber() {
const searchValue = $('#searchInput').val().trim();
if (!searchValue) return;
// Удаляем предыдущую подсветку
$('.highlight-search').removeClass('highlight-search');
const rows = $('#tableBody tr');
let found = false;
rows.each(function() {
const numberCell = $(this).find('td:nth-child(3)');
const cellText = numberCell.text().trim();
if (cellText === searchValue) {
numberCell.addClass('highlight-search');
// Прокрутка к найденной строке
$('.table-container').animate({
scrollTop: $(this).offset().top - $('.table-container').offset().top + $('.table-container').scrollTop() - 100
}, 500);
found = true;
// Устанавливаем таймер на удаление подсветки через 3 секунды
setTimeout(() => {
numberCell.removeClass('highlight-search');
}, 3000);
// Выводим сообщение в консоль для отладки
console.log('Найдено совпадение:', cellText);
return false; // Прерываем цикл, так как нашли нужную строку
}
});
if (!found) {
alert('Точное совпадение номера не найдено');
}
}
function initiateDeleteConfirmation(rowId) {
isDeleting = true; // Устанавливаем флаг подтверждения удаления
var deleteCell = (‘tr[data−id=′{rowId}'] td:last-child`);
// Проверяем, не находится ли уже в состоянии подтверждения
if (deleteCell.data('confirming')) {
return; // Если подтверждение уже запрошено, ничего не делаем
}
// Устанавливаем флаг подтверждения
deleteCell.data('confirming', true);
// Создаем контейнер для кнопок "Да" и "Нет"
var buttonsContainer = $('<div>').addClass('confirm-buttons');
var yesButton = $('<button>')
.text('Да')
.addClass('confirm-yes-button btn btn-success btn-sm me-2')
.click(function() {
deleteConfirmed(rowId);
});
var noButton = $('<button>')
.text('Нет')
.addClass('confirm-no-button btn btn-secondary btn-sm')
.click(function() {
cancelDeleteConfirmation(rowId);
});
buttonsContainer.append(yesButton);
buttonsContainer.append(noButton);
// Заменяем содержимое ячейки на контейнер с кнопками
deleteCell.empty();
deleteCell.append(buttonsContainer);
}
function deleteConfirmed(rowId) {
.ajax({
url: '/delete_row',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id: rowId }),
success: function(response) {
if (response.status === 'success') {
// Удаляем строку из таблицы
(tr[data-id='${rowId}']).remove();
} else {
console.error('Ошибка при удалении записи:', response.message);
// Можно добавить уведомление пользователю о неудаче
}
// Восстанавливаем кнопку "Удалить" и сбрасываем флаг
cancelDeleteConfirmation(rowId);
},
error: function(xhr, status, error) {
console.error('Произошла ошибка при удалении записи:', error);
// Можно добавить уведомление пользователю о неудаче
// Восстанавливаем кнопку "Удалить" и сбрасываем флаг
cancelDeleteConfirmation(rowId);
}
});
}
function cancelDeleteConfirmation(rowId) {
var deleteCell = (‘tr[data−id=′{rowId}'] td:last-child`);
// Сбрасываем флаг подтверждения
deleteCell.data('confirming', false);
// Восстанавливаем кнопку "Удалить"
deleteCell.empty();
var deleteButton = $('')
.text('Удалить')
.addClass('delete-button btn btn-danger btn-sm')
.click(function() {
initiateDeleteConfirmation(rowId);
});
deleteCell.append(deleteButton);
isDeleting = false; // Сбрасываем глобальный флаг
}
function loadCurrentDL() {
const selectedDate = getSelectedDate();
.ajax({
url: '/get_current_dl',
type: 'GET',
data: { date: selectedDate },
success: function(response) {
if (response.status === 'success') {
('#initial-dl').val(response.current_dl);
} else {
('#initial-dl').val(''); // Можно установить значение по умолчанию или показать сообщение
console.warn(response.message);
}
},
error: function(xhr, status, error) {
console.error('Ошибка при получении текущего DL:', error);
('#initial-dl').val('');
}
});
}
function markUnpackedDays(year, month, force = false) {
const key = ${year}-${String(month).padStart(2, '0')};
if (!force && unpackedDaysCache[key] !== undefined) {
fpInstance.redraw(); // Перерисовываем календарь для применения стилей
return;
}
// Запрашиваем неупакованные дни для выбранного месяца и года
fetch(`/get_unpacked_days?year=${year}&month=${month}`)
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
unpackedDaysCache[key] = new Set(data.unpacked_days);
console.log(`Неупакованные дни для ${key}:`, unpackedDaysCache[key]);
} else {
console.error('Ошибка при получении неупакованных дней:', data.message);
unpackedDaysCache[key] = new Set(); // Инициализируем пустым множеством
}
fpInstance.redraw(); // Перерисовываем календарь после обновления данных
})
.catch(error => {
console.error('Ошибка при запросе неупакованных дней:', error);
unpackedDaysCache[key] = new Set(); // Инициализируем пустым множеством
fpInstance.redraw();
});
}
Given your description, it seems that the processing flag in your activationglaz.py script is not being set correctly, leading to ARM3 showing "process is running" status continuously. Also, the sparkline shows continuous pulses instead of a single pulse when activationglaz.py starts.
Here's how you can fix it:
Ensure processing is set correctly in activationglaz.py:
Modify your main_process function in activationglaz.py to ensure that processing is set to False when the script exits, even if it exits early due to a network issue or any other reason. Move the processing = True line inside the try block and adjust your function like this:
def main_process(SN):
global processing # Declare as global to modify the global variable
try:
internet_up = is_connected()
if not internet_up:
logger.warning("No network connection. Waiting for network...")
update_device_status(False, internet_up=internet_up)
return # Exit if no network
processing = True # Start processing
update_device_status(True, internet_up=internet_up)
# Start heartbeat thread
heartbeat_thread = threading.Thread(target=send_heartbeat, daemon=True)
heartbeat_thread.start()
# Your existing main process code
# ...
finally:
processing = False # Stop the heartbeat thread
internet_up = is_connected()
update_device_status(False, internet_up=internet_up)
# Turn off the screen
logger.info(f"Turning off screen on device {SN}...")
# Rest of your cleanup code
Explanation:
By moving the try block to cover all the code after ensuring there's an internet connection, we guarantee that the processing flag is reset to False in the finally block, even if the function exits early due to a return statement.
Update the Flask app to handle ARM3's processing status properly:
In your Flask app, you need to adjust the get_device_status function to detect when the processing status changes for ARM3 and only set a single impulse in the sparkline when activationglaz.py starts.
First, initialize a global variable to keep track of previous processing states:
# Add this at the top of your Flask app
previous_processing_states = {}
Then, modify the get_device_status function as follows:
@app.route('/get_device_status', methods=['GET'])
def get_device_status():
devices = Device.query.all()
device_statuses = {}
threshold = timedelta(seconds=5) # Reduced time threshold for quick offline detection
now = datetime.utcnow()
for device in devices:
name = device.name
# Retrieve the previous processing state
prev_processing = previous_processing_states.get(name, False)
if device.copying:
status = 'copying'
activity_value = random.choice([0, 1, 0, 1, 2, 1, 0])
elif device.sending_number:
status = 'sending_number'
activity_value = random.choice([2, 3, 2, 3, 4, 3, 2])
else:
if device.last_active and now - device.last_active <= threshold:
if device.internet_up:
status = 'online'
activity_value = 1
else:
status = 'no_internet'
activity_value = 0
else:
status = 'offline'
activity_value = 0
# If device is in processing, adjust status and activity_value
if device.processing:
if device.name == 'ARM3':
if not prev_processing:
# Processing started on ARM3, send a single impulse
activity_value = 5 # Single impulse
status = 'online' # Keep status as online for ARM3
else:
# Do not change activity_value, keep it as normal
pass
else:
status = 'processing'
activity_value = random.choice([2, 3, 2, 3, 4, 3, 2])
device_statuses[name] = {
'status': status,
'processing': device.processing # Passing process info
}
activity_data[name].append(activity_value)
logging.debug(f"Device {name}: status {status}, activity {activity_value}")
# Update previous_processing_states
previous_processing_states[name] = device.processing
# Convert activity_data to serializable format
activity_data_serializable = {name: list(data) for name, data in activity_data.items()}
return jsonify({
'status': 'success',
'devices': device_statuses,
'activity': activity_data_serializable
})
Explanation:
We're using previous_processing_states to track when processing status changes for each device.
For ARM3, we check if processing has changed from False to True (i.e., processing has just started). If so, we set a single high activity_value (e.g., 5) to create a single pulse in the sparkline.
We keep the status as 'online' for ARM3, even when processing is True, to prevent it from showing 'processing' status continuously.
After handling the status and activity value, we update previous_processing_states with the current processing status.
Adjust the JavaScript code if necessary:
Ensure that your front-end JavaScript code properly displays the sparkline based on the activity data received from the server. Since we're updating the activity_value for ARM3 to have a single high value when activationglaz.py starts, the sparkline should reflect this change accordingly.
Here's a snippet that shows how the sparkline might be updated in the updateSparklines function:
function updateSparklines(devices, activity) {
for (const [name, status] of Object.entries(devices)) {
const sparklineSpan = $(`#${name}-sparkline`);
const data = activity[name];
// Determine line color based on device status
let lineColor = 'green'; // Default color
if (status === 'processing') {
lineColor = 'green'; // Color for processing state
} else if (status === 'copying') {
lineColor = 'orange';
} else if (status === 'sending_number') {
lineColor = 'blue';
} else if (status === 'no_internet') {
lineColor = 'red';
}
// Check for impulse (e.g., value > 4)
const lastValue = data[data.length - 1];
if (lastValue > 4) {
lineColor = 'purple'; // Color for impulse
}
if (sparklineSpan.data('sparkline-initialized')) {
// Update existing Sparkline
sparklineSpan.sparkline(data, {
type: 'line',
width: '100%',
height: '20px',
lineColor: lineColor,
fillColor: 'transparent',
spotColor: 'red',
minSpotColor: 'blue',
maxSpotColor: 'orange',
highlightSpotColor: 'blue',
highlightLineColor: 'blue'
});
} else {
// Initialize Sparkline if not already
sparklineSpan.sparkline(data, {
type: 'line',
width: '100%',
height: '50px',
lineColor: lineColor,
fillColor: 'transparent',
spotColor: 'red',
minSpotColor: 'blue',
maxSpotColor: 'orange',
highlightSpotColor: 'blue',
highlightLineColor: 'blue'
});
sparklineSpan.data('sparkline-initialized', true);
}
}
}
Explanation:
We check the status and activity data for each device to determine how to update the sparkline.
By checking for a high lastValue (e.g., greater than 4), you can customize the line color or styling to indicate the impulse.
This should ensure that the sparkline for ARM3 shows a single pulse when activationglaz.py starts and remains normal otherwise.
Additional Notes:
Ensure that any global variables (activity_data, previous_processing_states, etc.) are properly initialized and managed in your app.
Remember to handle any exceptions or edge cases where the processing status might not be correctly updated due to network issues or script errors.
Test the changes thoroughly to confirm that ARM3 now shows "process is running" status only when activationglaz.py is running and the sparkline shows a single impulse at the script's start.
By making these adjustments, you should achieve the desired behavior where ARM3 only shows "process is running" status and a single pulse in the sparkline when the activationglaz.py script is started.