Skip to content

Commit

Permalink
слияние с рабочей версией, которая показала себя стабильной за прошед…
Browse files Browse the repository at this point in the history
…шие 1.5 месяца (содержит множество исправлений)
  • Loading branch information
Qandra-Si committed Dec 19, 2020
2 parents 4f7e9ce + 35d9789 commit 8ebec4e
Show file tree
Hide file tree
Showing 26 changed files with 1,435 additions and 1,261 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ time python eve_sde_tools.py --cache_dir=./.q_industrialist
# Rebuilding invPositions.yaml file...
# ...
# real 24m39,000s
time python q_dictionaries.py --cache_dir=./.q_industrialist
# for example:
# real 1m2,000s
```

### Шаг 3. Подготовка к первому запуску программного обеспечения Q.Industrialist
Expand Down
3 changes: 2 additions & 1 deletion database/002.create_schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ CREATE TABLE qi.workflow_monthly_jobs
wmj_quantity INTEGER NOT NULL, -- кол-во кораблей (фитов) запланированных для ежемесячного производства
wmj_eft CHARACTER VARYING(16383), -- 16 Кб для текстового представления фита (очень много всего в карго?)
wmj_remarks CHARACTER VARYING(127), -- дополнительная информация
wmj_conveyor NOT NULL DEFAULT FALSE, -- признак того, что список модулей предназначаен для производства на конвейере
wmj_conveyor BOOLEAN NOT NULL DEFAULT FALSE, -- признак того, что список модулей предназначаен для производства на конвейере
CONSTRAINT pk_wmj PRIMARY KEY (wmj_id)
)
TABLESPACE pg_default;
Expand All @@ -128,6 +128,7 @@ CREATE TABLE qi.workflow_factory_containers
wfc_name CHARACTER VARYING(63), -- наименование контейнера (может устаревать, нужен для сигнализации)
wfc_active BOOLEAN NOT NULL DEFAULT TRUE, -- признак использования контейнера (отключенные нужны для наблюдения содержимого заданных ангаров)
wfc_disabled BOOLEAN NOT NULL DEFAULT FALSE, -- признак отсутствия контейнера в ангаре (был перемещён, и актуализирован как "сейчас отсутствует")
wfc_station_num INTEGER NOT NULL DEFAULT 1, -- номер станции (т.е. группы настроек factory:station_id2, factory:station_id3,...)
CONSTRAINT pk_wfc PRIMARY KEY (wfc_id)
)
TABLESPACE pg_default;
Expand Down
6 changes: 6 additions & 0 deletions database/002a.upgrades.sql
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,9 @@ SELECT DISTINCT
(SELECT sdei_number FROM eve_sde_integers WHERE sdei_id=wij_bp_tid AND sdei_category=6) AS iq,
(SELECT sdei_number FROM eve_sde_integers WHERE sdei_id=wij_bp_tid AND sdei_category=7) AS rq
FROM workflow_industry_jobs;

insert into qi.modules_settings(ms_module,ms_key,ms_val) values(1000, 'factory:blueprints_hangars2', '[6,7]');
insert into qi.modules_settings(ms_module,ms_key,ms_val) values(1000, 'factory:station_id2', '1032809060173');
insert into qi.modules_settings(ms_module,ms_key,ms_val) values(1000, 'factory:station_name2', 'JK-Q77 - Copy & Invent (t1 rigs)');

ALTER TABLE qi.workflow_factory_containers ADD COLUMN wfc_station_num integer NOT NULL DEFAULT 1;
22 changes: 20 additions & 2 deletions eve_esi_interface/eve_esi_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,9 +195,17 @@ def get_esi_paged_data(self, url, fully_trust_cache=False):
cached_data = self.__take_cache_from_file(url)
if not self.__offline_mode and fully_trust_cache and not (cached_data is None) and ("json" in cached_data):
# аналогично методу get_esi_data, хотя вроде в этом методе HttpError-ы не ожидаются?!
if not ("Http-Error" in cached_data["headers"]):
if not ("Http-Error" in cached_data["headers"][0]):
return cached_data["json"] if "json" in cached_data else None
if self.__offline_mode:
if cached_data is None:
return None
# Offline mode (выдаёт ранее сохранённый кэшированный набор json-данных)
if "Http-Error" in cached_data["headers"][0]:
code = int(cached_data["headers"][0]["Http-Error"])
self.__esi_raise_for_status(
code,
'{} Client Error: Offline-cache for url: {}'.format(code, url))
# Offline mode (выдаёт ранее сохранённый кэшированный набор json-данных)
return cached_data["json"] if "json" in cached_data else None
else:
Expand Down Expand Up @@ -235,7 +243,17 @@ def get_esi_paged_data(self, url, fully_trust_cache=False):
# 200 corporations/98615601/contracts/?page=1 14:10:23 "3f60dac1..."
# 304 corporations/98615601/contracts/?page=2 14:10:23 "fb294fda..." (из кеша)
# в этом случае, если уже встречались 200-коды, то etag не отправляем
page_data = self.__client.send_esi_request_http(data_path, etag)
try:
page_data = self.__client.send_esi_request_http(data_path, etag)
except requests.exceptions.HTTPError as err:
status_code = err.response.status_code
if status_code == 404: # это нормально, CCP используют 404-ответ для индикации "нет данных" ingame-доступа
if 1 == page:
# сохраняем информацию в кеше и выходим с тем же кодом ошибки
self.__dump_cache_into_file(url, [{"Http-Error": 404}], None)
raise
except:
raise
if page_data.status_code == 304:
# ускоренный вывод данных из этого метода - если находимся в цикле загрузке данных с сервера
# и при первом же обращении к первой же странице совпал etag, следовательно весь набор актуален
Expand Down
27 changes: 20 additions & 7 deletions eve_esi_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,14 +516,27 @@ def find_containers_in_hangars(
# пытаемся получить станцию, как item (это возможно, если она есть в корп-ассетах, т.е. является
# имуществом корпорации, иначе она принадлежит альянсу, или корпорация просто имеет там офис)
__station_dict = next((a for a in corp_assets_data if a["item_id"] == int(station_id)), None)
if __station_dict is None:
__office_dict = next((a for a in corp_assets_data if (a["location_id"] == int(station_id)) and (a["location_flag"] == "OfficeFolder")), None)
# на своих станциях тоже офис бывает
__office_dict = next((a for a in corp_assets_data if (a["location_id"] == int(station_id)) and (a["location_flag"] == "OfficeFolder")), None)

if (__station_dict is None) and (__office_dict is None):
raise Exception('Not found station or office {} in assets!!!'.format(station_id))

# поиск контейнеров на станции station_id в ангарах hangars_filter
return __find_containers_in_hangars_nested(
station_id if not (__station_dict is None) else __office_dict["item_id"],
hangars_filter,
sde_type_ids,
corp_assets_data)
__containers = []
if not (__station_dict is None):
__containers = __find_containers_in_hangars_nested(
station_id,
hangars_filter,
sde_type_ids,
corp_assets_data)
if not (__office_dict is None):
__containers2 = __find_containers_in_hangars_nested(
__office_dict["item_id"],
hangars_filter,
sde_type_ids,
corp_assets_data)
for __cont in __containers2:
if next((c for c in __containers if c['id'] == __cont['id']), None) is None:
__containers.append(__cont)
return __containers
45 changes: 44 additions & 1 deletion eve_sde_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
run the following command from this directory as the root:
>>> python eve_sde_tools.py --cache_dir=~/.q_industrialist
>>> python q_dictionaries.py --cache_dir=~/.q_industrialist
"""
import sys
import os
Expand Down Expand Up @@ -252,7 +253,7 @@ def get_market_groups_chain_by_type_id(sde_type_ids, sde_market_groups, type_id)

def get_root_market_group_by_type_id(sde_type_ids, sde_market_groups, type_id):
groups_chain = get_market_groups_chain_by_type_id(sde_type_ids, sde_market_groups, type_id)
if groups_chain is None:
if (groups_chain is None) or not groups_chain:
return None
return groups_chain[0]

Expand Down Expand Up @@ -452,6 +453,48 @@ def get_manufacturing_product_by_blueprint_type_id(blueprint_type_id, sde_bp_mat
return None, None, None


def get_industry_material_efficiency(
# признак - это чертёж или формула?
__is_reaction_formula,
# кол-во run-ов
runs_quantity,
# кол-во из исходного чертежа (до учёта всех бонусов)
__bpo_materials_quantity,
# me-параметр чертежа
material_efficiency):
if __is_reaction_formula:
# TODO: хардкодим -2.2% structure role bonus
__stage1 = runs_quantity * __bpo_materials_quantity
# учитываем бонус профиля сооружения
__stage2 = float(__stage1 * (100.0 - 2.2) / 100.0)
# округляем вещественное число до старшего целого
__stage3 = int(float(__stage2 + 0.99))
# ---
__need = __stage3
elif __bpo_materials_quantity == 1:
# не может быть потрачено материалов меньше, чем 1 штука на 1 ран,
# это значит, что 1шт*11run*(100-1-4.2-4)/100=9.988 => всё равно 11шт
__need = runs_quantity
else:
# TODO: хардкодим -1% structure role bonus, -4.2% installed rig
# см. 1 x run: http://prntscr.com/u0g07w
# см. 4 x run: http://prntscr.com/u0g0cd
# см.11 x run: https://prnt.sc/v3mk1m
# см. экономия материалов: http://prntscr.com/u0g11u
# ---
# считаем бонус чертежа (накладываем ME чертежа на БПЦ)
__stage1 = float(__bpo_materials_quantity * runs_quantity * (100 - material_efficiency) / 100.0)
# учитываем бонус профиля сооружения
__stage2 = float(__stage1 * (100.0 - 1.0) / 100.0)
# учитываем бонус установленного модификатора
__stage3 = float(__stage2 * (100.0 - 4.2) / 100.0)
# округляем вещественное число до старшего целого
__stage4 = int(float(__stage3 + 0.99))
# ---
__need = __stage4
return __need


def get_market_groups_tree_root(groups_tree, group_id):
if not (str(group_id) in groups_tree):
return group_id
Expand Down
69 changes: 58 additions & 11 deletions php_interface/qi_digger.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,37 +57,45 @@ function get_conn() {
$params = NULL;
//---
$action = htmlentities($_POST['action']);
if (($action == 'edit') && isset($_POST['fit']) && isset($_POST['quantity']) && isset($_POST['eft'])) {
if (($action == 'edit') &&
isset($_POST['fit']) &&
isset($_POST['quantity']) &&
isset($_POST['eft']))
{
$wmj_id = htmlentities($_POST['fit']);
$wmj_conveyor = isset($_POST['conveyor']) ? 't' : 'f'; // всегда установлен в on (в список не попадают off значения)
$wmj_quantity = htmlentities($_POST['quantity']);
if (is_numeric($wmj_id) && is_numeric($wmj_quantity) &&
(get_numeric($wmj_id) >= 1) && (get_numeric($wmj_quantity) >= 1)) {
$wmj_eft = $_POST['eft'];
if (!empty($wmj_eft)) {
$query = 'UPDATE workflow_monthly_jobs SET wmj_quantity=$2,wmj_eft=$3 WHERE wmj_id=$1;';
$params = array($wmj_id, $wmj_quantity, $wmj_eft);
$query = 'UPDATE workflow_monthly_jobs SET wmj_quantity=$2,wmj_eft=$3,wmj_conveyor=$4 WHERE wmj_id=$1;';
$params = array($wmj_id, $wmj_quantity, $wmj_eft, $wmj_conveyor);
if (isset($_POST['remarks'])) {
$wmj_remarks = $_POST['remarks'];
if (!empty($wmj_remarks)) {
$query = 'UPDATE workflow_monthly_jobs SET wmj_quantity=$2,wmj_eft=$3,wmj_remarks=$4 WHERE wmj_id=$1;';
$query = 'UPDATE workflow_monthly_jobs SET wmj_quantity=$2,wmj_eft=$3,wmj_conveyor=$4,wmj_remarks=$5 WHERE wmj_id=$1;';
array_push($params, $wmj_remarks);
}
}
}
}
}
//---
elseif (($action == 'add') && isset($_POST['quantity']) && isset($_POST['eft'])) {
elseif (($action == 'add') &&
isset($_POST['quantity']) &&
isset($_POST['eft'])) {
$wmj_conveyor = isset($_POST['conveyor']) ? 't' : 'f'; // всегда установлен в on (в список не попадают off значения)
$wmj_quantity = htmlentities($_POST['quantity']);
if (is_numeric($wmj_quantity) && (get_numeric($wmj_quantity) >= 1)) {
$wmj_eft = $_POST['eft'];
if (!empty($wmj_eft)) {
$query = 'INSERT INTO workflow_monthly_jobs(wmj_quantity,wmj_eft) VALUES($1,$2);';
$params = array($wmj_quantity, $wmj_eft);
$query = 'INSERT INTO workflow_monthly_jobs(wmj_quantity,wmj_eft,wmj_conveyor) VALUES($1,$2,$3);';
$params = array($wmj_quantity, $wmj_eft, $wmj_conveyor);
if (isset($_POST['remarks'])) {
$wmj_remarks = $_POST['remarks'];
if (!empty($wmj_remarks)) {
$query = 'INSERT INTO workflow_monthly_jobs(wmj_quantity,wmj_eft,wmj_remarks) VALUES($1,$2,$3);';
$query = 'INSERT INTO workflow_monthly_jobs(wmj_quantity,wmj_eft,wmj_conveyor,wmj_remarks) VALUES($1,$2,$3,$4);';
array_push($params, $wmj_remarks);
}
}
Expand All @@ -99,13 +107,26 @@ function get_conn() {
$ms_val_id = htmlentities($_POST['id']);
$ms_val_name = htmlentities($_POST['name']);
$ms_val_hangars = htmlentities($_POST['hangars']);
$station_num = ''; // 1
if (isset($_POST['station_num'])) {
$station_num = htmlentities($_POST['station_num']);
if ($station_num == '1')
$station_num = '';
else if (!is_numeric($station_num))
$station_num = '';
}
if (is_numeric($ms_val_id)) {
$query = <<<EOD
UPDATE modules_settings SET ms_val=v.v
FROM (VALUES ('factory:station_id',$1),('factory:station_name',$2),('factory:blueprints_hangars',$3)) AS v(k,v)
WHERE ms_key=v.k AND ms_module IN (SELECT ml_id FROM modules_list WHERE ml_name=$4);
FROM (VALUES ($1,$2),($3,$4),($5,$6)) AS v(k,v)
WHERE ms_key=v.k AND ms_module IN (SELECT ml_id FROM modules_list WHERE ml_name=$7);
EOD;
$params = array($ms_val_id, $ms_val_name, '['.$ms_val_hangars.']', 'workflow');
$params = array(
'factory:station_id'.$station_num, $ms_val_id,
'factory:station_name'.$station_num, $ms_val_name,
'factory:blueprints_hangars'.$station_num, '['.$ms_val_hangars.']',
'workflow'
);
}
}
//---
Expand Down Expand Up @@ -141,5 +162,31 @@ function get_conn() {
}
}
}
else if ($method == 'industry') {
$conn = NULL;
$query = NULL;
$params = NULL;
$action = htmlentities($_POST['action']);
if (($action == 'settings') && isset($_POST['conveyor_boxes'])) {
$ms_val_convboxes = htmlentities($_POST['conveyor_boxes']);
$query = <<<EOD
UPDATE modules_settings SET ms_val=v.v
FROM (VALUES ($2,$3)) AS v(k,v)
WHERE ms_key=v.k AND ms_module IN (SELECT ml_id FROM modules_list WHERE ml_name=$1);
EOD;
$params = array(
'workflow',
'industry:conveyor_boxes', '['.$ms_val_convboxes.']'
);
}
//---
if (!is_null($query)) {
$conn = get_conn();
pg_query_params($conn, $query, $params)
or die('pg_query_params err: '.pg_last_error());
pg_query($conn, 'COMMIT;');
pg_close($conn);
}
}
}
?>
Loading

0 comments on commit 8ebec4e

Please sign in to comment.