beforeRelationshipDelete: double access

Hi,
this is my problem:
I have 2 custom modules (ModuleA, ModuleB) placed in relation to each other. Of course ModuleB is presented as a subpanel of ModuleA. ModuleA presents total values, each record in ModuleB presents partial values:
ModuleB
quantity record
1 50
2 40

ModuleA
tot 90

Now, when I add a record in ModuleB, I need to modify the values in ModuleA, so, following the example above, adding a new record (3) with quantity 10, ModuleA is modified, becoming 100. Similarly when I delete a record in the subpanel, I need to modify the total of ModuleA.
All this is handled by logic_hooks of ModuleB, for insertion there is no problem, it works perfectly, the problems are in the afterRelationshipDelete of ModuleB, apparently it is executed 2 times and I don’t understand why.

function beforeRelationshipDelete(&$bean, $event, $arguments) {
				
		$bean->load_relationship('<relationship_name>');
			
			$id=$bean-><relationship_name>->get(); //ID								
			if($id[0]!=""){
				$beanModuleA = BeanFactory::getBean('<ModuleA >', $id[0]);
				$beanModuleA ->tot= $beanModuleA ->tot- $bean->quantity;
								
				$bean->deleted=1;
				$bean->save();
				$beanModuleA ->save();
			}
}

if I delete the relation from the subpanel it works, but the double access occurs if I delete the record directly from ModuleB

I also tried with afterRelationshipDelete.

Can anyone tell me how to solve it please? Thanks

Add two lines in your logic hook file as shown below screenshot:

thanks for the reply jessica1

Let me know if this works for you or not?