Hello everyone,
In the sample code below, you will find Source, Target, and Intermediate templates.
In this dummy use case, the intermediate template receives some optional record types and/or templates and extracts the fields of interest from them to create and fill the Target template accordingly.
Regardless of the time I spent on this, I could not be sure about the most efficient and proper way to do realize this simple idea. Moreover, things get easily uglier when a record type or template specified as input parameters contain some other templates or record types within them and maybe with some additional optional types.
I believe once you check the code & comments, the idea will become clearer to you. I’m open to any suggestions on the issue. Thank you very much for your interest and time in advance.
module Sample where
type Source_Key = (Party, Text, Int)
type Target_Key = (Party, Int)
type Intermediate_Key = (Party, Text)
data Passport = Passport with
  name : Optional Text
  age : Int
    deriving(Eq, Show)
    
template Source
  with
    sign : Party
    name: Text
    age: Int
  where
    signatory sign
    key (sign, name, age) : Source_Key
    maintainer key._1
template Target
  with
    sign: Party
    name: Text
    age: Int
    country: Text
    gender: Text
  where
    signatory sign
    key (sign, age) : Target_Key
    maintainer key._1
template Intermediate
  with
    sign : Party
    attr : Text
  where
    signatory sign
    key (sign, attr) : Intermediate_Key
    maintainer key._1
    controller sign can
      nonconsuming  Create : ()
        with
          passport :  Optional Passport
          template_key : Optional Source_Key
        do
          case passport of -- check if passport is set
            None -> -- pass.
                return()
            Some x -> 
                -- get fields of interest from the record type and assign them into corresponding set of variables.
                return ()
          
          case template_key of -- check if template key is set
            None -> -- do pass 
              return ()
            Some cid -> do 
              (_, fetched_template) <- fetchByKey @Source cid -- fetch the contract
              -- get fields of interest from the fetched template type and assign them into corresponding set of variables.
              return ()
          
          -- finally create the Target template and fill it with the previously taken data.
          create Target with sign = sign, name = fetched_template.name, age = passport.age.. 
          return ()


