In chapter 678, why did Madara suddenly turn into Kaguya? Was this all planned from beginning?
When Black Zetsu impaled Madara, he transfered Kaguya's will into Madara. By this process, Kaguya was revived by using Madara's body as the host vessel. And yes, it was planned from beginning by Zetsu.
Black Zetsu's history:
He was created by Kaguya and served only her. He acted as if he was Madara's creation, so he could facilitate the revival of his "mother", aka Kaguya. To do this, he planned the activation of Infinite Tsukuyomi by influencing Madara and the Akatsuki.
Further reading: Kaguya Ōtsutsuki
Black Zetsu is a shapeless manifestation of Kaguya's will, created before she was sealed by Hagoromo and Hamura. It planned to manipulate Indra Otsutsuki and his descendants to one day wield the Rinnegan and activate the Infinite Tsukuyomi.
Once Madara activated the Infinite Tsukuyomi and trapped everyones chakra inside the God Tree, Black Zetsu then stabbed Madara while he was sapped of his chakra, and uses his Ten Tail Jinchuriki body and combined his will to create a pseudo Kaguya.
Madara was used as a middle for Kaguya’s revival as black Zetsu was an creation of Kaguya then sought revenge after Hagoromo And Hamura Sealed Kaguya. Black Zetsu Manipulated Indra into fighting his own brother and then there was a clan created called the Uchiha’s and Madara was an Uchiha therefore he was an perfect suiting for Zetsu’s plan and was tricked into believing that black Zetsu was helping him but found out when he had absorbed the victim Shinobi’s chakra who were affected by the Infinite Tsukuyomi And then was tricked by Zetsu by getting pierced by black zetsu and then being used as a middle for Kaguya’s Revival.
just before her sons could completely seal her, Kaguya had manifested her will in the form of an artificial human called Black Zetsu. With the agenda of reviving its "mother", Black Zetsu manipulated Hagoromo's eldest son, Indra Ōtsutsuki, as well as his descendants within the Uchiha clan and his brother's descendants within the Senju clan in an attempt to get one of them to awaken the Rinnegan and break the seal. Madara Uchiha would eventually succeed in obtaining the Rinnegan, and Black Zetsu began secretly manipulating world events to have Kaguya revived.