DmitrMakeev commited on
Commit
3583688
·
verified ·
1 Parent(s): 0b6bc0c

Update nutri_call.html

Browse files
Files changed (1) hide show
  1. nutri_call.html +40 -109
nutri_call.html CHANGED
@@ -624,119 +624,50 @@
624
  </fieldset>
625
 
626
  <script>
627
- document.getElementById('calculate-btn').addEventListener('click', function() {
628
- // Получение значений с проверкой
629
- const getValue = (id) => {
630
- const element = document.getElementById(id);
631
- if (!element) {
632
- console.error(`Element with id ${id} not found`);
633
- return 0;
634
- }
635
- const val = parseFloat(element.value);
636
- return isNaN(val) ? 0 : val;
637
- };
638
-
639
- // Формирование данных для сервера
640
- const requestData = {
641
- fertilizerConstants: {
642
- "CaN2O6": {
643
- "NO3": getValue('fert_ca_no3'),
644
- "Ca": getValue('fert_ca_ca')
645
- },
646
- "KNO3": {
647
- "NO3": getValue('fert_kno3_no3'),
648
- "K": getValue('fert_kno3_k')
649
- },
650
- "NH4NO3": {
651
- "NH4": getValue('fert_nh4no3_nh4'),
652
- "NO3": getValue('fert_nh4no3_no3')
653
- },
654
- "MgSO4": {
655
- "Mg": getValue('fert_mgso4_mg'),
656
- "S": getValue('fert_mgso4_s')
657
- },
658
- "KH2PO4": {
659
- "P": getValue('fert_kh2po4_p'),
660
- "K": getValue('fert_kh2po4_k')
661
- },
662
- "K2SO4": {
663
- "K": getValue('fert_k2so4_k'),
664
- "S": getValue('fert_k2so4_s')
665
- }
666
- },
667
- profileSettings: {
668
- 'P': getValue('profile_p'),
669
- 'K': getValue('profile_k'),
670
- 'Mg': getValue('profile_mg'),
671
- 'Ca': getValue('profile_ca'),
672
- 'S': getValue('profile_s'),
673
- 'NO3': getValue('profile_no3'),
674
- 'NH4': getValue('profile_nh4'),
675
- 'liters': parseInt(document.getElementById('liters-input').value) || 1
676
- }
677
- };
678
-
679
- // ВЫВОД ОТПРАВЛЯЕМЫХ ДАННЫХ В КОНСОЛЬ
680
- console.log("Данные для отправки на сервер:");
681
- console.log(JSON.stringify(requestData, null, 2));
682
-
683
- // Отправка на сервер
684
- fetch('/calculation', {
685
- method: 'POST',
686
- headers: {
687
- 'Content-Type': 'application/json',
688
- },
689
- body: JSON.stringify(requestData)
690
- })
691
- .then(response => {
692
- if (!response.ok) {
693
- return response.json().then(err => { throw new Error(err.error || 'Server error'); });
694
- }
695
- return response.json();
696
- })
697
- .then(data => {
698
- console.log("Ответ от сервера:", data);
699
 
700
- // Заполнение полей с результатами
701
- const fertilizerFields = {
702
- "Сульфат магния": "magnesium_sulfate",
703
- "Кальциевая селитра": "calcium_nitrate",
704
- "Монофосфат калия": "monopotassium_phosphate",
705
- "Аммоний азотнокислый": "ammonium_nitrate",
706
- "Калий сернокислый": "potassium_sulfate",
707
- "Калий азотнокислый": "potassium_nitrate"
708
- };
709
 
710
- // Очистка полей перед заполнением
711
- Object.values(fertilizerFields).forEach(id => {
712
- const field = document.getElementById(id);
713
- if (field) field.value = '';
714
- });
 
 
 
 
 
715
 
716
- // Заполнение граммовок удобрений
717
- if (data.fertilizers) {
718
- data.fertilizers.forEach(fert => {
719
- const fieldId = fertilizerFields[fert.name];
720
- if (fieldId) {
721
- const field = document.getElementById(fieldId);
722
- if (field) {
723
- field.value = fert.grams ? fert.grams.toFixed(3) : "0";
724
- }
725
- }
726
- });
727
- }
 
 
 
 
 
728
 
729
- // Заполнение EC если есть поле
730
- const ecField = document.getElementById('profile_ec');
731
- if (ecField && data.ec !== undefined) {
732
- ecField.value = data.ec.toFixed(2);
733
- }
734
- })
735
- .catch(error => {
736
- console.error('Ошибка:', error);
737
- alert('Ошибка при расчете: ' + error.message);
738
- });
739
- });
740
  </script>
741
 
742
 
 
624
  </fieldset>
625
 
626
  <script>
627
+ @app.route('/calculation', methods=['POST'])
628
+ def handle_calculation():
629
+ try:
630
+ global NO3_RATIO, NH4_RATIO, TOTAL_NITROGEN, VOLUME_LITERS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
631
 
632
+ # 1. Получаем данные
633
+ data = request.get_json()
634
+ if not data:
635
+ return jsonify({"error": "No JSON data"}), 400
 
 
 
 
 
636
 
637
+ # 2. Обновляем глобальные переменные из запроса
638
+ if 'ratios' in data:
639
+ NO3_RATIO = float(data['ratios'].get('NO3_RATIO', 8.25))
640
+ NH4_RATIO = float(data['ratios'].get('NH4_RATIO', 1.00))
641
+
642
+ if 'total_nitrogen' in data:
643
+ TOTAL_NITROGEN = float(data['total_nitrogen'])
644
+
645
+ if 'volume' in data:
646
+ VOLUME_LITERS = float(data['volume'])
647
 
648
+ # 3. Создаем калькулятор с текущими значениями
649
+ calculator = NutrientCalculator(volume_liters=VOLUME_LITERS)
650
+
651
+ # 4. Расчет
652
+ calculator.calculate()
653
+
654
+ # 5. Возвращаем результаты
655
+ return jsonify({
656
+ "fertilizers": calculator._format_fertilizers(),
657
+ "profile": calculator._format_profile(),
658
+ "ec": calculator.calculate_ec(),
659
+ "deficits": calculator.calculate_deficits(),
660
+ "used_ratios": {
661
+ "NO3_RATIO": NO3_RATIO,
662
+ "NH4_RATIO": NH4_RATIO
663
+ }
664
+ })
665
 
666
+ except Exception as e:
667
+ return jsonify({
668
+ "error": "Internal server error",
669
+ "details": str(e)
670
+ }), 500
 
 
 
 
 
 
671
  </script>
672
 
673