How to calculate self-consumed energy [2 x Shelly Em + SolarMan to ZCS Inverter]

Hello everyone.
I have two electrical panels on two floors connected to the general electricity meter, each with a shelly em.
I have an inverter connected directly to the general electricity meter.
I would have liked to put a third shelly em directly in the general electricity meter, but I don’t know where to put the shelly clamps, because on one side I get the inverter cables and on the other I get the cables of the two electrical panels, all connected together in the general electricity meter. Not having a way to record the energy fed into the grid and the energy withdrawn, I have the solarman sensors and sensors of the two shelly em. So I have the total production and the total consumption.

In the energy dashboard I only have these two values, I would like to see how much of the energy I produce is consumed, and how much I actually withdraw, and how much I put into the grid. I tried to create a sensor

- name: "Into the grid daily max"
  unit_of_measurement: "Wh"
  device_class: "energy"
  state_class: "total"
  state: "{{ max(((states('sensor.solarman_pv_generation_today')|float(0) * 1000 - (states('sensor.generale_channel_1_energy')|float(0) + states('sensor.shelly_em_channel_1_energy')|float(0)))) * 1, 0) }}"

Adding this in the energy dashboard, everything seems to work, but at the end of the day, when the inverter turns off, there is a strange peak at the end that throws off all the calculations.

Thanks