DmitrMakeev commited on
Commit
a363dd9
·
verified ·
1 Parent(s): 843948e

Update nutri_call.html

Browse files
Files changed (1) hide show
  1. nutri_call.html +111 -40
nutri_call.html CHANGED
@@ -326,50 +326,121 @@
326
 
327
  <script>
328
 
329
- @app.route('/calculation', methods=['POST'])
330
- def handle_calculation():
331
- try:
332
- global NO3_RATIO, NH4_RATIO, TOTAL_NITROGEN, VOLUME_LITERS
333
-
334
- # 1. Получаем данные
335
- data = request.get_json()
336
- if not data:
337
- return jsonify({"error": "No JSON data"}), 400
 
 
 
338
 
339
- # 2. Обновляем глобальные переменные из запроса
340
- if 'ratios' in data:
341
- NO3_RATIO = float(data['ratios'].get('NO3_RATIO', 8.25))
342
- NH4_RATIO = float(data['ratios'].get('NH4_RATIO', 1.00))
343
-
344
- if 'total_nitrogen' in data:
345
- TOTAL_NITROGEN = float(data['total_nitrogen'])
346
-
347
- if 'volume' in data:
348
- VOLUME_LITERS = float(data['volume'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
 
350
- # 3. Создаем калькулятор с текущими значениями
351
- calculator = NutrientCalculator(volume_liters=VOLUME_LITERS)
352
-
353
- # 4. Расчет
354
- calculator.calculate()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
 
356
- # 5. Возвращаем результаты
357
- return jsonify({
358
- "fertilizers": calculator._format_fertilizers(),
359
- "profile": calculator._format_profile(),
360
- "ec": calculator.calculate_ec(),
361
- "deficits": calculator.calculate_deficits(),
362
- "used_ratios": {
363
- "NO3_RATIO": NO3_RATIO,
364
- "NH4_RATIO": NH4_RATIO
365
- }
366
- })
 
 
 
 
367
 
368
- except Exception as e:
369
- return jsonify({
370
- "error": "Internal server error",
371
- "details": str(e)
372
- }), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  </script>
374
 
375
 
 
326
 
327
  <script>
328
 
329
+ <script>
330
+ document.getElementById('calculate-btn').addEventListener('click', function() {
331
+ // Получение значений с проверкой
332
+ const getValue = (id) => {
333
+ const element = document.getElementById(id);
334
+ if (!element) {
335
+ console.error(`Element with id ${id} not found`);
336
+ return 0;
337
+ }
338
+ const val = parseFloat(element.value);
339
+ return isNaN(val) ? 0 : val;
340
+ };
341
 
342
+ // Формирование данных для сервера
343
+ const requestData = {
344
+ fertilizerConstants: {
345
+ "CaN2O6": {
346
+ "NO3": getValue('fert_ca_no3'),
347
+ "Ca": getValue('fert_ca_ca')
348
+ },
349
+ "KNO3": {
350
+ "NO3": getValue('fert_kno3_no3'),
351
+ "K": getValue('fert_kno3_k')
352
+ },
353
+ "NH4NO3": {
354
+ "NH4": getValue('fert_nh4no3_nh4'),
355
+ "NO3": getValue('fert_nh4no3_no3')
356
+ },
357
+ "MgSO4": {
358
+ "Mg": getValue('fert_mgso4_mg'),
359
+ "S": getValue('fert_mgso4_s')
360
+ },
361
+ "KH2PO4": {
362
+ "P": getValue('fert_kh2po4_p'),
363
+ "K": getValue('fert_kh2po4_k')
364
+ },
365
+ "K2SO4": {
366
+ "K": getValue('fert_k2so4_k'),
367
+ "S": getValue('fert_k2so4_s')
368
+ }
369
+ },
370
+ profileSettings: {
371
+ 'P': getValue('profile_p'),
372
+ 'K': getValue('profile_k'),
373
+ 'Mg': getValue('profile_mg'),
374
+ 'Ca': getValue('profile_ca'),
375
+ 'S': getValue('profile_s'),
376
+ 'NO3': getValue('profile_no3'),
377
+ 'NH4': getValue('profile_nh4'),
378
+ 'liters': parseInt(document.getElementById('liters-input').value) || 1
379
+ }
380
+ };
381
 
382
+ // ВЫВОД ОТПРАВЛЯЕМЫХ ДАННЫХ В КОНСОЛЬ
383
+ console.log("Данные для отправки на сервер:");
384
+ console.log(JSON.stringify(requestData, null, 2));
385
+
386
+ // Отправка на сервер
387
+ fetch('/calculation', {
388
+ method: 'POST',
389
+ headers: {
390
+ 'Content-Type': 'application/json',
391
+ },
392
+ body: JSON.stringify(requestData)
393
+ })
394
+ .then(response => {
395
+ if (!response.ok) {
396
+ return response.json().then(err => { throw new Error(err.error || 'Server error'); });
397
+ }
398
+ return response.json();
399
+ })
400
+ .then(data => {
401
+ console.log("Ответ от сервера:", data);
402
 
403
+ // Заполнение полей с результатами
404
+ const fertilizerFields = {
405
+ "Сульфат магния": "magnesium_sulfate",
406
+ "Кальциевая селитра": "calcium_nitrate",
407
+ "Монофосфат калия": "monopotassium_phosphate",
408
+ "Аммоний азотнокислый": "ammonium_nitrate",
409
+ "Калий сернокислый": "potassium_sulfate",
410
+ "Калий азотнокислый": "potassium_nitrate"
411
+ };
412
+
413
+ // Очистка полей перед заполнением
414
+ Object.values(fertilizerFields).forEach(id => {
415
+ const field = document.getElementById(id);
416
+ if (field) field.value = '';
417
+ });
418
 
419
+ // Заполнение граммовок удобрений
420
+ if (data.fertilizers) {
421
+ data.fertilizers.forEach(fert => {
422
+ const fieldId = fertilizerFields[fert.name];
423
+ if (fieldId) {
424
+ const field = document.getElementById(fieldId);
425
+ if (field) {
426
+ field.value = fert.grams ? fert.grams.toFixed(3) : "0";
427
+ }
428
+ }
429
+ });
430
+ }
431
+
432
+ // Заполнение EC если есть поле
433
+ const ecField = document.getElementById('profile_ec');
434
+ if (ecField && data.ec !== undefined) {
435
+ ecField.value = data.ec.toFixed(2);
436
+ }
437
+ })
438
+ .catch(error => {
439
+ console.error('Ошибка:', error);
440
+ alert('Ошибка при расчете: ' + error.message);
441
+ });
442
+ });
443
+ </script>
444
  </script>
445
 
446