Script: Move records to groups according to tag

Following up on the question from @Hens here, I propose the JavaScript code below as an external script in a smart rule. It moves records depending on their tag to pre-defined group(s). Thus, a record with tag tag1 would be moved to group1 in database1 (see the explanation below the script for details).

const tagsForGroups = { "tag1": ["database1", "group1"],
  "tag2": ["database2", "group2"],
  "tag3": ["database3", "group3"]
};


function performsmartrule(records) {
  const app = Application("DEVONthink 3")
  records.forEach(r => {
    const tag = r.tags().length && r.tags()[0] || undefined;
    if (!tag) return;
    const targetGroup = tagsForGroups[tag];
    if (!targetGroup) return;
    const locationGroup = app.createLocation(targetGroup[1], {in: app.databases[targetGroup[0]]});
    app.move({record: r, to: locationGroup})
  })
}

How it works:

  • The object (“record” in AppleScript parlance) tagsForGroups at the top defines the relationship between tag name and target database/group. Each tag name is assigned an Array whose first element is the database name and the second one the group name. This assumes that the group is at the database’s top level. If it’s hidden in a subgroup, use a complete path to it like parent1/parent2/parent3/group. The names for tags, databases and groups must be changed to meet your requirements, of course.
  • the function performsmartrule receives the list of records selected by the smart rule’s conditions. Those should at least include tag is not <empty>.
  • the function loops over all records and
    • saves the first tag (if there is at least one tag) in the variable tag. If no tags exist, it continues with the next record.
    • saves the object from tagsForGroups with a matching tag name in the variable targetGroup. If no matching tag name is found, it continues with the next record.
    • it then gets the group (locationGroup) object for this database/group combination with createLocation, thus either creating a new group or retrieving the existing one
    • finally, it moves the current record to locationGroup

The script is not extensively tested, but it worked at least for one record :wink: I’m sure it can be implemented in AppleScript as well, but I’m not going there.

3 Likes