We can register aftersave events and code stuff ourselves, and we can set Workflows through the GUI. Both essentially do the same thing: trigger the aftersave event. But in what order? Are the Workflows always last? Does the create/register order of the workflows and events matter?
If I remember correctly there is no order. The events are extracted from the database and executed in the order that the database gives them to the application.
Ah OK, so the workflow could be fired after, before or somewhere at random in between other aftersave events?
I've done some testing by writing the result of the query that gets all the event handlers to a file and inspecting that (include/events/VTEventTrigger.inc around line 98, variable $evtinfosbyname). The events are grouped by their type (aftersave, beforesave and so on), and then by their ID (column eventhandler_id in vtiger_eventhandlers). That means that the event with the lowest ID will be fired first. So if you want to fire something before the workflow aftersave kicks in (it has one of the lowest ID's since it is installed with the system) you need to create a custom workflow function and place it in a workflow. Basically every eventhandler you register will be fired in the order you register it, and always after the workflow has done its thing.
We came up with a very simple but effective solution. When you register an event handler that you want to run before workflows do you can now register (make sure your corebos is more recent than the 12-12-2018 version) an entity.aftersave.first event (note the .first at the end). This code will do its business before workflows get launched. It you have code that you need to run a portion before and a portion after workflows of, you have to register two events, both a normal aftersave and an aftersave.first.