Calculate split energy usage

Hello,
a friend of mine just got a photovoltaics system installed on his house.
He got a 10kw string inverter and a 10kw hybrid inverter both from fronius. On the hybrid inverter is a byd hvm storage system.
In his house are two flats. One for him and one, where two other people are in.
The complete house only has one utility meter.
So he got two fronius smart meter installed. One for the whole house and one only for the other flat where the other two people are living.

He agreed on different prices with the tenants for electricity from the grid, electricity from the battery and electricity from the PV system.

Sensors i have available for calculation:
Energy to grid
Energy from grid
Energy from string inverter
Energy from hybrid inverter
Energy to the other flat

Sensors i calculate with riman sum:
Energy to the battery
Energy from the battery
Generated pv energy from hybrid inverter

Than i created a sensor that calculates the energy used in his flat with the sensors i have available.

How can i split the sum used energy from the other flat to the three different sensors counting the kWh used from pv directly, from storage and imported from the grid?

Thank you for you help

My first idea was to to it with power values.
But when i try to calculate the used power from his flat, i always get negative and positiv values.
I think this is because not all sensors update at the same time.